Skip to content

fix(memory): avoid loading unrelated tombstones on session updates - #168098

Merged
steipete merged 6 commits into
mainfrom
fix/bounded-memory-session-queries
Oct 10, 2026
Merged

steipete merged 6 commits into
mainfrom
fix/bounded-memory-session-queries

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Related: #167838

What Problem This Solves

Fixes: updating one session reloads forgotten-session records for the entire session corpus, copying unrelated data into the Gateway and occupying its memory-search worker.

User Impact

Session-memory updates check only their selected sessions. Forgotten sessions remain excluded from startup catch-up, updates, dreaming, backfill, and recall across every query page.

The SQL-variable repair from #164336 (21f9fae8ad9d319c5d3b956a71ddff61315a6a15) is already on main but absent from the verified 2026.9.9 package. This PR addresses the separate recurring rows/bytes cost. The linked issue remains open until a release containing its repair is published.

Why This Change Was Made

Targeted sync resolves its session/archive selection before checking forgotten-session membership, retaining admitted active/archive counterparts for selected session IDs from the same discovery snapshot. The owning query processes 256 candidate IDs per page and returns matching integer positions, bounding result rows and bytes independently of stored record sizes. Full scans process every page; no exclusions are truncated. The obsolete full-row reader/type and redundant caller conversions are removed. Publication-time tombstone checks remain authoritative.

No configuration, public SDK, schema, retained-data, or migration changes. Full canonical session inventory discovery remains linear; explicit forget and scheduled promotion still return complete origin arrays on their cold paths. Paging adds round trips to full scans. This does not establish an atomic snapshot across pages or constant total corpus memory.

Evidence

Head 797a6e39b787d3834d1d5e71111c5d0b57fab75a passed all required types, lint/format, and 1,741 tests (four existing skips) on Node 24.19.0: the complete memory-core module plus eight dependent test files, 165 files passed/one skipped, eight shards, 1,387.91 s wrapper wall time. The complete origin suite also passed on Node 24.16.0 and 24.21.0 (12 tests each; 42.69 s and 41.61 s wrapper wall time). The three local changed suites passed all 51 tests in 360.95 s cold wrapper time. Regression cases took 271 ms (row/byte budget), 1,597 ms (target selection), and 8,727 ms (real-manager archive cleanup); final hosted CI passed run 38025936762, with 14 test jobs totaling 1,797 job-seconds (209 s parallel wall span; whole job costs, not marginal regression cost).

ClawSweeper’s exact-head review confirms no actionable findings and sufficient live proof. Both prior P2 findings are addressed: archive-only sync now preserves its active counterpart, and the budget observer covers both native all() and iterate() without weakening its row/byte assertions. The archive regression fails with production unchanged at the previous PR head; the query regression still fails with only its production owner reverted.

Fresh real Gateway proof compared this head with merged main 1f861ef5f85ed16d7fb0cdcf39e025f5a7adb170 on AWS Crabbox cbx_98e783cb102e.

The credential-free r7a.xlarge had 32 GB RAM and Node 24.19.0. AWS was the authorized fallback after Blacksmith source staging stalled. Both revisions used isolated state and ephemeral loopback ports with actual pnpm openclaw gateway run, WebSocket chat.inject, and HTTP memory_search in FTS-only mode.

Large fixture: 1,000 canonical sessions, 100,000 origin rows, 100,000 tombstones; 998 canonical sessions forgotten with synthetic 8 KiB reasons. Exactly two sessions remain eligible.

Large-store observation Main Candidate
Maximum rows per targeted query 998 0 unrelated rows
Maximum serialized result per targeted query 8,254,459 B 2 B
Maximum instrumented query heap increase 13,331,856 B 5,984 B
Maximum instrumented query time 30.218 ms 0.127 ms
Maximum startup query rows / bytes 998 / 8,254,459 B 256 / 2,963 B
Forgotten update query rows / bytes 998 / 8,254,459 B 1 / 11 B
Update-to-index publication time 5,850 ms 5,898 ms

Both revisions produced exactly one updated chunk, returned the new text in search, excluded forgotten text, passed every health probe, and shut down gracefully. All observed tombstone SQL ran in workers. The earlier small-store control (three canonical sessions/100 rows) also preserved results on both revisions. Timings and query heap deltas include instrumentation (including serialization on the iterator path); total Gateway heap/RSS varied with GC, and end-to-end publication time did not materially improve. The demonstrated bound is on query results and allocations.

Archive-only live proof: actual Gateway sessions.delete published an archive notification; a warmed fixture writer restored the same canonical SID in 1.777 s (main: 1.805 s), before the existing five-second debounce. After archive publication and graceful manager drain, the original active source, hash, and chunks were unchanged before any search could rebuild them. A restarted Gateway returned the live transcript in search. The same small-store flow on previous head 56d40dba1e75 failed with Archive-only sync deleted or changed a still-active SQLite counterpart, after restoration in 1.685 s and a graceful shutdown. This proves the live observation catches the reviewed cleanup defect.

The first two follow-up live attempts were fixture failures, not product verdicts: readiness initially preceded agent inspection (/startupz fixes the probe), then the restoration acknowledgement incorrectly included a cold corpus-verification read. V3 warms the reader and records mutation/verification separately; no product timing or assertions were weakened.

  • Negative controls: reverting all eight production files made targeted sync query unrelated-thread; reverting only the query owner made the budget regression return 513 rows against a 256-row limit. The tests stayed intact and candidate source was restored afterward.
  • All required type lanes passed: core, six relevant core test-type graphs, extensions production and test. Changed-file lint: zero warnings/errors; formatting and diff checks passed. SDK export/surface, database-worker, assertion/mock, and line-cap guards passed before the final integration.
  • Independent Codex autoreview of final tree 06fdd8ef42c5fbcfc3d8251c4469edd6a0ce9493: scoped-clean, no actionable P0–P2 findings. Deslop removed the superseded reader and redundant conversions.
Commands, provenance, and investigation details

Final full-module/version gates: run_4e870ccf0123510ceccb4fd9b47df4ba, 2,412.358 s total setup/check time, on cbx_98e783cb102e. Final live comparison and archive negative control: run_a51e75d07eb9a11f590dc296cccc0a6c on that same lease, 535.972 s total. Metrics collection: run_b96519b7077ef8412371b2f9e6faaabb. Source was delivered as a 2,128-byte incremental Git bundle with a public prerequisite; exact HEAD/tree were verified before canonical secretless bootstrap and isolated dependency install. No operator state, credentials, or ports were used.

Prior-head evidence retained: the wider memory-core/memory-host-sdk/dependent run passed 2,207 tests on 56d40dba1e75/Node 24.21.0 (run_c658d8f7bc66feb09f78391dc5e93183, cbx_df9d573f0a8b). Earlier small/large comparison: run_7c74f9083f53c882b7a5135d81cc694a on cbx_fcf1be08794f, 364.205 s. Both earlier leases were stopped and list-verified.

TMPDIR=/private/tmp/oc-r7-memq node scripts/crabbox-wrapper.mjs run \
  --provider aws --id cbx_98e783cb102e --no-sync --no-hydrate \
  --idle-timeout 90m --ttl 240m --timing-json \
  --script /private/tmp/oc-r7-memq/deliver-feedback-unit.sh

TMPDIR=/private/tmp/oc-r7-memq node scripts/crabbox-wrapper.mjs run \
  --provider aws --id cbx_98e783cb102e --no-sync --no-hydrate \
  --idle-timeout 90m --ttl 240m --timing-json \
  --script /private/tmp/oc-r7-memq/deliver-feedback-live-v3.sh

# Inside the verified remote checkout:
pnpm tsgo:core
pnpm tsgo:core:test --ci-graphs-json '["core-test-plugin-sdk","core-test-agents-sessions","core-test-commands","core-test-infra","core-test-other","core-test-packages"]'
pnpm tsgo:extensions
pnpm tsgo:extensions:test
mapfile -t memq_tests < <(rg --files extensions/memory-core -g '*.test.ts' | sort)
node scripts/run-vitest.mjs "${memq_tests[@]}" \
  packages/memory-host-sdk/src/host/read-file-manager-compat.test.ts \
  extensions/memory-wiki/src/query.test.ts src/entry.memory-json.test.ts \
  src/config/sessions/session-accessor.sqlite-reclamation-memory.test.ts \
  src/commands/doctor-memory-startup.test.ts src/commands/doctor-agent-memory-schema.test.ts \
  src/infra/kysely-sync.test.ts src/plugins/contracts/extension-package-project-boundaries.test.ts

node --import ./scripts/tsx.mjs /tmp/memq-live/run.mjs \
  --out /private/tmp/oc-r7-memq/feedback-large-candidate-v3 --label feedback-candidate --expect bounded
# From the separate pinned-main checkout:
node --import ./scripts/tsx.mjs /tmp/memq-live/run.mjs \
  --out /private/tmp/oc-r7-memq/feedback-large-main-v3 --label feedback-main --expect baseline
# From previous PR head 56d40dba1e75, expected archive-preservation failure:
node --import ./scripts/tsx.mjs /tmp/memq-live/run.mjs \
  --out /private/tmp/oc-r7-memq/archive-negative-gateway --label archive-negative \
  --expect bounded --sessions 3 --rows 100 --reason-bytes 32
# Earlier normal-store controls used the same --sessions/--rows/--reason-bytes values.

The final local focused command was node scripts/run-vitest.mjs extensions/memory-core/src/memory/manager-reads.test.ts extensions/memory-core/src/memory-entry-origins.test.ts extensions/memory-core/src/memory/manager-sync-ops.startup-catchup.test.ts --maxWorkers=1: 51 tests passed, 360.95 s cold wrapper wall including worker preparation. The archive test against unchanged production failed for the intended missing live source (291.03 s cold wrapper).

Constant-width owner probes showed complete tombstone results growing from 88,001 B / 5.43 ms at 1k rows, to 880,001 B / 62.56 ms at 10k, and 8,800,001 B / 465.05 ms at 100k. The 100k origin reader returned 15.9 MB in 589 ms. Candidate full tombstone membership took 1,098 ms / 1.9 MB serialized ID-array output, documenting the full-scan paging tradeoff. Origin full-row readers serve explicit forget/scheduled promotion, not ordinary per-search membership.

The first full-module run exposed a test observer error: it consulted cached schema-admission facts after a worker created the optional tombstone table. The helper now checks the actual schema before independently reading persisted rows; assertions and recovery behavior are unchanged. The full suites now pass. One test-only unbound-method exception is source-verified: Reflect.apply explicitly supplies the intercepted SQLite statement receiver. Production keeps the expression-builder receiver without suppression. The portable observer retains the native iterator and its cleanup while counting yielded rows and serialized bytes; full origin-suite passes on three supported Node patch levels and the Node 24.16 negative control verify both execution paths.

ClawSweeper's existing issue finding concerns release inclusion. Official tarball integrity and embedded release commit bcfc88812a35243893585dbeca87ca41b48272ca were independently verified, and the coordinator-requested issue comment records the remaining release work. This PR does not publish that release or close its issue.

Exact change size against the merged main baseline

Production: +118/-102 (net +16); tests/support: +198/-67; docs: +4/-0. The production LOC exception is needed for page coordination, integer result projection, and preserving active/archive counterpart facts for cleanup. The obsolete full-row contract and redundant conversions are deleted; no compressed or unrelated edits offset the increase.

4	0	docs/concepts/memory-provenance.md
12	12	extensions/memory-core/src/dreaming-phases.ts
28	22	extensions/memory-core/src/memory-entry-origin-reads.ts
3	8	extensions/memory-core/src/memory-entry-origins-task.ts
87	8	extensions/memory-core/src/memory-entry-origins.test.ts
24	12	extensions/memory-core/src/memory-entry-origins.ts
5	8	extensions/memory-core/src/memory-forget-recovery.test.ts
6	9	extensions/memory-core/src/memory-forget.phase-signals.test.ts
8	8	extensions/memory-core/src/memory-forget.sources.test.ts
7	10	extensions/memory-core/src/memory-forget.test.ts
6	9	extensions/memory-core/src/memory-forget.worker-settlement.test.ts
29	5	extensions/memory-core/src/memory/manager-reads.test.ts
43	36	extensions/memory-core/src/memory/manager-session-sync-ops.ts
4	2	extensions/memory-core/src/memory/manager-sync-ops.startup-catchup.test-support.ts
33	8	extensions/memory-core/src/memory/manager-sync-ops.startup-catchup.test.ts
5	6	extensions/memory-core/src/session-backfill.ts
2	6	extensions/memory-core/src/short-term-promotion-record.ts
13	0	extensions/memory-core/src/test-helpers.ts
1	0	src/plugin-sdk/memory-core-host-engine-storage.ts

Filter targeted session sync before checking forgotten-session membership. Query bounded pages of candidate identities and return only matching positions, preserving all exclusions without transferring stored tombstone records. Remove the obsolete complete-row reader and migrate startup, dreaming, backfill, and recall callers.

Related: #167838. The separate SQL-variable repair already exists on main; release inclusion remains open.
@clawsweeper

clawsweeper Bot commented Oct 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: memory-core Extension: memory-core size: M labels Oct 10, 2026
@steipete
steipete marked this pull request as ready for review October 10, 2026 02:29
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR checks forgotten-session membership only for selected sessions using bounded pages of integer results.

Example: Update one eligible session among 1,000 sessions with 998 forgotten sessions.

  • Before: The supplied Gateway trace returned 998 unrelated tombstone records totaling 8,254,459 bytes.
  • After: The targeted query returned no unrelated records while the updated transcript remained searchable.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused owner-level repair with supplied shipped-entry-point proof, meaningful negative controls, successful exact-head CI, and no remaining findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The exact-head Gateway trace exercises actual transcript updates, memory search, large-store tombstone queries, and archive cleanup in isolated state; results preserve search and exclusions, and the previous-head negative control detects the cleanup defect.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Ordinary session updates transfer unrelated forgotten-session records and consume memory-search worker capacity on large stores.
Reason: The measured query-result reduction addresses the stated problem without new product surface; the PR explicitly preserves the full-scan paging tradeoff.

Merge readiness

✅ Ready for maintainer review

This PR addresses a distinct memory-query cost still present on current main. The earlier findings are resolved, and no actionable defects remain.

Priority: P2
Reviewed head: 797a6e39b787d3834d1d5e71111c5d0b57fab75a

Before merge

None.

Findings

None.

Agent review details

How this fits together

Memory Core consumes transcript updates and corpus selections, checks durable forget tombstones in its retrieval worker, and passes eligible sources to indexing, dreaming, backfill, and recall.

flowchart TD
  A[Transcript updates and corpus scans] --> B[Select sessions and retain counterparts]
  B --> C[Page candidate session IDs]
  C --> D[Retrieval worker tombstone query]
  D --> E[Matching integer positions]
  E --> F[Eligible memory sources]
  F --> G[Publication with live tombstone checks]
Loading

Technical review

Best possible solution:

Land the bounded membership queries with the preserved counterpart snapshot, while keeping release inclusion tracked separately.

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

Current-main source exposes the whole-corpus, full-record query path, and the supplied pinned Gateway comparison demonstrates its allocation cost; this review ran no target code.

Is this the best way to solve the issue?

The patch repairs selection and projection at their existing owners, migrates all consumers, and removes the obsolete full-row reader while preserving publication-time exclusions.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 77bbc865a05b.

Provenance checked

  • Forget exclusion semantics keeps the original intent (9d9dc31: Record session lineage and durable tombstones so forgotten sessions cannot be re-admitted by ingestion, backfill, or indexing.)
  • Worker-owned lineage reads keeps the original intent (fa2cbc0: Move lineage planning reads off the caller thread while retaining noncreating optional-table behavior and existing write authority.)
  • Large-selection query encoding keeps the original intent (21f9fae: Avoid SQLite bind-variable limits using the shared encoded string-set primitive.)
  • Targeted corpus snapshot keeps the original intent (04f9a20: Carry one corpus snapshot from target resolution into indexing so discovery changes cannot redirect the selected identity.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit fa2cbc0 adds extensions/memory-core/src/memory-entry-origin-reads.ts:61 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: fa2cbc023e0b; files: extensions/memory-core/src/memory-entry-origin-reads.ts)

PR surface

Source +16, Tests +131, Docs +4. Total +151 across 19 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 8 118 102 +16
Tests 10 198 67 +131
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 320 169 +151

Review metrics

Metric Value Why it matters
Production versus test growth Production +118/-102; tests/support +198/-67. Production growth implements page coordination and counterpart preservation; test growth protects query result budgets, complete exclusions, and archive cleanup.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Reduces recurring worker and allocation pressure on large memory stores without changing user settings or established memory behavior.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-10T02:36:46.661Z sha 56d40db :: needs changes before merge. :: [P2] Preserve active counterparts in the archive cleanup snapshot | [P2] Observe both supported SQLite query execution paths
  • reviewed 2026-10-10T02:45:16.253Z sha 56d40db :: needs changes before merge. :: [P2] Preserve active counterparts in the archive cleanup snapshot | [P2] Observe both supported SQLite query execution paths
  • reviewed 2026-10-10T03:01:35.300Z sha 56d40db :: needs changes before merge. :: [P2] Preserve active counterparts in the archive cleanup snapshot | [P2] Observe both supported SQLite query execution paths
  • reviewed 2026-10-10T05:04:49.205Z sha 797a6e3 :: needs maintainer review before merge. :: none

Reviewed October 10, 2026, 1:15 AM ET / 05:15 UTC (Revision 5).

@steipete
steipete marked this pull request as draft October 10, 2026 02:39
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Oct 10, 2026
@steipete
steipete marked this pull request as ready for review October 10, 2026 04:58
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@steipete
steipete merged commit 2aec177 into main Oct 10, 2026
218 of 219 checks passed
@steipete
steipete deleted the fix/bounded-memory-session-queries branch October 10, 2026 05:45
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…penclaw#168098)

* fix(memory): bound forgotten-session queries during updates

Filter targeted session sync before checking forgotten-session membership. Query bounded pages of candidate identities and return only matching positions, preserving all exclusions without transferring stored tombstone records. Remove the obsolete complete-row reader and migrate startup, dreaming, backfill, and recall callers.

Related: openclaw#167838. The separate SQL-variable repair already exists on main; release inclusion remains open.

* refactor(memory): simplify ingestion candidate collection

* test(memory): inspect persisted tombstones after recovery

* fix(memory): preserve live counterparts during archive sync
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: 🦞 diamond lobster Very strong PR readiness with only minor 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.

1 participant