Repository navigation
improve(memory): drop embedding cache copies the published index already serves - #195369
roboclaw-bot merged 5 commits into
Conversation
- After an ordinary sync publishes its memory files, and after a full rebuild publishes, delete cache rows of the primary sync identity written since that run started whose exact bytes every published chunk carrying the hash holds, when at least one of those chunks is a memory-file chunk under the same published identity, input format and dimensions. - Rows whose vector differs from any published variant, unpublished rows, session-only hashes, aliases and other identities are kept. - Ordinary syncs retire only when the memory sync returned normally and left no dirty or full-retry state, so failed, partial and deferred runs keep every row for their retry; the skipped sync's start carries to the next clean sync, which retires those rows once its publication serves them. - New cache.retire worker command on SQLite and PostgreSQL: one write transaction per page of 256 candidates in (updated_at, hash) order on the updated_at index, one chunk read per page, yields between pages, stops while closing. - Runs before the cap prune, outside every publication transaction, gated on cache.enabled. Errors are logged and never reach publication or retry state. - The 1a published-meta identity gate is shared through readMemoryPublishedVectorMeta. The kernel is registered as worker-only in the database worker inventory. - Existing cases that read generated vectors back from the cache as a probe (reindex recovery, chunk publication retry, source and session races, legacy-format upgrade, declared-dimension repair, PostgreSQL rebuild reuse) hold retirement through keepPublishedCacheDuplicates; their assertions are unchanged. - manager-cache-rebuild.test.ts re-seeds the rows an older build kept, and its full-mode cap case holds retirement so the cap still settles the rows. - Docs describe the retention rule.
- After a full rebuild publishes, a second cache.retire pass covers rows last written before the rebuild started, with the same predicate, page bound and failure isolation as the pass over the rows the rebuild wrote. The two fences meet at the rebuild start, so together they cover every row of the identity, and the replacement index rewrote every chunk. - Rows whose vector differs from every published variant, ambiguous hashes, unpublished rows and session-only hashes are kept. - Ordinary syncs still retire only rows written since they, or the oldest earlier sync that did not finish cleanly, started; older rows wait for the next full rebuild. - manager-cache-rebuild.test.ts now expects the superseded rows alone after a published rebuild. Docs describe the full-rebuild pass.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. What this changesThis PR removes embedding-cache rows after successful publication when the memory index holds identical vectors. Example: Force-rebuild the demonstrated upgraded SQLite store containing 977 cache rows.
Review scores
ProductKind: Performance · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 1 item remains Keep this PR open: it provides useful, demonstrated storage savings, but deleting valid cache entries still requires the storage owner's retention decision. Priority: P2 Decision needed
Before merge
FindingsNone. Agent review detailsHow this fits togetherMemory Core converts memory files and session sources into a published search index; its publication workers also maintain the reusable embedding cache on SQLite and PostgreSQL. flowchart LR
A[Memory files and sessions] --> B[Memory sync owner]
B --> C[Cache and published vector lookup]
C --> D[Embedding provider for misses]
B --> E[Publication worker]
E --> F[Published search index]
E --> G[Post publication cache retirement]
Technical reviewBest possible solution: Adopt bounded duplicate retirement through the existing publication workers only after the storage owner accepts its documented storage-versus-re-embedding tradeoff. Do we have a high-confidence way to reproduce the issue? Current-main source retains generated cache copies, and the contributor's CLI comparisons demonstrate their storage cost; this read-only review ran no target code. Is this the best way to solve the issue? The smallest complete implementation uses the existing publication workers and one shared predicate, preserves failed-run reuse, and keeps cleanup outside publication transactions; accepting the retention policy remains an owner choice. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 819ee5e41aec. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +263, Tests +747, Docs +19, Other +3. Total +1032 across 26 files. Added test files: 4. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes: No label changes. Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReviewed November 11, 2026, 12:42 AM ET / 05:42 UTC (Revision 4). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
5a75f21 to
8b5b0f0
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review Merged current main (one import conflict in |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…ady serves (openclaw#195369) Retire exact embedding-cache duplicates after clean publication through the existing SQLite/PostgreSQL worker owners. Include both newly published duplicates and older duplicates after a full rebuild, while preserving failed-run, disabled-cache, ambiguous-vector and session-only rows. Patrick-Erichsen instructed landing after disclosure of the retention alternatives and re-embedding costs; the accepted both-stage decision is recorded in the PR. Validation: independently reviewed source and qualified shipped-CLI/SQLite/PostgreSQL proof at their recorded executing revisions; exact-head CI42966846081 attempt2 and security/dependency publication succeeded. The original cancelled attempt remains historical evidence. Co-authored-by: Mitchell Etzel <[email protected]> Co-authored-by: Patrick-Erichsen <[email protected]>
Align the Memory shutdown regression with #195369: a successful full publication now retires its redundant embedding-cache row. Preserve the accepted-sync, published-text, executor-reuse and lease-release checks. Co-authored-by: obviyus <[email protected]> Co-authored-by: steipete <[email protected]>
…198153) Align the Memory shutdown regression with openclaw#195369: a successful full publication now retires its redundant embedding-cache row. Preserve the accepted-sync, published-text, executor-reuse and lease-release checks. Co-authored-by: obviyus <[email protected]> Co-authored-by: steipete <[email protected]>
…196378) fix(memory): let large memory rebuilds finish without running out of worker memory A full memory rebuild ran out of its 512 MiB worker and restarted on every attempt when the index held tens of thousands of embedded chunks, for example after the chunking-format upgrade from 2026.10.9, so vector search never came back and search kept serving the old keyword index. Two steps held a whole pass in one worker. Vector reuse now reads cached embeddings in pages of whole hashes sized to 8 MiB of decoded vectors. The SQLite publication worker now parses each staged row as it arrives and keeps its vector as a Float64Array instead of JSON, turning one row at a time back into a number array at source.replace, which stays one atomic replace. Stored bytes, schema and retention are unchanged, no table is added, and the PostgreSQL path is untouched. Evidence: a 94,919-chunk index at 1536 dimensions built through the real import and memory index paths in a secretless node:24.22.1 container with a stand-in embeddings server. On the PR base and current main, the format-upgrade rebuild and memory index --force ran out of memory after 19-33 s with the read worker near 490 MiB, and a running Gateway retried and failed again while search served the keyword index. With this change both rebuilds finish in 320-415 s with peak worker heaps near 100-110 MiB, no embedding calls, byte-identical stored vectors and vector search hits. A 634-chunk index and an already-rebuilt index behave the same on both. The red changed-extensions bundles are three memory-core integrity tests that fail on main since #194484: #196378 (comment). Net 0 test lines. Details: #196378 (comment). Thanks @garrytan. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 3e7fb1b) Release adaptation: page the release branch's existing cache-only reads; do not import newer published-vector fallback, PostgreSQL, or retirement owners. Retain provider identity order, disabled-cache behavior and SQLite publication contracts. Packed staging is unchanged from the source fix. Companion review: 3ea0883 (#195369) is a separate cache-retention change, not required for bounded reads or packed staging; intentionally excluded. No later PR-number follow-ups. Existing transfer/settlement fixtures retain the same protocol. No storage format, schema or retention change. Proof: Node syntax checks and exact production staging-helper value/order, replay and fragmented-tail checks pass. Full owner tests/typecheck remain unrun: isolated worktree has no dependencies; no install authorized. Independent review remains with the parent (worker cannot spawn children). Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vincentkoc <[email protected]> (cherry picked from commit 8d8df0799fba9770b913bdc9be546915c8351a8c)
Refs #168777
What Problem This Solves
The memory embedding cache keeps a second full copy of every vector the published memory index already holds, so most of a large cache (64% of a 50,000-row cache in #168777) is duplicate data.
User Impact
User impact: memory databases stop growing a second copy of published vectors. On a 4096-dim store the cache table drops from 32.9 MB to 0.95 MB after the first full rebuild, with no new embedding calls. The cost: text copied into a different memory file, and switching back to an earlier provider or model, are embedded again (details below). No schema change and no user action.
Why This Change Was Made
Stage 1a (#185968) lets ordinary memory-file edits reuse vectors from the published index. The embedding cache still keeps its own copy of every vector it wrote, so most cache rows duplicate a published chunk. This change deletes those copies after a successful publication, in two commits:
perf(memory): retire cache rows a publication already serves): after an ordinary sync publishes its memory files, and after a full rebuild publishes, the cache rows that run wrote are deleted when the published index holds the same bytes.perf(memory): retire existing cache duplicates after a full rebuild): after a full rebuild publishes, older rows that the new index holds are deleted too. This commit can be dropped on its own (the "1b only" option below).Accepted decision: both-stage cache retirement
On November 13, 2026, @Patrick-Erichsen instructed landing after the retention alternatives and their re-embedding costs were disclosed in the review and landing discussion. This records acceptance of the current proposal: both 1b and step 2, including the three re-embedding costs below. The linked discussion is for team reference and requires sign-in.
This is the maintainer acceptance of the intentional valid-cache retention change required by
docs/reference/database-schemas/storage-changes.md, "Review checkpoint for material changes". No source or retention semantics were changed to obtain acceptance.Alternatives considered:
perf(memory): retire existing cache duplicates after a full rebuild. Rows written after the upgrade are retired as in A. Rows already in the cache stay until the cap prune evicts them. Not measured separately.Why both: each cost below is paid as one embedding call per affected chunk, like any cache miss today; switching back to an earlier provider or model can re-embed the whole store. None changes what is published or searched: chunk checksums and search hits match base after every step below. The savings grow with the store: 64% of a 50,000-row cache in #168777, and on the upgraded 2026.11.2 store below the cache vectors go from 500,224 B on base to 7,168 B on head. Rolling back to the newest build without this PR needs no repair: base works on a cleaned store with the same inputs and results as on its own store (table under "Rolling back"). Accepting 1b only keeps an existing store's duplicates until the cap prune reaches them.
The accepted policy:
A cache row of the active primary embedding identity is deleted after a successful publication when every published chunk carrying its text hash holds exactly the same bytes, at least one of those chunks belongs to a memory file, and the published index metadata binds the same provider, model, provider key, input format and dimensions. Nothing else is deleted:
Accepting this means accepting these re-embedding costs, which the cache used to absorb:
How it runs
cache.retirecommand on the SQLite publication worker and the PostgreSQL binding. One write transaction handles one page of up to 256 candidates in(updated_at, hash)order onidx_memory_embedding_cache_updated_at, with one chunk read per page. The caller yields between pages and stops while closing.readMemoryPublishedVectorMeta.Evidence
Measured costs
On a fresh store, the CLI proof drove the built
openclaw memory indexandopenclaw memory searchthrough a loopback/v1/embeddingsstub with 64 and 4096 dimensions. It ran on 120 memory files with 965 distinct chunks, comparing base 476cce7 against this head. Chunk checksums are identical between the two builds after every step.With 4096 dimensions, the same sequence leaves a 32,952,320 B cache table on base and 4,096 B on head. The failed run's 6 rows stay until the full rebuild here, because each CLI command is a new process. A long-lived manager deletes them at its next clean sync.
Upgrading an existing store (head run on the base store above): ordinary syncs leave older rows in place. The first full rebuild takes the cache from 990 rows to 28, the 28 that no published chunk holds, and embeds nothing. At 4096 dimensions the table goes from 32,952,320 B to 946,176 B.
Time and lock hold (synthetic SQLite store, 4096 dimensions, both passes run back to back):
Each page holds the writer for well under the 5 s busy timeout discussed in #143640. The cost per page grows with the chunk table, because chunks have no hash index and each page reads the chunks for its 256 hashes. The database file does not shrink: freed pages are reused by later writes, as after any delete.
Upgrade from latest stable ([email protected]) and data-model compatibility
All runs use the shipped CLI (
openclaw memory index/status/search,openclaw doctor --fix,openclaw database port) in isolatedOPENCLAW_STATE_DIR/HOMEdirectories, with no Gateway process. Embeddings come from a loopback/v1/embeddingsstub (64 dims, deterministic except for one step). PostgreSQL is 17.11 with pgvector 0.8.7 in a local container bound to 127.0.0.1.Builds:
[email protected]from npm (dist-taglateston 2026-11-08).The existing store, written by 2026.11.2
user_versionSQLite: 2026.11.2 store upgraded to head, with base as control
Head and base both refuse the v27 store until it is migrated:
uses schema version 27; stop active agents and run openclaw doctor --fix to upgrade it to schema version 41 before using it.This PR adds no schema change and touches no.sqlorsrc/statefile, so the 27 to 41 migration is main's. Each arm ranopenclaw doctor --fix --non-interactive, then the steps below.80149dabdoctor --fix(v27 to v41)80149dabmemory status80149dab80149dab80149dabea07cfb0ef7fdec9ef7fdec9Final cache vector bytes: 7,168 on head and 500,224 on base.
memory_embedding_cachediffers in row count, and the schema is identical.memory_index_metais byte-identical before and after every step on both arms.doctor --fixrewritesopenclaw.jsonas JSON and addsmeta,wizardandskillsentries on both arms. Thememory,models,plugins,gatewayandagents.defaultsblocks are semantically identical to the 2026.11.2 file.Rolling back
OpenClaw state database <state>/state/openclaw.sqlite uses newer schema version 39; this build supports 22. ... To use an older build, restore your pre-update backup created with openclaw backup create.Once main has migrated a store, 2026.11.2 cannot open it, so its missing read-through (below) cannot re-embed anything on that store. Going back means restoring the pre-update backup, which still holds the full 2026.11.2 cache.3d677fde3d677fdePublished read-through (198b761) is not in 2026.11.2. The evidence:
git merge-base --is-ancestor 198b761c325 v2026.11.2exits 1.CHANGELOG.mdhas no improve(memory): reuse unchanged chunks after ordinary edits #185968 entry.PostgreSQL
2026.11.2 has no PostgreSQL memory store, so a stable PostgreSQL upgrade does not exist.
docs/reference/database-engines.mdsays: "Workboard is currently the only PostgreSQL-supported store. Shared state, agent/session storage, and other stores continue using SQLite."Two substitutes were run instead.
1. Existing PostgreSQL store written by base 476cce7, upgraded to head. The fixture steps match the SQLite store, including the session transcript and the non-deterministic copy. The store was then copied with
CREATE DATABASE ... TEMPLATEso head and base each start from identical data.e33dad37e33dad37b9636702addc9f90memory_index_metais unchanged.memory_embedding_cachediffers in row count between head and base.2. The 2026.11.2 SQLite store moved to PostgreSQL the supported way, then upgraded to head. The steps:
doctor --fix, thenopenclaw database port --to postgres --dry-run, thenopenclaw database port --to postgres(run with base). The port completed with 0 embedding inputs and rebuilt the memory index on PostgreSQL (996 chunks).Head and base then ran on copies of the ported store:
7ead0c537ead0c5350edc75f50edc75fAcross all SQLite and PostgreSQL arms, 57 search runs return the same hits as 2026.11.2. The session file id is normalized for the store written on PostgreSQL.
Not covered
Per-step measurements for every run
Columns: inputs sent to the embedding stub; search hits; agent DB user_version (schema_meta version on PostgreSQL); chunk rows (memory/session); chunk checksum over path, line, hash and the decoded float32 vector; cache rows split by whether the row equals every published copy of its hash, differs from one, or has no published chunk; cache vector bytes; sha256 of the
memory_index_meta_v1value; cache checksum. Step prefixes: P populate, U upgrade, R rollback, T port, X PostgreSQL. stable-rollback-on-head stops at the schema refusal quoted above (exit 1 on every command).stable-populate (version=2026.11.2 node=v24.22.2)
head-on-stable (version=2026.11.1 rev=9c16f4e808423fb5d71214988bdde6307b36c158)
base-on-stable (version=2026.11.1 rev=476cce7a8a343ac1524bf12276da839a690cff8a)
stable-rollback-on-head (version=2026.11.2 rev=npm state=head-on-stable)
base-rollback-on-head (version=2026.11.1 rev=476cce7a8a343ac1524bf12276da839a690cff8a state=head-on-stable)
base-rollback-on-base (version=2026.11.1 rev=476cce7a8a343ac1524bf12276da839a690cff8a state=base-on-stable)
pg-base-populate (version=2026.11.1 node=v24.22.2)
pg-head-on-base (version=2026.11.1 rev=9c16f4e808423fb5d71214988bdde6307b36c158 state=pg-base-populate)
pg-base-on-base (version=2026.11.1 rev=476cce7a8a343ac1524bf12276da839a690cff8a state=pg-base-populate)
pg-port-stable (version=2026.11.1 rev=476cce7a8a343ac1524bf12276da839a690cff8a pgdb=pg_port)
pg-head-on-port (version=2026.11.1 rev=9c16f4e808423fb5d71214988bdde6307b36c158 state=pg-port-stable)
pg-base-on-port (version=2026.11.1 rev=476cce7a8a343ac1524bf12276da839a690cff8a state=pg-port-stable)
database port --to postgres output (paths shortened)
{ "phase": "complete", "engine": "postgres", "stores": [ "<state>/agents/main/agent/openclaw-agent.sqlite", "<state>/openclaw.sqlite" ], "plannerStatistics": [ { "path": "<state>/agents/main/agent/openclaw-agent.sqlite", "result": { "status": "analyzed", "tables": 50 } }, { "path": "<state>/openclaw.sqlite", "result": { "status": "analyzed", "tables": 98 } } ], "backup": "<state>/recovery/database-port/d38d1051-35c6-431e-8660-f6610fef8f99", "remainingSqlite": [ "<state>/control/services.sqlite", "<state>/client/credentials.sqlite" ], "manifest": "<state>/recovery/database-port/d38d1051-35c6-431e-8660-f6610fef8f99/manifest.json", "serverCapacity": "unknown; former PostgreSQL namespaces retained", "restart": "Start the Gateway through its service owner.", "memoryRebuilds": [ { "agentId": "main", "path": "<state>/agents/main/agent/openclaw-agent.sqlite", "status": "rebuilt", "elapsedMs": 3789, "files": 123, "chunks": 996, "plannerStatistics": { "status": "analyzed", "tables": 51 } } ] }Tests
manager-embedding-cache-retire.test.tsandmanager-embedding-cache-retire.postgres.test.tscover the kernel on SQLite and PostgreSQL:updated_atrange. A bare OR keyset sorted the remaining rows on every page under the step-2 fence.manager.cache-duplicate-retirement.test.tscovers the manager:keepPublishedCacheDuplicates, and their assertions are unchanged. They cover reindex recovery, chunk publication retry, source and session races, legacy-format upgrade, declared-dimension repair, and PostgreSQL rebuild reuse.manager-cache-rebuild.test.tsre-seeds the rows an older build kept, and expects only superseded rows after a published rebuild.docs/concepts/memory-builtin.mddescribes the rule.Not covered by a test: the retained cache size the worker and the PostgreSQL binding track after a retirement. It is adjusted by the removed count, the same way
cache.clearadjusts it.Landing review and recovered current-head CI
The independently reviewed source remains
6a7323d419eef267e12afbc6b6273902fafb8823. CI run 42966846081, attempt 2 completed successfully after one documented failed-job recovery. The new PostgreSQL 1/3 execution ran both conformance and the previously interrupted PostgreSQL 16 Gateway cron smoke successfully, followed by a successful aggregate gate. Passing lanes reused from attempt 1 retain their original execution. The original whole-job deadline cancellation and failed aggregate are preserved as historical evidence; successful recovery supplies missing coverage, not proof that an infrastructure cause was repaired. The post-CI Security Review publisher published successful CI, security-sensitive and dependency statuses for this exact head. No CI was rerun for the later acceptance or for age.The earlier shipped-CLI, SQLite/PostgreSQL upgrade/port/rollback measurements below retain their stated executing revisions. Current-main composition is conflict-free, with the production patch unchanged from the completed source review.
Checks
On 6a7323d (merged with main 277e32c):
extensions/memory-core/src/memory: 113 files passed, 6 skipped; 1043 tests passed, 56 skipped, 0 failed.*.postgres.test.tsfiles: 59 of 59 passed.pnpm check:changed: every lane passes except the dead export scan. It lists the same 86 unused exports on main 277e32c, all inextensions/knowledgeandsrc/, none in a file this PR touches.pnpm build: passes.config/test-lines-allocations/195369-memory-cache-retire.txtallocates the 747 added test lines (kernel tests on SQLite and PostgreSQL, the manager scenarios above, and the existing-test holds).