Skip to content

Name the real work in event loop stall records - #7241

Merged
ymichael merged 1 commit into
mainfrom
bb/server-o4-stall-attribution-names-the-wrong-work-thr_h65vwu3zj7
Nov 9, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/server-o4-stall-attribution-names-the-wrong-work-thr_h65vwu3zj7

Conversation

@ymichael

@ymichael ymichael commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Event loop stalled records could only name work that had been wrapped with runEventLoopWorkSync: daemon WebSocket messages, timeline builds and a few sweep steps. SQLite transactions, plugin RPC/HTTP handlers, plugin event handlers, plugin load and plugin background services were async frames, and async frames are never candidates. So the longest measured synchronous work in most five-second windows was a 0.4 ms daemon heartbeat. In production logs server.210–214.log (Nov 6 08:00 → Nov 7 10:46), 912 of 959 stalls (95%, 184.5 s of summed max delay) were unattributed, and 614 of them had longestSynchronousWork = "ws:daemon heartbeat". The 29 heartbeat stalls that were candidates had a median of 114 ms wall but 16.7 ms CPU. The heartbeat itself was waiting inside its host_daemon_sessions write transaction, and nothing recorded that. The CPU-profile records found the real work (61 s of the 97 s of core samples were in the transaction wrapper), but they named plugin code only by a build-directory UUID.

What changed

  • apps/server/src/services/system/event-loop-work.ts
    • Keeps only the longest blocking unit per window, instead of an array of every completed unit.
    • Each sync unit records wall time, main-thread CPU, and process voluntary/involuntary context switches.
    • Async frames are passed through AsyncLocalStorage as objects, so callbacks and timers a plugin scheduled while it loaded keep their attribution. A completed frame drops its parent pointer, so caller chains cannot grow.
    • Each runEventLoopWork call now also measures its synchronous part before the first await, as <label> (until first await).
    • When a child took at least half of its parent's time, the label names the chain, e.g. ws:daemon heartbeat > db:transaction deferred: update "host_daemon_sessions" ….
    • New stall fields: longestSynchronousWorkCaller (the enclosing request, plugin invocation, sweep, plugin load or service), plus longestSynchronousWorkVoluntaryContextSwitches and longestSynchronousWorkInvoluntaryContextSwitches.
  • packages/db/src/connection.ts: a new synchronousWorkTracker connection option.
    • Every transaction becomes a unit labelled db:transaction <mode>: <first write SQL>, or the first statement's SQL when the transaction only reads (redacted, 120 chars).
    • Statements of 1 ms or more are recorded as db:<op> <sql>.
    • The server wires the option in initDb.
  • plugin-runtime.ts: plugin load (plugin:<id> load) and background services (plugin:<id> service <name>) now run inside work frames. RPC, HTTP, event, schedule and hook invocations were already framed through invokeWrapped.
  • packages/process-utils stall attribution: the capture command now carries plugin code locations, taken from the runtime's existing pluginCodeLocations map. Event loop stall attribution records gain owners (sampled ms per plugin:<id>) and a per-stack owner. This work runs in the profile worker, so it costs the main thread nothing.
  • From slice S5: Thread timeline build blocked the event loop now logs cpuDurationMs, voluntaryContextSwitches and involuntaryContextSwitches.
  • Docs: docs/debugging-and-qa.md (stall diagnosis) and docs/configuration.md.
  • No wire, CLI, or plugin SDK changes.

How you verified

Regression tests, all written against this change:

  • apps/server/test/system/event-loop-work.test.ts uses a real migrated DB and blocks inside SQLite with Atomics.wait. It covers:
    • a slow transaction inside a trivial daemon message is named by its first write;
    • a short child does not take credit for its parent's time;
    • a transaction after an await names the plugin RPC and request as callers;
    • a plugin handler's synchronous start is measured;
    • background work scheduled during plugin load keeps plugin:<id> load;
    • a plugin handler started from a daemon message nests under it;
    • self-scheduling work does not grow the caller chain;
    • windows reset.
  • packages/db/test/connection.test.ts: the tracker receives transaction labels by first write, read-only labels, slow statement records, and no literal values.
  • packages/process-utils/test/stall-attribution.test.ts and performance-diagnostics.test.ts: native frames are charged to the calling plugin, and a real profile records owners.
  • apps/server/test/services/threads/timeline-build-log.test.ts: the log carries CPU and context-switch fields.
  • plugin-reload-collection.test.ts caught a retention bug in the first draft: a lazy label closure shared its V8 context with the plugin factory. It passes now.

Commands:

  • pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/db --filter=@bb/process-utils
  • pnpm exec turbo run test --filter=@bb/process-utils --filter=@bb/db: 120 and 663 tests pass.
  • apps/server vitest over test/services/plugins, test/system, test/services/threads, internal-event-append-ownership and skeleton: 1,185 tests. builtin-plugins hot-reload timed out once at load ~40; it passed on rerun. plugin-authoring-docs needed build:types first.
  • turbo run lint on all three packages and oxfmt --check on the changed files.

Live check: a source dev server (pnpm start --data-dir <empty dir> --perf-diagnostics, not signed in), with the same scenario run on origin/main code and on this branch. The load was a local probe plugin: a route that spins 300 ms synchronously, a route that spins 300 ms after an await, and a service that spins 250 ms on start. The forced slow transaction came from a second process holding BEGIN IMMEDIATE on bb.db for 2.5 s.

Forced stall origin/main This branch
plugin service start (spins 250 ms) 284.6 ms unattributed, ws:daemon heartbeat (4.4 ms) 262.7 ms candidate: plugin:o4-probe service spinner (until first await), caller POST /api/v1/plugins/reload, 250 ms wall / 205.9 ms CPU
plugin HTTP handler, sync (300 ms) 350.1 ms unattributed, ws:daemon heartbeat (0.7 ms) 308 ms candidate: plugin:o4-probe http POST /slow-sync (until first await), caller POST /api/v1/plugins/o4-probe/http/slow-sync, 300.1 ms wall / 261 ms CPU
plugin HTTP handler, after await (300 ms) 311.7 ms unattributed, ws:daemon heartbeat. Profile record: no plugin named 325.6 ms unattributed (not measurable on the main thread). Profile record: owners: [plugin:o4-probe 257.4 ms]
bb.db write lock held by another process 901.3 ms candidate: ws:daemon heartbeat, 893.8 ms wall / 4.4 ms CPU 730.5 ms candidate: ws:daemon heartbeat > db:transaction deferred: update "host_daemon_sessions" … > db:get update "host_daemon_sessions" …, 717.7 ms wall / 2.6 ms CPU, 0 voluntary / 205 involuntary switches

Overhead, measured in-process with 300k iterations, 5 rounds, at load average 20–40, so the numbers are noisy:

  • sync unit: 1.8 → 2.5 µs (extra resourceUsage pair);
  • async work frame: 0.7 → 3.3 µs (the new first-segment measurement);
  • recording a ≥1 ms statement: 0.01–0.02 µs;
  • statements under 1 ms: one extra comparison.

A drizzle immediate transaction (select + update) costs about 100–120 µs on the same machine, so the ~2.5 µs per transaction is about 2%.

Not covered: code a plugin runs after its first await is still not attributed in the immediate Event loop stalled record. That would need promise hooks or a worker per plugin. With diagnostics on, the profile record now names that work by plugin id.

AGENT GENERATED

🤖 Generated with Claude Code

Stall records named "ws:daemon heartbeat" as the longest synchronous work
in most windows because DB transactions, plugin handlers and plugin
background work were not measured. Record every bb.db transaction (labelled
by its first write), single statements of 1 ms or more, and the synchronous
part of each request, plugin invocation, plugin load and plugin service
before its first await. Name the dominant child chain and the calling work,
and add main-thread CPU and context switches to the longest unit and to the
slow timeline build log. Profile stall attribution now totals sampled time
per plugin id.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael marked this pull request as ready for review November 9, 2026 17:36
@ymichael
ymichael merged commit 867cd3c into main Nov 9, 2026
51 checks passed
@ymichael
ymichael deleted the bb/server-o4-stall-attribution-names-the-wrong-work-thr_h65vwu3zj7 branch November 9, 2026 17:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant