Repository navigation
Add opt-in server CPU profiles and performance diagnostics - #4751
Conversation
|
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.
|
|
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.
|
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
performanceDiagnosticsexperiment. Addpnpm start --perf-diagnostics,pnpm start:worktree --perf-diagnostics, and the equivalentbb-appflag /BB_PERF_DIAGNOSTICS=1startup 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 explicitperformanceDiagnosticsAvailablefield in/system/config(independent of the persisted experiment value). The experiment is changed live in Settings → Experiments, withbb 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.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.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
start-server.tsdirect 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
158bc08635has 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-diagnosticsserver at 158bc08, with real HTTP requests and recorder output, in the fresh isolated QA store. This supplements the earlier collection smoke test.parseShellCommandIntents → splitShellCommandSegments → tokenizeShellWords; inclusive parser samples 597/1,058 non-idle samples. Independent health probe max 404.36 ms corroborated blocking.runsamples 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:
currentWorkcan 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
currentWorkwithinFlightWorkAtObservation; replacedslowestWorkwithlongestSynchronousWorkand explicit wall/CPU milliseconds. Pending asynchronous long polls remain context, not implied causes. Profile-save records now carrysampleTimeBasis: elapsedandnativeFramesMayIncludeWaiting: 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:worktreeinstance 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.