Skip to content

wcprof: experimental wall-clock profiler + counterfactual bottleneck analyzer - #13393

Merged
sipsma merged 3 commits into
dagger:mainfrom
sipsma:wcprof
Jun 16, 2026
Merged

sipsma merged 3 commits into
dagger:mainfrom
sipsma:wcprof

Conversation

@sipsma

@sipsma sipsma commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Adds wcprof: an experimental, cheap wall-clock profiling system for the engine, plus an offline analyzer that finds latency bottlenecks by counterfactual simulation.

This is built to systematically catch the class of problem that CPU/memory profiles can't see: serial wall-clock taxes like the ~300ms un-pooled CNI netns setup that used to run before every container start while nothing else made progress.

Design

The engine is unusually well-shaped for this: since evaluation became dagql-native, every cross-operation blocking relationship flows through a handful of choke points we own (dagql singleflight, lazy-eval waiters, service starts, cache-volume locks, exec completion channels, the nested-client boundary). That means the true waits-for graph can be recorded at the choke points rather than inferred from span nesting. And since the recipe digest is already computed for every call, op identity is free.

wcprof records three fixed-size event types into sharded in-memory buffers with interned strings (~72B/event, default cap ~4M events; when profiling is off, every hook is a single atomic load + nil check):

  • ops — timed intervals with kind (call, call_exec, lazy, exec, exec_phase, service_start, session_phase, internal), class (e.g. Container.withExec, exec.setupNetwork), instance ident (recipe digest / exec id), structural parent (via context), outcome (hit/executed/joined/do_not_cache/...), and a work-type tag separating engine overhead from user work (container process runtime) and external I/O.
  • waits — exact blocked-on intervals (who waited on which op or named resource, why, from when to when), recorded by the waiter at the choke point itself.
  • links — non-blocking correlations, most importantly exec op ↔ nested client ID, so module-function calls back into the API stitch under the exec that hosts them.

Hook points:

  • dagql getOrInitCall: one call op per caller (cache hits and DoNotCache included — deliberately recording what OTel suppresses), one shared call_exec op per resolver execution (waiters record singleflight join edges against it), and a publish op for result publication cost.
  • dagql evaluateOne: lazy ops classed by the call that created the lazy value (cost attribution) with wait edges from the triggering/joining ops (blocking attribution) — the two views stay separate.
  • engineutil executor: per-exec op + named phase ops (setupNetwork, setupRootfs, ..., runContainer), plus an exec.containerStart vs exec.processRun split so engine overhead and user process time are distinguishable.
  • core container exec: cache-volume lock waits, prepareMounts / applyOutputs phases.
  • core services: service_start ops with waiter join edges (start singleflight + health checks).
  • engine server serveQuery: per-query session phases (attachables wait, workspace load, module load, schema build, query root).

Enabling and dumping

Two scopes:

  • Per-session: the hidden dagger --profile flag records only that session's work — including its nested module/SDK clients — via a context mark applied at the session server and propagated through derived contexts.
  • Engine-global: record everything. Enabled at startup via the engine's hidden --wcprof flag or _DAGGER_WCPROF=1, or toggled at runtime through the debug endpoint: POST on|off to /debug/wcprof/enabled (GET reports state). Disabling keeps buffered events dumpable and re-enabling reuses the same recorder, so dumps from before/after merge cleanly.

GET /debug/wcprof/dump streams a JSON header line (string table, open ops for hang visibility) followed by one JSON event per line, flushing the buffer by default; periodic drains of long runs merge losslessly at analysis time.

Why not OTel

The existing telemetry path is unsuitable for this both in cost and in shape: AroundFunc proto-encodes the full call DAG per span, every span is written to per-client SQLite databases (fanned out to all parent clients), and repeated/cache-hit calls are deliberately suppressed via ShouldEmitTelemetry, so most calls never appear at all. Spans also only give a tree + timestamps; they can't say why an op was idle mid-flight.

Analyzer (cmd/wcprof-analyze, engine/wcprof/wcanalyze)

Reconstructs the op graph (parents, waits, nested-client re-parenting), computes self-time (duration minus waits minus child intervals), then runs a replay-based discrete-event simulation of the recorded schedule under counterfactual hypotheses: "class X's self-time scaled by f" for f ∈ {0, 0.5, 0.9}, assuming unlimited resources (never CPU-bound; v1 simplification). Classes are ranked by how much end-to-end makespan each would actually save — which handles critical-path shifts, singleflight dedup (shared work counted once), and dependency chains, unlike naive "total time per class" tables.

It also reports per-class stats with outcome histograms and duplicate-execution detection, an end-of-workload blocking chain, dead-air gaps (uninstrumented blocking), and drift diagnostics.

The replay is compiled once into flat action arrays and what-if simulations run in parallel, so large dumps stay tractable: a 9.7M-event dump analyzes in ~74s.

How it worked in practice

Testbed: dagger call engine-dev container sync, cold cache, profiled via the dev engine. ~223s wall, ~169k ops, ~25MB dump, zero dropped events, ~1s to analyze. Also run against the full TestModule integration suite (12-way-parallel sessions, ~402s): 9.7M events / 1.3GB across periodic drains, merged and analyzed in ~74s.

The simulated baseline makespan is checked against the actual makespan as a fidelity metric, and that check earned its keep: it caught three real replay-model bugs during bring-up, found via the included diagnostics (DriftOrigins, ExplainFinish, fallback-anchor counters):

  1. Frame mixing: normalizing the first root's sim time to 0 while ops reached through cross-tree wait targets anchored at original timestamps inflated makespan +53%. The simulation now stays entirely in the original trace's time frame.
  2. Ident-based exec waits can resolve to the wrong exec when call digests are shared across execs; removed in favor of the exec op being a context-child plus the replay's implicit-join rule, which models the dependency exactly. (Waits that ended before their target's recorded end — abandoned/canceled — are also no longer treated as joins.)
  3. Fallback anchoring at recorded start times silently re-pinned chains to original times whenever an op's finish was needed while its parent was mid-replay, collapsing counterfactual propagation (processRun×0 "saved" 55ms instead of 41.7s). Fallbacks now anchor at parent sim start + recorded offset.

After those fixes the baseline drift is −0.0% on every dataset measured (smoke, full builds, synthetic chains, the 9.7M-event integration suite).

Results on the testbed: the go build itself (exec.processRun, user work) dominates at ~42–69s recoverable; the top engine-actionable class is Host.directory (filesync) at ~4s; HTTPState._resolve has 207s of total self-time but correctly ranks as a non-bottleneck (parallel to the build) — exactly the total time ≠ bottleneck discrimination this is for. One real finding already: exec.setupNetwork has p50 125µs but p95 1.52s (44–55s total across ~230 execs) — a netns-pool exhaustion tail, the same class as the original CNI problem.

Validation (known-answer test)

During bring-up, a temporary file-gated injection aid added an artificial delay in setupNetwork (removed before merge). On a strictly serial 10-exec chain with 300ms injected: the analyzer ranked exec_phase:exec.setupNetwork #1 and predicted save@0 = 3.32s; disarming the injection and re-running measured the chain section shrink from 3.57s to 0.46s (actual recovery 3.11s — prediction within ~7%, which also covers the organic tail it zeroes). With the injection disarmed the class dropped out of the rankings entirely — no false positive. On the engine-dev build the same injection predicted only ~2.4s saved despite ~48s wall growth: execs there start in parallel with the build/download chains, so per-exec start taxes mostly don't serialize in that workload (and cross-run wall comparisons are polluted by network variance — validate within-run via the sim, or on serial synthetic chains).

Known v1 limitations (deliberate)

  • Lock waits are modeled as fixed delays (no release→acquire causality).
  • Unlimited-resources assumption; parallel self-time includes mutex contention and scheduler queueing (e.g. egraphMu pressure shows up as dagql.publishResult self-time — itself a useful signal).
  • Leaf I/O internals (git fetch, image pull, filesync) are not yet sub-instrumented; they appear as self-time of their calling op, and the unexplained-self-time/dead-air reports are the guide for where to hook next.
  • One engine-wide recorder and event buffer: per-session enablement scopes what gets recorded, but all enabled sessions share the buffer and dumps.
  • What-if rankings operate on per-class self time, so "umbrella" ops whose time is correctly decomposed into children (e.g. ModuleSource.asModule) don't rank as a unit yet — see direction below.

Status & direction

This is a usable first cut: the collection path is cheap and safe to leave in the engine, and the analyzer's counterfactual rankings have been validated against known-answer injections and real workloads. The plan is to keep iterating in-tree rather than grow this branch. Rough laundry list of where we want to take it:

  • Higher-level/subtree analysis: what-ifs and attribution over spans that encapsulate other spans (e.g. "module loading as a whole", per-dagger call latency decomposition), not just leaf-class self-time.
  • A lot more data: leaf I/O ops (git/registry/filesync internals), lock release→acquire causality, finer exec phases, richer op metadata (e.g. distinguishing internal SDK/codegen execs from user execs).
  • Multiple data sources, one model: ingest OTel spans, Go pprof data (e.g. mutex-contention profiles), and eBPF-derived signals for what happens inside user execs (so user work stops being a black box) — alongside wcprof's native events, all for the same workflow run, compiled down to the same op/wait graph so the same counterfactual analysis runs over the union.
  • Resource-capacity awareness: model that CPUs, disk bandwidth, and network bandwidth are finite, so simulated speedups stop assuming infinite parallelism and contention shows up as such in rankings.
  • Cross-run workflows: comparing profiles between runs/versions to catch wall-clock regressions, and per-session scoping of dumps.

🤖 Generated with Claude Code

@tiborvass

Copy link
Copy Markdown
Contributor

This is super promising! What's needed to mark this as ready ?

@sipsma

sipsma commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

This is super promising! What's needed to mark this as ready ?

Mainly a pass at double checking that the new probes and data won't have performance overhead in production code scenarios. Other than that it's definitely something we can merge early and iterate on as a side dev-tool.

Will get back to ASAP so it doesn't go stale.

@sipsma
sipsma marked this pull request as ready for review June 12, 2026 00:02
@sipsma
sipsma requested review from grouville, tiborvass and vito June 12, 2026 00:04
sipsma and others added 3 commits June 16, 2026 13:17
…analyzer

Adds an experimental, cheap wall-clock profiling system (wcprof) for the
engine plus an offline analyzer that finds latency bottlenecks by
counterfactual simulation. Built to systematically catch the class of
problem that CPU/memory profiles can't see: serial wall-clock taxes like
the ~300ms un-pooled CNI netns setup that used to run before every
container start while nothing else made progress.

Why not OTel
============
The existing telemetry path is unsuitable for this both in cost and in
shape: AroundFunc proto-encodes the full call DAG per span, every span is
written to per-client SQLite databases (fanned out to all parent clients),
and repeated/cache-hit calls are deliberately suppressed via
ShouldEmitTelemetry, so most calls never appear at all. Spans also only
give a tree + timestamps; they can't say *why* an op was idle mid-flight.

Design
======
The engine is unusually well-shaped for this: since evaluation became
dagql-native, every cross-operation blocking relationship flows through a
handful of choke points we own (dagql singleflight, lazy-eval waiters,
service starts, cache-volume locks, exec completion channels, the
nested-client boundary). That means the true waits-for graph can be
*recorded* at the choke points rather than inferred from span nesting.
The recipe digest is already computed for every call for cache lookup, so
op identity is free.

wcprof records three fixed-size event types into sharded in-memory
buffers with interned strings (~72B/event, default cap ~4M events,
disabled = one atomic load per hook site):

- ops: timed intervals with kind (call, call_exec, lazy, exec,
  exec_phase, service_start, session_phase, internal), class
  (e.g. Container.withExec, exec.setupNetwork), instance ident (recipe
  digest / exec id), structural parent (via context), outcome
  (hit/executed/joined/do_not_cache/...), and a work-type tag separating
  engine overhead from user work (container process runtime) and
  external I/O.
- waits: exact blocked-on intervals (who waited on which op or named
  resource, why, from when to when), recorded by the waiter at the choke
  point itself.
- links: non-blocking correlations, most importantly exec op <-> nested
  client ID so module-function calls back into the API stitch under the
  exec that hosts them.

Hook points in this commit:
- dagql getOrInitCall: one call op per caller (cache hits and DoNotCache
  included -- deliberately recording what OTel suppresses), one shared
  call_exec op per resolver execution (waiters record singleflight join
  edges against it), and a publish op for result publication cost.
- dagql evaluateOne: lazy ops classed by the call that *created* the lazy
  value (cost attribution) with wait edges from the triggering/joining
  ops (blocking attribution) -- the two views stay separate.
- engineutil executor: per-exec op + named phase ops (setupNetwork,
  setupRootfs, ..., runContainer), plus an exec.containerStart vs
  exec.processRun split so engine overhead and user process time are
  distinguishable.
- core container exec: cache-volume lock waits, prepareMounts /
  applyOutputs phases.
- core services: service_start ops with waiter join edges (start
  singleflight + health checks).
- engine server serveQuery: per-query session phases (attachables wait,
  workspace load, module load, schema build, query root).

Plumbing: hidden `dagger --profile` flag -> ClientMetadata.Profile ->
engine-global recorder (also `_DAGGER_WCPROF=1`); dump+flush endpoint at
GET /debug/wcprof/dump alongside the other engine debug endpoints. The
dump is a JSON header line (string table, open ops for hang visibility)
followed by one JSON event per line.

Analyzer (cmd/wcprof-analyze, engine/wcprof/wcanalyze)
======================================================
Reconstructs the op graph (parents, waits, nested-client re-parenting),
computes self-time (duration minus waits minus child intervals), then
runs a replay-based discrete-event simulation of the recorded schedule
under counterfactual hypotheses: "class X's self-time scaled by f" for
f in {0, 0.5, 0.9}, assuming unlimited resources (never CPU-bound, v1
simplification). Classes are ranked by how much end-to-end makespan each
would actually save -- which handles critical-path shifts, singleflight
dedup (shared work counted once), and dependency chains, unlike naive
"total time per class" tables. Also reports per-class stats with outcome
histograms and duplicate-execution detection, an end-of-workload blocking
chain, dead-air gaps (uninstrumented blocking), and drift diagnostics.

How it worked in practice
=========================
Testbed: `dagger call engine-dev container sync`, cold cache, profiled
via the dev engine (hack/dev). ~223s wall, ~169k ops, ~25MB dump, zero
dropped events, ~36s to analyze.

The simulated baseline makespan is checked against the actual makespan
as a fidelity metric, and that check earned its keep: it caught three
real replay-model bugs during bring-up, found via the included
diagnostics (DriftOrigins, ExplainFinish, fallback-anchor counters):
1. Frame mixing: normalizing the first root's sim time to 0 while ops
   reached through cross-tree wait targets anchored at original
   timestamps inflated makespan +53%. The simulation now stays entirely
   in the original trace's time frame.
2. Ident-based exec waits can resolve to the wrong exec when call
   digests are shared across execs; removed in favor of the exec op
   being a context-child plus the replay's implicit-join rule, which
   models the dependency exactly. (Waits that ended before their
   target's recorded end -- abandoned/canceled -- are also no longer
   treated as joins.)
3. Fallback anchoring at recorded start times silently re-pinned chains
   to original times whenever an op's finish was needed while its parent
   was mid-replay, collapsing counterfactual propagation (processRun x0
   "saved" 55ms instead of 41.7s). Fallbacks now anchor at parent sim
   start + recorded offset.

After those fixes the baseline drift is -0.0% on every run measured
(smoke, two full builds, two synthetic chains).

Results on the testbed: the go build itself (exec.processRun, user work)
dominates at ~42-69s recoverable; the top engine-actionable class is
Host.directory (filesync) at ~4s; HTTPState._resolve has 207s of total
self-time but correctly ranks as a non-bottleneck (parallel to the
build) -- exactly the total-time != bottleneck discrimination this is
for. One real finding already: exec.setupNetwork has p50 125us but p95
1.52s (44-55s total across ~230 execs) -- a netns-pool exhaustion tail,
the same class as the original CNI problem.

Validation (known-answer test)
==============================
A file-gated injection aid (/tmp/wcprof-inject-netns-delay-ms inside the
engine container, only consulted while profiling) injects an artificial
delay in setupNetwork. On a strictly serial 10-exec chain with 300ms
injected: the analyzer ranked exec_phase:exec.setupNetwork #1 and
predicted save@0 = 3.32s; disarming the injection and re-running measured
the chain section shrink from 3.57s to 0.46s (actual recovery 3.11s,
prediction within ~7%, which also covers the organic tail it zeroes).
With the injection disarmed the class dropped out of the rankings
entirely -- no false positive. On the engine-dev build the same injection
predicted only ~2.4s saved despite ~48s wall growth: execs there start in
parallel with the build/download chains, so per-exec start taxes mostly
don't serialize in that workload (and cross-run wall comparisons are
polluted by network variance -- validate within-run via the sim, or on
serial synthetic chains).

Known v1 limitations (deliberate)
=================================
- recorder is engine-global (any profiled client enables it);
  per-session scoping is future work
- lock waits are modeled as fixed delays (no release->acquire causality)
- unlimited-resources assumption; parallel self-time includes mutex
  contention and scheduler queueing (e.g. egraphMu pressure shows up as
  dagql.publishResult self-time -- itself a useful signal)
- leaf I/O internals (git fetch, image pull, filesync) are not yet
  sub-instrumented; they appear as self-time of their calling op, and
  the unexplained-self-time/dead-air reports are the guide for where to
  hook next

Usage
=====
  ./hack/dev
  ./hack/with-dev ./bin/dagger --profile call engine-dev container sync
  curl -s http://localhost:6060/debug/wcprof/dump > /tmp/wcprof.dump
  go run ./cmd/wcprof-analyze /tmp/wcprof.dump

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
…i-drain dumps

The analyzer choked on a full TestModule profile (9.8M events, 9.68M ops,
1125 roots): the replay rebuilt and re-sorted every op's action list on
every one of ~600 what-if simulations with map-based memos, projecting to
hours. The per-op timeline is factor-independent, so it is now compiled
once per graph into flat arrays (dense int32 op indices, pre-sorted action
streams with the join/fixed/abandoned wait classification baked in), each
simulation is a pure slice-based DP over that program, and the
(class, factor) simulations run in parallel (bounded at 8 workers to cap
per-sim state memory). Results are unchanged (known-answer fixtures plus a
regression check against a previous dump: identical drift, cycle and
fallback-anchor counts).

  engine-dev build dump (191k events): 36s -> 1.2s
  TestModule dump set (9.8M events):   killed at 37min -> 74s, 16GB peak

Also adds multi-dump merging (wcanalyze.LoadMulti + variadic args in
wcprof-analyze): long runs are drained periodically via the dump endpoint
to stay under the recorder's event cap, and the drains merge losslessly
because the string table only grows, op IDs are unique, the epoch is
fixed, and the drop counter is cumulative. The TestModule run needed this:
9.8M events vs the 4M default cap, zero drops with 40s drains.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Pre-merge cleanup of how profiling is enabled, replacing the original
"any --profile client stickily enables the engine-global recorder
forever" prototype behavior with two explicit scopes:

- Engine-global: enabled at startup via the (hidden) --wcprof engine
  flag or _DAGGER_WCPROF=1, and toggleable at runtime through a new
  debug endpoint: POST "on"/"off" (or any boolean) to
  /debug/wcprof/enabled; GET reports state. Disabling stops global
  recording but keeps the recorder and buffered events dumpable, lets
  sessions that opted in keep recording, and lets in-flight recorded
  ops finish. Re-enabling reuses the same recorder, so dumps from
  before/after merge cleanly (same epoch).

- Per-session: a client connecting with ClientMetadata.Profile (the
  hidden --profile CLI flag) records only its own session's work.
  The flag is latched onto the daggerSession, which nested module/SDK
  clients share, so their work is included. serveQuery marks request
  contexts via wcprof.ContextWithProfiling; hooks record iff a recorder
  exists AND (global mode is on, OR the context carries the mark or a
  recorded parent op ID). The mark survives context.WithoutCancel, so
  lazy evaluations, execs, and service starts inherit it. Known
  degradation: a profiled call that singleflight-joins an unprofiled
  session's in-flight execution records an unresolved wait (modeled by
  the analyzer as a fixed delay); cross-session joins are effectively
  nonexistent today, so this is acceptable.

Also:

- Remove the netns delay-injection validation aid from setupNetwork;
  it served its purpose validating the analyzer and should not merge.
- Disabled-path overhead audit: every hook is a single atomic load +
  nil check when profiling was never enabled; the one allocation found
  on that path (the "cachelock:"+key concat per cache-volume lock) is
  now gated behind wcprof.Enabled(ctx). Once a recorder exists,
  unprofiled work pays the atomic load plus two ctx.Value walks
  (~100ns/hook); zero impact for engines that never enable profiling.

Validated on a rebuilt dev engine: fresh engine reports off and dump
returns 503; an unprofiled session leaves the recorder absent; a
--profile session records (26k events) while the next unprofiled
session adds exactly 0; POST on/off flips recording for unprofiled
sessions (26k events vs 0) with the buffer still dumpable after off;
invalid POST bodies return 400. A --profile `dagger call` that loads
workspace toolchain modules produced a 149k-event dump in which nested
SDK clients are fully captured (single stitched root, simulated
baseline drift -0.0%).

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
@sipsma
sipsma merged commit 6499f42 into dagger:main Jun 16, 2026
78 checks passed
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