Repository navigation
fix(memory): migrate embedding cache in bounded batches and record oversized rows - #164303
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 October 3, 2026, 8:47 AM ET / 12:47 UTC. ClawSweeper reviewWhat this changesThe PR converts legacy memory embedding caches in bounded windows, skips oversized or malformed vectors, and reports those skips as recoverable Doctor warnings. Warning SQLite table change This PR modifies persisted SQLite tables in Merge readiness⛔ Blocked before merge - 3 items remain The patch remains useful: current main still passes unbounded cache text into a JavaScript SQLite function. No blocking code defect was found, but the required published-updater compatibility run remains unproven. Priority: P1 Review scores
Verification
How this fits togetherMemory storage keeps reusable embedding vectors in each agent’s SQLite database. During upgrades, Doctor converts legacy vectors and reports migration outcomes to the updater. flowchart TD
A[Legacy agent database] --> B[Doctor migration]
B --> C[Bounded cache windows]
C --> D{Valid bounded vector}
D -->|Yes| E[Preserved binary cache row]
D -->|No| F[Recoverable skip warning]
E --> G[Schema commit]
F --> H[Doctor and update results]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +82, Tests +75, Docs +6. Total +163 across 6 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep the bounded conversion in the existing migration owner and establish published-updater compatibility before landing. Do we have a high-confidence way to reproduce the issue? Yes: source identifies unbounded legacy cache TEXT crossing the native UDF boundary, and the supplied before-fix traces show heap-limit aborts. This reviewer did not execute a reproduction. Is this the best way to solve the issue? Yes: bounding text inside SQLite and reporting skipped derived rows through the existing schema and Doctor owners is a focused repair; upgrade-path verification remains necessary. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against e6ec522a023d. 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
|
* origin/main: fix(test): restore fixture state and await async completion (#164222) refactor(sessions): stage and settle pending inputs in workers (#164284) fix: speech-only replies fail when models include reasoning (#164285) fix(nextcloud-talk): avoid webhook migration for unconfigured channels fix: guide background skill reviews through Workshop proposals (#164292) test(build): reject AI dependencies in retained config repairs refactor(channels): require canonical private-network settings (#163535) fix(memory): migrate embedding cache in bounded batches and record oversized rows (#164303) feat(state): incognito actor memory and Codex history routing (P5c, inactive) (#164224) refactor(synology-chat): remove unused route account ID (#164280) test(ui): await web push preference publications (#164295) perf(scripts): avoid compiler projects for runtime import parsing (#164243) fix(worktrees): create workspaces from nested Windows repositories (#164249) test(agents,channels,cli): remove low-value tests (batch d173) (#164302) perf(workboard): serve cards per board revision and push changes instead of polling (#164301) refactor(sqlite): deslop sqlite stores (#164271) chore(ui): refresh control ui locales (#164299) refactor(events): deslop listener and disposal plumbing (#164221) fix: canonicalize fresh worker reasoning signatures (#164287)
…ersized rows (#164303) The validating Doctor inside openclaw update died natively (SIGABRT, Reached heap limit, v8::String::NewFromOneByte <- node:sqlite UserDefinedFunction::xFunc <- DatabaseSync::Exec) while migrating a multi-GiB memory_embedding_cache: node:sqlite materializes each TEXT embedding as a JS string before the UDF runs, so one oversized row or a large table killed the child with no exit code and the update failed with no reason. The memory-storage migration now guards embedding size inside SQL (rows over 1 MiB never reach JS), reads 128-row windows, parses in JS, records skipped rows as recoverable Doctor warnings (count + first rowids), and stays idempotent on rerun. No schema version or table change; no heap flag. Reported on Discord (#9.5->9.7, raman hero). (cherry picked from commit fabc10f)
…ersized rows (openclaw#164303) The validating Doctor inside openclaw update died natively (SIGABRT, Reached heap limit, v8::String::NewFromOneByte <- node:sqlite UserDefinedFunction::xFunc <- DatabaseSync::Exec) while migrating a multi-GiB memory_embedding_cache: node:sqlite materializes each TEXT embedding as a JS string before the UDF runs, so one oversized row or a large table killed the child with no exit code and the update failed with no reason. The memory-storage migration now guards embedding size inside SQL (rows over 1 MiB never reach JS), reads 128-row windows, parses in JS, records skipped rows as recoverable Doctor warnings (count + first rowids), and stays idempotent on rerun. No schema version or table change; no heap flag. Reported on Discord (openclaw#9.5->9.7, raman hero).
What Problem This Solves
Fixes Doctor failures during updates when a legacy embedding cache contains oversized JSON values. Reported by
@raman heroin Discord #9.5->9.7 on October 2, updating 2026.9.5 → 2026.9.7 with a 5.4 GiB agent database and roughly 3 GiB embedding cache. The child died with an unknown exit code and a native SQLite UDF/string-allocation stack.User Impact
Doctor skips malformed or oversized rebuildable cache entries and reports their count and first eight rowids as recoverable warnings. Valid cached vectors retain their identities, provider metadata, and age. Source text and other canonical data are preserved; skipped cache entries regenerate on demand.
Why This Change Was Made
The existing per-row conversion prevents whole-statement retention but still lets SQLite pass unbounded TEXT into a JavaScript UDF. The storage migration now reads 128-row windows by rowid, checks a 1 MiB byte cap inside SQLite, parses only bounded values in JavaScript, and writes each converted vector while keeping other fields inside SQLite. The byte check covers multibyte text and embedded NULs.
The agent schema owner carries skip diagnostics into Doctor's existing recoverable-warning receipts, which feed warning lines and update step details. Each window starts after the preceding rowid; a completed conversion is a no-op on rerun. The existing enclosing transaction still rolls an interrupted schema migration back. No schema-version, configuration, dependency, or Doctor heap-flag changes.
Fresh, package, and git-update Doctor launches inherit
NODE_OPTIONS; none adds a Doctor heap limit. The git build's separate heap setting does not apply to Doctor.Evidence
Local macOS / Node 26.10.0, isolated synthetic SQLite fixtures; TEXT was constructed inside SQLite rather than materialized in JavaScript:
On this Node build, the pre-fix 536,870,915-byte fixture exited successfully without a skip diagnostic; the 96 MiB fixtures above produced the native aborts.
Both new regressions failed on the original code because the expected skip diagnostics were absent. They cover three rowid windows with 64-bit identities, valid vector preservation, oversized/malformed row removal, no-op rerun, and successful schema-21 Doctor migration with recoverable warnings. The existing 3000-cache/3000-chunk-vector regression under a 96 MiB heap is retained.
Touched suites passed three times on the final implementation using the repository's Vitest wrapper with
--maxWorkers=1(36 tests per pass):memory-schema-storage-migration.test.tsstate-migrations.media-persistence.test.tsThe added cache regression took 82–119 ms; the added Doctor regression took 2.54–5.35 s. The Doctor suite exercises real schema, transcript, and archive migrations; its slowest wall-clock pass also included roughly 61 s of shared compiler preparation on the loaded host.
node scripts/check-changed.mjspassed, including core and all 27 test type graphs, lint, dependency and database guards, dead-export scans, and runtime import-cycle checks. Codex P1 review completed with no accepted P0/P1 findings.Importer coverage used the original selected order: all 875 files are accounted for, with no missing, extra, or duplicate paths across continuations. The 872 ordinary files recorded 12,054 passing, 38 skipped, and five failing cases. Three live files collected successfully with provider opt-ins absent; their 23 tests were skipped, so this is import/collection evidence, not live-provider proof.
The broad importer run is not all green. Five unchanged suites failed:
server.sessions.fixture-lifecycle.test.ts— retained state after required close failurebackup-create.test.ts— private agent DB=truesession-accessor.sqlite-byte-size.test.ts— active contextdoctor-heartbeat-task-migration.test.ts— supplied environment timing/cleanuploader.capability-factory.test.ts— retirement with prior success=trueSource tracing places these outside the changed embedding conversion; no independently executed main baseline is claimed. No failing importer timeout, retry, skip, or assertion was changed. Ordinary totals combine finalized config summaries (8,767 passed / 33 skipped / four failed) with observed infra cases (3,287 passed / five skipped / one failed). That infra invocation has no final summary: native shutdown exited 130 with indeterminate completion and retained its resources. Later invocations used fresh owned storage and only previously unrun paths.
Importer failure diagnostics
The unchanged
src/gateway/server.sessions.fixture-lifecycle.test.tscase “retains fixture state and fences successors after a required Gateway close failure” hit its existing 90-second managed-child deadline (90.192 s). Retained artifacts show cold Gateway setup/native-worker preparation continuing at about 83 s, with 1,829 fresh tsx cache entries. The probe had not created its session directory, ownership markers, journal, or report, so its intended close-failure assertions were not reached. The nested fixture does not pass the existing prepared-worker handoff. This is source/artifact attribution, not a baseline replay.The failed fixture also retained an unreleased resource claim and reported indeterminate process-tree cleanup. Its namespace and compiled cache generation were preserved. Remaining, previously unrun files continued in a fresh owned namespace through the existing runner.
Additional importer failure:
src/infra/backup-create.test.ts, “backupCreateCommand: private agent DB=true,” timed out at its existing 120-second deadline (120.035 s); thefalsesibling passed in 1.744 s. The private case creates a minimal schema-1 database without memory tables and follows ownership checks, not the changed embedding migration. Retained artifacts show fixture removal had deleted the database and almost all contents, while directory enumeration of the remaining synthetic plugin subtree blocked in filesystem I/O. This supports a cleanup stall on this host; it is not a baseline replay or proof that the expected rejection assertion passed. The worker acknowledged stop and entered process exit, but termination timed out. Its resources remain preserved. No timeout, assertion, or skip was changed.The infrastructure invocation was cancelled through the runner's normal signal path after all other workers finished and only the exiting backup worker remained. Native cleanup exited 130 and retained its namespace and compiled generation with
processTreeState: indeterminate. Its infrastructure section records 3,287 passing cases, five skipped, and one failed across 201 files, but has no final summary; these are observed case results, not a passing config. The preceding gateway-methods section passed one file and four tests. Previously unrun files continued in a separate owned namespace without reusing the retained resources.Additional importer assertion:
src/config/sessions/session-accessor.sqlite-byte-size.test.ts, “sizes active context without reading transcript overflow payloads,” failed in 301 ms (expected false to be true); all nine sibling reader cases passed. The assertion requires every compiledevent_jsoncolumn-read opcode in sizing queries to carry SQLite's byte-length-only flag. The active-context header query also filters event type through a navigation expression with a conditional full-JSON fallback, which explains an unflagged payload opcode. This assertion inspects compiled branches and does not itself demonstrate an overflow-page read for the fixture. The fresh/current-schema fixture skips the changed embedding migration. This is source-based attribution to the existing query/assertion path, not an independently executed main baseline; the failure is retained without changing the assertion.Additional importer assertion:
src/commands/doctor-heartbeat-task-migration.test.ts, “uses the supplied environment for legacy session timing and cleanup,” failed in 3.039 s. It expected anchor2000001800000and received2000003000000, exactly the separately seeded ambient session's timing. Both the fixture and migration use fixednowMs = 2000000000000, ruling out elapsed wall time. Source forwards the supplied environment and explicit store path, so the finer lookup/overwrite cause remains unresolved. The fresh/current-schema fixture does not invoke the changed memory-storage conversion. This failure is recorded without a baseline replay, timeout change, or assertion weakening.Additional importer assertion:
src/plugins/loader.capability-factory.test.ts, “owns failed catalog initialization without revoking an earlier success (prior success: true),” failed in 24 ms because a retained provider method did not throw after cache retirement. Source tracing shows catalog initialization does not mark its exported function as a factory, so its returned ordinary provider object bypasses instance binding; retirement quiesces the instance but does not fence that plain method. The fixture disables memory and does not invoke database migration. This is source attribution to the existing plugin instance/catalog owner, not a baseline replay; the assertion remains unchanged.Unchanged slow tests and preparation cost
Single cases over 30 seconds and files over 120 seconds of summed reported case time are recorded below under the standing pre-existing-suite waiver. Timings are local; hosted CI time is not yet measured.
src/gateway/server.sessions.list-store-materialization.test.ts— retains titles/previews beyond the handle capsrc/gateway/server-close.agent-databases.test.ts— joins scheduled plugin work before closing storessrc/gateway/server-methods/chat.reset-visible-yield.test.ts— preserves the held descendant's reset outcomesrc/commands/doctor-session-canonical-keys.scale.test.ts— repairs deep owner aliasessrc/gateway/server.chat.gateway-server-chat-b.test.ts— 80 cases, summed test timesrc/flows/doctor-health.fleet-preflight.test.ts— reuses the admitted original capture and refuses changed evidencesrc/infra/state-migrations.caller-mode.refusal.test.ts— leaves Doctor-only discovery out of automatic executionsrc/agents/main-session-recovery/main-session-restart-recovery.test.ts— summed case timesrc/flows/doctor-health.test.ts— summed case timesrc/auto-reply/reply/session.test.ts— summed case timesrc/infra/backup-create.test.ts— summed case time, including the failed 120.035-second case abovesrc/infra/state-migrations.test.ts— summed case timesrc/config/sessions/session-accessor.test.ts— summed case timesrc/cli/doctor-output.process.test.ts— retained custom-agent preview/repairsrc/cli/doctor-output.process.test.ts— deferred Doctor-only state convergencesrc/commands/doctor-config-preflight.process.test.ts— v17 additive-schema repairsrc/commands/doctor-session-sqlite.deferred-plugin.test.ts— summed case timetest/e2e/qa-lab/runtime/codex-auth-product-proof.e2e.test.ts— mixed legacy-auth repairsrc/commands/doctor.auth-profile-consumers.e2e.test.ts— unoccupied destination / occupied destination / interactive Doctortest/e2e/qa-lab/runtime/gateway-codex-refusal-product-proof.e2e.test.ts— misalignment / retryable / bio casestest/oauth-refresh-authority-chain.e2e.test.ts— pending peer/shared rotationsrc/auto-reply/reply/agent-runner.runreplyagent.e2e.test.ts— summed case timetest/e2e/qa-lab/runtime/gateway-codex-refusal-product-proof.e2e.test.ts— summed case timeThe first importer invocation's shared tsdown build took 20m54.6s, built 96 plugins, and passed the CLI bootstrap and 53 built Doctor/plugin closure checks. This was preparation cost, separate from test time.
Change size: production +102/−20 lines; tests +76/−1; documentation +7/−1 (total +185/−22, six files).