Skip to content

fix(memory): rebuild reuses cached embeddings instead of evicting them first - #182968

Merged
steipete merged 2 commits into
mainfrom
upd/upd-l1899
Oct 24, 2026
Merged

steipete merged 2 commits into
mainfrom
upd/upd-l1899

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Fixes #182886. Thanks @etzelm for the reproduction and provider-input counts.

What Problem This Solves

Full memory rebuilds at the embedding-cache cap evict cached vectors before later rebuild batches read them, turning a few misses into provider calls for the whole index. Forced indexing and the rebuild after an agent database-engine port share this path.

User Impact

Rebuilds reuse cached vectors and embed only the misses. The cache may temporarily grow by newly generated vectors during a rebuild; publication, failure, and abandonment trim it back to the existing cap. Suspended background rebuilds retain their vectors until resumption or discard. A process interruption can leave excess rows until the next synchronization prunes them. Incremental writes retain their per-commit capacity bound. No configuration, schema, or dependency changes.

Why This Change Was Made

The existing rebuild owner tracks pending cache cleanup alongside its staged index. Generated-cache writes defer eviction while that rebuild exists, and the same pruning owner handles SQLite and PostgreSQL cleanup. This avoids another corpus pass or holding a full vector-cache snapshot in JavaScript. Failed rebuilds preserve the published index and retain generated vectors under the normal cache policy.

The separate PostgreSQL query-plan issue #182808 already has PR #182821; this PR leaves its eviction query unchanged. A bounded nearby test repair captures SQL while native statements are live, preserving existing cache-capacity assertions after Node finalizes those statements.

Evidence

Acceptance: with 8 reusable vectors and 4 missing vectors in a cache at capacity, embed exactly 4 inputs, keep all 12 indexed chunks, and settle back to the cap. Cover both populated and empty published indexes, plus failed publication and suspended shutdown.

  • Base dc3a0a6a3d7a: the original manager regressions sent 12 inputs instead of 4, for both populated and empty published indexes. The extracted focused suite passes both cases, failure cleanup, and incremental commit bounds: 4 tests, 9.55s of test time. These need the real manager/cache/publication composition; cache-helper tests alone miss the cascade.
  • Real CLI with a loopback HTTP embedding stub and a 50,000-row cache containing 8 needed vectors: SQLite memory index --force embedded exactly 4 inputs, published 12 chunks, and finished with 50,000 cache rows.
  • Real PostgreSQL CLI memory index --force, with the same 50,000-row/8-hit/4-miss fixture and an empty derived index: exactly 4 inputs, 12 chunks, and 50,000 cache rows afterward.
  • Node focused replay: 74 tests passed across the other five files. The raw-cache suite initially had 4 failures because its observer read StatementSync.sourceSQL after disposal; after repairing that observer, 19/19 passed in 10.20s wall time (0.2s tests). Query counts, query plans, storage, and rollback assertions remain intact. Together these cover 93 distinct passing cases.
  • The six-file replay took 527.46s wall time, including 138.145s shared worker compilation and additional module preparation. The earlier recovery run passed 30 tests in 357.22s wall time (53% test time), with repeated pre-existing manager/worker startup. No individual test exceeded 30s. The shutdown case verified 8 suspended cache rows trim to 2 on close (2.268s).
  • Touched-file run-tsgo, oxlint, oxfmt, Madge (0 cycles), and git diff --check pass. Isolated Codex review found no actionable P0–P2 issues.

All product invocations used isolated HOME/state, distinct service profiles, and synthetic data. PostgreSQL uses a disposable local UTF8 PostgreSQL 17 database with the documented search extensions. A remote attempt failed authentication before returning a lease; no remote proof is claimed.

The full database port attempt stopped during preparation: the fresh server initially lacked unaccent, and the retained manifest then refused resume/rollback with “observed changed source data; required captured original SQLite image.” No engine switch or successful port is claimed. Captures remain intact. PostgreSQL cache proof uses a fresh PostgreSQL-backed CLI rebuild with an empty derived index instead.

The full check:changed SQLite-inventory step was omitted under the campaign's local gate budget; PR CI is the broad proof. CI seconds are not yet available. Diff: production +25/-9, tests +194/-58 (including moving the existing capacity case), docs +9/-3.

Defer embedding-cache eviction while full memory indexing is staged so new
misses cannot evict cached vectors that later batches still need. Trim after
publication or discard, including failure and suspended-rebuild shutdown.
Incremental writes keep their existing per-commit capacity bound.

Also capture SQL while native test statements are live, preserving the cache
capacity assertions on Node after statement finalization.

Fixes #182886
Thanks @etzelm for the reproduction and provider-input counts.
@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: memory-core Extension: memory-core size: M labels Oct 24, 2026
@steipete
steipete marked this pull request as ready for review October 24, 2026 22:12
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T23:23:04.261592Z cdac943 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR preserves cached embeddings throughout full memory rebuilds and trims excess cache rows after publication or discard.

Example: A rebuild needs 12 vectors, with 8 cached and 4 missing in a cache at capacity.

  • Before: Miss writes evict unread cached vectors, causing all 12 inputs to be embedded.
  • After: Only 4 inputs are embedded, all 12 chunks are indexed, and the cache returns to its configured cap.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level repair with concrete CLI result reports and meaningful lifecycle regressions; no actionable findings or unnecessary production machinery were identified.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR reports real memory index --force execution through the manager, HTTP embedding adapter, and publication owner on isolated SQLite and PostgreSQL 17 stores, yielding exactly 4 inputs, 12 chunks, and 50,000 final cache rows; the unsuccessful database-port attempt is explicitly excluded.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Rebuilding memory unnecessarily sends already-cached text to the embedding provider, increasing cost and downtime.
Reason: The reported failure is concrete, and maintainer authorship plus the explicit documented tradeoff settles the choice to allow temporary cache growth.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses the current rebuild eviction cascade with a focused change, and no actionable defect was found. Exact-head PostgreSQL CI remains pending.

Priority: P2
Reviewed head: 082693d551b8b0e91ad17bffbfe280102b30074a

Before merge

None.

Findings

None.

Agent review details

How this fits together

The memory-core indexing manager reads source chunks and cached vectors, requests missing embeddings, and atomically publishes a replacement search index while retaining the published database as the cache owner.

flowchart LR
  A[Memory and session sources] --> B[Rebuild manager]
  C[Published embedding cache] --> B
  B --> D[Embedding provider]
  D --> C
  B --> E[Shadow index]
  E --> F[Atomic publication]
  F --> G[Existing cache pruning]
  G --> C
Loading

Technical review

Best possible solution:

Retain reusable vectors until the existing rebuild owner finishes or discards its work, then apply the existing cache cap.

Do we have a high-confidence way to reproduce the issue?

Current-main cache reads leave timestamps unchanged while miss writes evict unread hits; the reporter supplies CLI counts and the PR reports base-failing manager regressions, but this review ran no target code.

Is this the best way to solve the issue?

The patch addresses eviction at its existing lifecycle owner without a cache snapshot, extra corpus pass, schema change, or competing policy path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 0f6631638b2e.

Provenance checked

  • Full-rebuild cache capacity changes intended behavior with a stated reason (7f7c87f: Pre-insert reservation prevents temporary shared-database growth, following the earlier database-growth safeguard.)
  • Canonical cache ownership and failed-work reuse keeps the original intent (fix(memory): reuse completed embeddings after failed rebuilds #144404: Successful embeddings persist independently of shadow-index publication so failed rebuilds can reuse completed work.)
  • Suspended rebuild lifetime keeps the original intent (6387f3a: Retain private SQLite rebuild progress across foreground turns and discard it on owner close or invalidation.)
  • Native SQL test observation keeps the original intent (6d1dd21: Consolidated capacity tests retain query-count, query-plan, storage, and rollback assertions; capturing SQL before statement disposal preserves those assertions.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 6387f3a adds extensions/memory-core/src/memory/manager-reindex-ops.ts:58 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6387f3ad3b07; files: extensions/memory-core/src/memory/manager-reindex-ops.ts)

PR surface

Source +16, Tests +136, Docs +6. Total +158 across 8 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 3 25 9 +16
Tests 4 194 58 +136
Docs 1 9 3 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 228 70 +158

Review metrics

Metric Value Why it matters
Production versus test changes Production +25/-9; tests +194/-58 Production growth adds cleanup tracking to the existing owner; tests protect distinct populated-index, empty-index, failure, incremental-capacity, and shutdown behavior.

Labels

Label changes:

  • add P2: Cache-cap rebuilds can incur avoidable embedding-provider charges and substantially extend indexing or planned database-port downtime.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Cache-cap rebuilds can incur avoidable embedding-provider charges and substantially extend indexing or planned database-port downtime.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 24, 2026, 6:28 PM ET / 22:28 UTC.

@steipete
steipete merged commit 355a5ae into main Oct 24, 2026
95 checks passed
@steipete
steipete deleted the upd/upd-l1899 branch October 24, 2026 23:42
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
…m first (openclaw#182968)

At the embedding cache cap, a full memory rebuild evicted cached vectors it had not read yet to make room for each miss, then re-embedded them too, so the rebuild after database port could send every chunk to the provider. Memory Core now defers eviction while a rebuild consumes cached vectors and trims to the cap on publication or discard, including failure and shutdown; incremental writes keep their capacity bound. Live SQLite and PostgreSQL rebuilds embed only the misses (4 instead of 12) and finish at the 50,000-row cap. Fixes openclaw#182886. Thanks @etzelm.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: memory-core Extension: memory-core P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Memory rebuild after database port --family agent re-embeds every chunk when the embedding cache is at its cap, though most vectors are cached

1 participant