Skip to content

nsolid Phase 2: profiles, redacted snapshots, blocked loops, loop and GC metrics - #4

Open
edsadr wants to merge 4 commits into
claude/nsolid-p1-1-transportfrom
claude/nsolid-p2-diagnose
Open

edsadr wants to merge 4 commits into
claude/nsolid-p1-1-transportfrom
claude/nsolid-p2-diagnose

Conversation

@edsadr

@edsadr edsadr commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Phase 2 of nsolid-bun, the third PR of the stack:

  1. nsolid: Phase 0, an N|Solid agent that the Console can see and drive #1 Phase 0 (base: main)
  2. nsolid Phase 1: the agent a Console can rely on #2 Phase 1 (base: the Phase 0 branch)
  3. This PR, Phase 2 (base: the Phase 1 branch)
  4. nsolid Phase 3: traces, logs, source code, continuous profiles, HTTP/DNS and handle metrics #5 Phase 3 (base: this PR's branch)

Phase 2 makes a Bun process diagnosable from the N|Solid Console: CPU profiles and heap snapshots on demand for any thread, GC and event-loop metrics, and blocked-loop events with the stack that blocked. The Console-side Phase 2 work is in the Console repository, in a draft pull request of its own.

Phase 2 items

  • Layer 1: event-loop and GC metrics per thread, and perf_hooks.eventLoopUtilization()
  • Layer 2: the profile command, through JSC's VM trap, with (idle), (program) and (garbage collector) samples
  • Layer 3: the snapshot command: our own V8-format builder, redacted, chunked, with a memory guard
  • Layer 4: blocked-loop events with the blocked thread's stack
  • Layer 5: the nsolid module, part 2: profile, profileEnd, snapshot, the asset toggles
  • Layer 6: exit reports for crashes and aborts
  • InfoBody carries the runtime and the agent's capabilities

Rebased on 2026-12-04 onto main at 6cab274, which brings in oven-sh/bun at 39b4945. The commit SHAs in this description are the rebased ones. What the rebase changed here: upstream moved us_loop_run_bun_tick into loop.c, around one us_internal_loop_wait for epoll, kqueue and IOCP, so the loop timing moved there with it; and WebKit's String has no utf8() now, so the snapshot writer calls makeUTF8CString.

What does this PR do?

Loop timing and eventLoopUtilization (commit 124cf10)

  • usockets records, per JavaScript thread, when its loop waits in the poll and for how long, the events each poll returns, and the iterations. Only the thread writes them; the agent reads them with atomic loads.
  • A hook, unset unless the agent runs, is called at the start of each outermost tick.
  • perf_hooks: nodeTiming.loopStart and nodeTiming.idleTime are the loop's, and eventLoopUtilization() is Node's (v26.3.0). Before, it returned zeros. On the same script it now reads within a few percent of Node.

The agent's Phase 2 (commit 94348a2)

  • Metrics (layer 1), per thread, with N|Solid's names and formulas:
    • the loop: loopIdleTime, loopIterations, loopIterWithEvents, eventsProcessed, eventsWaiting, providerDelay, processingDelay, loopUtilization, loopIdlePercent, loopAvgTasks, loopEstimatedLag, res5s to res15m;
    • GC: gcCount, gcForcedCount, gcFullCount, gcMajorCount, and gcDurUs (median and 99th percentile of the last 1,000 collections).
    • gcDurUs is each collection's wall time, from JSC's start to its end (decision P2-5), not the pause N|Solid measures.
  • CPU profiles (layer 2):
    • Started and stopped through JSC's shell-timeout trap, so a thread busy in JS answers at once (P2-3).
    • JSC samples a thread only while it runs JS. Gaps are filled at the sampling interval: (idle) where the loop waited, (garbage collector) where it collected, (program) elsewhere. A mostly idle process shows mostly (idle).
    • N|Solid's errors in N|Solid's order: 1008 assets disabled, 409 in progress (or --cpu-prof holds the profiler), 410 no such thread, 1003 failure.
    • A profile running when the process exits is sent, and the exit names it.
  • Heap snapshots (layer 3, P2-1 and P2-2):
    • A new builder, NSolidHeapSnapshot.cpp, on JSC's public HeapAnalyzer interface. It writes V8's format with V8's node types, snapshot first and strings last, as the Console's scanner requires.
    • With redaction, which the Console always asks for, string nodes are named (redacted), as N|Solid's are. Regexp sources are left out too.
    • It writes 1 MiB chunks, never one string.
    • It refuses with 1005 when the estimate is over half the memory left (MemAvailable, or the cgroup limit). The estimate is 320 bytes per heap cell; a snapshot of 1.2 million cells added 234 bytes per cell to the peak RSS.
    • Errors: 1008, 1004 (NSOLID_DISABLE_SNAPSHOTS), 409, 410, 1005.
  • Blocked loops (layer 4):
    • A 100 ms watchdog on the agent's thread finds a loop out of its poll for blockedLoopThreshold ms (default 200, NSOLID_BLOCKED_LOOP_THRESHOLD, reconfigure).
    • ExportBlockedLoop carries the thread's stack, taken through the VM trap: script frames only, up to 100, 1-based and source-mapped as Error.stack is.
    • ExportUnblockedLoop follows when the loop iterates again, with that iteration's length. One pair per episode.
    • A thread blocked outside JS (a synchronous native call) gets its event with an empty stack after 1 s, where N|Solid sends none (P2-4). The plan said 100 ms; on the debug build the trap round trip took 70 to 145 ms, so the wait is 1 s.
  • The nsolid module, part 2 (layer 5): profile(timeout = 600000, cb), profileEnd(cb), snapshot(cb), enableAssets(), disableAssets(), with N|Solid's signatures, messages and status codes. The agent sends the assets with metadata reason: "Agent API". heapProfile and heapSampling answer 404. start() and the asset toggles now update nsolid.config at once.
  • Crash exits (layer 6, P2-6):
    • The crash handler calls a hook in bun_core once only one thread is left reporting.
    • The hook hands the reason and trace string to Phase 1's signal reporter, which sends ExportExit with the signal (SIGSEGV, SIGABRT, ...) and the error, and acknowledges. The wait is 6 s at most.
    • A crash of the agent's own thread can't be reported.
  • Info: runtime (bun, its version, jsc, the agent's version) and capabilities (the commands and settings the agent supports), the proposed fields 18 and 19.

Fixes from CI (commits 7457466 and 17aa8ad)

  • CI's release build crashed (a null address) in the main-thread snapshot test, which the debug build never did.
  • The builder kept each edge's property or variable name as the raw pointer the collector handed it, which is only sure to live through the call. It read the name only after the collection, while allocations sweep the heap. Each edge now holds its name, as JSC's own V8 snapshot builder does (17aa8ad).
  • 7457466 names plain objects only when they have a realm, and declares the crash hook on Unix only.

How did you verify your code works?

  • bun bd test test/js/bun/nsolid/nsolid-agent.test.ts: all 42 tests pass on the debug build, with the whole file running concurrently (37 s). The 15 new ones cover:

    • loop and GC metrics over OTLP;
    • profiles of the main thread, a worker and a thread busy in JS, and their errors, --cpu-prof, and the exit;
    • snapshots: a string planted in the heap is absent once redacted and present otherwise, the V8 format checks out, chunks, a worker's heap, and the errors;
    • blocked loops: a threshold set by reconfigure is honored, a block under it sends nothing, and the main thread's and a worker's stacks name the function and line;
    • a loop blocked in native code, with an empty stack;
    • the module's profile, profileEnd and snapshot, with and without an agent;
    • exits by segfault and by panic.
  • bun bd test test/js/node/perf_hooks/perf_hooks.test.ts: the new eventLoopUtilization test passes. "net entries are instanceof PerformanceEntry" fails here because this container has no IPv6; it is unrelated.

  • Driven with -e: eventLoopUtilization reads idle 233 ms, active 108 ms on a script where Node reads 249 ms and 101 ms.

  • The bun-types test passes, except the bindgen check, which needs WebKit's code generators that this container doesn't have.

  • Against a local N|Solid Console, with this debug binary and the Console's Bun end-to-end suite: all 10 tests pass. The Console:

    • lists the process as Bun on JavaScriptCore, and takes its settings, metrics, info and packages;
    • analyzes a CPU profile of the main thread, with (idle) labeled as JavaScriptCore's;
    • downloads a heap snapshot without the secret the app keeps, and summarizes it by class;
    • stores a blocked loop with the stack of the demo's blocking function, then its end;
    • fires a loop_blocked rule grouped by agent, whose profile diagnostic completes and is linked from the alert;
    • charts GC and event-loop metrics for the main thread, and records the exit.

    The first run had one failure, a race in the Console's test (it read the alert before the diagnostic was added to it). Fixed there.

  • 64fee75, before the rebase: the snapshot tests pass on the debug build. The release crash is not reproduced locally (a release build does not fit this machine), so this PR's Linux x64 check is what confirms it.

Not done here:

  • clippy and mordant didn't run locally (no disk room for a second Rust target); CI runs them.
  • The memory guard has no test: nothing here can make the memory left small enough.

After the rebase: every check passes at 17aa8ad, and bun bd test test/js/bun/nsolid/nsolid-agent.test.ts passes on the debug build.


Generated by Claude Code

@ns-control-tower

Copy link
Copy Markdown

ns-control-tower

Note

Reviewing the latest changes on this PR — this may take a few minutes.
This comment will be updated in place with the findings; no other top-level comments will be posted.

…on from it

usockets records, per JavaScript thread, when its loop waits in the poll and
for how long, how many events each poll returns, and how many iterations the
loop has run. Only the thread writes these; other threads read them with
atomic loads. A hook, unset unless the N|Solid agent runs, is called at the
start of each outermost tick.

perf_hooks uses them: nodeTiming.loopStart and nodeTiming.idleTime are the
loop's, and eventLoopUtilization() is Node's (v26.3.0), where it returned
zeros before. On the same script it now reads within a few percent of Node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013nEe5T77UhAYmQxqQRbPpR
…d GC metrics, crash exits

Phase 2 of the agent: a Bun process can be diagnosed from the N|Solid
Console.

- Event loop and GC metrics, per thread, as N|Solid defines them:
  loopIdleTime, loopIterations, loopIterWithEvents, eventsProcessed,
  eventsWaiting, providerDelay, processingDelay, loopUtilization,
  loopIdlePercent, loopAvgTasks, loopEstimatedLag, res5s to res15m, and
  gcCount, gcForcedCount, gcFullCount, gcMajorCount and gcDurUs (wall time of
  each collection; median and 99th percentile of the last 1,000).
- The `profile` command: a CPU profile of any thread, started and stopped
  through JSC's shell-timeout trap, so a thread busy in JS answers at once.
  Gaps between samples are filled with (idle) where the loop waited,
  (garbage collector) where it collected, and (program) elsewhere. A profile
  running when the process exits is sent, and the exit names it.
- The `snapshot` command: a heap snapshot in V8's format from our own builder
  on JSC's HeapAnalyzer interface. With redaction, which the Console always
  asks for, string nodes are named "(redacted)". It is written in 1 MiB
  chunks, and refused with N|Solid's 1005 when it would take more than half
  of the memory left (measured at about 240 bytes per heap cell).
- Blocked loops: a 100 ms watchdog sends loop_blocked past
  blockedLoopThreshold with the thread's stack (source-mapped, 100 frames),
  then loop_unblocked with the iteration's length. A thread blocked outside
  JavaScript gets its event with an empty stack after 1 s, where N|Solid
  sends none.
- nsolid.profile(), profileEnd(), snapshot(), enableAssets() and
  disableAssets() with N|Solid's signatures and status codes; heapProfile
  and heapSampling answer 404.
- Crash exits: a segfault, abort or panic sends ExportExit with the signal,
  the crash's reason and its trace string, through the signal reporter.
- Info carries the runtime and the commands and settings the agent supports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013nEe5T77UhAYmQxqQRbPpR
…re the crash hook on Unix only

The release build crashed (a null address) taking the snapshot in the
redaction test, which the debug build passes. The builder asked JSC for a
constructor name of every object, through each one's property lookup. Bun's
own V8 builder does that only for plain objects with a realm; other objects,
and closures compiled ahead of time, are named after their class. The builder
now does the same, and skips edges JSC reports with no target or no name.

Bun__NSolid__recordCrash is only called on Unix: declared everywhere, it was
dead code on Windows, which mordant checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013nEe5T77UhAYmQxqQRbPpR
…ntil the snapshot is written

The collector hands the analyzer a property's or a variable's name that is
only sure to live through the call. The snapshot is written after the
collection, while allocations sweep the heap, and a name whose last holder
was swept could be gone by then. Each edge now holds its name, as JSC's own
V8 snapshot builder does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013nEe5T77UhAYmQxqQRbPpR
@edsadr
edsadr force-pushed the claude/nsolid-p2-diagnose branch from 64fee75 to c61d906 Compare December 4, 2026 14:57
@edsadr
edsadr force-pushed the claude/nsolid-p2-diagnose branch from c61d906 to 17aa8ad Compare December 4, 2026 15:09
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.

3 participants