Repository navigation
Description
Outcome
Keep the proxy server alive when the usage worker is slow or fails under Bun 1.3.14. Usage analytics may become degraded, but timeout handling must never terminate and respawn a worker while Bun transpiler jobs may still be in flight.
Problem
The server crashed after five usage-worker watchdog restarts. Bun reported six workers spawned and five terminated, matching the restart cycle. The files named in the panic are victims, not faulty application modules: the decoded stack fails in Bun's RuntimeTranspilerStore while replacement-worker imports are being parsed.
This matches oven-sh/bun#33936, where Worker.terminate() can free VM-owned transpiler state still used by a pool thread. The proposed upstream fix, oven-sh/bun#33939, is still unmerged. Bun 1.3.14 is both the installed and latest stable release, so a stable upgrade is not currently a fix.
Claudeflare exposes the bug by terminating and immediately respawning the usage worker after readiness, acknowledgement, worker-error, message-error, and synchronous post failures. Source startup also loads the TypeScript worker directly, causing Bun to transpile its repository dependency graph inside the worker.
Required changes
Degrade analytics without worker churn
- Remove automatic usage-worker termination and respawn. A controller creates at most one worker during its lifetime.
- On readiness timeout, set health to
degraded, retain the worker, and continue buffering up to 1,000 messages. Drop newly arriving messages once the bound is reached. A latereadymessage clears the error, returns health toready, and flushes each retained message once. - On acknowledgement timeout, remove only that pending acknowledgement, set
lastError, and mark healthdegraded; do not terminate, respawn, or resend the timed-out message. A later valid acknowledgement for another pending message may restorereadyhealth. - On worker error, message error, or synchronous
postMessagefailure, mark healthstopped, clear timers, pending acknowledgements, and the startup queue, then safely drop future analytics messages. Keep proxy responses independent of this state. - Extend the shared usage-worker health state with
degraded; retain the existing health fields and report the failure reason throughlastError. - Preserve graceful shutdown. Send the shutdown control message and call
terminate()only aftershutdown-completeconfirms the async writer flushed. If the shutdown deadline expires or posting the shutdown message fails, reject shutdown and leave the unreferenced worker for process exit; do not force-terminate it.
Use the existing JavaScript sidecar in source mode
- Add
build:workerscripts to the server and TUI packages using their existingpost-processor.worker.jsbuild command, and reuse those scripts from each package's build. - Make normal server
start/devand TUIdevscripts build the sidecar before launching source code. Make rootstart,server,dev:server, andtuidelegate to those package scripts. - In the source server and TUI entrypoints, set
CF_USAGE_WORKER_PATHto that app'sdist/post-processor.worker.jswhen the file exists and the variable is unset. - Preserve an explicit
CF_USAGE_WORKER_PATHas highest priority, existing compiled-binary/desktop sidecar resolution, and the TypeScript fallback for direct/test execution when no sidecar exists.
Retry transient SQLite write contention
- Include the underlying error message in persisted
AsyncDbWriterfailure log text. - Retry jobs that fail with
SQLITE_BUSY,SQLITE_LOCKED, or a case-insensitivedatabase is lockedmessage up to three times after the initial attempt, using 100 ms, 500 ms, and 1,000 ms yielding delays. - Keep the job at the head of the FIFO sequence while retrying. Count and log one permanent failure only after all retries are exhausted; do not retry unrelated errors.
- Preserve the current schema, retention behavior, database ownership, and shutdown queue flush.
Documentation
- Document that readiness and acknowledgement timeouts degrade usage analytics instead of restarting the worker, and reference the Bun 1.3.14 worker-terminate/transpiler defect.
- Document that normal source server/TUI startup builds and selects the JavaScript worker sidecar automatically.
Governing authority and likely paths
AGENTS.mdkeeps usage-worker handoff inpackages/proxy, persistence behavior inpackages/database, and source/compiled paths documented.docs/architecture.md,docs/data-flow.md,docs/database.md,docs/configuration.md, anddocs/deployment.mddefine the relevant behavior.- Likely implementation areas are
packages/proxy/src/usage-worker.ts,packages/database/src/async-writer.ts, the server/TUI entrypoints and package scripts, shared health types, focused tests, and the relevant documentation.
Dependencies
None. The upstream Bun fix explains the native failure but is not a blocker; this ticket owns application-side containment on Bun 1.3.14.
Non-goals
- Do not upgrade, patch, or vendor Bun, and do not require an unreleased canary.
- Do not add worker respawn/backoff, a content-addressed runtime bundle, byte-aware or message-type-aware queue eviction, or a new worker protocol.
- Do not move persistence between threads, change database schema or retention behavior, or change provider routing and public proxy responses.
- Do not stop, restart, signal, or otherwise interrupt the running Claudeflare service during implementation or validation.
Acceptance criteria
- Delayed readiness and acknowledgement do not call
terminate()or create a replacement worker; late readiness flushes the bounded startup queue exactly once.- Verify with deterministic controller tests, including a terminate-forbidden fake and more than 1,000 pre-ready messages.
- Worker errors, message errors, and synchronous posting failures transition health to
stopped, clear pending state, spawn no replacement, and make later analytics sends safe no-ops.- Verify with focused controller state and delivery-count tests.
- Graceful shutdown flushes successfully and terminates only after
shutdown-complete; a shutdown timeout does not terminate the worker.- Verify both completion and timeout paths with terminate-call assertions.
- Normal source server and TUI scripts build and select their JavaScript sidecar, while explicit environment override and no-sidecar TypeScript fallback precedence remain correct.
- Verify entrypoint/path tests and successful server/TUI worker-sidecar builds.
- A transient SQLite lock succeeds on retry, a persistent lock records one final failure after three retries, unrelated failures are not retried, FIFO order is preserved, and the persisted error text contains the SQLite message.
- Verify with deterministic
AsyncDbWriterunit tests using short injected retry delays or a fake delay function.
- Verify with deterministic
- Focused tests, server and TUI builds, and repository
bun run verifypass on Bun 1.3.14 under the reduced-priority wrapper required byAGENTS.md.
agent_level: 4
Created by gpt-5.6-sol@high:019fdd77-706e-7641-b057-9223fcdf2dd2; materially revised after independent review.
Activity
ipo commentedon Aug 7, 2026
IMPLEMENTATION_READY
Commit: b732167 (fix: contain usage worker failures (#20))
Evidence:
Caveats:
Signed: gpt-5.6-sol@medium:019fdda5-5917-76d3-b3ef-88827358ac6d
ipo commentedon Aug 7, 2026
ACCEPT
Candidate:
b7321671489cedb7c7285266f3c3e97e2ef95e4c(base50ad8c80b9349ca1e9d5fb0b6e3007a0b2b40fc0). Independent audit found no in-scope acceptance failure.Evidence:
bun test packages/proxy/src/usage-worker.test.ts packages/database/src/async-writer.test.ts apps/server/src/usage-worker-sidecar.test.ts apps/tui/src/usage-worker-sidecar.test.ts apps/server/src/build-and-exports.integration.test.ts→ 27 pass, 0 fail. This covers the 1,000-message bound/drop behavior, late-ready single flush, forbidden termination/no respawn, ACK degradation/recovery without resend, terminal stop/drop paths, confirmed-vs-timeout shutdown termination, exact SQLite attempts/delays/FIFO/error logging, and path/script precedence.bun run build:server && bun run build:tui && bun run typecheck→ pass; both JS sidecars and compiled targets built, and all workspace TS projects passed.terminate()call is in confirmed shutdown handling. Source entrypoints configure the sidecar before runtime bootstrap creates the worker; explicit env, executable-adjacent compiled sidecar, and TS fallback remain ordered.git diff --check→ pass; prohibited Bun/schema/migration/provider/lockfile scope is unchanged; docs match runtime behavior.Repository
bun run verifyis baseline-constrained, not candidate-regressed: reduced-prioritybun run lint:checkreports six failures only in files byte-unchanged from base;packages/runtime-server/package.jsonis unchanged and already omits its direct@ccflare/typesdependency; all hard-coded-port test files implicated by occupied protected port 8080 are unchanged. Per the ticket, I did not contact or interrupt that service. These conditions do not invalidate the independently demonstrated #20 delta.Signed: gpt-5.6-sol@medium:019fddbe-fd3d-78f2-9bd5-9b5f7a841167
fix: contain usage worker failures (#20)
ipo commentedon Aug 7, 2026
Integrated as
b7321671489cedb7c7285266f3c3e97e2ef95e4conmainvia one-commit fast-forward.Verification evidence:
mainandorigin/mainare clean and synchronized (0 0).verifybaseline exceptions remain the documented pre-existing port-8080/workspace-manifest/untouched-formatting failures; the running service was not interrupted.