Repository navigation
fix(memory): prevent cache overflow during forced reindex publication - #135373
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
Apply the existing cache cap before copying memory tables into the shared agent database; failed full rebuilds must not prune the primary cache. Preserve incremental cleanup and expose per-source chunk payload bytes. Related: #135347. Thanks Alexis for reporting the 2026.8.1 database-growth and session-loss incident. No schema, retention, or config changes.
21d4aea to
28bc8f9
Compare
|
@clawsweeper review Please complete the review for |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Codex review: needs maintainer review before merge. Reviewed September 1, 2026, 2:33 PM ET / 18:33 UTC. ClawSweeper reviewWhat this changesThe PR caps the embedding cache in the temporary full-reindex database before publication, preserves the published cache on failed rebuilds, and adds per-source memory payload-byte diagnostics. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readinessNo blocking correctness finding: the branch repairs the cache at the reindex owner boundary and retains ordinary cleanup on non-reindex exits. This maintainer-owned PR should remain open until its exact-head required checks finish successfully. Priority: P1 Review scores
Verification
How this fits togetherMemory Core indexes workspace and retained-session content into tables within the per-agent SQLite database. Forced reindexing builds replacement memory tables in a temporary database, then atomically publishes those tables while Gateway and CLI consumers continue using the published database. flowchart LR
A[Memory files and sessions] --> B[Memory index sync]
B --> C[Temporary reindex database]
C --> D[Cache limit]
D --> E[Atomic memory-table publication]
E --> F[Shared agent database]
F --> G[CLI and Gateway status]
Decision needed
Why: The source review and submitted real behavior trace support the patch, but the PR is maintainer-labeled and its captured required-check rollup remains in progress. Before merge
Agent review detailsSecurityNone. PR surfaceSource -4, Tests +208, Docs +7, Other 0. Total +211 across 12 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Land the owner-boundary repair after exact-head CI is green, while leaving retention, embedding-codec, corpus-size, and recovery-documentation work with their narrower related items. Do we have a high-confidence way to reproduce the issue? Yes. Current-main source shows the full-reindex failure path reaches live-cache pruning after the shadow operation, and the supplied exact-head Gateway/CLI trace exercises successful publication and controlled failure preservation. Is this the best way to solve the issue? Yes. Capping the cache in the shadow immediately before the existing atomic publication is the narrow owner-boundary repair; retaining the live cache after a failed full rebuild avoids compensating downstream or replacing the shared database. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 59bcbd156fa3. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (2 earlier review cycles) |
Address pre-land review: cover ordinary preflight and unresolved-target cleanup without mutating a forced rebuild cache after failure. Keep payload-byte scans on explicit diagnostics and preserve fresh status --index results. Extend real SQLite regressions for the early exits and serving-manager isolation.
|
The two actionable findings are addressed in The sync finalizer now encloses provider preflight and unresolved-target exits, while the existing fallback catch boundary stays unchanged. New real-database regressions failed on the reviewed head for all three ordinary/targeted cleanup cases and now pass. An explicitly forced, non-targeted rebuild still preserves the primary cache if preflight fails; its preservation case also passes. Payload-byte aggregation now uses the existing explicit source-diagnostic owner. Normal memory-search status stays count-only; a SQLite generated-column probe verifies it does not evaluate payload columns. Diagnostic managers recompute bytes after indexing and do not change the serving manager. The separate diagnostic refactor was absorbed here to resolve the pre-land finding. All 224 cases in the seven affected test files pass. The runtime rebuild and candidate autoreview passed; the full isolated Gateway/CLI atomic-publication and diagnostic-freshness traces are being refreshed. Exact-head CI is running. The PR will not land before that proof and CI complete. No schema, config, environment, retention, or protocol change was added. |
|
Merged via squash.
|
…openclaw#135373) * fix(memory): bound shadow cache before reindex publication Apply the existing cache cap before copying memory tables into the shared agent database; failed full rebuilds must not prune the primary cache. Preserve incremental cleanup and expose per-source chunk payload bytes. Related: openclaw#135347. Thanks Alexis for reporting the 2026.8.1 database-growth and session-loss incident. No schema, retention, or config changes. * chore(memory): remove unused status adapter type import * test(memory): assert source payload sizes in integration fixtures * fix(memory): preserve sync cleanup and isolate byte diagnostics Address pre-land review: cover ordinary preflight and unresolved-target cleanup without mutating a forced rebuild cache after failure. Keep payload-byte scans on explicit diagnostics and preserve fresh status --index results. Extend real SQLite regressions for the early exits and serving-manager isolation. * style(memory): remove redundant reindex boolean conversion
Expose database/WAL bytes, reusable allocation, and retained embedding-cache payloads in explicit memory diagnostics. Guide memory reset users through the existing offline Doctor compaction workflow before rebuilding. Keep one SQLite database per agent, with no schema, table, layout, retention, migration, or configuration changes. This completes the operator recovery flow after the cache-publication and safe-reset fixes in #135373 and #135653. Real Linux and macOS CLI/Gateway proof preserved 43 non-index tables and schema version 19, refused compaction while the Gateway was running, reclaimed 11,096,064 bytes after stopping it, and rebuilt searchable memory. Focused tests, builds, changed checks, and independent review passed. The maintainer explicitly waived npm advisory endpoint timeouts; other applicable CI checks passed or were skipped. Fixes #135347. Thanks @AlexisBallo2 for the report.
…law#137876) Expose database/WAL bytes, reusable allocation, and retained embedding-cache payloads in explicit memory diagnostics. Guide memory reset users through the existing offline Doctor compaction workflow before rebuilding. Keep one SQLite database per agent, with no schema, table, layout, retention, migration, or configuration changes. This completes the operator recovery flow after the cache-publication and safe-reset fixes in openclaw#135373 and openclaw#135653. Real Linux and macOS CLI/Gateway proof preserved 43 non-index tables and schema version 19, refused compaction while the Gateway was running, reclaimed 11,096,064 bytes after stopping it, and rebuilt searchable memory. Focused tests, builds, changed checks, and independent review passed. The maintainer explicitly waived npm advisory endpoint timeouts; other applicable CI checks passed or were skipped. Fixes openclaw#135347. Thanks @AlexisBallo2 for the report.
Related: #135347
What Problem This Solves
Fixes an issue where users rebuilding memory after a provider or corpus change could copy an oversized embedding cache into the shared agent database before the cache limit was enforced. A failed full rebuild could also prune the existing primary cache even though the replacement was never published. Thanks Alexis for reporting the 2026.8.1 database-growth and session-loss incident.
Why This Change Was Made
Enforce the existing cache policy in the shadow before publishing memory-owned tables. Keep live-cache cleanup around all ordinary sync exits, including preflight failures, unresolved targets, and partially committed incremental failures. An explicitly forced non-targeted rebuild preserves the primary even if preflight fails. The existing shadow database, publication transaction, revision fence, and shared session-store ownership remain unchanged. Remove the thin sync wrapper and the status database adapter; explicit diagnostic status now reads actual SQLite aggregates and reports per-source chunk payload bytes; ordinary serving-manager status stays count-only.
User Impact
Full reindex publication never copies cache rows beyond the existing 50,000-entry limit; failed shadow rebuilds no longer mutate the primary cache.
memory statusand JSON status report stored text-plus-JSON-embedding bytes by source. This is payload size, not physical file allocation: cache, FTS/vector tables, SQLite overhead, WAL, and free pages are excluded.This is a bounded repair, not a claim that the entire reported 35 GB is explained or that a large legitimate corpus is capped. It does not shrink previously allocated primary files or recover deleted canonical sessions.
Evidence
The two new owner-boundary regressions fail against unchanged production code: a primary-only SQLite trigger rejects transient cache overflow inside publication, and a failed shadow build removes existing primary cache rows. Both pass after the repair. A real incremental-write/progress-failure regression preserves live cleanup. The earlier targeted-sync test was corrected to use an eligible canonical SQLite session; its loose transcript file had exercised a no-op instead.
Focused tests: 224 cases passed across reindex recovery, targeted sync, startup catch-up, real memory-search tools, SQLite status aggregation, and the memory CLI. Three additional early-exit regressions failed on the reviewed head and now pass; a fourth verifies forced-preflight preservation. Diagnostic-scoping regressions failed before the refactor and now prove ordinary status does not evaluate payload columns and diagnostic bytes refresh after indexing without changing the serving manager. The status tests exercise real SQLite with Unicode byte sizes, filtering, and empty sources rather than asserting mocked query text.
Commands:
Live proof (isolated real Gateway and built CLI)
PASS on the rebuilt runtime stamped
b514778a7dd6057324b51d378a1c393a60627bab, after addressing pre-land review (2026-09-01 18:19–18:21 UTC). The run used a fresh state/home/workspace, free loopback ports, synthetic tokens, a deterministic local HTTP embedding endpoint, 1,200 generated memory files plus one bootstrap file, 12 retained reset artifacts, and three real Gateway-created sessions. Gateway memory search was disabled so the CLI was the sole index writer; this is not a foreground chat/recall or live external-provider claim.The successful rebuild indexed 1,201 memory chunks and 15 session chunks. With the embedding request held, the primary memory digest stayed unchanged while real Gateway
sessions.list,sessions.patch,chat.inject, and health calls succeeded. A synthetic transaction-level cache observer was installed only after normal CLI schema validation and those RPCs, immediately before embedding release, then removed before the next CLI startup. It would abort any transient primary cache overflow: observed publication peak and final count were both exactly 50,000. The concurrent session write survived publication.Successful publication grew the primary file from 75,284,480 to 84,828,160 bytes for the larger corpus. Sampled peak primary plus sidecars was 169,721,344 bytes (transactional WAL included); peak shadow plus sidecars was 90,816,096 bytes. These are observed bounds for this corpus, not a global disk-size cap. The failure phase explicitly seeded one excess legacy cache row; all 50,001 survived, with identical primary DB/WAL/SHM sizes and no changes to any non-memory owner table.
Per-source byte values matched independent SQL byte counts. On this 1,216-chunk corpus, 32 alternating warm runs measured median aggregate time 0.104 ms count-only versus 2.225 ms with diagnostic byte reporting (+2.121 ms; 21.3x). Ordinary memory-search status does not run that byte aggregate; the row-header work is restricted to explicit source diagnostics. SQLite
octet_lengthavoids reading overflow payloads, but adds row-header reads; large-corpus/cold-disk latency is not established. FTS and sqlite-vec logical rows were hashed, not private FTS posting-list bytes.Two earlier harness-only attempts were retained: normal schema validation rejected prematurely installed synthetic observer triggers; then a benchmark compared SQLite null-prototype rows with plain objects. The harness lifecycle and symmetric count projection were corrected without changing product code or weakening assertions.
Diagnostic freshness live proof
A second isolated real Gateway/CLI run passed on the same committed runtime (2026-09-01 18:21–18:22 UTC). Initial memory status reported 8 files, 8 chunks, and 14,369 payload bytes; the canonical session source reported 1 file, 1 chunk, and 1,431 bytes. After corpus edits, ordinary diagnostic status preserved those stored index facts.
memory status --index --jsonthen reported 11 files, 22 chunks, and 58,368 memory bytes, exactly matching independent SQL BLOB-byte totals. Canonical session-owner digests remained unchanged by indexing, and subsequent Gateway session reads/writes and health calls succeeded. Both proof runs ended with zero owned processes. Ordinary memory-search query scoping is covered by real-manager tests and the SQLite payload-evaluation regression, not claimed as Gateway memory-search RPC coverage.Checks
All 224 focused cases passed together after both ClawSweeper findings were addressed. The first full hosted memory lane caught two exact-shape status expectations; the final diagnostic-scoped implementation restores the ordinary consumer shapes, and both real-manager suites pass. The earlier head had complete green CI. Run33541484671 caught the now-corrected redundant Boolean conversion and an unrelated main-branch TS2790 error in the auth-login fixture introduced by #135355. Existing repair #135407 landed as
01129d7bbe06ba05f1e4850d6b6a38c4f2a2c22b; its ancestry and corrected source were verified on origin/main before the final CI push. Fresh exact-head CI is green forb514778a7dd6057324b51d378a1c393a60627bab.The full native CLI build succeeded after the existing declaration repair #135360 landed; the revised runtime was rebuilt with the native QA profile and canonical build-provenance step. Candidate and committed-branch autoreviews are clean at the configured P0 threshold. The original changed-surface checks completed through native retries after a transient canonical-dependency snapshot ENOENT. The diagnostic pass caught a test-only template-expression lint error, and the final pass caught a redundant Boolean conversion; both are corrected. The failed plugin-lint phase and all remaining native guards were rerun successfully. Final owner-focused rerun: 50/50 passed. No gate is skipped.
Source trace: memory CLI index →
MemoryIndexManager.sync→MemoryManagerSyncOps.runSync→ shadow rebuild →publishMemoryDatabaseTables→ existing SQLite transaction. Incremental, targeted, provider-fallback, and source-wide batch paths retain their owners. Status reads remain on the published handle. The same agent file holdssession_nodes,session_windows, andtranscript_events; it must not be replaced wholesale.History: raw-parent diff for
053ff9e399f(#131121), which is an ancestor of v2026.8.1, shows pruning moved out of the shadow and into the outer finalizer. The new tests prove both consequences. No schema, codec, retention limit, configuration, environment variable, dependency, or protocol change is included.Production: +255/-259 (net -4). Tests: +257/-49 (net +208). Docs: +8/-1. Assertion baseline: one existing allowance removed to match the deleted status adapter cast; no gate was weakened.
Remaining maintainer decisions and support guidance
Proposed docs/support correction: never delete
agents/<agentId>/agent/openclaw-agent.sqliteas a memory-index recovery action. It also owns canonical session history and transcripts. Preserve the complete database and sidecars before owner-approved recovery. Deleting it is not an index reset.Separate derived-index storage, embedding codecs, a total corpus-size/retention policy, and “from now onward” source enablement remain material store/product decisions. This PR does not implement them. #131085 and #114612 retain those broader questions; #135347 remains open for the incident's unresolved attribution and safe-recovery follow-up.
NO-FOLLOW-UP: the rent-paying diagnostic-query refactor was absorbed to resolve pre-land review; no further bounded cleanup is justified beyond the explicitly gated store/corpus decisions.
Pre-land ClawSweeper review: both actionable findings and all three Rank-up moves are addressed—ordinary early-exit cleanup, diagnostic-only byte aggregation, and refreshed focused/live proof. The first review execution failed without an actionable diagnostic; normal re-review completed. Native merge previously stopped without a completed review; no gate was bypassed. The reviewed-head findings, their failing reproductions, and the resolution are recorded in the review thread.
Latest pre-land review: the completed ClawSweeper review at 2026-09-01 18:19 UTC reports no remaining source-backed finding and sufficient real-runtime proof. Its remaining Rank-up move—wait for exact-head CI—is satisfied. The reviewer could not hydrate current main; the maintainer checkout independently compared the affected owner files against main
59bcbd156faand found no intervening changes.