Skip to content

Report async work to the dependency graph - #240

Merged
Domiii merged 2 commits into
dominik/node-dg-v8from
dominik/node-dg-async
Nov 17, 2026
Merged

Domiii merged 2 commits into
dominik/node-dg-v8from
dominik/node-dg-async

Conversation

@Domiii

@Domiii Domiii commented Nov 17, 2026 •

Copy link
Copy Markdown

🤖

Summary

  • Problem: node's async work is not in the dependency graph.
    • Async work here means I/O callbacks, timers, setImmediate, process.nextTick and queueMicrotask.
    • A dependency chain stops at the first callback boundary.
    • Example: the chain after await fetch() cannot reach the socket read, nor the main script.
  • This enables dependency chains across node's async boundaries, back to the main script.
  • Solution: report every async_hooks op.
    • The op's init adds a node.
    • Each of its callbacks runs in an execution of that op.
    • One choke point per side covers every op.
  • node#239 provides the dependency graph API, the gates and the promise reporting.

Model: async_hooks

  • Async op: a resource with an async id, created at init.
  • Callback window: each callback of an op runs between push_async_context(id) and pop_async_context(id).
    • These push and pop AsyncHooks' async id stack.
  • Native callbacks reach the window through InternalCallbackScope.
    • MakeCallback, CallbackScope and N-API callbacks use it.
  • JS callbacks reach the window through emitBefore and emitAfter.
    • These are pushAsyncContext and popAsyncContext.
    • Timers, immediates, ticks and AsyncResource#runInAsyncScope use them.
  • So: init sites plus the stack's push, pop and clear see every op and every callback.

Op classes

  • The init site chooses a class, AsyncOp. The class decides the kinds.
  • Timers and microtasks reuse the kinds Chromium reports.
    • So the existing analysis applies to them, including timer delays in limiting-path analysis.
class init sites init node callback node edge
kGeneric all other inits asyncInit{type} asyncCallback scheduler
kTimer Timeout timerScheduled{duration, singleShot} timerFired baseTimer
kMicrotask queueMicrotask enqueueMicrotask runMicrotask scheduler
kScript id 1, the main script marker{ExecuteScript, StartExecution} the init node itself none
  • type is the async_hooks provider type, e.g. TCPWRAP.
  • The kScript marker is the root of every chain.
    • It is created after the first checkpoint.
    • Its window is inside the {1, 0} callback scope of StartExecution.
  • The last init of an id wins.
  • A destroy removes the op.
  • Ids without an init get no window.
    • Id 0 belongs to timer, immediate and platform scopes. Their per-item windows carry the graph.
    • PROMISE ids exist only with async_hooks promise tracking. node#239 covers promises.

Sites

  • AsyncWrap::EmitAsyncInit, before the no-init-hooks return
    • Every native op is initialized here: AsyncReset, node::EmitAsyncInit, N-API async contexts.
    • So it adds the kGeneric init node.
  • AsyncWrap::EmitDestroy, and JS emitDestroyScript after the invalid id return
    • All destroys pass here, also without destroy hooks.
    • So the op is removed and the op map stays bounded.
  • AsyncHooks::push_async_context, pop_async_context, clear_async_id_stack, and JS pushAsyncContext, popAsyncContext
    • Every callback window starts and ends here.
    • The JS calls are placed after the paths that fall back to C++. So no window is reported twice.
  • JS init sites: Timeout and insertGuarded, Immediate, nextTick, AsyncResource
    • These are all JS callers of newAsyncId that create a resource.
  • StartExecution, after the first checkpoint
    • Id 1 has no init.
    • So the root marker is added here.

Balance

  • Windows mirror the async id stack by slot.
  • A window saves the execution depth when it begins.
  • Shrinking the stack unwinds to the lowest saved depth of the removed slots.
    • This also ends executions whose end was skipped.
    • Example: a termination that escapes a promise reaction job.
    • Example: clearAsyncIdStack after a fatal exception drops windows without popping them.
  • A push first unwinds stale slots at or above its own slot.

queueMicrotask while recording

  • The fast path enqueues the callback without an async id. Without an id, there is no op and no node.
  • The existing slow path creates AsyncResource('Microtask').
    • node takes it whenever AsyncLocalStorage or async hooks are in use.
  • While instrumented, the slow path is taken as well.
    • An internal options object marks the resource as kMicrotask.
      • It is compared by identity. No property of user options is read.
  • Effects in recordings, the same as with AsyncLocalStorage in use:
    • One more async id per microtask. Later asyncId values shift.
    • One AsyncResource and one bound function per microtask.
    • runMicrotask and runInAsyncScope frames appear in error stacks.
    • Exceptions still reach the microtask error reporting.
  • Unrecorded runs keep the fast path.

Gates

  • JS gate: a boolean in internal/async_hooks.
    • prepareExecution sets it from DependencyGraphInstrumented().
      • So it is not part of the startup snapshot.
    • Unrecorded runs, workers and ShadowRealms: false. JS makes 0 binding calls.
    • The value is recorded. So JS takes the same paths when recording and replaying.
    • Every binding result JS sees is the same when recording and replaying.
    • Timer fields are read only while instrumented.
      • Legacy enrolled timers are user objects.
  • C++ gate: DependencyGraphEnabled().
    • Every method returns before any work unless it is true.
    • So nodes, edges, JSON and the op map exist only when replaying.

Coverage

  • Covered: native ops, N-API, MakeCallback, timers, immediates, ticks, AsyncResource, queueMicrotask.
  • Model limits:
    • A handle's callbacks are scheduled by the handle's init, not by the readStart or write that caused them.
    • timeout.refresh() keeps the original timerScheduled node.
    • triggerAsyncId is not an edge.
  • Deferred to a follow-up: EventEmitter#emit and EventTarget#dispatchEvent, as dispatchEvent executions.

Data

  • Recording overhead, build linux-node-20261117-57ad6a5448fc-ebf9f47bec04-dev (BK runtime-node-build-and-test RFC: Remove Ryan's Freelist feature nodejs/node#569).
    • Benchmark: 1e6 await, 1e5 queueMicrotask, 1e5 nextTick, 1e4 setImmediate, 1e4 fs.stat, recorded.
    • Medians of 3 runs, ms:
build wall await queueMicrotask nextTick setImmediate fs.stat
nodejs#569 874 411 32 24 69 232
nodejs#569, RECORD_REPLAY_DISABLE_FEATURES=["dependency-graph"] 810 393 7 21 67 230
main nodejs#554, other driver pin 825 402 6 19 66 233
  • The feature-off row is the clean comparison.
    • It is the same binary and driver.
  • Cost, as rate × scale:
    • queueMicrotask: about 0.25 µs more per microtask, from the slow path.
    • nextTick: about 30 ns more per tick.
    • setImmediate and fs.stat: within noise.
    • Total for this benchmark: +8% wall time.
  • The node-core UnboundSymbol crash in statfs is fixed upstream by backend af54141a7e (Eslint 4.1.0 nodejs/node#13895). This PR's REPLAY_BACKEND_REV contains that fix.

Merge order

  • node#239 merges first, then this PR.
  • This PR pins REPLAY_BACKEND_REV to the backend master commit that contains backend#13900.

@Domiii
Domiii added this pull request to stack #241 November 17, 2026 13:14
@Domiii Domiii self-assigned this Nov 17, 2026
@Domiii
Domiii force-pushed the dominik/node-dg-async branch from 27ab060 to 47cdee4 Compare November 17, 2026 13:20
Async ops (async_hooks) are reported to the Replay dependency graph with
the shapes Chromium uses, so the backend's dependency chains connect I/O,
timers, ticks and microtasks to the code that scheduled them.

- An op's init adds a node and each of its callbacks runs in a dependency
  execution of a run node, between push_async_context and
  pop_async_context. The op class decides the kinds (AsyncOp,
  src/node_dependency_graph.h): Timeouts are timerScheduled -baseTimer->
  timerFired, queueMicrotask() is enqueueMicrotask -scheduler->
  runMicrotask, everything else asyncInit{type} -scheduler-> asyncCallback.
  The main script runs in a marker{ExecuteScript} node, created after the
  first checkpoint, which is the root of the chains.
- Init sites: AsyncWrap::EmitAsyncInit for native ops, and the JS ops'
  constructors (Timeout, Immediate, nextTick, AsyncResource). Windows: the
  C++ and JS async id stack push/pop/clear. Destroys erase the op.
- Windows mirror the async id stack by slot and save the dependency
  execution depth when they begin. Shrinking the stack unwinds to it, which
  also ends executions whose end was skipped (a termination escaping a
  promise reaction job, a stack clear after a fatal exception).
- queueMicrotask() takes its AsyncResource path while instrumented, so the
  microtask has an async op.

Prod behavior. Unrecorded runs: the JS sites check a boolean that is false
and make no binding calls; queueMicrotask() is unchanged; the C++ sites
check a cached flag and return. Recordings (with the dependency-graph
feature, the default): JS paths depend only on
v8::recordreplay::DependencyGraphInstrumented(), which is recorded, so they
are the same when recording and replaying. The binding calls return after
checking a cached flag; nodes, edges and the op map only exist when
replaying. The only JS-visible change in recordings is queueMicrotask()
taking the path it takes whenever AsyncLocalStorage or async hooks are in
use: an async id and an AsyncResource per microtask, and its frames in
error stacks. The binding results JS sees are the same when recording and
replaying.
…backend#13900) and the weak-ref harness fix (backend#13901)
@Domiii
Domiii force-pushed the dominik/node-dg-async branch from 57ad6a5 to 89884a1 Compare November 17, 2026 14:43
@Domiii
Domiii marked this pull request as ready for review November 17, 2026 15:07
@Domiii
Domiii merged commit 6097a91 into main Nov 17, 2026
3 checks passed
@Domiii
Domiii deleted the dominik/node-dg-async branch November 17, 2026 15:08
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.

1 participant