Repository navigation
fix(state): avoid repeated read worker startup on Bun - #161040
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: needs maintainer review before merge. Reviewed September 29, 2026, 3:59 AM ET / 07:59 UTC (Revision 2). ClawSweeper reviewWhat this changesBun shared-state reads reuse warm SQLite readers and workers, while native resource closes still wait for worker exit; the branch adds lifecycle tests and updates Bun documentation. Merge readiness✅ Ready for maintainer review Keep open: current main still retires every successful Bun read worker and bypasses retained readers. The branch addresses that gap, has credible production-path proof, and shows no confirmed blocking defect. Priority: P1 Review scores
Verification
How this fits togetherGateway and CLI state requests pass through a bounded worker pool to read OpenClaw's shared SQLite database. The pool returns the read result and either retains a healthy Bun worker or joins its exit when native cleanup is required. flowchart LR
A[Gateway state request] --> B[Read admission]
B --> C[Two-worker read pool]
C --> D{Native reader closed?}
D -- No --> E[Reuse warm worker]
D -- Yes --> F[Join worker exit]
E --> G[State result]
F --> G
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource -2, Tests +143, Docs +1. Total +142 across 11 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Use the existing bounded pool for healthy Bun state reads and retain worker-exit settlement whenever native SQLite resources close. Do we have a high-confidence way to reproduce the issue? Yes. Current-main source forces Bun worker retirement and prevents reader borrowing, and the contributor reports before-and-after worker counts through a real Bun pool; this read-only review did not execute the path. Is this the best way to solve the issue? Yes. The patch uses the existing pool and reader lifecycle, with native-close signaling to preserve Bun's worker-exit cleanup boundary. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 98e3f67d93b8. 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 (1 earlier review cycle)
|
Install schema tracking before registering the Bun native-disposal callback so statement-cache invalidation wraps the schema authorizer tracker. Dynamic denials must revoke cached version reads while native closes still require read-worker retirement.
|
Merged via squash.
|
## 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 openclaw#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: openclaw#161003 reduces the worker bundle separately; openclaw#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]>
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 loggedGateway profile acquisition authority expiredseconds later because profile resolution finished after the socket closed.sessions.listtook 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
sessions.listand 20sessions.catalog.listcalls issued 28 shared-state reads, 0 fresh admissions, 2 read workers total, no retirements;sessions.listmedian 1.1 ms,sessions.catalog.listmedian 0.9 ms.pnpm test <file> --maxWorkers=1):openclaw-state-db-read-connection.cache.test.ts10 passed, 74.09 s wall (includes cold worker compilation);openclaw-state-read-worker.test.ts32 passed, 29.24 s wall;openclaw-state-read-worker.bun.test.ts1 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 tsgopassed (22.54 s); the state-logging test type lane passed (12.36 s). Installedoxfmt --check, type-awareoxlinton all changed TypeScript, andgit diff --checkpassed.src/infra/sqlite-schema-facts.test.tsunderOPENCLAW_VITEST_RUNTIME=bunfailed on the first head, passed on main, and passes on the fixed head (Bun subset 32 passed; Node focused 129 passed).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.