Skip to content

fix(diagnostics): batch CPU profiles to avoid repeated startup stalls - #196422

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-cpuprofile-start-freeze-20260919
Nov 10, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-cpuprofile-start-freeze-20260919

Conversation

@steipete

@steipete steipete commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Repeated CPU profiling pauses a large Gateway once for every profile start, making consecutive production profiling windows expensive on Node 24.

User Impact

Operators can request diagnostics.cpuProfile with { "windows": 12, "windowMs": 5000 } to collect a set with one profiler start and stop. Empty params keep the existing five-second behavior. The caller must allow the whole batch to finish; no profiler remains active between requests.

Why This Change Was Made

The existing capture owner retains concurrency, cancellation, authority, redaction, and cleanup. A batch returns one standard profile plus windowBoundariesMicros, preserving signed sample deltas without duplicating the call graph. Requests allow 1–30 windows of 100–5000 ms, at most 150 seconds requested. Oversized batch responses retain the existing profile-too-large refusal and never replace the timeline with a summary.

Node 24 batches use the inspector's 10 ms interval because its native API ignores interval options. The first startup pause remains; subsequent windows need no restart. Node 26 keeps the shared native path. This is an additive RPC change with no protocol-version bump, config option, or database change.

Evidence

  • Regression confirmed red before implementation; 63 focused RPC/owner tests pass, covering busy behavior, signed-delta sample conservation, window continuity, bounds, and response refusal.
  • Runtime build, generated validators, native Swift/Kotlin protocol checks, 20 Chromium browser tests, and two Gateway recovery E2E cases pass.
  • Final Codex autoreview and ClawSweeper found no actionable findings on head 015b79a53f27566000a2b564294ca6650e6d4438.
  • Node 24.22.1 real dist Gateway: five alternating pairs plus two A/A sets, 89 valid captures and 12 busy probes. Median cumulative startup per 12-window set 4,886.62 → 416.34 ms; main-thread stalls ≥50 ms 4,921.09 → 407.46 ms; start/stop counts 12/12 → 1/1. Paired startup reductions were 91.23–91.87%, versus 2.32% A/A spread. Every batch had one measured stall; largest batch response was 66,202 bytes.
  • Thirty-second idle windows had zero profiler starts/stops. Main CPU was 1.2112% before and 0.3986% after; settling prevents treating that decrease as a causal overhead estimate. No persistent sampler was added.
  • pnpm check:changed exposed dead-export failures in untouched modules, reproduced on exact parent 1ebc46e1a52ff2b8828b6186e7b5ab943227c9ae. Source introductions/caller migrations are attributed; these are main regressions, not passing checks. The benchmark preload's typed-lint finding and protocol-registry export guard were corrected and their checks pass.

Handwritten production growth is 45 lines; generated validators add 32 net lines with mechanical predicate renumbering. The additive caller contract accounts for the growth. Tests add 92 lines with a matching allocation. No capture manager, cache, or persistent sampler was added.

The synthetic fixture had 10,800 sessions, 4,300 settled runs, 40 plugins, five WebSocket clients and four mock-model warmup runs. Its agent DB was 268 MB on macOS arm64/APFS, not a 35 GiB/btrfs qualification. Absolute startup magnitude is therefore not a production claim. Empty-call baseline and batch use the same candidate dist. Whole-set CPU savings also include Node 24's native-versus-10 ms inspector sampling difference. Allocation volume was not measured; heap/RSS are retained-memory measurements. All source/runtime hashes stayed unchanged, and the isolated Gateway was shut down cleanly.

CI has two session-test failures outside this change. The fork authorization-code mismatch reproduces on exact CI main parent a0ec2b5b4ba6532237705777a470a1d154cd1ccc and traces to #194129 preserving valid sharing facts while its older test still expects generic invalidation. The visible-spawn failure also reproduces on that exact main parent and traces to #196206 routing repository URLs through managed worktrees while the old test still expects direct-project rejection. Security Review passed on this exact head.

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T03:44:18.358221Z 015b79a PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts size: XL labels Nov 10, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 10, 2026
@clawsweeper

clawsweeper Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR adds bounded CPU-profile batches that share one profiler start and stop while preserving the existing empty-parameter behavior.

Example: An operator needs twelve consecutive five-second CPU profiling windows on Node 24.

  • Before: Twelve separate diagnostics.cpuProfile requests each start and stop the profiler.
  • After: One request with {"windows":12,"windowMs":5000} returns one profile and thirteen window boundaries after a single start and stop.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The patch is focused and source-consistent, but its promised real Gateway performance evidence is unfinished.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Operators collecting consecutive CPU profiles repeatedly pause a large Node 24 Gateway during profiler startup.
Reason: The maintainer-authored direction provides a focused diagnostic capability while retaining existing defaults and one capture owner.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it adds useful, owner-approved batching that current main lacks, and source review found no discrete introduced correctness defect.

Priority: P2
Reviewed head: 015b79a53f27566000a2b564294ca6650e6d4438

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Supply completed Node 24 batch-versus-single Gateway measurements and batch lifecycle output; the reported red-before-fix regression result is not independently shown.
Agent review details

How this fits together

The administrator diagnostics RPC validates capture parameters, passes caller authority and cancellation to the shared profiling owner, and returns a bounded, sanitized in-memory profile.

flowchart LR
  A[Administrator RPC caller] --> B[Diagnostics parameter validator]
  B --> C[Existing profile handler]
  C --> D[Shared capture lifecycle]
  D --> E[Runtime profiler]
  E --> F[Sanitized profile and window boundaries]
  F --> A
Loading

Technical review

Best possible solution:

Keep batching inside the existing capture owner, preserving empty-parameter behavior, native sample data, bounded responses, and caller-lifetime cleanup.

Do we have a high-confidence way to reproduce the issue?

Current main starts a separate capture for every empty-parameter request, so repeated profiler starts are source-verifiable; the Node 24 stall magnitude was not independently reproduced during this read-only review.

Is this the best way to solve the issue?

The smallest complete implementation extends the existing capture duration and returns boundaries over the unchanged sample timeline, avoiding duplicate graphs or another lifecycle owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 66c2b325e049.

Provenance checked

  • CPU capture backend changes intended behavior with a stated reason (ab21d37: Native profiling shares the Node 26 recorder's active sampler and code map to avoid another heap scan; the linked PR supplied real Gateway measurements.)
  • Oversized CPU profile handling changes intended behavior with a stated reason (08b1e57: Oversized ordinary captures return bounded hot-stack summaries so startup profiling remains useful; batch requests explicitly refuse that substitution because it would discard their timeline.)
  • Capture lifecycle and administrator diagnostics keeps the original intent (2e82124: Provide ephemeral, sanitized administrator CPU attribution without a debugger listener, with cancellation, cleanup, and bounded publication.)
  • Generated protocol validators keeps the original intent (f52fb07: Generate fixed-schema predicates ahead of runtime; the generated changes add the CPU parameter validator and mechanically renumber subsequent predicates.)

Testing

Proof path: unit tests only.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 4e06032 adds src/logging/diagnostic-cpu-profile.ts:24 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 4e0603284676; files: src/logging/diagnostic-cpu-profile.ts)
  • Vincent Koc: Raw commit 2e82124 adds src/logging/diagnostic-cpu-profile.ts:106 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2e82124af668; files: src/logging/diagnostic-cpu-profile.ts)

PR surface

Source +77, Tests +92, Docs +32, Other +318. Total +519 across 17 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 10 8453 8376 +77
Tests 2 94 2 +92
Docs 1 36 4 +32
Config 0 0 0 0
Generated 0 0 0 0
Other 4 320 2 +318
Total 17 8903 8384 +519

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Additive RPC parameters 2 optional integer parameters; maximum requested capture 150 seconds windows accepts 1–30 and windowMs accepts 100–5000; neither adds persisted configuration.
Handwritten production versus tests Runtime/protocol net +45 lines; tests net +92 lines The production growth adds the bounded caller contract within existing owners; tests cover parameter bounds, backend selection, timeline preservation, busy refusal, and oversized-batch rejection.

Labels

Label changes:

  • add P2: Reduces repeated profiling stalls during an administrator diagnostic workflow without changing ordinary captures or startup defaults.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Reduces repeated profiling stalls during an administrator diagnostic workflow without changing ordinary captures or startup defaults.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Classify the two failing session-test jobs using matching baseline failure evidence or a demonstrated diff-caused repair.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 9, 2026, 10:56 PM ET / November 10, 2026, 03:56 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Addressing the two evidence notes in the final-head review:

  1. Completed Gateway proof and red-before-fix result. On Node 24.22.1, five alternating 12-window pairs plus two A/A sets produced 89 valid profiles and 12 successful concurrent-busy assertions. Median cumulative startup was 4,886.62 → 416.34 ms, measured main-thread stalls ≥50 ms 4,921.09 → 407.46 ms, and starts/stops 12/12 → 1/1. Every batch had one stall, preserved all samples across 13 boundaries, and stayed below 1 MiB (largest: 66,202 bytes). A/A startup spread was 2.32%; paired reductions were 91.23–91.87%. Idle windows had zero profiler starts/stops; no persistent sampler remained. The owner is src/logging/diagnostic-cpu-profile.ts:158–183; boundaries and byte refusal are at :57–88, with signed-delta/conservation and busy tests at src/logging/diagnostic-cpu-profile.test.ts:146–208. Before the implementation, the new RPC admission case at src/gateway/server-methods/diagnostics.cpu-profile.test.ts:98 failed with Number of calls: 0 (1 failed, 23 passed). Afterward, all 63 focused cases pass. The PR body now includes the complete measurements and their limits: 268 MB synthetic DB on macOS/APFS, not full 35 GiB/btrfs qualification; allocation volume unmeasured; active CPU savings also include the Node 24 sampling-interval difference.

  2. Both failed CI jobs are reproduced and attributed on the exact tested main parent. Run 42751096193 attempt 1 checked merge aee9ce47198c3e562fe85ee3eda156924bd2470d, whose parents are main a0ec2b5b4ba6532237705777a470a1d154cd1ccc and this PR head. Both exact failing cases reproduce unchanged on that main parent. sessions-rewind.storage.test.ts:792 expects the generic authorization-change code after public membership removal; fix(gateway): shared-session runs lose access after session list updates #194129 (d53921ac1424) deliberately preserves prepared facts across broad notifications at session-sharing-preparation.ts:200–213, so the owner now returns the concrete participation-required code. server.sessions.create-worktree-spawn.test.ts:307 expects the former direct-project sandbox-failure state; fix: keep project session scratch out of shared clones #196206 (97e91a16d636) routes pending project URLs through managed worktree preparation at server-methods/session-create-project.ts:416–418, leaving that expectation stale. These owner/test inputs are unchanged in the tested PR merge. They are reported as main regressions, not relabeled green. Independent security-fast and Security Review passed.

The reviewed head remains 015b79a53f27566000a2b564294ca6650e6d4438; no code changed after the review. There were zero unchecked items in the review. @clawsweeper re-review

@steipete
steipete merged commit 9cebce4 into main Nov 10, 2026
164 of 172 checks passed
@steipete
steipete deleted the steipete/perf-micro-cpuprofile-start-freeze-20260919 branch November 10, 2026 04:17
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant