Skip to content

fix(memory): reuse completed embeddings after failed rebuilds - #144404

Merged
jalehman merged 2 commits into
mainfrom
pb-f1e/memory-quota-rebuild
Sep 11, 2026
Merged

jalehman merged 2 commits into
mainfrom
pb-f1e/memory-quota-rebuild

Conversation

@jalehman

@jalehman jalehman commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Related: #91354, #132708

What Problem This Solves

Fixes an issue where users retrying a failed memory-index rebuild would send successful embedding work to the provider again, even after a manager restart. On a large, quota-limited rebuild, discarding those completed results can repeatedly consume the same allowance without finishing the index.

The generic OpenAI-compatible embedding adapter also discarded structured HTTP status, quota, and retry metadata. Its errors could not fully participate in the bounded retry policy already landed in #134959.

Why This Change Was Made

Keep the published agent database as the canonical embedding-cache owner, separate from atomic shadow-index publication. Persist validated successful inline batches, successful split leaves, and completed per-file/source-wide runtime batches immediately. A later indexing failure can discard the incomplete shadow without discarding reusable embeddings. Remove the full-cache shadow seeding and cache replacement at publication.

Cache writes validate source snapshots and respect provider generations, database lifetime/revisions, workspace locking, and session tombstones. Reserve cache capacity before insertion, enforce the canonical cache cap after successful full rebuilds (including all-cache-hit rebuilds), and reject malformed vectors before retaining them. If separate requests disagree about vector dimensions, invalidate only the ambiguous provider identities so a subsequent retry can recover; retain other providers' caches and the published index. Reuse remains bounded by configured cache retention and compatible provider identity/content hashes.

A nonempty Forget selection now clears the selected agent's entire embedding cache, including unpublished rebuild results that cannot be selected through published chunk provenance. This is the accepted no-schema tradeoff: unrelated published index entries remain searchable, but future indexing may need to regenerate their cached embeddings. Dry runs report the whole-cache count without mutation; empty selections do neither.

The remaining generic adapter fix uses the existing shared HTTP-error owner and redacts reflected request credentials. This branch was rebased after #134959; it does not replace that PR's cooldown profiles, Google RetryInfo parsing, permanent-quota classification, or interactive search budget. The only retry-policy addition here is a completed-batch callback used by the cache owner.

User Impact

  • With embedding caching enabled, retries can reuse compatible completed work instead of requesting it again after a failed rebuild or manager restart.
  • The previous published index stays available until the replacement is successfully published.
  • Rebuild preparation no longer copies the entire embedding cache into a temporary database.
  • Generic OpenAI-compatible failures retain retry/status metadata and redact reflected request credentials.
  • Forget removes cached embeddings from unfinished rebuilds as well as the published-index-derived data covered by the existing purge.

This is a partial repair for the linked reports, not a complete quota-management solution. It does not add shared cross-agent quota admission, persist or resume unfinished remote Batch jobs, add Batch support to another provider, explain every rebuild phase, or suppress legitimate upgrade-triggered rebuilds. No new configuration, database schema, or dependency is introduced.

Evidence

  • Follow-up final validation: the complete changed-file gate passed (exit 0), including all TypeScript lanes, lint, dead-export scans, and storage/plugin guards. The exact staged follow-up passed P0–P2 autoreview with no actionable findings.
  • Review follow-up: a new real-SQLite regression reproduced the cache-cap defect (three retained rows with maxEntries: 1 after a successful cache-only rebuild). Pruning after successful publication fixes it with zero provider requests; the failed-rebuild preservation control remains green.
  • Follow-up regression suite: 71 tests passed across five files, covering recovery, cache capacity, source races, Forget, and chunk publication. The three CI publication failures were old assertions that treated the embedding cache as part of the atomic index. The updated tests still require every published index table to roll back, and separately require completed embeddings to survive and be reused without additional provider calls.
  • Existing-database compatibility: recovery fixtures create a published index/cache, fail a subsequent rebuild, close and reopen the manager, and verify reuse plus index preservation. The legacy-schema test still requires doctor rather than silently accepting an incompatible schema. This change introduces no schema migration; whole-cache Forget remains the documented, accepted behavior tradeoff.
  • Rebased focused validation: 177 tests passed across ten files (36 generic adapter tests across two focused files; 141 memory tests across eight files), including recovery/restart, late failure, per-file/source-wide batch retention, malformed vectors, source races, Forget, cache capacity, publication, and the existing cooldown/query-budget regressions.
  • A cross-batch dimension regression was observed failing before the fix: after restart, otherwise-correct provider responses were still rejected because the earlier wrong-dimension batch remained cached. It now passes and also verifies that unrelated provider caches survive invalidation.
  • Recovery regressions demonstrate the original failure order: successful embeddings, later shadow failure, manager restart, then retry. The repaired retry sends no new requests for retained inputs while the old published index survives the failed attempt.
  • Generic adapter proof uses a real loopback HTTP server returning a synthetic 429/Retry-After response. Memory tests use isolated SQLite fixtures and deterministic fake providers, never a user's live memory database.
  • Initial P0–P2 autoreview: passed, no actionable findings. Both accepted findings from earlier candidates were addressed: the superseded unbounded retry implementation was removed during rebase, and cross-batch dimension poisoning was reproduced and repaired.
  • Initial changed-file gate passed for all 19 changed paths, including four TypeScript graph lanes, formatting, core and extension lint, ratchets, plugin/database boundaries, import-cycle checks, dead-export scans, and the selected contract tests.
  • No paid-provider reproduction, full repository test suite, or complete application build was run. These fixtures do not establish external provider billing behavior or the cause of the reporter's apparent Gemini Batch stall.
Changes walkthrough
File Change
extensions/memory-core/src/memory/manager-embedding-ops.ts Persist successful results through the canonical cache owner with lifetime/source/revision fencing.
extensions/memory-core/src/memory/manager-embedding-cache.ts Validate cached vectors, deduplicate writes, and reserve bounded capacity.
extensions/memory-core/src/memory/manager-embedding-policy.ts Report successful split leaves before later work can fail.
extensions/memory-core/src/memory/manager-sync-ops.ts Retain canonical cache ownership and enforce retention after successful publication.
extensions/memory-core/src/memory/manager-sync-base.ts Remove obsolete cache-copying implementation.
extensions/memory-core/src/memory/manager-db.ts Publish index tables without replacing the live cache.
extensions/memory-core/src/memory-forget.ts Clear the entire cache for nonempty selections and invalidate pending work.
src/plugins/openai-compatible-embedding-provider.ts Preserve typed HTTP metadata and redact reflected credentials.
extensions/memory-core/src/memory/manager.reindex-recovery.test.ts Cover successful-work retention, restart, malformed output, and failure boundaries.
extensions/memory-core/src/memory/manager-memory-source-race.test.ts Assert stale source embeddings are not retained.
extensions/memory-core/src/memory/manager-embedding-cache.test.ts Prove replacement at capacity never transiently overflows.
extensions/memory-core/src/memory/manager-embedding-policy.test.ts Cover successful split-leaf callbacks.
extensions/memory-core/src/memory/manager-chunk-writer.test.ts Prove atomic index rollback while completed embeddings survive and are reused.
extensions/memory-core/src/memory/manager-db.test.ts Prove publication preserves the canonical cache.
extensions/memory-core/src/memory/manager-sync-yield.test.ts Remove tests for the deleted shadow-cache seed path.
extensions/memory-core/src/memory-forget.test.ts Cover whole-cache counts, repeat purges, and empty selections.
src/plugins/openai-compatible-embedding-provider.http-error.test.ts Exercise metadata and credential redaction through loopback HTTP.
docs/cli/memory.md Document the Forget cache-clearing tradeoff.
docs/concepts/memory-provenance.md Document retention and purge behavior for unfinished rebuilds.
config/assertion-safety-baseline.txt Shrink the ratchet after removing cache-seeding code.

@clawsweeper

clawsweeper Bot commented Sep 10, 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.

@jalehman
jalehman marked this pull request as ready for review September 10, 2026 20:49
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: memory-core Extension: memory-core size: XL maintainer Maintainer-authored PR labels Sep 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 10, 2026
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 10, 2026, 8:02 PM ET / September 11, 2026, 00:02 UTC (Revision 2).

ClawSweeper review

What this changes

Memory indexing retains completed embeddings across failed rebuilds, bounds the retained cache, clears unpublished cached results during Forget, and preserves structured provider error metadata.

Merge readiness

⛔ Blocked before merge - 1 item remains

The prior cache-cap blocker is resolved, and no remaining blocking defect was found. The recovery improvement remains necessary on current main; the related merged cooldown work does not supersede it.

Priority: P2
Reviewed head: b1d2cdcd5cd59d3e272067381275823d4b47aca4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent recovery repair with meaningful regression coverage; the prior actionable finding is resolved.
Proof confidence 🌊 off-meta tidepool Not applicable: The repository state identifies a MEMBER author, so the external-contributor proof gate does not apply. Inspected recovery fixtures use real SQLite with fake providers; the adapter test uses real loopback HTTP, without claiming external quota or billing coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The repository state identifies a MEMBER author, so the external-contributor proof gate does not apply. Inspected recovery fixtures use real SQLite with fake providers; the adapter test uses real loopback HTTP, without claiming external quota or billing coverage.
Evidence reviewed 9 items Prior finding addressed: The GitHub commit diff adds canonical-cache pruning after successful publication. The corresponding regression starts with three retained rows and a cap of one, requires zero embedding requests, and checks the surviving cache and published content. The adjacent failed-rebuild control still requires cache preservation.
Current main still needs the recovery change: At the fetched main revision, full rebuilds still seed the shadow embedding cache and prune it before publication; publication still deletes and replaces the live cache from the shadow. Completed work therefore remains coupled to successful shadow publication.
Latest release comparison: The supplied latest release revision also contains shadow-cache seeding and pre-publication pruning. This check does not establish the proposed recovery behavior as shipped.
Findings None None.
Security None None.

How this fits together

Memory Core converts workspace files and session transcripts into searchable text and vector indexes. Its embedding cache avoids repeated provider requests, while shadow databases keep incomplete rebuilds from replacing the published index.

flowchart TD
  A[Memory files and sessions] --> B[Prepare content chunks]
  B --> C{Cached embedding available?}
  C -->|Yes| E[Build shadow index]
  C -->|No| D[Embedding provider]
  D --> F[Validate and retain completed embeddings]
  F --> E
  E -->|Successful rebuild| G[Publish searchable index]
  H[Forget selected sessions] -->|Clear retained embeddings| F
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +251, Tests +334, Docs +12, Other 0. Total +597 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 8 398 147 +251
Tests 9 437 103 +334
Docs 2 18 6 +12
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 20 854 257 +597

Review metrics

Metric Value Why it matters
Production versus test growth Production net +251 lines; tests net +334 lines Production growth implements durable cache writes and validation fences; test growth covers recovery, capacity, deletion, and publication failures.

Stored data model

Persistent data-model change detected: unknown-data-model-change: extensions/memory-core/src/memory-forget.ts, unknown-data-model-change: extensions/memory-core/src/memory/manager-embedding-cache.ts, unknown-data-model-change: extensions/memory-core/src/memory/manager-embedding-ops.ts, unknown-data-model-change: extensions/memory-core/src/memory/manager-sync-base.ts, unknown-data-model-change: extensions/memory-core/src/memory/manager-sync-ops.ts, unknown-data-model-change: src/plugins/openai-compatible-embedding-provider.ts, and 8 more. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep one bounded, durable embedding cache independent of atomic index publication, with source validation and Forget invalidation preserving the documented deletion contract.

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

Yes, from source: complete embeddings during a full rebuild, fail before shadow publication, restart, and retry. Current main discards that shadow work; the supplied regressions exercise this order, but were not run in this read-only review.

Is this the best way to solve the issue?

Yes. Separating reusable provider results from atomic index publication fixes the owning lifecycle without another cache or schema, and the follow-up restores successful-rebuild retention enforcement.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 48b319e240fa.

Labels

Label justifications:

  • P2: This is a bounded memory-index recovery improvement that avoids repeating completed embedding work after failures.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The repository state identifies a MEMBER author, so the external-contributor proof gate does not apply. Inspected recovery fixtures use real SQLite with fake providers; the adapter test uses real loopback HTTP, without claiming external quota or billing coverage.

Evidence

What I checked:

  • Prior finding addressed: The GitHub commit diff adds canonical-cache pruning after successful publication. The corresponding regression starts with three retained rows and a cap of one, requires zero embedding requests, and checks the surviving cache and published content. The adjacent failed-rebuild control still requires cache preservation. (extensions/memory-core/src/memory/manager-sync-ops.ts:637, b1d2cdcd5cd5)
  • Current main still needs the recovery change: At the fetched main revision, full rebuilds still seed the shadow embedding cache and prune it before publication; publication still deletes and replaces the live cache from the shadow. Completed work therefore remains coupled to successful shadow publication. (extensions/memory-core/src/memory/manager-sync-ops.ts:539, 48b319e240fa)
  • Latest release comparison: The supplied latest release revision also contains shadow-cache seeding and pre-publication pruning. This check does not establish the proposed recovery behavior as shipped. (extensions/memory-core/src/memory/manager-sync-ops.ts:539, 1391f7cd2d40)
  • Cache ownership and write fencing: Completed batches use the captured published database, validate vectors and source snapshots, and recheck generation lifetime and database revision before synchronous cache writes. Searches retain the published index while rebuild work uses its separate database context. (extensions/memory-core/src/memory/manager-embedding-ops.ts:653, b1d2cdcd5cd5)
  • Publication and restart coverage: The inspected tests preserve published index tables after injected publication failures while separately requiring completed cache rows to survive and avoid new provider calls. Recovery coverage also closes and reopens the manager, and the legacy-schema test retains the existing Doctor requirement. Tests were inspected, not executed during this review. (extensions/memory-core/src/memory/manager.reindex-recovery.test.ts:312, b1d2cdcd5cd5)
  • Forget compatibility tradeoff: The captured PR body explicitly records acceptance of whole-cache deletion without a schema change. Source returns before mutation for dry runs and empty selections; nonempty purges invalidate pending work and clear the selected agent's cache. Documentation explains that unrelated published entries remain searchable but later indexing can regenerate embeddings. (extensions/memory-core/src/memory-forget.ts:590, b1d2cdcd5cd5)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • shojikumaru: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-10T20:58:23.369Z sha 2c17271 :: blocked before merge. :: [P2] [P2] Enforce the cache cap after an entirely cached rebuild

@jalehman

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressed the successful all-cache-hit rebuild retention finding in b1d2cdc. The new SQLite regression failed with three cache rows at a cap of one, then passed after pruning the canonical cache only after successful publication. Failed-rebuild preservation remains covered.

Also corrected the three CI chunk-publication tests to verify both intended contracts: published index tables roll back on failure, while completed embeddings remain cached and are reused without additional provider calls. All 71 focused tests, the complete changed-file gate, and final staged P0–P2 autoreview passed. The PR description now includes these results and existing-database/legacy-schema compatibility boundaries.

@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added 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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 11, 2026
@jalehman
jalehman merged commit cd9be2b into main Sep 11, 2026
190 of 191 checks passed
@jalehman
jalehman deleted the pb-f1e/memory-quota-rebuild branch September 11, 2026 00:52
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 11, 2026
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 maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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.

1 participant