Repository navigation
fix: retain shared-state snapshots through worker failures - #160946
Conversation
Keep preparation, query, and cleanup under the existing read owner. Retain native child custody across disposable Worker loss, preserve admitted source identities, and join cleanup before releasing the original directory. Preserve existing schema, retention, SDK, and exact-native backup contracts.
|
🦞👀 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 September 29, 2026, 10:36 AM ET / 14:36 UTC (Revision 15). ClawSweeper reviewWhat this changesThe branch retains shared-state SQLite snapshot preparation, queries, and native cleanup across Worker failures, with fault tests, recovery documentation, and worker packaging entries. Merge readiness⛔ Blocked before merge - 6 items remain Keep open. Current main lacks the retained read lifecycle, and the branch has credible real SQLite fault-injection proof with no discrete code finding. The documented outage behavior after loss of the broker process still needs an independent maintainer decision. The previous review’s generic config or default upgrade concern is not supported by the introduced paths. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw serves shared-state SQLite reads through workers for Gateway and agent requests. Snapshot staging prepares private bytes, a broker retains the native child, and the read worker returns results before cleanup releases temporary files. flowchart LR
A[Shared-state read] --> B[Source and authority capture]
B --> C[Snapshot staging worker]
C --> D[Broker-owned native child]
D --> E[Private snapshot]
E --> F[Read worker query]
F --> G[Confirmed cleanup and result]
Decision needed
Why: The patch deliberately treats broker loss as unknown native custody; choosing that outage behavior requires maintainer judgment beyond the contributor’s stated acceptance. Before merge
Agent review detailsSecurityNone. PR surfacePR surface statistics unavailable: the file list is incomplete. Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep the original snapshot directory fenced until native closure is confirmed, with a documented service-recovery path for broker-process loss. Do we have a high-confidence way to reproduce the issue? Yes, from source and the reported negative controls: current main still separates worker transport from cleanup, while the PR exercises Worker-loss and native-close ordering. This read-only review did not execute a current-main reproduction. Is this the best way to solve the issue? Yes for the Worker-loss defect: retaining source, task, and native cleanup under their existing owners addresses the lifetime boundary. Broker-process-loss availability remains a maintainer choice. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 68b547f6c4dd. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (14 earlier review cycles; latest 8 shown)
|
|
Review disposition for The bounded retained-service loops are intentional causal tests. The queued-failure case requires B to make progress while A’s Promise wrapper and the initiating microtask remain unrun. It separately checks native execution has stopped, the host exit callback has not run, and the original directory’s SQLite token remains locked. The staging-owner cases similarly require progress before awaiting the result, including servicing an earlier release and failed cleanup through a later request. Awaiting an event-loop callback in these sections would remove the condition under test. Setup and teardown already use lifecycle gates. The 2 ms Measured earlier Linux receiving times for the cited cases were 549, 541, 591, 766, and 761 ms; their five-file, 16-case runtime shard took 9.36 seconds. That receiving command later failed a separate gate, so these figures describe the completed runtime segment only. Node and Bun evidence is retained separately. These are observed case/shard times, not invented per-file CI costs or current-head whole-CI success. Broker-loss handling remains explicitly limited: loss of the disposable Worker can be recovered through its surviving broker, but loss of the broker itself leaves native-child custody unknown. Resource claims reject and remain fenced; a termination attempt does not manufacture a resource-close receipt, and retrying the same request is not claimed to recover it. I accept that conservative failure boundary for this repair. Operational recovery uses the existing service stop/restart owner while preserving fenced temporary roots. Existing abandoned-copy reclamation still requires inactive creator and child tokens, its age grace, and normal ownership checks; restarting alone does not prove child closure or authorize manual deletion. No stored-data, schema, retention, configuration, or public SDK contract changes are introduced. The review’s The latest CI packaging defect is corrected by adding exactly three reachable dynamic dependencies to the wrapper inventory. The unchanged original test reproduced the same three missing paths; the correction passes all 19 existing closure/extraction/bootstrap tests, the changed-file gate, and a fresh independent P2 review. Exact-head CI remains pending; cancelled earlier jobs are not passing coverage. |
## What Problem This Solves Fixes Control UI authentication timeouts and severely delayed Gateway state reads when running on Bun. On a Bun-hosted production Gateway, browser connects authenticated and then hit `handshake timeout ... phase=auth_validated`; the same connections logged `Gateway profile acquisition authority expired` seconds later because profile resolution finished after the socket closed. `sessions.list` took up to 184 s while the host was ~90% idle. Thread sampling showed ~28 new shared-state read worker threads per 10 s (~0.7 s each) through the two-slot pool, i.e. roughly 3 reads/s of total capacity, so reconnect storms kept the queue saturated and the login gate reported the Gateway as unreachable. ## User Impact Successful shared-state reads reuse warm workers and SQLite readers. Native cleanup still waits for worker exit when a reader closes. No configuration, schema, stored-data retention, or migration changes are required. ## Why This Change Was Made Node has reused successful read workers since #151929. Bun was retiring a worker after every read and bypassing retained readers, so worker startup saturated the two-worker pool. This change keeps healthy Bun reads warm while routing host resource closes through existing pool rotation. The existing native SQLite disposal callback records task-internal closes, including identity replacement, snapshots, and quarantine admission; the existing cleanup reply makes the host join worker exit. Bun reader idle cleanup belongs to the pool’s existing 30-minute timeout. Transcript discovery remains unchanged: its native readers must close before captured aliases are released, so Bun still needs worker exit there. Ordinary transcript reads already reuse workers. Related: #161003 reduces the worker bundle separately; #160946 overlaps the shared-state transport file. This PR makes no bundling changes. Known remaining Bun cost (follow-up, not a regression): a cold read without a warm main-thread borrow runs fresh admission, which opens and closes the quarantine store per read when that store exists, so such reads still retire their worker on Bun. The warm Gateway RPC path below does not hit it. The second commit keeps schema-fact tracking installed before the Bun disposal hook. Installing the statement-invalidation wrapper first let schema tracking overwrite it, so a cached version read survived a dynamic authorizer denial (caught by the Bun unit shard in CI on the first head). ## Evidence - Bun 1.4.2 with selected SQLite 3.53.4: Kysely sync insert/select followed by close left the same database, WAL, and shared-memory descriptors open in lsof. Thread exit remains required. - Real Bun Gateway (isolated state, signed CLI device auth): authenticated connect plus 20 `sessions.list` and 20 `sessions.catalog.list` calls issued 28 shared-state reads, **0 fresh admissions, 2 read workers total, no retirements**; `sessions.list` median 1.1 ms, `sessions.catalog.list` median 0.9 ms. - Real Bun pool, 50 successful reads: **50 worker starts before → 1 after**; **29.527 seconds → 0.837 seconds** on a synthetic database. Canonical path-close returned with zero live workers and one confirmed native exit. - Exact original-source negative control: all three new regressions failed for the intended reasons. The real Bun test covers repeated-read worker counts, host-close settlement, successful task-internal close, and quarantine admission close; the Node runtime seam covers idle retention and successful identity replacement. - Changed-file costs (`pnpm test <file> --maxWorkers=1`): `openclaw-state-db-read-connection.cache.test.ts` **10 passed, 74.09 s wall** (includes cold worker compilation); `openclaw-state-read-worker.test.ts` **32 passed, 29.24 s wall**; `openclaw-state-read-worker.bun.test.ts` **1 passed, 7.07 s wall** (2.1 s actual test time). The child starts real Bun once to prove native worker exit; these timings include repository test startup, and no sleeps/polling were added. - `pnpm tsgo` passed (**22.54 s**); the state-logging test type lane passed (**12.36 s**). Installed `oxfmt --check`, type-aware `oxlint` on all changed TypeScript, and `git diff --check` passed. - Focused sibling tests: **172 passed across nine files**, 65.44 s wall, covering read connection errors, settlement, authority, worker command replies, quarantine cleanup, native SQLite/Kysely behavior, pool reuse/FIFO/rotation, and resource cleanup. Independent Codex review: scoped-clean, no actionable P0–P2 findings. - CI fix (second commit): `src/infra/sqlite-schema-facts.test.ts` under `OPENCLAW_VITEST_RUNTIME=bun` failed on the first head, passed on main, and passes on the fixed head (Bun subset 32 passed; Node focused 129 passed). - Production: **+33/-35 (net -2)**. Tests and test support: **+154/-11 (net +143)**. Docs: **+1/-0**. CI timing is not yet available; no CI dispatch or rerun requested. Proof is local on macOS with synthetic data. No production Gateway was restarted or deployed; this does not claim a full reconnect-storm load test. The real-Bun regression skips when Bun 1.4+ is unavailable. Co-authored-by: Peter Steinberger <[email protected]>
Prepare the Memory Core facade’s compiled worker dependencies through the existing runner owner before Vitest starts. Keep the runtime export assertion and its deadline unchanged. Extend the actual pre-spawn lifecycle cases to cover direct and project-selected contract tests, including exclusions. Validation: causal preparation-order failure, 35 artifact-owner cases, 19 unchanged package-contract cases, changed-file checks, and independent review.
Carry the original complete-removal operation into re-imported callers instead of treating it as token retirement followed by another pathname deletion. Preserve both original and current reader fences, native join, and retry against the original cleanup owner. Remove the retired async registration path. Exercise real replacement bytes and target loss, and inject Cron copy/removal failures in the actual workers. Both original regressions fail; the correction passes 35 Node cases, the canonical Bun lifecycle case, types, lint, export checks, and independent reviews.
…170605) A shared SQLite snapshot lease threw "SQLite snapshot lease cleanup did not complete" whenever its base cleanup resolved false. Best-effort bases (prepareSqliteReadOnlyLocation without a signal) resolve false only after warning and keeping the directory registered for exit cleanup, so the lease turned successful reads into failures and dropped the original error. On native Windows Bun, private snapshots stay busy after logical close, which made withSqliteSnapshotSource, read-only state opens, the update guard and ownership inspection fail. #168859 merged lease release and preparation close into one helper and widened a throw that #160946 had scoped to preparation close. Lease cleanup now resolves false again without closing the producer, so custody stays with the cleanup registry. Preparation close and orphan cleanup still throw: a close cannot discharge producer custody that removal never released. Strict bases are unchanged because they already throw with their cause. Synchronous cleanup after a refused async cleanup now reports false instead of true. Schema preflight still treats false as fatal by its own policy; #169572 handles that separately.
…penclaw#170605) A shared SQLite snapshot lease threw "SQLite snapshot lease cleanup did not complete" whenever its base cleanup resolved false. Best-effort bases (prepareSqliteReadOnlyLocation without a signal) resolve false only after warning and keeping the directory registered for exit cleanup, so the lease turned successful reads into failures and dropped the original error. On native Windows Bun, private snapshots stay busy after logical close, which made withSqliteSnapshotSource, read-only state opens, the update guard and ownership inspection fail. openclaw#168859 merged lease release and preparation close into one helper and widened a throw that openclaw#160946 had scoped to preparation close. Lease cleanup now resolves false again without closing the producer, so custody stays with the cleanup registry. Preparation close and orphan cleanup still throw: a close cannot discharge producer custody that removal never released. Strict bases are unchanged because they already throw with their cause. Synchronous cleanup after a refused async cleanup now reports false instead of true. Schema preflight still treats false as fatal by its own policy; openclaw#169572 handles that separately.
…7526) A resource failure may arrive over parent IPC after the worker socket has already observed it and finished native cleanup. Do not reject the parent's pending close with that delayed failure; keep reporting the original error and wait for the independent close receipt or actual cleanup failure. Add a deterministic delayed-failure regression with retained custody and close/release assertions. This preserves the separate execution and native settlement contract from #160946 and #173154. Validation: regression red on the old owner; 30 focused cases pass under Node and Bun with one worker. Targeted types, lint, format and P2 review pass.
…nclaw#177526) A resource failure may arrive over parent IPC after the worker socket has already observed it and finished native cleanup. Do not reject the parent's pending close with that delayed failure; keep reporting the original error and wait for the independent close receipt or actual cleanup failure. Add a deterministic delayed-failure regression with retained custody and close/release assertions. This preserves the separate execution and native settlement contract from openclaw#160946 and openclaw#173154. Validation: regression red on the old owner; 30 focused cases pass under Node and Bun with one worker. Targeted types, lint, format and P2 review pass.
Related: #144592
What Problem This Solves
Shared-state reads can release temporary snapshot files or a read slot before the SQLite child has finished when snapshot preparation fails or its supervising Worker exits.
User Impact
Snapshot-backed reads retain their original source and cleanup ownership through cancellation, worker loss, and retries. Cleanup cannot accidentally delete a replacement directory. No configuration, stored-data, schema, retention, or public SDK change is required.
Why This Change Was Made
The existing asynchronous read owner now consumes retained preparation, query, and cleanup operations. The existing spawn broker keeps custody of the native child when its supervising Worker disappears. Later readers can advance an earlier reader's pending release, while source identity, inherited snapshot bytes, FIFO admission, and error precedence remain with their existing owners.
This is a substantial lifecycle change with real consumers in the existing shared-state read path. An already-open native database that outlives its pathname still uses its exact owner's awaited backup; migrating that compatibility path remains separate work. Loss of the broker process itself retains unknown custody rather than reporting successful cleanup.
Evidence
Causal controls and actual SQLite snapshot/native-child lifecycle tests passed on Node and Bun. The original Linux receiving selection passed 166 unique cases across 18 files; a Darwin-only metadata case has its separate Darwin result. Broker construction and startup passed 41 cases after the original eager-path-resolution control failed. The earlier main composition passed 136 worker-pool, retained-read, warm-source, and update-run cases, canonical changed gates, and the full build. Independent full-source and semantic reviews are clean.
Own CI findings were repaired at their owners: a receiver-bound callback declaration, a type-only cycle, generated fixtures using retired private transport APIs, and missing wrapper dependencies. Type-only corrections emit identical JavaScript. The generated fixture preserves the canonical 17-case child order: 16 passed, one intentional skip, and the expected refused-teardown assertion. All 19 source-closure and extracted-wrapper/bootstrap tests pass on the final composition.
The latest merge preserves main’s Bun warm-reader fix. The original transport causes five starts and five retirements for five reads; the resolved transport reuses one SQLite target and still joins native exit on host close, internal reader close, and quarantine admission. The test separately counts its one SQL-free lifetime supervisor and checks the exact total. Affected Node suites passed 90 cases, the final real-Bun lifecycle test passed, and 26 schema cases passed under Bun. Core typing, all 27 test type groups, lint, three unused-export scans, value-cycle checks, and the normal staged changed gate passed. A fresh independent P2 review covers the two translated files.
An extra forced-Bun cache-file run passed eight cases and failed two Node idle-timer assertions. The canonical classifier selects that unchanged file for Node under all runtime policies; its Bun early return intentionally delegates disposal to pool exit. Those extra failures remain recorded, with no skip, timeout, or assertion change. They are not a full Bun-cache pass.
The subsequent Cron composition preserves captured descendant selectors, their nested topology links, and exact UTF-8 input accounting in the existing request owner. Both new requests fail with the old owner; the resolved owner passes 58 request/snapshot cases and the full selected changed gate, including core and 27 test type groups. The qualified Bun lifecycle source is unchanged.
Prior exact-head CI run 36542996883 failed on main’s Windows-upgrade fixture assigning to read-only
ChildProcess.pid; baseline and actual-merge source/config/dependency blobs match, and an isolated compiler control reproduces it without project imports. Main’s canonical correction is included in this merge. Its 85 cancelled jobs are not passing coverage. CI run 36554189098 had two failed jobs. The package contract triggered cold worker compilation inside its test deadline; the maintained runner now prepares that worker graph before spawning Vitest. Two actual ordering controls fail on the old runner, and the correction passes all 35 runner cases plus the unchanged 19 package-contract cases. The original 120-second CI timeout did not reproduce locally, so it is not waived as unrelated. The other six cleanup/admission assertions reproduce identically on untouched main 88e0f4a: six failures and 33 passes under the original two-worker setting. This is a focused macOS baseline reproduction, not a full Linux CI-order pass. Their canonical repair continues separately; failed and cancelled jobs are not passing coverage. This PR does not claim completion of the separate cached-native compatibility migration.CI run 36564413861 exposed three further roots. The real run-entry settlement tests needed the existing host-broker fork route; the same five failures reproduced on untouched main, and the canonical correction passes the original 136-case selection. A registry fixture omitted the read-context export: its original 58 failures and 34 unhandled errors are corrected by sharing the existing synthetic capture closure. All 62 owning cases and the original 30-file, 515-case selection pass, with unchanged assertions and case order; local file-completion scheduling is recorded separately.
The Cron cleanup failures also exposed a real stale-adapter defect. The original owner could remove a snapshot before a re-imported caller performed a second pathname deletion. The async facade now passes the original complete-removal operation, retaining both reader fences and the actual native close/removal receipt. Real replacement-directory and lost-target controls fail on the original code; the correction passes 35 Node cases and the canonical real-Bun lifecycle case. Core typing, all 27 test type groups, three unused-export scans, selected guards, formatting and scoped lint pass, with independent reviews. These are composed selected checks: the initial combined command stopped on an earlier help-command build lock, whose exact owned recovery is retained; it is not reported as a successful whole command. The required merge of current main preserves canonical test routing and awaits existing asynchronous repository creation in the Gateway fixture. All 107 receiving cases and the selected changed gate pass; the two overlapping paths have a clean independent review. Exact-head CI36577604268 has one independently attributed pre-existing root: four GitHub publication-event cases run in the thread project although their canonical repository writer requires the host broker. Fourteen relevant source/configuration/dependency inputs match tested main0993807; an independent main control reproduces the same four failures before this PR’s retained-read code. The existing routing correction is now canonical in36a2d8d6. The106 cancelled jobs remain unproved. Landing uses the explicitly authorized native pre-existing-failure route, retaining the failed/cancelled CI status and all enforced security/review checks.
Review disposition and broker-loss limits.