Repository navigation
fix(memory): avoid full vector scans for small source updates - #140102
maximilliangrand wants to merge 1 commit into
Conversation
|
🦞👀 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. Reviewed September 6, 2026, 9:06 AM ET / 13:06 UTC. ClawSweeper reviewWhat this changesMemory Core’s local search index switches source cleanup to individual vector-key deletes so small updates avoid scanning unrelated vectors, with regression coverage for isolation and recovery. Merge readiness⛔ Blocked before merge - 1 item remains This remains a useful, focused fix: current main retains the full-scan cleanup query, and the related work does not supersede it. The added production CLI evidence resolves the previous proof request. No blocking correctness finding remains. Priority: P2 Review scores
Verification
How this fits togetherMemory Core indexes memory files and session transcripts for search. When a source changes or disappears, its synchronization pipeline removes old vector and text records before publishing the updated index. flowchart TD
A[Changed or removed source] --> B[Memory synchronization]
B --> C[Source write transaction]
C --> D[Read matching chunk identifiers]
D --> E[Delete matching vectors]
E --> F[Update canonical and text records]
E --> G[Record rebuild debt on failure]
F --> H[Updated memory search]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +6, Tests +197. Total +203 across 2 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep source-scoped point deletion with existing transaction and recovery semantics, accepting the measured dense-workload tradeoff while broader Gateway isolation remains separate work. Do we have a high-confidence way to reproduce the issue? Yes: current main’s IN-subquery cleanup and sqlite-vec 0.1.9’s planner establish the full-scan mechanism; the contributor also supplies a failing-before query-plan regression. This review did not execute it or reproduce the broader Gateway incident. Is this the best way to solve the issue? Yes: the patch changes the existing cleanup owner, reuses the indexed source lookup, and preserves deletion scope and recovery behavior without adding schema or configuration. Its dense-deletion cost is explicitly measured. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against b4c940701a28. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Thanks @maximilliangrand for the sparse vector-cleanup investigation, the query-plan regression, and the dense-workload measurements. |
Related: #134575
What Problem This Solves
Resolves a problem where updating or removing a small memory source scans the entire vector index. As unrelated memory accumulates, each incremental cleanup spends more time synchronously occupying the Gateway thread. The full-scan query remains in current main.
Why This Change Was Made
sqlite-vec 0.1.9 gives the existing
DELETE ... WHERE id IN (SELECT ...)a full-scan plan. Select source IDs through the existing(path, source)index and stream them through one prepared scalar-key delete instead. This preserves the deletion set across models, surrounding transactions, missing-vector handling, and rebuild-debt policy without introducing schema, worker, or configuration changes.This complements #103201 (session chunk deltas) and #136482 (publication isolation); their inspected changes retain the source-wide
INdelete. It does not replace either effort.User Impact
Small memory updates and removals no longer scan unrelated vector rows. Newly indexed sources also avoid a full scan when they have no old vectors to remove. This is a sparse-cleanup scaling fix, not a claim that all memory operations or the whole Gateway become faster.
Tradeoff: individual point deletes are slower for dense deletion. In the synthetic 100,000-vector case below, deleting half the index takes about 655 ms rather than 450 ms. Keeping one simple, source-scoped path avoids adding global counting or adaptive deletion policy; the table includes both sparse and dense workloads.
Evidence
SCAN memory_index_chunks_vec VIRTUAL TABLE INDEX 0:1. It passes with the repair. Scalar deletion uses sqlite-vec's point plan (... INDEX 1:2!___); regression assertions use query plans rather than wall-clock thresholds.node scripts/check-changed.mjspassed, including production/test typechecks, lint, formatting, plugin boundaries, dead-export scans, storage guards, and import-cycle checks. Independent autoreview found no actionable P0–P2 findings; the final regression rerun passed after test-only typing/ordering cleanup.8fbaac420e2d91a1e1472887bdca63bd96ca7ba2: 54 successful checks, none failed or pending when checked on September 6.After-fix OpenClaw CLI behavior proof
Ran the normal
pnpm openclaw memory index,memory search, andmemory status --deep --jsonflow on the submitted head, using the built production Memory Core plugin, a task-owned workspace/database, and real local Ollama 0.32.9 embeddings. No embedding-provider mocks. Model:all-minilm, digest1b226e2802dbb772b5fc32a58f103ca1804ef7501331012de126ab22f67475ef, native 384-dimensional vectors. All indexed documents are synthetic. Updates/removals used incremental indexing, without--force.Terminal excerpts below omit startup/config warnings and unrelated JSON fields; file edits and database verification are annotated separately:
Before/update/removal snapshots contained 2/2/1 canonical chunks and 2/2/1 vectors. The replacement vector ID/bytes changed; the removed source had no remaining vector. The ordered ID+embedding SHA-256 for
memory/unrelated.mdstayedf3590cdf171bd187d2dad81f09a42df19755206b2d1ea582646ccc7b22e9d10cthrough all three states. Its search content and vector score were preserved; hybrid final scores vary slightly with corpus statistics. The production cleanup observer recorded one old row for both update and removal. Rebuild state remainedclean.Dense source removal through the real CLI
Also indexed two generated maintenance journals with default chunking, then removed one through
memory index. These are chosen synthetic source sizes, not a claim about the distribution of real user documents. Each size ran three removal rounds; the closed, checkpointed fixture database was restored between rounds. All embeddings were generated by the real provider through OpenClaw indexing.All six commands exited successfully and committed. The resulting databases contained 119 and 938 chunks/vectors respectively, no target rows, unchanged retained vector IDs/bytes, and clean rebuild state. Final
memory status --deep --jsonreporteddirty: false,index.state: complete,semanticAvailable: true,dims: 384, andembeddingProbe.ok: true.Timing used an external observational Node preloader, leaving the submitted source and SQL unchanged. It wraps the exact source-ID statement's native
iterate(); the synchronous production point deletes execute between yielded rows. One record is buffered per cleanup and written at process exit. Vector timing therefore includes native iteration and the actual production delete loop, excludes statement preparation, and includes observer overhead. Transaction timing starts afterBEGIN IMMEDIATEsucceeds and ends afterCOMMIT, excluding lock acquisition and including FTS/canonical work and commit. CLI startup/model-loading time is not reported as cleanup time.These measurements quantify the after-fix cost at these source sizes; they do not establish a before/after end-to-end speedup or Gateway responsiveness guarantee. The disclosed 50,000-row dense microbenchmark regression below remains a real tradeoff. Large replacement writes also remain synchronous: growing the retained journal from ~128 KiB to ~1 MiB held its write transaction for 344 ms, of which old-vector cleanup was 1.746 ms. This patch targets dependence on unrelated vector count, not all synchronous indexing work.
Production-loop timing observer (loaded through NODE_OPTIONS=--import)
The observer delegates to the native iterator; it neither substitutes SQL nor synthesizes embeddings. This excerpt shows the cleanup timing mechanism; transaction timing separately observes native
execboundaries as described above.SQL strategy comparison
Synthetic SQLite microbenchmark, Apple M4 / macOS ARM64, Node 26.7.0, SQLite 3.53.4, sqlite-vec 0.1.9. In-memory tables, 128-dimensional vectors, same database restored by rollback between runs; one warm-up and six measured rounds with alternating baseline/candidate order. Values are conventional medians. Timing includes statement preparation and deletion, excludes transaction begin/rollback and result verification.
The microbenchmark executes the two SQL strategies against generated rows in real vec0 tables; the CLI proof above separately exercises the production memory manager with real local embeddings. Neither is an end-to-end Gateway latency benchmark or a reproduction of the full 12–24-second incident in #134575.
Regression commands and standalone benchmark reproduction
From a checkout with pinned dependencies installed: