Repository navigation
wcprof: experimental wall-clock profiler + counterfactual bottleneck analyzer - #13393
Merged
Merged
Conversation
Contributor
|
This is super promising! What's needed to mark this as ready ? |
Contributor
Author
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. |
…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]>
vito
approved these changes
Jun 16, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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):
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.Hook points:
getOrInitCall: onecallop per caller (cache hits and DoNotCache included — deliberately recording what OTel suppresses), one sharedcall_execop per resolver execution (waiters record singleflight join edges against it), and a publish op for result publication cost.evaluateOne:lazyops 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.setupNetwork,setupRootfs, ...,runContainer), plus anexec.containerStartvsexec.processRunsplit so engine overhead and user process time are distinguishable.prepareMounts/applyOutputsphases.service_startops with waiter join edges (start singleflight + health checks).serveQuery: per-query session phases (attachables wait, workspace load, module load, schema build, query root).Enabling and dumping
Two scopes:
dagger --profileflag 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.--wcprofflag or_DAGGER_WCPROF=1, or toggled at runtime through the debug endpoint:POST on|offto/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/dumpstreams 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 fullTestModuleintegration 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):
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 isHost.directory(filesync) at ~4s;HTTPState._resolvehas 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.setupNetworkhas 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 rankedexec_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)
dagql.publishResultself-time — itself a useful signal).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:
dagger calllatency decomposition), not just leaf-class self-time.🤖 Generated with Claude Code