Skip to content

fix(memory): session sync deletes and re-embeds every indexed chunk as transcripts grow - #103201

Merged
steipete merged 27 commits into
openclaw:mainfrom
wr-web:fix/incremental-session-chunk-diff
Oct 10, 2026
Merged

steipete merged 27 commits into
openclaw:mainfrom
wr-web:fix/incremental-session-chunk-diff

Conversation

@wr-web

@wr-web wr-web commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Related: #40919

What Problem This Solves

Growing session transcripts rewrite every indexed chunk on each sync. With the embedding cache disabled, they also send unchanged text to the embedding provider again, spending local CPU/GPU time on repeated work.

User Impact

Session appends retain unchanged chunk rows and embeddings. Only new or changed chunks are embedded and published, including when caching is disabled. Truncation and provenance changes still take effect; full rebuilds retain complete replacement.

No user configuration, database schema, row encoding, chunk identity, or migration changes. Existing indexes remain usable. Full transcript preparation still occurs; this fixes embedding and publication amplification.

Why This Change Was Made

Delta publication stays inside the existing SQLite worker. Retained rows are staged first and validated transactionally before indexed writes. Missing rows cause one full-source retry after releasing the workspace lock. Both indexing paths share preparation and recovery. The existing lazy chunk writer owns provenance updates, and vector cleanup/rebuild debt retain their existing owner. Empty sources preserve the optimization from #146150.

Main was merged without rebasing or replacing @wr-web's commits. The branch consumes main's timeout, batch-retry, embedding-format, and admitted-table helpers. The latest conflict resolution moves the kernel to the shared SQLite tableExists helper; its delta logic is unchanged. The canonical test fixture now honors cacheEnabled: false, which previously fell back to enabled caching and masked provider work.

Production: +376/-123 (net +253, down from the original +326). Tests/support: +310/-2. Docs: +3/-0. Tooling: one stale max-lines exemption removed. Neutral production would require unrelated deletion or dropping staged transfer, drift recovery, or publication safeguards.

Evidence

Final head: 2bb17071d149f380cdb10ceee516994c9d74d928. Integrated main: 51e7ca28cb945c522ad7e1ca994790fba5eeed12. Runtime proof uses 3b60992c552e23017e87b99b2b967cabc6cdb4c9; the sole later change removes the stale baseline entry.

Real CLI → Memory Core → publication worker → Ollama nomic-embed-text, behind a loopback logging proxy on macOS/Node 26.11.1. Synthetic 100-turn session, then two appended turns. The candidate used a copy of main's existing index; cache disabled for this comparison:

Measurement after two appended turns Main (c75ff3cbf56e) Candidate runtime
Indexed chunks 29 29
Embedding requests 6 1
Embedded inputs 29 1
Unchanged rows kept untouched 0/28 28/28
Index revision 30 → 89 30 → 33

All embedding requests succeeded. The default-cache control on main sent one input, showing that caching hides provider work but not row churn. Current main still clears/replaces the source rows. The candidate index completed in 37.42s; early/latest searches took 20.90s/25.36s and returned the correct retained and updated ranges without stale warnings. The latest top-result range 198–205 contains the appended turns.

The corrected replay preserves the baseline config byte for byte, including the proxy address. An earlier fixture restart changed that address, correctly invalidated the endpoint-scoped provider key, and forced a full rebuild. That run is excluded from delta proof; no product code was changed for the fixture error.

# OPENCLAW_STATE_DIR and OPENCLAW_CONFIG_PATH point to isolated synthetic state.
pnpm openclaw --profile memory-sync memory index --verbose
pnpm openclaw --profile memory-sync memory search topic-001 --max-results 5 --min-score 0 --json
pnpm openclaw --profile memory-sync memory search topic-102 --max-results 5 --min-score 0 --json

Validation:

  • Corrected session-delta regression fails on main at retained-row equality: 157.09s wall.
  • Final integration: eight focused files, 103/103 tests via node scripts/run-vitest.mjs <files> --maxWorkers=1, 777.40s command wall (720.70s Vitest). Test callback totals: session-delta 12.054s, publication-transfer 13.572s, source-kernel 0.679s, vector-state 0.046s, targeted-sync 0.029s, index-retention 17.632s, existing reindex-recovery 197.377s and startup-catchup 95.225s. The owning-boundary regression exercises real manager preparation, native session storage, worker publication, and provider-input exclusion. The earlier nine-file 170/170 run remains evidence for unchanged probe, timeout-policy, and shadow-owner behavior.
  • Full pnpm build: pass, 2338.01s. Production/test types: pass, 57.38s/54.16s. Scoped oxlint: pass, 934.44s including declaration preparation under the supported budget. Formatting and git diff --check pass.
  • Assertion-safety, max-lines, line-cap, database-worker, test-timeout-race, test-mock-exports, config-doc, and plugin-inventory checks pass. Max-lines initially found the same stale doctor-test exemption present in pinned main; that test is 877 lines in both main and candidate. Removing only the obsolete exemption made the check pass in 80.56s. No baseline growth or test-timeout increase.
  • Exact-head CI run 38042571477 passed, including openclaw/ci-gate. Its three changed-extension test bundles took 242–255s each, 742 aggregate job-seconds including setup and sibling tests; this is not isolated regression cost. ClawSweeper reviewed this exact head: 5/6, proof sufficient, no findings or Before merge items.
  • Fresh Codex autoreview of the final head: scoped-clean through P2, with no accepted/actionable finding. Hosted review and CI are checked against the pushed head separately.

Builds and tests were serialized after an earlier attempt collided with generated package artifacts. Proof files and logs distinguish that tooling failure, the changed-route fixture, and the passing runs.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 10, 2026
@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR retains unchanged session chunks and embeds and publishes only new or changed chunks.

Example: Append two turns to the supplied 100-turn session with embedding caching disabled.

  • Before: Main embeds 29 inputs and rewrites all 29 indexed chunks.
  • After: The candidate embeds one input, retains 28 unchanged rows, and keeps early and appended content searchable.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, useful repair with shipped CLI evidence, existing-index reuse, meaningful regression coverage, and successful exact-head CI.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied real CLI run exercises Memory Core preparation, worker publication, and Ollama embeddings on isolated synthetic macOS state, demonstrating retained rows, reduced embedding inputs, and correct searches; the measured production revision is unchanged at the reviewed head.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Growing conversations repeatedly rewrite unchanged indexed content and, without caching, repeat embedding work.
Reason: The repair addresses demonstrated amplification while preserving search representation and existing settings; whole-transcript preparation and separate WAL checkpoint problems remain outside its stated scope.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: current main still replaces unchanged session chunks, and this focused repair has sufficient runtime proof, passing exact-head CI, and no actionable findings.

Priority: P1
Reviewed head: 2bb17071d149f380cdb10ceee516994c9d74d928

Before merge

None.

Findings

None.

Agent review details

How this fits together

Memory Core prepares session transcripts, requests embeddings, and publishes searchable chunks through its existing SQLite worker.

flowchart LR
  A[Session transcript] --> B[Memory Core preparation]
  B --> C[Worker index read]
  C --> D[Session delta planner]
  D --> E[Embedding provider]
  D --> F[Publication worker]
  E --> F
  F --> G[SQLite chunks and search indexes]
Loading

Technical review

Best possible solution:

Land the session-only delta through the existing publication worker while keeping full rebuilds as complete replacements.

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

Yes: append to an indexed session with caching disabled and sync again; current main routes the changed transcript to complete source replacement, matching the supplied CLI comparison and affected-user report.

Is this the best way to solve the issue?

This is an appropriate owner-level repair: content-addressed row retention removes embedding and publication amplification without adding offsets, rotation policy, configuration, or another writer.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Complete source replacement changes intended behavior with a stated reason (f7a2f1c: The merged consolidation moved complete source mutations into the database owner while preserving prior behavior; it did not establish that behavior's original introduction.)
  • Worker publication and bounded transfer keeps the original intent (a1f9ced: Move native publication off the Gateway thread while retaining transaction admission, custody, cancellation, tombstones, and settlement.)
  • Lazy chunk-writer construction keeps the original intent (5dfe8ff: Avoid constructing unused chunk-write queries for empty sources; the previously reported regression is fixed at this head.)
  • Vector cleanup keeps the original intent (1349c4c: Bound whole-source vector point deletes and retain atomic rollback before recording rebuild debt; the shared cleanup keeps those whole-source semantics.)
  • Typed chunk and provenance writer changes intended behavior with a stated reason (6a1160a: Reuse publication-scoped typed statements while preserving stored values and write ordering; retained rows now reuse this owner for changed provenance only.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main still replaces the complete source: The current-main kernel calls clear before writing every replacement; clear deletes all chunks for the source and path. (extensions/memory-core/src/memory/manager-source-index-kernel.ts:71, dd036a4b1d85)
  • Delta publication preserves the existing owner: Retained rows precede new rows, are revalidated inside the transaction, and remain untouched except for changed provenance; omitted rows are removed with derived-data cleanup. (extensions/memory-core/src/memory/manager-source-index-kernel.ts:124, 2bb17071d149)
  • Drift recovery and deletion fences: A missing retained row returns without indexed writes and triggers one full-source retry after releasing the workspace lock; canonical session tombstones and transaction/commit admission remain enforced. (extensions/memory-core/src/memory/manager-embedding-ops.ts:608, 2bb17071d149)
  • Supplied shipped-entry-point proof: The PR body records real CLI indexing and search through Memory Core's worker and Ollama on isolated synthetic macOS state: one embedded input, 28 retained rows, and correct early/latest search ranges after an append to a copied existing index. (3b60992c552e)
  • Runtime proof remains applicable: The only change after the runtime-proof revision removes an obsolete max-lines exemption; production and test bytes are unchanged. (config/max-lines-baseline.txt:343, 2bb17071d149)
  • Exact-head CI: Authenticated, paginated check-run reads verify successful openclaw/ci-gate, changed-extension tests, types, architecture guards, and docs checks on the reviewed head, with no failing checks returned. (2bb17071d149)

Likely related people:

  • Peter Steinberger: Raw commit f7a2f1c adds extensions/memory-core/src/memory/manager-source-index-kernel.ts:43 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f7a2f1cfe82f; files: extensions/memory-core/src/memory/manager-source-index-kernel.ts)

PR surface

Source +253, Tests +308, Docs +3, Other -1. Total +563 across 16 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 9 376 123 +253
Tests 5 310 2 +308
Docs 1 3 0 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 16 689 126 +563

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +376/-123; tests/support +310/-2 Growth supplies delta planning, bounded retained-row transfer, transactional validation, and recovery within the existing owner; tests cover distinct manager, transfer, and native-storage contracts.

Root-cause cluster

Relationship: same_root_cause
Canonical: #40919
Summary: The canonical issue tracks growing-session full replacement; this PR supplies the focused repair and remains unmerged.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Current source confirms repeated full-session writes, and an affected official-release user reports substantial write pressure and interrupted turns during normal long-running sessions.
  • 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 (14 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-06T18:58:54.878Z sha 38b2a12 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-06T19:54:18.722Z sha 2462805 :: blocked before merge. :: none
  • reviewed 2026-10-06T20:49:31.951Z sha 2462805 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T00:50:00.667Z sha 1d32296 :: needs changes before merge. :: none
  • reviewed 2026-10-10T01:49:46.974Z sha 67fafb5 :: needs changes before merge. :: [P2] Restore lazy chunk-writer creation for empty replacements
  • reviewed 2026-10-10T02:55:17.852Z sha 795f5bf :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T04:58:41.621Z sha a091577 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T09:54:10.733Z sha 2bb1707 :: needs maintainer review before merge. :: none

Reviewed October 10, 2026, 6:20 AM ET / 10:20 UTC (Revision 15).

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. P1 High-priority user-facing bug, regression, or broken workflow. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels Jul 10, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 25, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 8, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Aug 9, 2026
@wr-web
wr-web force-pushed the fix/incremental-session-chunk-diff branch from c073fe1 to 6800327 Compare August 9, 2026 05:20
@openclaw-barnacle openclaw-barnacle Bot added triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Aug 9, 2026
@wr-web
wr-web force-pushed the fix/incremental-session-chunk-diff branch from 6800327 to 53fd0f9 Compare August 9, 2026 06:13
@wr-web
wr-web force-pushed the fix/incremental-session-chunk-diff branch from 53fd0f9 to 05e4875 Compare August 9, 2026 06:39
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. label Aug 9, 2026
@wr-web

wr-web commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 9, 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 repository_dispatch).
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 removed the rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. label Aug 9, 2026
@Hawkeye2611

Copy link
Copy Markdown

Reproduced on Windows, and the growth rate makes this a daily-restart problem rather than a slow leak.

Host: OpenClaw 2026.9.5 (ec9c1a1), Windows 11 x64, native (no WSL), Node 26.4.0, local embeddings (Ollama / bge-m3), memory.search.sources: ["memory","sessions"].

Measured growth after a clean restart

The gateway was restarted at 12:02Z specifically to clear a stalled WAL. Measured 2.5 h later, with no unusual workload — one long-running interactive session:

value
gateway uptime 2.51 h
openclaw-agent.sqlite 1188.7 MB
openclaw-agent.sqlite-wal 1121.7 MB
growth rate ~447 MB/h
WAL / DB ratio 0.94

The WAL reached the size of the database itself within three hours of a clean start. An earlier measurement on this host (2026-09-26) put sustained growth at ~1,100 MB/h while the session index was actively catching up.

Checkpoint cannot drain it

Frame-level readings from the WAL index (mxFrame, nBackfill, reader marks) during the same window:

openclaw-agent.sqlite   nBackfill 265 of mxFrame 248,751
                        reader marks [265, 36358, 178858, 248751]
                        unchanged across 4 consecutive checks

nBackfill is still at the value it had immediately after restart, so nothing has been written back at all. PRAGMA wal_checkpoint(TRUNCATE) fails with database is locked while the gateway holds those marks — only process termination releases them. A dedicated hourly checkpoint task reports success and changes nothing.

Write distribution, matching this PR's premise

Measured on this host on 2026-09-26, rows written per hour:

table rows/h
memory_index_chunks 3,201
memory_embedding_cache 139
transcript_events 27

Factor ~120 between indexed chunks and actual transcript events. Of those 3,201 chunk writes, 2,898 belonged to the single growing session JSONL — which was also its total chunk count at the time, i.e. 100% of the file rewritten in one wave per sync. Not duplicated writes (checked: 0 exact duplicate session_id + event_json groups), but fully repeated ones. That is the delete-and-reinsert pattern this PR replaces with a delta path.

Practical impact

Without the fix the only mitigation here is restarting the gateway every two to three days, which terminates any running session. The secondary effect is worse than the disk usage: with a multi-GB WAL, database is locked starts aborting turns — one 600 s CLI timeout on 2026-10-03 traced back to this.

This PR has been open since 2026-07-10 with CI green, no failing checks and no review. If a second affected host with numbers helps move it, I'm glad to run any specific before/after measurement on Windows.

wr-web and others added 9 commits October 7, 2026 02:43
Resolve the worker-publication conflict by taking main's memory-core
publication owner; the branch-side manager writer is replaced by the
worker-kernel session delta in the following commit.
Growing session transcripts were republished with a whole-source
replacement on every dirty sync, so DB/FTS/vector churn and embedding
work scaled with the full transcript instead of its new tail.

Session publication now keeps rows whose content-addressed chunk ids are
unchanged. The manager only plans: it reads indexed ids through the
publication worker and embeds new chunks. The worker kernel, inside its
write transaction, verifies retained rows, writes new rows, deletes ids
the publication omits, and refreshes provenance only when it changed.
If a retained row vanished before the write lock, nothing is written and
the manager immediately republishes the source in full. Full reindexes
into a shadow keep the existing whole-source path. No schema, config, or
search-result changes.

Closes openclaw#40919
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

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 P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: L 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.

3 participants