Skip to content

Add opt-in server CPU profiles and performance diagnostics - #4751

Merged
ymichael merged 9 commits into
mainfrom
bb/opt-in-performance-diagnostics
Oct 5, 2026
Merged

ymichael merged 9 commits into
mainfrom
bb/opt-in-performance-diagnostics

Conversation

@ymichael

@ymichael ymichael commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

When an operation took hundreds of milliseconds, existing logs could show elapsed time without a CPU stack or nearby GC/CPU evidence. The default event-loop logger also ignored stalls below 500 ms. This left incidents such as the observed 189 ms timeline projection unexplained after the fact.

What changed

Require two gates: startup permission and the default-off performanceDiagnostics experiment. Add pnpm start --perf-diagnostics, pnpm start:worktree --perf-diagnostics, and the equivalent bb-app flag / BB_PERF_DIAGNOSTICS=1 startup setting. Default behavior remains unchanged. Startup permission requires a restart. The experiment toggle is visible in Settings → Experiments only when startup permission is present, using the explicit performanceDiagnosticsAvailable field in /system/config (independent of the persisted experiment value). The experiment is changed live in Settings → Experiments, with bb settings experiment performanceDiagnostics true|false, or the existing SDK experiments update endpoint. Neither gate alone starts collection. Turning the experiment off restores normal logging thresholds and stops/flushes the recorder without a restart; saved profiles remain. No daemon profiling is enabled.

  • Continuous 1 ms V8 CPU sampling, saved every 30 seconds to logs/performance/ under that server's data directory. Captures are retained for up to 12 hours with a total 1 GB (1,000,000,000 byte) budget, whichever limit is reached first. Oldest files are removed first; pending-file space is reserved within the budget. Each capture is capped at 12 MiB; oversized profiles are discarded. Unique filenames preserve recent captures across toggles and restarts; startup and each save enforce retention, including legacy slot files. Graceful shutdown saves the partial window. No inspector network port is opened.
  • Five-second log summaries with main-thread and process CPU time, loop utilization/delay, GC count/duration/max and memory. Profile log records include path, PID and UTC boundaries for correlation.
  • Lower thresholds while enabled: database operations 25 ms; API requests and loop stalls 100 ms. Existing database logs include elapsed and thread CPU time without adding SQL bindings.
  • CPU profiling failures log a warning and leave the server and summary logging usable. Files are written with private permissions. Launcher help, configuration docs, CLI guide and skill explain usage, retention, overhead and limitations.

The existing system-experiments table stores the new default-off key without a migration. No daemon wire contract, product cache, or request behavior changes. Profiling and extra logging add overhead. Summaries are interval-wide, not per-request attribution; profiles are sampled and cannot prove the cause of OS scheduling or native I/O waits. The historical projection incident remains unexplained. Profiles can contain local paths/function names and should be inspected before sharing.

How you verified

  • Original launcher/configuration/worktree command and native profiler verification passed (139 focused tests). Additional two-gate verification passes: real migrated DB and actual profiler tests cover both launch permissions, default-off state, live enable/disable, restart with persisted settings, rapid toggle/shutdown, and no artifacts without both gates. API experiment persistence, UI toggle mapping, prepared-statement live thresholds, restored loop threshold and existing request logging tests pass.
  • Turbo typechecks passed for server, launcher, config, scripts and process-utils, including dependencies.
  • A real isolated 32-second source-module smoke run generated two valid CPU profiles (rotation + shutdown), six performance summaries, and captured a deliberate 180 ms CPU loop both in CPU/delay fields and by function name in sampled stacks. This is component verification, not a production-server deployment or an overhead benchmark.
  • Targeted lint and diff checks pass for new/changed diagnostics code. The existing start-server.ts direct filesystem import triggers the repository's existing server import restriction when linting that entire file; this change adds no filesystem import there. Native file capture lives in process-utils.

Latest head 158bc08635 has 24 passing CI checks and three intentional skips. Visibility tests cover both startup-permission states with a persisted-on experiment, plus hidden/visible UI behavior. App/server/contract/integration typechecks pass. The demo server explicitly reports diagnostics unavailable; its 15 tests pass. Runtime fixtures include the new availability field.

Production was not restarted or profiled. Disable the experiment live to stop; removing launch permission additionally prevents subsequent toggles from starting collection. Already saved profiles remain.

End-to-end diagnostic usefulness

Tested the built pnpm start:worktree --perf-diagnostics server at 158bc08, with real HTTP requests and recorder output, in the fresh isolated QA store. This supplements the earlier collection smoke test.

Controlled case Observed latency What the captured artifacts established
Timeline with long synthetic shell scripts, three distinct threads HTTP 403.53 / 383.67 / 365.37 ms; short-command controls 68.21 / 19.32 / 21.61 ms Request/thread/time matched timeline projection 369.64 / 354.34 / 336.20 ms. Profile caller chains identify parseShellCommandIntents → splitShellCommandSegments → tokenizeShellWords; inclusive parser samples 597/1,058 non-idle samples. Independent health probe max 404.36 ms corroborated blocking.
External SQLite lock held 60 ms, three actual settings writes SQL wall 62.8 / 69.9 / 64.9 ms, CPU 0.5 / 0.5 / 0.4 ms; HTTP 64.16 / 70.93 / 65.81 ms, all 200 Diagnostic 25 ms SQL threshold captures waiting that ordinary 100 ms logging misses. Native run samples plus low SQL CPU distinguish waiting from computation; artifacts alone do not identify the lock owner.

Each timeline fixture starts with 1,505 events; stress changes command text from 31 to 288,028 characters. Real latest-page handler selects 640 stress rows / approximately 12.35 MB. First reads of distinct threads, alternating controls/stress, one server process, shared advisory heavy-job lock; other host load uncontrolled. Three samples are acceptance examples, not percentiles or production benchmarks. Five-second main-thread CPU rose from 117.9 to 1,330.3 ms in the CPU replay; GC max 3.9 ms, so GC alone does not explain the ~400 ms pause. Sampling counts are not exact CPU time. No production data or actual provider turn was used; scripts in stored events were never executed.

An initial 400 ms lock attempt returned SQLITE_BUSY / HTTP 500 after ~85 ms; the immediate cleanup toggle also encountered the held lock, then succeeded after release. Retained that failed exploratory result; the reason for its early busy return was not established. Final 60 ms controls all succeeded.

Interpretation limits exposed and documented: currentWork can name an unrelated asynchronous long poll; expected long polls can log slow response durations without loop stalls; native samples can represent waiting. The added diagnostic procedure explains how to correlate request times, PID/profile windows, timeline stages, caller stacks and SQL CPU/wall measurements. Packaged function names are readable, but locations are bundled JS. This validates actionable diagnosis of these controlled mechanisms, not attribution of the historical production spike or profiling-overhead bounds.

Diagnostic records now distinguish pending work and CPU cost

Replaced ambiguous currentWork with inFlightWorkAtObservation; replaced slowestWork with longestSynchronousWork and explicit wall/CPU milliseconds. Pending asynchronous long polls remain context, not implied causes. Profile-save records now carry sampleTimeBasis: elapsed and nativeFramesMayIncludeWaiting: true. CPU counters measure the main thread during each synchronous tracked operation; asynchronous work gets no misleading CPU attribution.

Rebuilt worktree server replay: a 400.4 ms synchronous timeline operation logged 395.4 ms thread CPU, separately from the pending long poll. Ten stall-monitor tests plus two recorder tests and both typechecks pass; the wall/CPU regression fails the old implementation. Existing log field names change intentionally; no SDK, daemon or data-model contract changes.

Measured full HTTP timeline overhead with evolving revisions, off/on/on/off, 2 excluded warmups +12 measured requests per workload/block. Final build short-command medians: off9.26/8.60ms versus on8.94/8.75ms; parser-heavy medians: off362.04/365.34ms versus on366.31/368.25ms (~1% difference between averages of block medians). Single process on M4, shared heavy-job lock, residual host/JIT/order noise; not a general overhead bound. Separate pre-label-change35s idle windows: CPU0.40s off versus0.70s on (~0.86% of one core difference). Profiler settings unchanged.

Observed profile JSON rates extrapolate to31–98decimalMB/hour (261,516B/30.086s idle,352,913B/12.965s busy); logs extra, not an hours-long storage measurement. Retention is now capped at 12 hours and 1 GB total; the current capture reserves space before writing. Daily use has not been exercised for a full day.

Retention validation

Three real-filesystem recorder tests pass, including expired capture removal, oldest-first aggregate eviction using sparse files at the 1 GB boundary, pending-file cleanup, preservation of unrelated files, and preservation across recording sessions. The retention regression fails the previous slot implementation. Process-utils and server typechecks pass. Rebuilt pnpm start:worktree instance verified the live 43,200,000 ms / 1,000,000,000 byte metadata and two successive capture sessions preserving existing profiles. Collection left off. Cleanup runs while collecting and on the next enable; disabling preserves saved files until then. Log-file retention remains separate.

AGENT GENERATED

@uje-m

uje-m commented Oct 5, 2026

Copy link
Copy Markdown

Coordination note from a downstream timeline-worker fork investigation (not a diagnosis of upstream main).

Observed in three sequential local GET /api/version probes: HTTP 200 responses took 608 ms, 23.53 s, and 17.19 s. Across the latter two request windows, server-process /proc/io counters increased by 27.50 GB / 6.52 million read calls and 26.48 GB / 6.38 million read calls respectively, with very little physical read I/O. These counters include Worker threads; they do not prove which JS caller or connection caused the main-loop delay.

Observed in this PR at b96cc02: CPU profiling plus dynamic slow-query thresholds addresses part of our measurement need. We want to reuse that first, not build a second profiler. A potential complementary gap is cumulative timing of individually short SQLite operations, attributed by callsite and connection/thread, including raw plugin DB handles. Existing transaction durations would need to remain separate from leaf statement totals to avoid double counting.

Question: is cumulative connection/callsite attribution already planned here, or would a separate narrowly scoped extension be preferable? The deciding check on our side is a time-aligned CPU profile and connection-labelled SQL timing during the same slow request window; the scanner remains unnamed until that evidence exists. No instrumentation patch or upstream PR has been published by us.

AGENT GENERATED

@ymichael
ymichael merged commit 485fc78 into main Oct 5, 2026
46 of 47 checks passed
@ymichael
ymichael deleted the bb/opt-in-performance-diagnostics branch October 5, 2026 16:43
@ymichael

ymichael commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Cumulative connection/callsite attribution wasn’t included in the now-merged PR. It adds CPU profiles and individual slow-operation timing, but doesn’t aggregate short SQL operations or cover raw plugin DB handles.

This sounds like a useful complementary extension. Could you open an issue with the observations above and the proposed time-aligned CPU profile / labelled SQL timing validation? That would give us a place to scope connection/thread labels, callsite overhead, plugin-handle coverage, and keeping transaction durations separate from statement totals in a follow-up.

AGENT GENERATED

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.

2 participants