Skip to content

fix(memory): session memory sync fails with too many SQL variables on large session stores - #164336

Merged
obviyus merged 2 commits into
openclaw:mainfrom
jayzhou2309:fix/memory-origin-bind-limit
Oct 3, 2026
Merged

obviyus merged 2 commits into
openclaw:mainfrom
jayzhou2309:fix/memory-origin-bind-limit

Conversation

@jayzhou2309

@jayzhou2309 jayzhou2309 commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #164283

What Problem This Solves

Fixes: memory-core session sync fails with too many SQL variables on every startup catch-up and session update when an agent has more sessions than SQLite's bind-parameter limit (32766 in the bundled build) and a forget tombstone table exists.

User Impact

User impact: session memory on large installs indexes again instead of retrying and failing every few minutes. Forgotten sessions stay excluded, and results are unchanged for small selections.

Why This Change Was Made

Session catch-up and update pass every corpus session ID to listMemorySessionTombstones. That worker query, and three sibling origin queries, bound each ID as its own SQLite parameter in an IN (...) list. Once the selection passed the limit, the query failed before the sync could finish.

All four now bind the selection as one JSON parameter through the existing sqliteStringSet helper, as the session and forget kernels already do:

  • readMemoryEntryOriginsInDatabase in packages/memory-host-sdk/src/memory-entry-origins.ts (session and entry-key filters). The SDK's kysely bridge now re-exports sqliteStringSet.
  • The origin-exists and session-tombstones reads in extensions/memory-core/src/memory-entry-origin-reads.ts.
  • deleteMemoryEntryOriginsInDatabase in extensions/memory-core/src/memory-entry-origins-delete.ts.

Agent filtering, ordering, and the delete's admitted transaction are unchanged.

Evidence

  • Red first. Test commit bbfbb07 adds "filters origins and tombstones by selections larger than SQLite's parameter limit" to extensions/memory-core/src/memory-entry-origins.test.ts. It sizes each selection at MAX_VARIABLE_NUMBER + 1 from PRAGMA compile_options and covers origin reads by session and by entry key, the tombstone read, prune (existence preflight plus delete by entry key), and delete by session. On upstream/main ad3762e it fails with WorkerTaskError: too many SQL variables. On the fix a2148d8 it passes in about 1.1s.
  • pnpm test:extension memory-core: 153 files, 1714 passed, 4 skipped. That includes the startup catch-up, session-update race, and forget concurrent-origin tests. packages/memory-host-sdk and extension-package-project-boundaries.test.ts: 63/63. pnpm tsgo:core, tsgo:extensions, and tsgo:extensions:test exit 0. scripts/run-oxlint.mjs exit 0, oxfmt --check clean, and pnpm lint:kysely OK on the changed files.
  • Real catch-up path. A throwaway probe (not committed) seeds 32767 real SQLite sessions with upsertSessionEntry and appendSessionTranscriptMessageByIdentity, forgets one, and lists the session corpus through the startup catch-up harness, so the tombstone read runs in the real memory worker:
## main ad3762ef8d2
PROBE sessions=32767 variableLimit=32766 -> error: WorkerTaskError: too many SQL variables

## fix a2148d8cea3
PROBE sessions=32767 variableLimit=32766 -> ok: corpus 32766 sessions, forgotten s-0 kept=false

Not verified: the reporter's Linux gateway on 2026.9.8, or the RSS pressure they saw during the retries.

AI disclosure: an AI agent (Claude Code) reproduced the failure, wrote the test and the fix, and ran the gates above: pnpm test extensions/memory-core/src/memory-entry-origins.test.ts --maxWorkers=1, pnpm test:extension memory-core, pnpm test packages/memory-host-sdk src/plugins/contracts/extension-package-project-boundaries.test.ts, pnpm tsgo:core, pnpm tsgo:extensions, pnpm tsgo:extensions:test, scripts/run-oxlint.mjs, oxfmt --check, pnpm lint:kysely, the corpus probe above, and the repo's autoreview skill.

🤖 Written and posted by an AI agent (Claude Code) on behalf of @jayzhou2309.

Maintainer verification

Verified exact head a2148d8cea32a08bff8872db289655d4d69b9d53 in secretless Docker. Thanks @jayzhou2309 for the complete fix and @nkarkare for reporting it.

  • Real Gateway before/after: Node 24.21.0, SQLite 3.53.4, native variable limit 32,766, and 32,768 canonical sessions with local stub embeddings. Baseline b12b4b98bb39f34ebdd907af49e3ad8fec771cb2 failed startup catch-up and a real chat.inject update; SQL tracing identified the unbounded memory_session_tombstones selection. This PR head completed catch-up with exactly 32,768 session sources and 32,768 chunks.
  • Update and search: another chat.inject call published its unique new text in exactly one transcript chunk; both total counts remained 32,768. Gateway memory_search returned session content after catch-up and again after the update. No SQL-variable, startup-catch-up, or session-update errors appeared in the completed candidate log.
  • Controls: the 3-session baseline and candidate each produced exactly 3 session sources and 3 chunks. The candidate's first cold search hit the existing 30-second tool deadline while indexing continued; publication completed about four minutes later, and subsequent searches succeeded. This is not a claim that cold-indexing cost or general RSS pressure is eliminated.
  • Regression: independently replayed the new test with the four query-owner files from pre-fix commit bbfbb073f913ea7b460fe315cb0970ce351cd0cd: it failed with WorkerTaskError: too many SQL variables. On the exact PR head, the origin, startup-catch-up, and session-update-race files passed 70 tests across 3 files (--maxWorkers=1, 108.41 seconds wrapper wall time).
  • Live smoke: one real gpt-5-mini request on this head through a passive proxy, reasoning low, output budget 4096; HTTP 200 and the expected response. Utility routing and scheduled jobs were disabled; no paid embeddings were used.
  • CI gate is successful, with no failing or cancelled checks. ClawSweeper is ready on the same SHA, with no findings.

No overlap with Pash/Sarah changes.

@clawsweeper

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

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 10:02 AM ET / 14:02 UTC.

ClawSweeper review

What this changes

Memory Core replaces per-ID SQL bindings in session-exclusion and memory-origin queries with bounded JSON selections and adds regression coverage for large stores.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: current main and v2026.9.8 retain the oversized-selection failure. The focused repair has relevant production-worker proof, and no introduced correctness defect was found.

Priority: P1
Reviewed head: a2148d8cea32a08bff8872db289655d4d69b9d53

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair reuses an established helper, preserves query semantics, and supplies relevant production-boundary proof.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The supplied before/after terminal trace exercises production corpus selection and the real SQLite memory worker with 32,767 persisted sessions, changing a bind-limit failure into successful selection while excluding the forgotten session. Supplemental regression coverage checks the sibling queries. No stored-data contract changes require migration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The supplied before/after terminal trace exercises production corpus selection and the real SQLite memory worker with 32,767 persisted sessions, changing a bind-limit failure into successful selection while excluding the forgotten session. Supplemental regression coverage checks the sibling queries. No stored-data contract changes require migration.
Evidence reviewed 9 items Pinned introduction and merge result: The merge-base-to-head diff introduces only the memory query repair, its internal helper bridge, and regression coverage. Raw test-merge parents are exactly the pinned main followed by the pinned PR head; its result preserves base-only work.
Current main remains affected: The session-tombstones worker branch still passes sessionIds directly into an IN predicate. The current-main origin reader likewise binds each selected session or entry separately.
Released implementation remains affected: The v2026.9.8 source retains direct sessionIds and entryKeys bindings. This establishes that the submitted repair is not already shipped in the supplied latest release.
Findings None None.
Security None None.

How this fits together

Memory Core turns session transcripts into searchable memory. Its SQLite workers read session exclusions and memory lineage so indexing skips forgotten sessions and cleanup targets the correct entries.

flowchart TD
 A[Session transcripts] --> B[Memory corpus selection]
 B --> C[SQLite memory worker]
 D[Forgotten session records] --> C
 E[Selected session and entry IDs] --> C
 C --> F[Bounded JSON selection]
 F --> G[Eligible sessions and matching origins]
 G --> H[Memory indexing and cleanup]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +4, Tests +59. Total +63 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 4 11 7 +4
Tests 1 59 0 +59
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 70 7 +63

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #164283
Summary: This PR is the candidate repair for the canonical memory-origin bind-limit report.

Members:

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

Technical review

Best possible solution:

Keep one bounded-selection implementation across the memory-origin query paths while preserving forgotten-session exclusion and admitted deletion semantics.

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

Yes: with an existing tombstone table, corpus selection exceeding SQLite's bind ceiling reaches the unbounded worker query on current main. The supplied before/after probe corroborates this path; this reviewer did not execute it.

Is this the best way to solve the issue?

Yes: reusing the established string-set helper repairs all affected query siblings without introducing chunking, another owner, or a changed storage contract.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P1: The current-release report and source show repeatedly failing session-memory synchronization on large stores.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The supplied before/after terminal trace exercises production corpus selection and the real SQLite memory worker with 32,767 persisted sessions, changing a bind-limit failure into successful selection while excluding the forgotten session. Supplemental regression coverage checks the sibling queries. No stored-data contract changes require migration.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The supplied before/after terminal trace exercises production corpus selection and the real SQLite memory worker with 32,767 persisted sessions, changing a bind-limit failure into successful selection while excluding the forgotten session. Supplemental regression coverage checks the sibling queries. No stored-data contract changes require migration.

Label justifications:

  • P1: The current-release report and source show repeatedly failing session-memory synchronization on large stores.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The supplied before/after terminal trace exercises production corpus selection and the real SQLite memory worker with 32,767 persisted sessions, changing a bind-limit failure into successful selection while excluding the forgotten session. Supplemental regression coverage checks the sibling queries. No stored-data contract changes require migration.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied before/after terminal trace exercises production corpus selection and the real SQLite memory worker with 32,767 persisted sessions, changing a bind-limit failure into successful selection while excluding the forgotten session. Supplemental regression coverage checks the sibling queries. No stored-data contract changes require migration.

Evidence

What I checked:

  • Pinned introduction and merge result: The merge-base-to-head diff introduces only the memory query repair, its internal helper bridge, and regression coverage. Raw test-merge parents are exactly the pinned main followed by the pinned PR head; its result preserves base-only work. (a2148d8cea32)
  • Current main remains affected: The session-tombstones worker branch still passes sessionIds directly into an IN predicate. The current-main origin reader likewise binds each selected session or entry separately. (extensions/memory-core/src/memory-entry-origin-reads.ts:60, e39c8734eda9)
  • Released implementation remains affected: The v2026.9.8 source retains direct sessionIds and entryKeys bindings. This establishes that the submitted repair is not already shipped in the supplied latest release. (packages/memory-host-sdk/src/memory-entry-origins.ts:61, fc23bc864e45)
  • Actual failing entry point: Corpus selection sends every discovered session ID to the tombstone reader. Startup catch-up and session-update target resolution consume this same corpus owner, explaining the reported failure before indexing completes. (extensions/memory-core/src/memory/manager-session-sync-ops.ts:79, a2148d8cea32)
  • Existing bounded-selection contract: sqliteStringSet supplies one bound json_each selection while preserving string normalization and outer ordering. Existing helper tests compare it with ordinary IN predicates for empty selections, duplicates, Unicode, NUL-containing strings, and injection-shaped values. The PR reuses this owner without changing agent predicates, transaction admission, schemas, or public signatures. (src/infra/kysely-sync.ts:56, a2148d8cea32)
  • Regression coverage: The added case derives the native bind ceiling and exercises larger selections through origin reads, tombstone reads, pruning preflight, and deletion. It verifies selected and retained rows rather than SQL text. The body reports a pre-fix failure and an approximately 1.1-second after-fix pass; tests were not executed during this read-only review. (extensions/memory-core/src/memory-entry-origins.test.ts:261, a2148d8cea32)

Likely related people:

  • Peter Steinberger: Raw commit fa2cbc0 adds extensions/memory-core/src/memory-entry-origin-reads.ts:42 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)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@obviyus
obviyus merged commit 21f9fae into openclaw:main Oct 3, 2026
135 checks passed
@obviyus

obviyus commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

Landed as 21f9fae. Thanks @jayzhou2309!

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
… large session stores (openclaw#164336)

Fixes openclaw#164283.

memory-core session-memory sync bound one SQL variable per session, so on installs with many sessions the startup catch-up and session update failed repeatedly with `too many SQL variables` and were retried. The affected queries now pass the session set as a single bound value instead of one variable per session. No schema changes, and the same rows sync.

Proof: on a real isolated Gateway seeded with 32,768 sessions and local stub embeddings, base reproduced the catch-up and update errors. This change completed catch-up with exactly 32,768 sources and chunks, published an update without changing those counts, and `memory_search` returned session content. A small 3-session control is unchanged. The regression test fails on base and passes here. A live gpt-5-mini call passed. Thanks @nkarkare for the report.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

memory-core: session memory sync fails with too many SQL variables

2 participants