Skip to content

perf(gateway): capture main-thread stall stack samples - #169535

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-stall-flight-recorder-20260919
Oct 12, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-stall-flight-recorder-20260919

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Main-thread stalls longer than one second can report task=unattributed with no stack evidence, making intermittent stalls difficult to investigate after they end.

User Impact

Operators get code-owned callback labels and, on Node 26, a bounded trailing CPU sample window naming the top inclusive frames. This does not change request handling or configuration. Node 24 and Bun retain callback attribution; their native profiling APIs do not provide the bounded coarse-sampling contract used here. The next normal Gateway deployment enables recording; no live Gateway was changed for this work.

Why This Change Was Made

The event-loop monitor owns recording and cleanup. It samples at 10 ms and rotates five-second native profiles, starting the next before stopping the previous so V8 keeps its sampler and code map alive. A single capped profile is insufficient: V8 discards new samples after its cap. Two bounded retained windows feed one sanitized diagnostic line when a stall occurs. That line explicitly represents a trailing window, because several callbacks can finish before the monitor drains its records.

Callback labels reuse the existing main-thread task owner at worker/control-port and SQLite reply decoding, HTTP/WebSocket/RPC dispatch, scheduler wakes, and config/skills watcher boundaries. Dependency-native work can remain unlabelled; the recorder provides stack evidence when V8 can symbolize it.

Production LOC: +192. The requested recorder is new diagnostic capability, with native lifecycle, bounded retention, redaction, and aggregation contracts. Existing attribution and frame-redaction owners are reused; there is no superseded recorder implementation to remove. No schema, persistent state, new dependency, or configuration option was added.

Evidence

Independent review: clean after correcting an initial finding about associating a batch's trailing samples with an individual callback.

Linux rig, Node 26.8.1, three alternating eight-second baseline/recording pairs with 5 ms of synchronous work per 20 ms tick: mean process CPU 25.24% → 25.89% (+0.66 percentage points of one core; +2.6% relative to this 25% load). Maximum initial start 64.5 ms; maximum rotation 0.31 ms.

An unlabelled setImmediate callback blocked for 1,500.14 ms. The recorder named syntheticUnnamedStall in 142 of 146 samples; serializing and summarizing took 3.6 ms and emitted 436 bytes. This used the real native V8 profiler and the production recorder. An initial run exposed V8's numeric script IDs; the adapter and regression fixture now reflect the native format.

Validation on the approved Linux rig: 408 tests across 27 files passed; one Windows-only test/file was skipped. Focused recorder/core/logging: 106 tests (70.42s wrapper); siblings: 167 tests (182.77s); export-collision guard passed; closure/PR-wrapper/test-plan guards: 135 tests (161.81s). The new recorder file executes in 37ms; the existing HTTP case with the new assertion executes in 716ms. Cold type/worker compilation accounts for the longer wrapper times.

Regression negative control: the HTTP test fails on the original handler at the new task-label assertion, then the patched source is restored and all 17 file hashes match.

The staged gate passed all type checks (core 78.07s, core-test shards 2640.05s) and failed only at the repository-wide dead-export audit. Re-running that exact audit on unchanged current main (656287c940a5287da9efe69aabde2348695e07e1) also fails: all 84 candidate findings are present in the baseline; zero findings involve this diff. The completion run uses the existing OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1 switch for that verified inherited audit. After a mechanical toSorted() lint fix, the owning changed-file format/lint plan passed (0 warnings/errors across 16 linted files), and all six recorder tests passed again. All remaining staged-gate checks are satisfied. No production Gateway was touched.

Remote setup attempts: Blacksmith Testbox tbx_01m4phcw069kxj7sw7765cm0vk failed source sync; AWS cbx_ff8718722459 lost workspace ownership during tests; Hetzner cbx_b5b3a9b1a2ef reached verified source but lacked pnpm on its bare image. All leases were stopped. The approved rig supplied the completed proof.

CI on exact head 1b4f4adf1a1129b16edc426d9590d41e6edadd09 failed only eager-import-closure.test.ts because the existing wrapper inventory duplicates src/chat/sender-identity.ts, src/sessions/input-provenance.ts, and src/sessions/user-turn-transcript.metadata.ts. Unchanged main parent d8d441f71b3c56639044912d3c55dca0768c48b2 reproduces the same failure (16 tests passed, 1 failed, 31.94s wall). The inventory and test are unchanged in the actual CI baseline 053dbe94df70aef67aa4e7c790933f8742869b35; the tested merge is 4ab369168208e18a7c730c81e5896a306b2d83a8. The successful fail-fast monitor cancelled sibling CI jobs; those cancellations are not claimed as passing coverage. Run: https://github.com/openclaw/openclaw/actions/runs/38195006595 . No CI rerun requested.

Name worker, HTTP, WebSocket, RPC, scheduler, and watcher callbacks. Retain bounded coarse V8 profile windows for stalls on Node 26, with shared frame redaction and monitor-owned cleanup.

Rig proof: 1500 ms unnamed callback identified; +0.66 CPU percentage points, 0.31 ms maximum rotation. Focused and sibling proof: 408 tests passed. Dead-export audit failures reproduced unchanged on main; all candidate findings are inherited.
@clawsweeper

clawsweeper Bot commented Oct 12, 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.

@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 1b4f4adf1a1129b16edc426d9590d41e6edadd09
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/server-http.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server/ws-connection/message-handler.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server/ws-connection/request-diagnostics.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server/ws-connection/request-start.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR adds callback labels and trailing Node 26 CPU stack samples to Gateway stall logs.

Example: An unnamed callback blocks the main thread for 1,500 ms on Node 26.

  • Before: The Gateway can report an unattributed stall without stack evidence.
  • After: A trailing profile summary can identify the blocking function; the supplied native probe identified syntheticUnnamedStall in 142 of 146 samples.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, coherent code with native recorder evidence and meaningful contract tests supports limited end-to-end confidence.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its body supplies a real Node 26 production-recorder probe, while the complete shipped Gateway logging flow remains unshown.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: Operators cannot identify intermittent main-thread stalls after they finish when callback attribution is unavailable.
Reason: The area owner's direction is established, the capability is distinct from existing profiling, and the supplied measurements support its operating cost.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR adds useful stall diagnostics absent from current main, and no actionable patch defect was found.

Priority: P2
Reviewed head: 1b4f4adf1a1129b16edc426d9590d41e6edadd09

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied native recorder probe does not exercise the complete shipped Gateway stall-to-log path.
Agent review details

How this fits together

The Gateway event-loop monitor combines callback timing with native CPU samples and emits sanitized diagnostic logs alongside existing health observations.

flowchart TD
  A[Gateway callbacks] --> B[Task attribution]
  C[Native V8 samples] --> D[Rotating recorder]
  B --> E[Event loop monitor]
  D --> E
  E --> F[Sanitized stall logs]
Loading

Technical review

Best possible solution:

Retain the monitor-owned recorder, existing callback attribution owner, and shared frame-redaction policy.

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

Current main can emit unattributed stall warnings without retained stack samples, and the supplied native probe demonstrates the requested diagnostic capability.

Is this the best way to solve the issue?

The implementation fits the existing monitoring boundary, preserves dispatch decisions, and explains why rotating capped recordings replace neither callback attribution nor on-demand profiling.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 16d913005f97.

Provenance checked

  • Callback attribution across Gateway, worker, and scheduler boundaries keeps the original intent (48b4bcb: perf(sqlite): keep transcript admission outside writer locks #168801 established one callback-attribution owner that measures synchronous execution without counting I/O waits; the new labels reuse it.)
  • Config and skills watcher callbacks keeps the original intent (52992fb: refactor: use fs-safe for file watching and preserve Doctor plugin captures #159226 consolidated filesystem observation; the wrappers preserve invalidation, readiness, recovery, and retirement decisions.)
  • Shared profiling conflict and frame-redaction policy keeps the original intent (1ac96c7: Earlier profiling work documented native start pauses and rejected growing continuous recordings; this PR explains its bounded rotating alternative while retaining existing on-demand behavior.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Introduced change and current-main gap: The pinned introduced diff adds the recorder and monitor integration; fetched main retains callback stall warnings without retained CPU stack samples. (src/gateway/server/event-loop-health.ts:295, 1b4f4adf1a11)
  • Recorder lifecycle and privacy: Rotation starts the replacement before stopping the previous profile, retained JSON is capped, frame summaries reuse the existing sanitizer, and monitor shutdown disposes recording. (src/logging/diagnostic-stall-flight-recorder.ts:76, 1b4f4adf1a11)
  • Direct native runtime dependency: The patch directly invokes Node's V8 profiling API, establishing the dependency-contract signal. Node 26.8.1 source confirms millisecond sampling options, sample-count limits, independently identified profile handles, and disposal through stop; its repository policy was also read. (lib/internal/v8/cpu_profiler.js:19, 7be6d3af31a6)
  • Supplied native behavior and accepted operating cost: The complete PR body reports a Linux Node 26.8.1 production-recorder probe and alternating baseline/recording measurements showing 0.66 percentage points additional CPU usage. The area owner's PR explicitly adopts this diagnostic capability and distinguishes the probe from a deployed Gateway run. (1b4f4adf1a11)
  • Inherited CI failure: The wrapper inventory already contains the three duplicate paths named by the failing closure assertion and is unchanged between the original parent and CI base. fix(doctor): update rehearsal fails on installs with no configured agents #169516 independently records the same failure on clean main. Cancelled checks are not passing coverage. (scripts/pr-lib/wrapper-components.txt:347, d8d441f71b3c)
  • Policy, ownership, and inspection limits: Root, Gateway, and docs AGENTS.md policies were read and applied; no maintainer-notes directory exists. Prior merged history establishes the author's diagnostic-area ownership. Some historical blobs were unavailable, and CI log redirects were blocked by the host allowlist; current source, commit metadata, and related PR evidence remained available. (AGENTS.md:1, 1b4f4adf1a11)

Likely related people:

  • Peter Steinberger: Raw commit 48b4bcb adds src/gateway/server/event-loop-health.ts:14 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 48b4bcb866fb; files: src/gateway/server/event-loop-health.ts)
  • Vincent Koc: Raw commit 75ba839 adds src/gateway/server/event-loop-health.ts:3 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 75ba8398f939; files: src/gateway/server/event-loop-health.ts)

PR surface

Source +192, Tests +166, Docs +18. Total +376 across 17 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 14 325 133 +192
Tests 2 167 1 +166
Docs 1 18 0 +18
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 17 510 134 +376

Review metrics

Metric Value Why it matters
Production versus tests Production +325/-133, net +192; tests +167/-1, net +166 Production growth implements native recording, lifecycle, and aggregation; tests protect rotation, cleanup, privacy, failure handling, and HTTP attribution.

Labels

Label changes:

  • add P2: Useful operational diagnostics with limited blast radius and no demonstrated urgent runtime regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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: Useful operational diagnostics with limited blast radius and no demonstrated urgent runtime regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-12T02:20:12.954Z sha 1b4f4ad :: needs maintainer review before merge. :: none

Reviewed October 11, 2026, 11:04 PM ET / October 12, 2026, 03:04 UTC (Revision 2).

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@steipete
steipete merged commit abfd6a2 into main Oct 12, 2026
104 of 151 checks passed
@steipete
steipete deleted the steipete/perf-micro-stall-flight-recorder-20260919 branch October 12, 2026 03:07
@steipete

Copy link
Copy Markdown
Contributor Author

Merged at the reviewed head 1b4f4adf1a1129b16edc426d9590d41e6edadd09 under the authorized inherited-failure exception.

CI run https://github.com/openclaw/openclaw/actions/runs/38195006595 failed only the existing eager-import-closure.test.ts inventory assertion: duplicate src/chat/sender-identity.ts, src/sessions/input-provenance.ts, and src/sessions/user-turn-transcript.metadata.ts entries. The identical test fails on unchanged main parent d8d441f71b3c56639044912d3c55dca0768c48b2 (16 passed, 1 failed). The inventory and test are unchanged in the CI baseline 053dbe94df70aef67aa4e7c790933f8742869b35; the same-head fail-fast monitor caused the cancelled sibling jobs. No CI rerun was requested, and those cancellations are not passing coverage.

Independent review found no actionable issues. Rig proof passed 408 tests, the final format/lint checks, and the type checks. The separate global dead-export audit was also qualified against unchanged main: all 84 candidate findings are inherited, with none in the changed files. The native merge wrapper refused its stale local tsx installation before a merge attempt, so the authorized SHA-pinned REST squash route was used.

Native capture identified the unnamed 1.5-second stall in 142 of 146 samples. Measured recording overhead was +0.66 CPU percentage points, with 0.31 ms maximum rotation and 3.6 ms capture/summary. No production Gateway was changed or restarted.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
Name worker, HTTP, WebSocket, RPC, scheduler, and watcher callbacks. Retain bounded coarse V8 profile windows for stalls on Node 26, with shared frame redaction and monitor-owned cleanup.

Rig proof: 1500 ms unnamed callback identified; +0.66 CPU percentage points, 0.31 ms maximum rotation. Focused and sibling proof: 408 tests passed. Dead-export audit failures reproduced unchanged on main; all candidate findings are inherited.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-sensitive-changed size: L 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