Skip to content

fix(state): avoid repeated read worker startup on Bun - #161040

Merged
steipete merged 2 commits into
mainfrom
steipete/bun-state-read-worker-reuse
Sep 29, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/bun-state-read-worker-reuse

Conversation

@steipete

@steipete steipete commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

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.

@clawsweeper

clawsweeper Bot commented Sep 29, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M labels Sep 29, 2026
@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 Sep 29, 2026
@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 29, 2026, 3:59 AM ET / 07:59 UTC (Revision 2).

ClawSweeper review

What this changes

Bun 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
Reviewed head: 94861204cde3bcb19039c4b1800c17d463d13ee7

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The focused lifecycle patch has direct Bun Gateway and native-exit evidence with no confirmed introduced defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR reports authenticated calls through a real Bun Gateway with two workers and no retirements, plus a before-and-after production-pool run showing 50 starts reduced to one and path-close exit observed. The introduced Bun child test covers the same owner boundary. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR reports authenticated calls through a real Bun Gateway with two workers and no retirements, plus a before-and-after production-pool run showing 50 starts reduced to one and path-close exit observed. The introduced Bun child test covers the same owner boundary. No stored-data contract changes.
Evidence reviewed 7 items Current main still retires Bun workers: Current main sets retirement for every Bun read outcome, including successful reads.
Current main bypasses retained Bun readers: The borrow condition explicitly excludes Bun, so current main does not provide the requested reader reuse.
PR worker lifecycle: The introduced Bun path rotates the pool for host resource closure and otherwise retains successful task workers; the pool remains bounded to two workers with an idle timeout.
Findings None None.
Security None None.

How this fits together

Gateway 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
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -2, Tests +143, Docs +1. Total +142 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 5 33 35 -2
Tests 5 154 11 +143
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 188 46 +142

Review metrics

Metric Value Why it matters
Production versus test growth production net -2 lines; tests and support net +143 lines The lifecycle change slightly shrinks production code while adding Bun boundary coverage.

Root-cause cluster

Relationship: canonical
Canonical: #161040
Summary: This PR owns Bun repeated worker startup. The merged Node reuse and worker-bundle changes overlap the area but address different runtime causes; the open snapshot PR addresses separate cleanup failures.

Members:

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

Technical review

Best 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: On Bun-hosted Gateways, repeated worker startup can saturate state reads and delay Control UI authentication.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR reports authenticated calls through a real Bun Gateway with two workers and no retirements, plus a before-and-after production-pool run showing 50 starts reduced to one and path-close exit observed. The introduced Bun child test covers the same owner boundary. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR reports authenticated calls through a real Bun Gateway with two workers and no retirements, plus a before-and-after production-pool run showing 50 starts reduced to one and path-close exit observed. The introduced Bun child test covers the same owner boundary. No stored-data contract changes.

Evidence

What I checked:

  • Current main still retires Bun workers: Current main sets retirement for every Bun read outcome, including successful reads. (src/state/openclaw-state-read-worker.ts:598, 98e3f67d93b8)
  • Current main bypasses retained Bun readers: The borrow condition explicitly excludes Bun, so current main does not provide the requested reader reuse. (src/state/openclaw-state-db-read-connection.ts:210, 98e3f67d93b8)
  • PR worker lifecycle: The introduced Bun path rotates the pool for host resource closure and otherwise retains successful task workers; the pool remains bounded to two workers with an idle timeout. (src/state/openclaw-state-read-worker.ts:40, 94861204cde3)
  • Native close signal: Bun SQLite disposal records a worker-local cleanup flag after schema tracking is installed; the read reply forwards that flag for retirement. (src/infra/node-sqlite.ts:154, 94861204cde3)
  • Real Bun lifecycle regression: The new child test runs the production read transport under Bun and checks repeated-read reuse, host path close, an internal close, and quarantine admission cleanup. The PR body reports 50 worker starts before versus one after, plus authenticated Gateway calls with two read workers and no retirements. (src/state/openclaw-state-read-worker.bun.test-support.ts:58, 94861204cde3)
  • Merged feature history: The earlier merged Node worker-reuse change explicitly retained Bun per-task retirement. This PR addresses that remaining Bun behavior, while the separately merged worker-bundle change and open snapshot-recovery PR concern distinct causes. (e6b30393d3b3)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-29T07:04:09.952Z sha 3121265 :: needs maintainer review before merge. :: none

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.
@steipete steipete self-assigned this Sep 29, 2026
@steipete
steipete merged commit e43402a into main Sep 29, 2026
238 checks passed
@steipete
steipete deleted the steipete/bun-state-read-worker-reuse branch September 29, 2026 08:37
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 30, 2026
## 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]>
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 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: M 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.

1 participant