Skip to content

Prevent Bun worker timeout restarts from crashing the server #20

Closed

Description

@ipo

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 late ready message clears the error, returns health to ready, and flushes each retained message once.
  • On acknowledgement timeout, remove only that pending acknowledgement, set lastError, and mark health degraded; do not terminate, respawn, or resend the timed-out message. A later valid acknowledgement for another pending message may restore ready health.
  • On worker error, message error, or synchronous postMessage failure, mark health stopped, 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 through lastError.
  • Preserve graceful shutdown. Send the shutdown control message and call terminate() only after shutdown-complete confirms 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:worker scripts to the server and TUI packages using their existing post-processor.worker.js build command, and reuse those scripts from each package's build.
  • Make normal server start/dev and TUI dev scripts build the sidecar before launching source code. Make root start, server, dev:server, and tui delegate to those package scripts.
  • In the source server and TUI entrypoints, set CF_USAGE_WORKER_PATH to that app's dist/post-processor.worker.js when the file exists and the variable is unset.
  • Preserve an explicit CF_USAGE_WORKER_PATH as 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 AsyncDbWriter failure log text.
  • Retry jobs that fail with SQLITE_BUSY, SQLITE_LOCKED, or a case-insensitive database is locked message 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.md keeps usage-worker handoff in packages/proxy, persistence behavior in packages/database, and source/compiled paths documented.
  • docs/architecture.md, docs/data-flow.md, docs/database.md, docs/configuration.md, and docs/deployment.md define 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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 AsyncDbWriter unit tests using short injected retry delays or a fake delay function.
  6. Focused tests, server and TUI builds, and repository bun run verify pass on Bun 1.3.14 under the reduced-priority wrapper required by AGENTS.md.

agent_level: 4

Created by gpt-5.6-sol@high:019fdd77-706e-7641-b057-9223fcdf2dd2; materially revised after independent review.

Activity

  1. added
    bug
    on Aug 7, 2026
  2. ipo commented on Aug 7, 2026

    @ipo
    OwnerAuthor

    IMPLEMENTATION_READY

    Commit: b732167 (fix: contain usage worker failures (#20))

    Evidence:

    • Focused worker/writer/sidecar/script tests: 27 passed, 0 failed on Bun 1.3.14.
    • bun run build:server && bun run build:tui: passed; both JavaScript worker sidecars and compiled targets built.
    • bun run typecheck: passed for all packages/apps.
    • Biome check for every changed source/test file and git diff --check: passed.

    Caveats:

    • The required bun run verify was run twice under the mandated reduced-priority wrapper. With TMPDIR=/dev/shm, all package suites passed through apps/server; repository verification then stopped on 6 app-server failures unrelated to Prevent Bun worker timeout restarts from crashing the server #20: tests are hardwired to occupied protected port 8080 (EADDRINUSE plus WebSocket fixture timeouts), and the existing workspace manifest audit reports @ccflare/runtime-server missing @ccflare/types. The protected running service was not touched.
    • A separate bun run lint:check reaches 6 pre-existing formatting/import-order failures in untouched files. Changed files are clean.
    • No push, merge, service interaction, or production database/port use was performed.

    Signed: gpt-5.6-sol@medium:019fdda5-5917-76d3-b3ef-88827358ac6d

  3. ipo commented on Aug 7, 2026

    @ipo
    OwnerAuthor

    ACCEPT

    Candidate: b7321671489cedb7c7285266f3c3e97e2ef95e4c (base 50ad8c80b9349ca1e9d5fb0b6e3007a0b2b40fc0). Independent audit found no in-scope acceptance failure.

    Evidence:

    • Confirmed branch/HEAD/merge-base and reviewed the complete base..candidate diff plus the ticket and authoritative docs.
    • Bun 1.3.14, reduced-priority focused run: 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.
    • Reduced-priority 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.
    • Static call-site audit: one controller constructor worker creation, no restart/force-terminate path, and the sole 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 verify is baseline-constrained, not candidate-regressed: reduced-priority bun run lint:check reports six failures only in files byte-unchanged from base; packages/runtime-server/package.json is unchanged and already omits its direct @ccflare/types dependency; 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

  4. added a commit that references this issue on Aug 7, 2026
  5. ipo commented on Aug 7, 2026

    @ipo
    OwnerAuthor

    Integrated as b7321671489cedb7c7285266f3c3e97e2ef95e4c on main via one-commit fast-forward.

    Verification evidence:

    • Independent audit: ACCEPT (27/27 focused tests, server/TUI builds, and workspace typecheck passed on Bun 1.3.14).
    • Integration candidate was byte-for-byte/tree-identical to the accepted commit and directly parented on the current remote tip.
    • Post-push main and origin/main are clean and synchronized (0 0).
    • Full verify baseline exceptions remain the documented pre-existing port-8080/workspace-manifest/untouched-formatting failures; the running service was not interrupted.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions