Skip to content

Wall-clock time: OTel profiling emission, truthful TUI durations, analyzer moved out of tree - #13588

Merged
sipsma merged 16 commits into
dagger:mainfrom
sipsma:wcprof-pr1
Jul 14, 2026
Merged

sipsma merged 16 commits into
dagger:mainfrom
sipsma:wcprof-pr1

Conversation

@sipsma

@sipsma sipsma commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

This PR does three things, listed in the order they appear in the commits:

  1. Teaches the engine to emit wall-clock profiling data over OpenTelemetry. wcprof (the engine's wall-clock profiler, for answering "why was my run slow?") could previously only analyze runs captured by its own in-process recorder. The engine now emits the same information on the ordinary OTel spans every run already produces — most importantly wait edges: records of exactly when an operation was blocked, on what, and why (a lazy evaluation, another call's execution, a service starting). That makes any exported trace analyzable after the fact, including traces already sitting in Dagger Cloud, and it is also what makes item 3 possible.

  2. Moves the wcprof analyzer out of this repo. The analysis half (graph reconstruction, counterfactual replay, bottleneck ranking) has grown complex enough that it is becoming a component of Dagger Cloud rather than an in-engine tool. The in-tree v1 analyzer is deleted here; it is re-homed in the Cloud codebase by the companion PR (https://github.com/dagger/dagger.io/pull/5112, merges after this one). The engine-side recorder and the new OTel emission stay.

  3. Makes the TUI report execution time truthfully. The duration next to a span has always been its wall-clock activity, shown as if the op itself were working the whole time. Because most Dagger operations are lazy, that number is frequently meaningless: call .stdout() on a container pipeline and stdout shows the whole 20 seconds, while the withExec that actually did the work is attributed almost nothing — and every trivial op in the chain (a withWorkdir, a withEnvVariable) claims seconds it never used. Using the wait edges from item 1, the TUI now shows the time each op actually spent executing, and a row that is currently blocked says what it is waiting on:

Screenshot 2026-07-07 at 11 22 14 AM

How it works, per commit

The emission (first five commits, one concern each):

  • Record the user command: the recorder interns each exec's argv so an analysis can rank "go build" instead of an anonymous exec blob.
  • Emit wait edges at the blocking points: whenever a dagql call waits — on another caller's in-flight execution, on a lazy evaluation it forced — the engine attaches a span link to the waiting span recording the target and the exact blocked window. Timestamps ride as decimal-string unix-nanos because they must round-trip bit-exact through JSON attribute maps on the Cloud path. A caller's own resolver execution and the lazy re-pointing of deferred work also carry explicit markers, so a consumer never has to guess causality from span nesting.
  • Split engine setup from user time in execs: container startup overhead and the user's actual process are separate spans, so slow infrastructure is distinguishable from a slow build.
  • Service startup as a first-class op: service.start gets its own span with wait edges from everyone blocked on it.
  • Trace completeness: the engine stamps a per-trace span-count checksum and synchronously flushes it at session teardown. Rationale: a dropped span that nothing references leaves no other evidence, and an analyzer must be able to refuse an incomplete trace rather than produce a confidently wrong answer.

The removal (sixth commit): deletes engine/wcprof/wcanalyze and cmd/wcprof-analyze (the offline loader/replay/ranking). engine/wcprof itself — the recorder and the emission above — remains.

The TUI (last four commits):

  • Ingest: the wait-edge link attributes were previously discarded at the TUI's telemetry ingest; keep them.
  • The model (dagql/dagui): decompose each span's time into "actually executing" vs "provably blocked", entirely from evidence — wait edges and the engine's deferred-work markers, never guesses from tree shape. The interesting rules, each there for a concrete reason: work nested under a row's own subtree counts as its own execution (a module call hosting its function isn't "waiting"); a blocked stretch resolves transitively to the op truly working at that instant, so users don't walk the chain by hand; in-flight waits are inferred from running markers because wait edges are only emitted once a wait ends; and a materiality threshold keeps ordinary rows rendering byte-identically to today — the existing golden tests passing unchanged is the regression proof of that.
  • Support-span streaming: frontends that stream a filtered span subset (the Cloud websocket) also need the twins/markers/wait-targets the model reads; enumerate and subscribe them.
  • Rendering (dagql/idtui): the self-time number in the pretty TUI, the final report, and plain mode; plus the live "waiting on X" suffix shown only while blocked. Deliberately no new panels, bars, or keybinds.

Testing

Every commit builds in isolation. go test ./core ./engine/wcprof/... ./dagql ./engine/engineutil ./engine/server is green with the analyzer removed; the emit-side behavior is asserted directly on recorded spans/attributes. The dagui model tests reproduce the real emitted span topology (execution twins, resume markers, late exec children) with exact-value assertions, and the pre-existing TUI goldens pass unchanged.

@sipsma sipsma changed the title wcprof: engine-side wall-clock profiling emission + honest-progress TUI; remove the in-tree analyzer Emit wall-clock profiling data via OpenTelemetry, report execution time truthfully in the TUI, move the wcprof analyzer out of tree Jul 7, 2026
@sipsma sipsma changed the title Emit wall-clock profiling data via OpenTelemetry, report execution time truthfully in the TUI, move the wcprof analyzer out of tree Wall-clock time: OTel profiling emission, truthful TUI durations, analyzer moved out of tree Jul 7, 2026
sipsma added 16 commits July 8, 2026 19:47
Add an interned op-metadata slot to the native wall-clock recorder so an op can
carry a small canonical string alongside its class/ident/client. The first use
is a user exec's scrubbed argv, encoded as the canonical scalar JSON-array
string and interned as the op's MetaID (0 when none), so repeated identical
argvs share one string id.

  - wcprof.go: Event.MetaID + openOp.metaID thread the interned id through the
    open-op table and the completed-event stream.
  - dump.go: MetaID is written into the JSON dump (both the open-op header and
    the compact event form) so the offline analyzer can read it back.
  - record.go: RecordOp/BeginOp honour OpOpts.Argv, marshalling and interning it
    once at record time.

This is the recorder half of the exec engine/user split; the executor emit side
(which stamps the same argv onto its OTel span) and the offline analyzer that
reads it land separately.

Signed-off-by: Erik Sipsma <[email protected]>
…e points

Add an optional second source for the wall-clock profiler that rides on the
engine's ordinary OTel spans, so a Dagger Cloud trace can be analyzed offline
without running the opt-in native recorder. The engine emits the same causal
model the native recorder captures inline -- shared-execution ops, per-caller
wait edges, and a causal-parent override for lazily-evaluated work -- as a small
set of extra span/link attributes (engine/telemetryattrs), which the offline
analyzer compiles into the same wcprof IR.

Emit sites (all gated only on telemetry being active):

  - otelprof_hooks.go: a singleflighted call_exec op per resolver execution plus
    a publishResult bracket, and a per-caller wait edge (EmitOTelWait) carrying
    purpose/reason/abs-ns timing and a target span, so a joiner's blocked time is
    attributed to the execution it waited on. A recording waiter whose target was
    never minted emits a targetless (all-zero) wait so the offline gate flags it
    rather than silently dropping the edge.

  - otelprof_lazy.go + cache.go: lazy evaluation re-points deferred work under a
    consumer-side `lazy` op via an explicit wcprof.parent causal-parent override
    on the direct re-pointed spans -- separating causal parentage from UI
    parentage so dagui renders unchanged. Emit, never inference: the analyzer
    reads only the attribute the engine writes.

Static profile-skip: the reflection / schema-walk class that normal telemetry
already hides emits a call_exec+publishResult pair per cache miss and dominates
OTel volume on a module-load workload. A pure static predicate
(profileSkip(receiverType, field) in core/telemetry.go) decides lookup-free
whether to profile a call; the immediate receiver type name is captured at the
object call site (objects.go -> CallRequest.ReceiverTypeName) and the decision
is stamped once onto the call frame (ResultCall.ProfileSkip), travelling with
the frame through clone()/fork() and JSON persistence so every singleflight
joiner and every derived child agrees by construction. It is a pure function of
the recipe and is EXCLUDED from every digest, so it can never perturb caching.
Native wcprof is opt-in/dev-only and keeps full detail (ungated).

The offline loader/gate that consume this shape live in the closed-source
analyzer; the emit contract here is machine-checked by in-package tests that
assert the exact exported span/link attribute shape.

Signed-off-by: Erik Sipsma <[email protected]>
…ource

Profile a container exec as an exec.run op with two phases -- an engine
containerStart phase and a user processRun phase -- so a slow `go build`
headlines as the user's slow command, not as engine overhead. Only processRun is
user work; containerStart stays engine time. Emitted on both profile sources:
the native recorder's phase ops, and (on the executor's ordinary OTel spans) an
exec.run / containerStart / processRun span split.

  - executor.go / executor_spec.go: capture the wall-clock setup/run boundary at
    the same started-callback the native recorder uses (one cheap atomic per run,
    read only when OTel emit is active), and thread the resolved exec ident.

  - container_exec.go: capture the fully-resolved user command (ProfArgs) at
    exec-run time BEFORE any engine shim (the QEMU emulator, the executor's
    /.init) wraps it -- a capture below a shim would headline the shim instead of
    the user's real program, worst on the slowest emulated execs. ProfArgs is
    json:"-" and set only after every exec digest is computed, so it can never
    perturb a cache key.

  - wcprof_argv.go: encode the command as the canonical scalar JSON-array string,
    bounded in arity and length, and stamp it onto the user processRun (native
    MetaID + OTel wcprof.exec.argv); the engine phase never carries argv, so each
    exec ranks under its own command class.

  - secret_scrub.go: add ScrubStrings, redacting the argv from the SAME registered
    secret set the stdout/stderr scrubbers use, before it is recorded or emitted.

The recorder's interning of this argv landed separately; the offline analyzer
reads it from both sources.

Signed-off-by: Erik Sipsma <[email protected]>
Profile service startup on the OTel source, mirroring the native recorder's
service_start op. The first installer to start a service mints a service.start
op scoping the start (incl. health-check) window; any other installer that
blocks on the in-flight start emits a service wait edge (dagql.EmitOTelWait,
reason=service) targeting it, so the blocked install time is attributed to the
service start it waited on.

The op is ui.passthrough so dagui keeps showing the long-lived `exec <args>`
service span rather than this start-window span -- the same causal-vs-UI
separation the other choke points use.

Signed-off-by: Erik Sipsma <[email protected]>
The OTel BatchSpanProcessor queue is non-blocking and silently DROPS spans on
overflow, and wall-clock analysis on silently-partial data is worthless. Guard
the whole Cloud path with a prevent-and-detect pair.

Detect -- an engine span-count completeness checksum (the producer half):

  - wcprofcount.go: a shared span-count processor tallies every engine span per
    trace, excluding the carrier span itself.
  - session.go: at session teardown the engine stamps the EXACT per-trace engine
    span total onto a wcprof.session_complete carrier span and force-flushes it
    under an uncanceled context, so the offline loader can refuse a trace whose
    received count is below the declared one (a silently dropped leaf) instead of
    ranking on partial data.
  - server.go: register the counter on every per-client tracer provider (shared
    instance) so nested-client spans count into the same trace.

Prevent -- large BOUNDED Cloud BSP queues:

  - livespan.go: NewLargeQueueLiveSpanProcessor sizes the queue to 256Ki slots
    (only a ~2MiB pointer ring) with a large export batch -- roughly 8x a cold
    engine build's ~30k live-double-emitted records -- so a big burst is absorbed
    with headroom. Kept BOUNDED (never block on full), so telemetry can never
    stall the build; any residual overflow is still caught by the checksum above.
  - session.go / engine.go: use it on every hop that feeds a Cloud trace (the
    engine's per-client DB processors and the CLI->Cloud exporter), the tail of
    which was where the completeness carrier first dropped.

  - otlpdump.go: surface DroppedLinksCount / DroppedAttributesCount in the debug
    dump so a link or link-attribute evicted by an SDK count limit is observable.

Signed-off-by: Erik Sipsma <[email protected]>
The offline wall-clock analyzer (engine/wcprof/wcanalyze and its
cmd/wcprof-analyze CLI, from the v1 profiler) moves to a closed-source home.
Only the emit side stays in the OSS engine -- the native recorder and the OTel
profiling source added on the engine's ordinary spans -- and nothing in the
engine imports the analyzer. Its end-to-end coverage moves with it; the emit
contract stays machine-checked here by the in-package emit-shape tests.

Signed-off-by: Erik Sipsma <[email protected]>
The engine emits runtime wait edges as OTel span links on the waiting
span (link purpose "wait", vocabulary in engine/telemetryattrs): the
target is the op being waited on, and the attributes carry the blocked
window as absolute unix-nano decimal strings plus a reason
(lazy / call_exec / singleflight / service). Until now the dagui
ingest discarded every link attribute except the purpose, so this
information never reached a frontend.

Extend SpanLink with the decoded wait metadata (reason + blocked
window) and give it a ProcessAttribute method as the single funnel for
link attributes, used by the OTLP ingest path (sdktrace link
attributes). Timestamps are parsed from the decimal-string encoding,
which is chosen on the emit side so values round-trip bit-exact
through JSON attribute maps. Wait links remain non-causal: they are
deliberately NOT wired into the cause/effect link handling.

This is pure plumbing: nothing consumes the fields yet.

Signed-off-by: Erik Sipsma <[email protected]>
A span's displayed duration has always been its merged activity time,
presented as if the op itself were working the whole while. Under lazy
evaluation that is systematically wrong: the op that *forces* a
deferred chain (e.g. Container.stdout evaluating earlier withExecs)
carries the whole wall-clock on its own row while doing microseconds of
real work, and every intermediate op in the forced chain shows the
same inflated number. The wait-edge telemetry (previous commit) carries
exactly the information needed to fix this; this commit adds the model
that consumes it.

TimeBreakdown decomposes a row's painted time into exactly two
categories plus gaps:

  - self time: time the op (or work rendered inside its own subtree)
    actually spent executing
  - waiting: time provably blocked on work rendered elsewhere, each
    stretch labeled with the op actually working at that instant and
    navigable to it
  - dormant time (a lazy value sitting unforced) is no category at
    all: it stays an unpainted gap, since the op is neither working
    nor waiting

Model rules, each of which exists for an observed reason:

  * Waiting comes ONLY from evidence: explicit wait edges, plus
    inferred windows (below). Tree shape alone never fabricates
    waiting, and a caller blocked on its own same-name execution twin
    (the call_exec span dagql emits per resolver run) is doing its own
    work, not waiting.

  * Subtree rule: a wait window whose resolved blocker renders inside
    the row's own subtree is the row hosting its own nested work (a
    module call running its function, a group span wrapping its
    pieces) and counts as self time; the detail is expandable below.
    Only blockers rendered elsewhere read as "waiting on X".

  * Transitive, per-instant resolution: if C waits on B, B on A, and A
    is working, C reads "waiting on A" for the stretch A worked, then
    advances. Users should never have to walk the chain by hand.
    Closed waits resolve through recorded edges; LIVE waits resolve by
    descending each blocker's own current blocked state until reaching
    an op that is running and not itself blocked. Both paths share the
    same resolver, with a depth cap and cycle guard; Via records the
    first hop.

  * Inferred waits: wait edges are only emitted when a wait ENDS, and
    they land via AddLink on spans that may stay open long after (a
    lazy-resume marker re-exports only on heartbeat or its own end).
    A live row would therefore tick up as if working and snap down
    when the edge lands - and a row whose own exec just started would
    lose its past blocked stretch entirely. So external deferred-work
    markers hanging off a row's execution also count as blocked
    windows for their interval, whether running or completed; overlap
    with explicit edges merges away in the union. Only marker spans
    that stand in for another op qualify, so plain children can never
    fabricate waiting.

  * Blocker labels prefer the real command: the exec argv attribute
    once the exec has run, else the blocker call's own args (known at
    chain-build time, so live labels name the command before it ever
    executes), else the span name; long commands truncate uniformly.

  * Calm by default: sub-visual slivers are absorbed into their
    neighbor, adjacent same-blocker stretches coalesce, and the
    breakdown is only Material when waiting is at least 1s AND at
    least 20% of painted time. Immaterial rows are expected to render
    byte-identically to today; existing golden tests are the proof.

WaitingNow exposes the live blocked state (is this row blocked right
now, and on what) derived from the same decomposition the display
uses, with a 1s tolerance so snapshot jitter cannot flap it.

Tests model the real emitted span topology - execution twins,
resume markers parented under their trigger, cause links back to the
origin op, late exec children - and assert exact values (specific
durations, targets, argv-derived labels) for: the forcing-op
decomposition, forced-op self-time splits, the subtree/hosting rule,
inferred past waits, live blocked-now with a frozen self-time number,
the forced-row-blocked-deeper recursion case, the live A-on-B-on-C
chain resolving to C, and label fallbacks.

Signed-off-by: Erik Sipsma <[email protected]>
…s' updates

Frontends that stream a filtered subset of spans (the Cloud trace
websocket sends only visible rows and their children) starve the
time breakdown without knowing it: the execution twins, lazy-resume
markers, wait-edge targets, cause chains, and argv-carrying exec
children that the model reads all hang OUTSIDE the visible set, so a
live browser quietly falls back to the wall-clock number while the
same trace renders correctly from a full local ingest.

TimeBreakdownSpans(visit) enumerates exactly the spans a row's
breakdown draws on beyond the row itself (bounded by the same depth
cap as resolution), so a streaming frontend can ship them alongside
each visible row and subscribe them for updates.

UpdatedSnapshots gains one predicate: a span subscribed by its own ID
now streams its updates too - previously only children of subscribed
parents did, so a support span whose parent was never subscribed would
be sent once and then go stale (its closing wait edges arrive as span
UPDATES via link-append + heartbeat re-export). Strictly additive:
more spans stream, none are lost.

Signed-off-by: Erik Sipsma <[email protected]>
… X" suffix

Apply the time breakdown to the TUI's displayed time. Two changes,
deliberately nothing more:

  * The duration next to a row is now its self time - the time the op
    actually spent executing - instead of merged activity time.
    Material rows only: rows below the materiality thresholds render
    byte-identically to before (existing goldens unchanged), completed
    material rows show just the self-time number with no extra
    decoration, and the number keeps today's styling (yellow while
    running, faint when done). Applied uniformly to the pretty
    frontend's rows, the final report, the check-name duration, and
    the plain frontend's DONE suffix via one shared helper.

  * A row that is blocked RIGHT NOW shows a dim suffix naming the op
    actually working at this moment, transitively resolved and labeled
    by its real command, e.g.:

        .stdout: String! 0.0s ... waiting on sh -c sleep 2; go build -o /tmp/waitdemo .

    The suffix appears only while blocked and disappears when the wait
    ends; the self-time number holds steady during the wait instead of
    ticking up (a blocked row accrues waiting, not self time). Watching
    a forced chain live, the suffixes converge on the one op doing
    real work and advance together as each phase completes.

  * The plain frontend additionally appends ", waited on X" to a
    material row's DONE line, since an append-only log has no later
    chance to show where the time went:

        Container.stdout DONE [0.0s, waited on /tmp/waitdemo]

Render tests cover completed self-time reporting (including the
no-decoration rule) and the live suffix with a frozen number, using
the same realistic span topology as the dagui model tests.

Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
…tor blockers

CI surfaced a failure-scenario regression the happy-path fixtures never
exercised: after a failed run leaves spans open forever, every span
still looks live, so the blocked-now machinery kept firing during the
FINAL render and the live descent walked the open-span chain up to the
session root - rows rendered "... waiting on POST /query" in the
telemetry goldens.

Three guards, defense in depth:

  * The renderer only asks "blocked right now?" while the run is still
    going (not in a final render) and never for a failed or canceled
    row - a dead run has no "now", and a failed row's story is its
    error, not whatever it was waiting on when things went wrong.

  * WaitingNow applies the same failed/canceled rule at the model
    level, so remote frontends (the Cloud UI) inherit it.

  * A resolved blocker that CONTAINS the row (an ancestor, ultimately
    the session root) is never a meaningful "waiting on X" target:
    chains that dead-end there yield no waiting at all instead of a
    contentless label.

Regression tests model the failure shape directly: an open-span chain
whose cause links dead-end at the root must produce zero waiting
segments, and a live-blocked row that fails must stop reporting
blocked-now.

Signed-off-by: Erik Sipsma <[email protected]>
CI telemetry goldens surfaced the wcprof.session_complete carrier span
rendering as a real row (e.g. "╰╴✔ wcprof.session_complete" in the
broken-* fixtures). The carrier is protocol bookkeeping - a count
messenger stamped at session teardown - not a unit of work, so no
frontend should draw it. Stamp dagger.io/ui.internal at emission: the
TUI hides internal spans below verbosity 3 (goldens run at 1), Cloud
inherits the same treatment, and the analyzer side is unaffected - the
loader reads the count attributes regardless of UI hints, and the
span-count processor already excludes the carrier by name.

Signed-off-by: Erik Sipsma <[email protected]>
telemetry.EndWithCause has a second job beyond ending the span: when
the error carries no [traceparent:...] annotation yet, it MUTATES the
error to stamp the ending span as its origin. Origin tracking drives
user-facing attribution - the CLI suppresses the trailing Error: block
only when every origin span was already rendered as a failed row, and
the origin sections render the stamped spans with their logs.

The profiling emission gave that job to spans no frontend draws. The
new passthrough/support spans (exec.run, service.start, the call_exec
twin, publishResult, lazy ops) end deepest, so on any failure they
stamped first, displacing the visible API-call span as the error
origin. CI showed the fallout across six test-split legs: redundant
"Error: exit code: 1 [traceparent:..] [traceparent:..]" blocks in the
telemetry goldens, "✘ exec.run" rendered in error-origin sections, and
- because the mutated error crosses type and wire boundaries - domain
messages ("invalid enum", reserved-name errors, ...) degrading to bare
"exit code: N" in the integration suites.

Introduce dagql.EndProfSpan and use it at all five sites: it links any
origins already tracked in the error and records the cleaned error as
the span status exactly like EndWithCause - the loader still reads the
op outcome - but never stamps. Origin-stamping stays where it lived
before this branch: the user-visible spans (core.AroundFunc) and the
lazy resume span, which predates the profiling emission and keeps its
UI role.

Verified: the affected telemetry goldens pass again (broken-*,
fail-effect, encapsulate, pending, fail-multi*), and the sampled
integration failures from the other legs (TestCustomEnumType,
TestReservedWords) pass with their domain messages restored.

Signed-off-by: Erik Sipsma <[email protected]>
…ribution

The profiling spans do a second job nobody gave them: because the
call_exec twin (and exec.run under it) is the CURRENT span on the
context user work runs under, every attribution surface that reads
"the current span" started naming an unrendered passthrough span:

  * the traceparent injected into a container env parents everything
    the container emits - the nested SDK client spans, the user
    process logs, and the traceparent extension the SDK stamps into a
    returned Error - so module-function logs re-homed to the twin and
    vanished from the function row, and function errors carried the
    twin as their origin, defeating the CLI already-shown-error
    suppression (redundant trailing Error: blocks, re-rendered error
    rows in the origin sections, the python-pending traceback gone);

  * the module-function error-origin fallback and the exec-error
    causeCtx in core stamped the twin directly.

Fix in two layers. dagql.MarkProfilingSpan records, when a profiling
span becomes current, the last user-facing span on the context;
dagql.UserFacingSpanContext resolves through it (and degrades to the
plain current span wherever the mark is absent). The catch: the exec
itself runs on a detached execution context - shared/deduped work,
possibly lazily resumed - that does not carry the calling resolver
context mark, so resolving at the executor still lands on a profiling
span. Core therefore captures the user-facing span at exec-setup time,
where it is still known, and hands it to the executor in-process via
ExecutionMetadata (json:"-", cache-key-safe, the ProfArgs pattern);
the executor prefers it for the traceparent injection.

Emission topology is unchanged: the twin and exec.run keep their
parents, wait edges, and statuses; only which span user-facing
attribution names reverts to what it was before the profiling emission
existed.

Verified: the remaining error-family telemetry goldens pass
(fail-log-native, fail-encapsulated, call-failing-dep,
call-bubbling-dep, python-pending, typescript-fail-log-native) with
fail-effect/pending/custom-span/use-exec-service/docker-build-fail
still green, and no traceparent/exec.run/session_complete strings left
in any golden diff.

Signed-off-by: Erik Sipsma <[email protected]>
go:lint (and ci:bootstrap, which runs it) flagged the previous two
commits: the lazyIsResume branch pushed evaluateOne to gocyclo 31
(limit 30), and the causeCtx edit left container_exec.go misformatted.

Extract the lazy-op span ending into endOTelLazyOp next to its begin
counterpart - which also reads better than a nolint bump - and gofmt
the comment block. go test ./dagql/ stays green.

Signed-off-by: Erik Sipsma <[email protected]>

@vito vito left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice to see a more sophisticated resolution to this! It's always been a hairy part of the data / UI pipeline, doing its best with the data it had.

@sipsma
sipsma merged commit e3b4e9c into dagger:main Jul 14, 2026
78 checks passed
TomChv pushed a commit to TomChv/dagger that referenced this pull request Jul 15, 2026
…lyzer moved out of tree (dagger#13588)

* feat(wcprof): intern per-op metadata (user exec argv) in the recorder

Add an interned op-metadata slot to the native wall-clock recorder so an op can
carry a small canonical string alongside its class/ident/client. The first use
is a user exec's scrubbed argv, encoded as the canonical scalar JSON-array
string and interned as the op's MetaID (0 when none), so repeated identical
argvs share one string id.

  - wcprof.go: Event.MetaID + openOp.metaID thread the interned id through the
    open-op table and the completed-event stream.
  - dump.go: MetaID is written into the JSON dump (both the open-op header and
    the compact event form) so the offline analyzer can read it back.
  - record.go: RecordOp/BeginOp honour OpOpts.Argv, marshalling and interning it
    once at record time.

This is the recorder half of the exec engine/user split; the executor emit side
(which stamps the same argv onto its OTel span) and the offline analyzer that
reads it land separately.

Signed-off-by: Erik Sipsma <[email protected]>

* feat(wcprof): emit the OTel wall-clock profiling source at dagql choke points

Add an optional second source for the wall-clock profiler that rides on the
engine's ordinary OTel spans, so a Dagger Cloud trace can be analyzed offline
without running the opt-in native recorder. The engine emits the same causal
model the native recorder captures inline -- shared-execution ops, per-caller
wait edges, and a causal-parent override for lazily-evaluated work -- as a small
set of extra span/link attributes (engine/telemetryattrs), which the offline
analyzer compiles into the same wcprof IR.

Emit sites (all gated only on telemetry being active):

  - otelprof_hooks.go: a singleflighted call_exec op per resolver execution plus
    a publishResult bracket, and a per-caller wait edge (EmitOTelWait) carrying
    purpose/reason/abs-ns timing and a target span, so a joiner's blocked time is
    attributed to the execution it waited on. A recording waiter whose target was
    never minted emits a targetless (all-zero) wait so the offline gate flags it
    rather than silently dropping the edge.

  - otelprof_lazy.go + cache.go: lazy evaluation re-points deferred work under a
    consumer-side `lazy` op via an explicit wcprof.parent causal-parent override
    on the direct re-pointed spans -- separating causal parentage from UI
    parentage so dagui renders unchanged. Emit, never inference: the analyzer
    reads only the attribute the engine writes.

Static profile-skip: the reflection / schema-walk class that normal telemetry
already hides emits a call_exec+publishResult pair per cache miss and dominates
OTel volume on a module-load workload. A pure static predicate
(profileSkip(receiverType, field) in core/telemetry.go) decides lookup-free
whether to profile a call; the immediate receiver type name is captured at the
object call site (objects.go -> CallRequest.ReceiverTypeName) and the decision
is stamped once onto the call frame (ResultCall.ProfileSkip), travelling with
the frame through clone()/fork() and JSON persistence so every singleflight
joiner and every derived child agrees by construction. It is a pure function of
the recipe and is EXCLUDED from every digest, so it can never perturb caching.
Native wcprof is opt-in/dev-only and keeps full detail (ungated).

The offline loader/gate that consume this shape live in the closed-source
analyzer; the emit contract here is machine-checked by in-package tests that
assert the exact exported span/link attribute shape.

Signed-off-by: Erik Sipsma <[email protected]>

* feat(wcprof): split engine setup from user process time in the exec source

Profile a container exec as an exec.run op with two phases -- an engine
containerStart phase and a user processRun phase -- so a slow `go build`
headlines as the user's slow command, not as engine overhead. Only processRun is
user work; containerStart stays engine time. Emitted on both profile sources:
the native recorder's phase ops, and (on the executor's ordinary OTel spans) an
exec.run / containerStart / processRun span split.

  - executor.go / executor_spec.go: capture the wall-clock setup/run boundary at
    the same started-callback the native recorder uses (one cheap atomic per run,
    read only when OTel emit is active), and thread the resolved exec ident.

  - container_exec.go: capture the fully-resolved user command (ProfArgs) at
    exec-run time BEFORE any engine shim (the QEMU emulator, the executor's
    /.init) wraps it -- a capture below a shim would headline the shim instead of
    the user's real program, worst on the slowest emulated execs. ProfArgs is
    json:"-" and set only after every exec digest is computed, so it can never
    perturb a cache key.

  - wcprof_argv.go: encode the command as the canonical scalar JSON-array string,
    bounded in arity and length, and stamp it onto the user processRun (native
    MetaID + OTel wcprof.exec.argv); the engine phase never carries argv, so each
    exec ranks under its own command class.

  - secret_scrub.go: add ScrubStrings, redacting the argv from the SAME registered
    secret set the stdout/stderr scrubbers use, before it is recorded or emitted.

The recorder's interning of this argv landed separately; the offline analyzer
reads it from both sources.

Signed-off-by: Erik Sipsma <[email protected]>

* feat(wcprof): emit a service.start op with installer wait edges

Profile service startup on the OTel source, mirroring the native recorder's
service_start op. The first installer to start a service mints a service.start
op scoping the start (incl. health-check) window; any other installer that
blocks on the in-flight start emits a service wait edge (dagql.EmitOTelWait,
reason=service) targeting it, so the blocked install time is attributed to the
service start it waited on.

The op is ui.passthrough so dagui keeps showing the long-lived `exec <args>`
service span rather than this start-window span -- the same causal-vs-UI
separation the other choke points use.

Signed-off-by: Erik Sipsma <[email protected]>

* feat(wcprof): guarantee the exported trace arrives complete toward Cloud

The OTel BatchSpanProcessor queue is non-blocking and silently DROPS spans on
overflow, and wall-clock analysis on silently-partial data is worthless. Guard
the whole Cloud path with a prevent-and-detect pair.

Detect -- an engine span-count completeness checksum (the producer half):

  - wcprofcount.go: a shared span-count processor tallies every engine span per
    trace, excluding the carrier span itself.
  - session.go: at session teardown the engine stamps the EXACT per-trace engine
    span total onto a wcprof.session_complete carrier span and force-flushes it
    under an uncanceled context, so the offline loader can refuse a trace whose
    received count is below the declared one (a silently dropped leaf) instead of
    ranking on partial data.
  - server.go: register the counter on every per-client tracer provider (shared
    instance) so nested-client spans count into the same trace.

Prevent -- large BOUNDED Cloud BSP queues:

  - livespan.go: NewLargeQueueLiveSpanProcessor sizes the queue to 256Ki slots
    (only a ~2MiB pointer ring) with a large export batch -- roughly 8x a cold
    engine build's ~30k live-double-emitted records -- so a big burst is absorbed
    with headroom. Kept BOUNDED (never block on full), so telemetry can never
    stall the build; any residual overflow is still caught by the checksum above.
  - session.go / engine.go: use it on every hop that feeds a Cloud trace (the
    engine's per-client DB processors and the CLI->Cloud exporter), the tail of
    which was where the completeness carrier first dropped.

  - otlpdump.go: surface DroppedLinksCount / DroppedAttributesCount in the debug
    dump so a link or link-attribute evicted by an SDK count limit is observable.

Signed-off-by: Erik Sipsma <[email protected]>

* chore(wcprof): remove the in-tree v1 wall-clock analyzer

The offline wall-clock analyzer (engine/wcprof/wcanalyze and its
cmd/wcprof-analyze CLI, from the v1 profiler) moves to a closed-source home.
Only the emit side stays in the OSS engine -- the native recorder and the OTel
profiling source added on the engine's ordinary spans -- and nothing in the
engine imports the analyzer. Its end-to-end coverage moves with it; the emit
contract stays machine-checked here by the in-package emit-shape tests.

Signed-off-by: Erik Sipsma <[email protected]>

* dagui: retain wait-edge link metadata at telemetry ingest

The engine emits runtime wait edges as OTel span links on the waiting
span (link purpose "wait", vocabulary in engine/telemetryattrs): the
target is the op being waited on, and the attributes carry the blocked
window as absolute unix-nano decimal strings plus a reason
(lazy / call_exec / singleflight / service). Until now the dagui
ingest discarded every link attribute except the purpose, so this
information never reached a frontend.

Extend SpanLink with the decoded wait metadata (reason + blocked
window) and give it a ProcessAttribute method as the single funnel for
link attributes, used by the OTLP ingest path (sdktrace link
attributes). Timestamps are parsed from the decimal-string encoding,
which is chosen on the emit side so values round-trip bit-exact
through JSON attribute maps. Wait links remain non-causal: they are
deliberately NOT wired into the cause/effect link handling.

This is pure plumbing: nothing consumes the fields yet.

Signed-off-by: Erik Sipsma <[email protected]>

* dagui: decompose span time into self time vs waiting

A span's displayed duration has always been its merged activity time,
presented as if the op itself were working the whole while. Under lazy
evaluation that is systematically wrong: the op that *forces* a
deferred chain (e.g. Container.stdout evaluating earlier withExecs)
carries the whole wall-clock on its own row while doing microseconds of
real work, and every intermediate op in the forced chain shows the
same inflated number. The wait-edge telemetry (previous commit) carries
exactly the information needed to fix this; this commit adds the model
that consumes it.

TimeBreakdown decomposes a row's painted time into exactly two
categories plus gaps:

  - self time: time the op (or work rendered inside its own subtree)
    actually spent executing
  - waiting: time provably blocked on work rendered elsewhere, each
    stretch labeled with the op actually working at that instant and
    navigable to it
  - dormant time (a lazy value sitting unforced) is no category at
    all: it stays an unpainted gap, since the op is neither working
    nor waiting

Model rules, each of which exists for an observed reason:

  * Waiting comes ONLY from evidence: explicit wait edges, plus
    inferred windows (below). Tree shape alone never fabricates
    waiting, and a caller blocked on its own same-name execution twin
    (the call_exec span dagql emits per resolver run) is doing its own
    work, not waiting.

  * Subtree rule: a wait window whose resolved blocker renders inside
    the row's own subtree is the row hosting its own nested work (a
    module call running its function, a group span wrapping its
    pieces) and counts as self time; the detail is expandable below.
    Only blockers rendered elsewhere read as "waiting on X".

  * Transitive, per-instant resolution: if C waits on B, B on A, and A
    is working, C reads "waiting on A" for the stretch A worked, then
    advances. Users should never have to walk the chain by hand.
    Closed waits resolve through recorded edges; LIVE waits resolve by
    descending each blocker's own current blocked state until reaching
    an op that is running and not itself blocked. Both paths share the
    same resolver, with a depth cap and cycle guard; Via records the
    first hop.

  * Inferred waits: wait edges are only emitted when a wait ENDS, and
    they land via AddLink on spans that may stay open long after (a
    lazy-resume marker re-exports only on heartbeat or its own end).
    A live row would therefore tick up as if working and snap down
    when the edge lands - and a row whose own exec just started would
    lose its past blocked stretch entirely. So external deferred-work
    markers hanging off a row's execution also count as blocked
    windows for their interval, whether running or completed; overlap
    with explicit edges merges away in the union. Only marker spans
    that stand in for another op qualify, so plain children can never
    fabricate waiting.

  * Blocker labels prefer the real command: the exec argv attribute
    once the exec has run, else the blocker call's own args (known at
    chain-build time, so live labels name the command before it ever
    executes), else the span name; long commands truncate uniformly.

  * Calm by default: sub-visual slivers are absorbed into their
    neighbor, adjacent same-blocker stretches coalesce, and the
    breakdown is only Material when waiting is at least 1s AND at
    least 20% of painted time. Immaterial rows are expected to render
    byte-identically to today; existing golden tests are the proof.

WaitingNow exposes the live blocked state (is this row blocked right
now, and on what) derived from the same decomposition the display
uses, with a 1s tolerance so snapshot jitter cannot flap it.

Tests model the real emitted span topology - execution twins,
resume markers parented under their trigger, cause links back to the
origin op, late exec children - and assert exact values (specific
durations, targets, argv-derived labels) for: the forcing-op
decomposition, forced-op self-time splits, the subtree/hosting rule,
inferred past waits, live blocked-now with a frozen self-time number,
the forced-row-blocked-deeper recursion case, the live A-on-B-on-C
chain resolving to C, and label fallbacks.

Signed-off-by: Erik Sipsma <[email protected]>

* dagui: enumerate time-breakdown support spans; stream subscribed spans' updates

Frontends that stream a filtered subset of spans (the Cloud trace
websocket sends only visible rows and their children) starve the
time breakdown without knowing it: the execution twins, lazy-resume
markers, wait-edge targets, cause chains, and argv-carrying exec
children that the model reads all hang OUTSIDE the visible set, so a
live browser quietly falls back to the wall-clock number while the
same trace renders correctly from a full local ingest.

TimeBreakdownSpans(visit) enumerates exactly the spans a row's
breakdown draws on beyond the row itself (bounded by the same depth
cap as resolution), so a streaming frontend can ship them alongside
each visible row and subscribe them for updates.

UpdatedSnapshots gains one predicate: a span subscribed by its own ID
now streams its updates too - previously only children of subscribed
parents did, so a support span whose parent was never subscribed would
be sent once and then go stale (its closing wait edges arrive as span
UPDATES via link-append + heartbeat re-export). Strictly additive:
more spans stream, none are lost.

Signed-off-by: Erik Sipsma <[email protected]>

* idtui: report self time as the span duration, with a live "waiting on X" suffix

Apply the time breakdown to the TUI's displayed time. Two changes,
deliberately nothing more:

  * The duration next to a row is now its self time - the time the op
    actually spent executing - instead of merged activity time.
    Material rows only: rows below the materiality thresholds render
    byte-identically to before (existing goldens unchanged), completed
    material rows show just the self-time number with no extra
    decoration, and the number keeps today's styling (yellow while
    running, faint when done). Applied uniformly to the pretty
    frontend's rows, the final report, the check-name duration, and
    the plain frontend's DONE suffix via one shared helper.

  * A row that is blocked RIGHT NOW shows a dim suffix naming the op
    actually working at this moment, transitively resolved and labeled
    by its real command, e.g.:

        .stdout: String! 0.0s ... waiting on sh -c sleep 2; go build -o /tmp/waitdemo .

    The suffix appears only while blocked and disappears when the wait
    ends; the self-time number holds steady during the wait instead of
    ticking up (a blocked row accrues waiting, not self time). Watching
    a forced chain live, the suffixes converge on the one op doing
    real work and advance together as each phase completes.

  * The plain frontend additionally appends ", waited on X" to a
    material row's DONE line, since an append-only log has no later
    chance to show where the time went:

        Container.stdout DONE [0.0s, waited on /tmp/waitdemo]

Render tests cover completed self-time reporting (including the
no-decoration rule) and the live suffix with a frozen number, using
the same realistic span topology as the dagui model tests.

Signed-off-by: Erik Sipsma <[email protected]>

* fix lint issues

Signed-off-by: Erik Sipsma <[email protected]>

* dagui,idtui: no "waiting on" for finished runs, failed rows, or ancestor blockers

CI surfaced a failure-scenario regression the happy-path fixtures never
exercised: after a failed run leaves spans open forever, every span
still looks live, so the blocked-now machinery kept firing during the
FINAL render and the live descent walked the open-span chain up to the
session root - rows rendered "... waiting on POST /query" in the
telemetry goldens.

Three guards, defense in depth:

  * The renderer only asks "blocked right now?" while the run is still
    going (not in a final render) and never for a failed or canceled
    row - a dead run has no "now", and a failed row's story is its
    error, not whatever it was waiting on when things went wrong.

  * WaitingNow applies the same failed/canceled rule at the model
    level, so remote frontends (the Cloud UI) inherit it.

  * A resolved blocker that CONTAINS the row (an ancestor, ultimately
    the session root) is never a meaningful "waiting on X" target:
    chains that dead-end there yield no waiting at all instead of a
    contentless label.

Regression tests model the failure shape directly: an open-span chain
whose cause links dead-end at the root must produce zero waiting
segments, and a live-blocked row that fails must stop reporting
blocked-now.

Signed-off-by: Erik Sipsma <[email protected]>

* engine/server: mark the session-complete carrier ui.internal

CI telemetry goldens surfaced the wcprof.session_complete carrier span
rendering as a real row (e.g. "╰╴✔ wcprof.session_complete" in the
broken-* fixtures). The carrier is protocol bookkeeping - a count
messenger stamped at session teardown - not a unit of work, so no
frontend should draw it. Stamp dagger.io/ui.internal at emission: the
TUI hides internal spans below verbosity 3 (goldens run at 1), Cloud
inherits the same treatment, and the analyzer side is unaffected - the
loader reads the count attributes regardless of UI hints, and the
span-count processor already excludes the carrier by name.

Signed-off-by: Erik Sipsma <[email protected]>

* dagql,engineutil,core: profiling spans never stamp error origins

telemetry.EndWithCause has a second job beyond ending the span: when
the error carries no [traceparent:...] annotation yet, it MUTATES the
error to stamp the ending span as its origin. Origin tracking drives
user-facing attribution - the CLI suppresses the trailing Error: block
only when every origin span was already rendered as a failed row, and
the origin sections render the stamped spans with their logs.

The profiling emission gave that job to spans no frontend draws. The
new passthrough/support spans (exec.run, service.start, the call_exec
twin, publishResult, lazy ops) end deepest, so on any failure they
stamped first, displacing the visible API-call span as the error
origin. CI showed the fallout across six test-split legs: redundant
"Error: exit code: 1 [traceparent:..] [traceparent:..]" blocks in the
telemetry goldens, "✘ exec.run" rendered in error-origin sections, and
- because the mutated error crosses type and wire boundaries - domain
messages ("invalid enum", reserved-name errors, ...) degrading to bare
"exit code: N" in the integration suites.

Introduce dagql.EndProfSpan and use it at all five sites: it links any
origins already tracked in the error and records the cleaned error as
the span status exactly like EndWithCause - the loader still reads the
op outcome - but never stamps. Origin-stamping stays where it lived
before this branch: the user-visible spans (core.AroundFunc) and the
lazy resume span, which predates the profiling emission and keeps its
UI role.

Verified: the affected telemetry goldens pass again (broken-*,
fail-effect, encapsulate, pending, fail-multi*), and the sampled
integration failures from the other legs (TestCustomEnumType,
TestReservedWords) pass with their domain messages restored.

Signed-off-by: Erik Sipsma <[email protected]>

* dagql,engineutil,core: profiling spans transparent to user-facing attribution

The profiling spans do a second job nobody gave them: because the
call_exec twin (and exec.run under it) is the CURRENT span on the
context user work runs under, every attribution surface that reads
"the current span" started naming an unrendered passthrough span:

  * the traceparent injected into a container env parents everything
    the container emits - the nested SDK client spans, the user
    process logs, and the traceparent extension the SDK stamps into a
    returned Error - so module-function logs re-homed to the twin and
    vanished from the function row, and function errors carried the
    twin as their origin, defeating the CLI already-shown-error
    suppression (redundant trailing Error: blocks, re-rendered error
    rows in the origin sections, the python-pending traceback gone);

  * the module-function error-origin fallback and the exec-error
    causeCtx in core stamped the twin directly.

Fix in two layers. dagql.MarkProfilingSpan records, when a profiling
span becomes current, the last user-facing span on the context;
dagql.UserFacingSpanContext resolves through it (and degrades to the
plain current span wherever the mark is absent). The catch: the exec
itself runs on a detached execution context - shared/deduped work,
possibly lazily resumed - that does not carry the calling resolver
context mark, so resolving at the executor still lands on a profiling
span. Core therefore captures the user-facing span at exec-setup time,
where it is still known, and hands it to the executor in-process via
ExecutionMetadata (json:"-", cache-key-safe, the ProfArgs pattern);
the executor prefers it for the traceparent injection.

Emission topology is unchanged: the twin and exec.run keep their
parents, wait edges, and statuses; only which span user-facing
attribution names reverts to what it was before the profiling emission
existed.

Verified: the remaining error-family telemetry goldens pass
(fail-log-native, fail-encapsulated, call-failing-dep,
call-bubbling-dep, python-pending, typescript-fail-log-native) with
fail-effect/pending/custom-span/use-exec-service/docker-build-fail
still green, and no traceparent/exec.run/session_complete strings left
in any golden diff.

Signed-off-by: Erik Sipsma <[email protected]>

* dagql,core: fix lint findings from the attribution fixes

go:lint (and ci:bootstrap, which runs it) flagged the previous two
commits: the lazyIsResume branch pushed evaluateOne to gocyclo 31
(limit 30), and the causeCtx edit left container_exec.go misformatted.

Extract the lazy-op span ending into endOTelLazyOp next to its begin
counterpart - which also reads better than a nolint bump - and gofmt
the comment block. go test ./dagql/ stays green.

Signed-off-by: Erik Sipsma <[email protected]>

---------

Signed-off-by: Erik Sipsma <[email protected]>
shykes pushed a commit that referenced this pull request Jul 16, 2026
…lyzer moved out of tree (#13588)

* feat(wcprof): intern per-op metadata (user exec argv) in the recorder

Add an interned op-metadata slot to the native wall-clock recorder so an op can
carry a small canonical string alongside its class/ident/client. The first use
is a user exec's scrubbed argv, encoded as the canonical scalar JSON-array
string and interned as the op's MetaID (0 when none), so repeated identical
argvs share one string id.

  - wcprof.go: Event.MetaID + openOp.metaID thread the interned id through the
    open-op table and the completed-event stream.
  - dump.go: MetaID is written into the JSON dump (both the open-op header and
    the compact event form) so the offline analyzer can read it back.
  - record.go: RecordOp/BeginOp honour OpOpts.Argv, marshalling and interning it
    once at record time.

This is the recorder half of the exec engine/user split; the executor emit side
(which stamps the same argv onto its OTel span) and the offline analyzer that
reads it land separately.

Signed-off-by: Erik Sipsma <[email protected]>

* feat(wcprof): emit the OTel wall-clock profiling source at dagql choke points

Add an optional second source for the wall-clock profiler that rides on the
engine's ordinary OTel spans, so a Dagger Cloud trace can be analyzed offline
without running the opt-in native recorder. The engine emits the same causal
model the native recorder captures inline -- shared-execution ops, per-caller
wait edges, and a causal-parent override for lazily-evaluated work -- as a small
set of extra span/link attributes (engine/telemetryattrs), which the offline
analyzer compiles into the same wcprof IR.

Emit sites (all gated only on telemetry being active):

  - otelprof_hooks.go: a singleflighted call_exec op per resolver execution plus
    a publishResult bracket, and a per-caller wait edge (EmitOTelWait) carrying
    purpose/reason/abs-ns timing and a target span, so a joiner's blocked time is
    attributed to the execution it waited on. A recording waiter whose target was
    never minted emits a targetless (all-zero) wait so the offline gate flags it
    rather than silently dropping the edge.

  - otelprof_lazy.go + cache.go: lazy evaluation re-points deferred work under a
    consumer-side `lazy` op via an explicit wcprof.parent causal-parent override
    on the direct re-pointed spans -- separating causal parentage from UI
    parentage so dagui renders unchanged. Emit, never inference: the analyzer
    reads only the attribute the engine writes.

Static profile-skip: the reflection / schema-walk class that normal telemetry
already hides emits a call_exec+publishResult pair per cache miss and dominates
OTel volume on a module-load workload. A pure static predicate
(profileSkip(receiverType, field) in core/telemetry.go) decides lookup-free
whether to profile a call; the immediate receiver type name is captured at the
object call site (objects.go -> CallRequest.ReceiverTypeName) and the decision
is stamped once onto the call frame (ResultCall.ProfileSkip), travelling with
the frame through clone()/fork() and JSON persistence so every singleflight
joiner and every derived child agrees by construction. It is a pure function of
the recipe and is EXCLUDED from every digest, so it can never perturb caching.
Native wcprof is opt-in/dev-only and keeps full detail (ungated).

The offline loader/gate that consume this shape live in the closed-source
analyzer; the emit contract here is machine-checked by in-package tests that
assert the exact exported span/link attribute shape.

Signed-off-by: Erik Sipsma <[email protected]>

* feat(wcprof): split engine setup from user process time in the exec source

Profile a container exec as an exec.run op with two phases -- an engine
containerStart phase and a user processRun phase -- so a slow `go build`
headlines as the user's slow command, not as engine overhead. Only processRun is
user work; containerStart stays engine time. Emitted on both profile sources:
the native recorder's phase ops, and (on the executor's ordinary OTel spans) an
exec.run / containerStart / processRun span split.

  - executor.go / executor_spec.go: capture the wall-clock setup/run boundary at
    the same started-callback the native recorder uses (one cheap atomic per run,
    read only when OTel emit is active), and thread the resolved exec ident.

  - container_exec.go: capture the fully-resolved user command (ProfArgs) at
    exec-run time BEFORE any engine shim (the QEMU emulator, the executor's
    /.init) wraps it -- a capture below a shim would headline the shim instead of
    the user's real program, worst on the slowest emulated execs. ProfArgs is
    json:"-" and set only after every exec digest is computed, so it can never
    perturb a cache key.

  - wcprof_argv.go: encode the command as the canonical scalar JSON-array string,
    bounded in arity and length, and stamp it onto the user processRun (native
    MetaID + OTel wcprof.exec.argv); the engine phase never carries argv, so each
    exec ranks under its own command class.

  - secret_scrub.go: add ScrubStrings, redacting the argv from the SAME registered
    secret set the stdout/stderr scrubbers use, before it is recorded or emitted.

The recorder's interning of this argv landed separately; the offline analyzer
reads it from both sources.

Signed-off-by: Erik Sipsma <[email protected]>

* feat(wcprof): emit a service.start op with installer wait edges

Profile service startup on the OTel source, mirroring the native recorder's
service_start op. The first installer to start a service mints a service.start
op scoping the start (incl. health-check) window; any other installer that
blocks on the in-flight start emits a service wait edge (dagql.EmitOTelWait,
reason=service) targeting it, so the blocked install time is attributed to the
service start it waited on.

The op is ui.passthrough so dagui keeps showing the long-lived `exec <args>`
service span rather than this start-window span -- the same causal-vs-UI
separation the other choke points use.

Signed-off-by: Erik Sipsma <[email protected]>

* feat(wcprof): guarantee the exported trace arrives complete toward Cloud

The OTel BatchSpanProcessor queue is non-blocking and silently DROPS spans on
overflow, and wall-clock analysis on silently-partial data is worthless. Guard
the whole Cloud path with a prevent-and-detect pair.

Detect -- an engine span-count completeness checksum (the producer half):

  - wcprofcount.go: a shared span-count processor tallies every engine span per
    trace, excluding the carrier span itself.
  - session.go: at session teardown the engine stamps the EXACT per-trace engine
    span total onto a wcprof.session_complete carrier span and force-flushes it
    under an uncanceled context, so the offline loader can refuse a trace whose
    received count is below the declared one (a silently dropped leaf) instead of
    ranking on partial data.
  - server.go: register the counter on every per-client tracer provider (shared
    instance) so nested-client spans count into the same trace.

Prevent -- large BOUNDED Cloud BSP queues:

  - livespan.go: NewLargeQueueLiveSpanProcessor sizes the queue to 256Ki slots
    (only a ~2MiB pointer ring) with a large export batch -- roughly 8x a cold
    engine build's ~30k live-double-emitted records -- so a big burst is absorbed
    with headroom. Kept BOUNDED (never block on full), so telemetry can never
    stall the build; any residual overflow is still caught by the checksum above.
  - session.go / engine.go: use it on every hop that feeds a Cloud trace (the
    engine's per-client DB processors and the CLI->Cloud exporter), the tail of
    which was where the completeness carrier first dropped.

  - otlpdump.go: surface DroppedLinksCount / DroppedAttributesCount in the debug
    dump so a link or link-attribute evicted by an SDK count limit is observable.

Signed-off-by: Erik Sipsma <[email protected]>

* chore(wcprof): remove the in-tree v1 wall-clock analyzer

The offline wall-clock analyzer (engine/wcprof/wcanalyze and its
cmd/wcprof-analyze CLI, from the v1 profiler) moves to a closed-source home.
Only the emit side stays in the OSS engine -- the native recorder and the OTel
profiling source added on the engine's ordinary spans -- and nothing in the
engine imports the analyzer. Its end-to-end coverage moves with it; the emit
contract stays machine-checked here by the in-package emit-shape tests.

Signed-off-by: Erik Sipsma <[email protected]>

* dagui: retain wait-edge link metadata at telemetry ingest

The engine emits runtime wait edges as OTel span links on the waiting
span (link purpose "wait", vocabulary in engine/telemetryattrs): the
target is the op being waited on, and the attributes carry the blocked
window as absolute unix-nano decimal strings plus a reason
(lazy / call_exec / singleflight / service). Until now the dagui
ingest discarded every link attribute except the purpose, so this
information never reached a frontend.

Extend SpanLink with the decoded wait metadata (reason + blocked
window) and give it a ProcessAttribute method as the single funnel for
link attributes, used by the OTLP ingest path (sdktrace link
attributes). Timestamps are parsed from the decimal-string encoding,
which is chosen on the emit side so values round-trip bit-exact
through JSON attribute maps. Wait links remain non-causal: they are
deliberately NOT wired into the cause/effect link handling.

This is pure plumbing: nothing consumes the fields yet.

Signed-off-by: Erik Sipsma <[email protected]>

* dagui: decompose span time into self time vs waiting

A span's displayed duration has always been its merged activity time,
presented as if the op itself were working the whole while. Under lazy
evaluation that is systematically wrong: the op that *forces* a
deferred chain (e.g. Container.stdout evaluating earlier withExecs)
carries the whole wall-clock on its own row while doing microseconds of
real work, and every intermediate op in the forced chain shows the
same inflated number. The wait-edge telemetry (previous commit) carries
exactly the information needed to fix this; this commit adds the model
that consumes it.

TimeBreakdown decomposes a row's painted time into exactly two
categories plus gaps:

  - self time: time the op (or work rendered inside its own subtree)
    actually spent executing
  - waiting: time provably blocked on work rendered elsewhere, each
    stretch labeled with the op actually working at that instant and
    navigable to it
  - dormant time (a lazy value sitting unforced) is no category at
    all: it stays an unpainted gap, since the op is neither working
    nor waiting

Model rules, each of which exists for an observed reason:

  * Waiting comes ONLY from evidence: explicit wait edges, plus
    inferred windows (below). Tree shape alone never fabricates
    waiting, and a caller blocked on its own same-name execution twin
    (the call_exec span dagql emits per resolver run) is doing its own
    work, not waiting.

  * Subtree rule: a wait window whose resolved blocker renders inside
    the row's own subtree is the row hosting its own nested work (a
    module call running its function, a group span wrapping its
    pieces) and counts as self time; the detail is expandable below.
    Only blockers rendered elsewhere read as "waiting on X".

  * Transitive, per-instant resolution: if C waits on B, B on A, and A
    is working, C reads "waiting on A" for the stretch A worked, then
    advances. Users should never have to walk the chain by hand.
    Closed waits resolve through recorded edges; LIVE waits resolve by
    descending each blocker's own current blocked state until reaching
    an op that is running and not itself blocked. Both paths share the
    same resolver, with a depth cap and cycle guard; Via records the
    first hop.

  * Inferred waits: wait edges are only emitted when a wait ENDS, and
    they land via AddLink on spans that may stay open long after (a
    lazy-resume marker re-exports only on heartbeat or its own end).
    A live row would therefore tick up as if working and snap down
    when the edge lands - and a row whose own exec just started would
    lose its past blocked stretch entirely. So external deferred-work
    markers hanging off a row's execution also count as blocked
    windows for their interval, whether running or completed; overlap
    with explicit edges merges away in the union. Only marker spans
    that stand in for another op qualify, so plain children can never
    fabricate waiting.

  * Blocker labels prefer the real command: the exec argv attribute
    once the exec has run, else the blocker call's own args (known at
    chain-build time, so live labels name the command before it ever
    executes), else the span name; long commands truncate uniformly.

  * Calm by default: sub-visual slivers are absorbed into their
    neighbor, adjacent same-blocker stretches coalesce, and the
    breakdown is only Material when waiting is at least 1s AND at
    least 20% of painted time. Immaterial rows are expected to render
    byte-identically to today; existing golden tests are the proof.

WaitingNow exposes the live blocked state (is this row blocked right
now, and on what) derived from the same decomposition the display
uses, with a 1s tolerance so snapshot jitter cannot flap it.

Tests model the real emitted span topology - execution twins,
resume markers parented under their trigger, cause links back to the
origin op, late exec children - and assert exact values (specific
durations, targets, argv-derived labels) for: the forcing-op
decomposition, forced-op self-time splits, the subtree/hosting rule,
inferred past waits, live blocked-now with a frozen self-time number,
the forced-row-blocked-deeper recursion case, the live A-on-B-on-C
chain resolving to C, and label fallbacks.

Signed-off-by: Erik Sipsma <[email protected]>

* dagui: enumerate time-breakdown support spans; stream subscribed spans' updates

Frontends that stream a filtered subset of spans (the Cloud trace
websocket sends only visible rows and their children) starve the
time breakdown without knowing it: the execution twins, lazy-resume
markers, wait-edge targets, cause chains, and argv-carrying exec
children that the model reads all hang OUTSIDE the visible set, so a
live browser quietly falls back to the wall-clock number while the
same trace renders correctly from a full local ingest.

TimeBreakdownSpans(visit) enumerates exactly the spans a row's
breakdown draws on beyond the row itself (bounded by the same depth
cap as resolution), so a streaming frontend can ship them alongside
each visible row and subscribe them for updates.

UpdatedSnapshots gains one predicate: a span subscribed by its own ID
now streams its updates too - previously only children of subscribed
parents did, so a support span whose parent was never subscribed would
be sent once and then go stale (its closing wait edges arrive as span
UPDATES via link-append + heartbeat re-export). Strictly additive:
more spans stream, none are lost.

Signed-off-by: Erik Sipsma <[email protected]>

* idtui: report self time as the span duration, with a live "waiting on X" suffix

Apply the time breakdown to the TUI's displayed time. Two changes,
deliberately nothing more:

  * The duration next to a row is now its self time - the time the op
    actually spent executing - instead of merged activity time.
    Material rows only: rows below the materiality thresholds render
    byte-identically to before (existing goldens unchanged), completed
    material rows show just the self-time number with no extra
    decoration, and the number keeps today's styling (yellow while
    running, faint when done). Applied uniformly to the pretty
    frontend's rows, the final report, the check-name duration, and
    the plain frontend's DONE suffix via one shared helper.

  * A row that is blocked RIGHT NOW shows a dim suffix naming the op
    actually working at this moment, transitively resolved and labeled
    by its real command, e.g.:

        .stdout: String! 0.0s ... waiting on sh -c sleep 2; go build -o /tmp/waitdemo .

    The suffix appears only while blocked and disappears when the wait
    ends; the self-time number holds steady during the wait instead of
    ticking up (a blocked row accrues waiting, not self time). Watching
    a forced chain live, the suffixes converge on the one op doing
    real work and advance together as each phase completes.

  * The plain frontend additionally appends ", waited on X" to a
    material row's DONE line, since an append-only log has no later
    chance to show where the time went:

        Container.stdout DONE [0.0s, waited on /tmp/waitdemo]

Render tests cover completed self-time reporting (including the
no-decoration rule) and the live suffix with a frozen number, using
the same realistic span topology as the dagui model tests.

Signed-off-by: Erik Sipsma <[email protected]>

* fix lint issues

Signed-off-by: Erik Sipsma <[email protected]>

* dagui,idtui: no "waiting on" for finished runs, failed rows, or ancestor blockers

CI surfaced a failure-scenario regression the happy-path fixtures never
exercised: after a failed run leaves spans open forever, every span
still looks live, so the blocked-now machinery kept firing during the
FINAL render and the live descent walked the open-span chain up to the
session root - rows rendered "... waiting on POST /query" in the
telemetry goldens.

Three guards, defense in depth:

  * The renderer only asks "blocked right now?" while the run is still
    going (not in a final render) and never for a failed or canceled
    row - a dead run has no "now", and a failed row's story is its
    error, not whatever it was waiting on when things went wrong.

  * WaitingNow applies the same failed/canceled rule at the model
    level, so remote frontends (the Cloud UI) inherit it.

  * A resolved blocker that CONTAINS the row (an ancestor, ultimately
    the session root) is never a meaningful "waiting on X" target:
    chains that dead-end there yield no waiting at all instead of a
    contentless label.

Regression tests model the failure shape directly: an open-span chain
whose cause links dead-end at the root must produce zero waiting
segments, and a live-blocked row that fails must stop reporting
blocked-now.

Signed-off-by: Erik Sipsma <[email protected]>

* engine/server: mark the session-complete carrier ui.internal

CI telemetry goldens surfaced the wcprof.session_complete carrier span
rendering as a real row (e.g. "╰╴✔ wcprof.session_complete" in the
broken-* fixtures). The carrier is protocol bookkeeping - a count
messenger stamped at session teardown - not a unit of work, so no
frontend should draw it. Stamp dagger.io/ui.internal at emission: the
TUI hides internal spans below verbosity 3 (goldens run at 1), Cloud
inherits the same treatment, and the analyzer side is unaffected - the
loader reads the count attributes regardless of UI hints, and the
span-count processor already excludes the carrier by name.

Signed-off-by: Erik Sipsma <[email protected]>

* dagql,engineutil,core: profiling spans never stamp error origins

telemetry.EndWithCause has a second job beyond ending the span: when
the error carries no [traceparent:...] annotation yet, it MUTATES the
error to stamp the ending span as its origin. Origin tracking drives
user-facing attribution - the CLI suppresses the trailing Error: block
only when every origin span was already rendered as a failed row, and
the origin sections render the stamped spans with their logs.

The profiling emission gave that job to spans no frontend draws. The
new passthrough/support spans (exec.run, service.start, the call_exec
twin, publishResult, lazy ops) end deepest, so on any failure they
stamped first, displacing the visible API-call span as the error
origin. CI showed the fallout across six test-split legs: redundant
"Error: exit code: 1 [traceparent:..] [traceparent:..]" blocks in the
telemetry goldens, "✘ exec.run" rendered in error-origin sections, and
- because the mutated error crosses type and wire boundaries - domain
messages ("invalid enum", reserved-name errors, ...) degrading to bare
"exit code: N" in the integration suites.

Introduce dagql.EndProfSpan and use it at all five sites: it links any
origins already tracked in the error and records the cleaned error as
the span status exactly like EndWithCause - the loader still reads the
op outcome - but never stamps. Origin-stamping stays where it lived
before this branch: the user-visible spans (core.AroundFunc) and the
lazy resume span, which predates the profiling emission and keeps its
UI role.

Verified: the affected telemetry goldens pass again (broken-*,
fail-effect, encapsulate, pending, fail-multi*), and the sampled
integration failures from the other legs (TestCustomEnumType,
TestReservedWords) pass with their domain messages restored.

Signed-off-by: Erik Sipsma <[email protected]>

* dagql,engineutil,core: profiling spans transparent to user-facing attribution

The profiling spans do a second job nobody gave them: because the
call_exec twin (and exec.run under it) is the CURRENT span on the
context user work runs under, every attribution surface that reads
"the current span" started naming an unrendered passthrough span:

  * the traceparent injected into a container env parents everything
    the container emits - the nested SDK client spans, the user
    process logs, and the traceparent extension the SDK stamps into a
    returned Error - so module-function logs re-homed to the twin and
    vanished from the function row, and function errors carried the
    twin as their origin, defeating the CLI already-shown-error
    suppression (redundant trailing Error: blocks, re-rendered error
    rows in the origin sections, the python-pending traceback gone);

  * the module-function error-origin fallback and the exec-error
    causeCtx in core stamped the twin directly.

Fix in two layers. dagql.MarkProfilingSpan records, when a profiling
span becomes current, the last user-facing span on the context;
dagql.UserFacingSpanContext resolves through it (and degrades to the
plain current span wherever the mark is absent). The catch: the exec
itself runs on a detached execution context - shared/deduped work,
possibly lazily resumed - that does not carry the calling resolver
context mark, so resolving at the executor still lands on a profiling
span. Core therefore captures the user-facing span at exec-setup time,
where it is still known, and hands it to the executor in-process via
ExecutionMetadata (json:"-", cache-key-safe, the ProfArgs pattern);
the executor prefers it for the traceparent injection.

Emission topology is unchanged: the twin and exec.run keep their
parents, wait edges, and statuses; only which span user-facing
attribution names reverts to what it was before the profiling emission
existed.

Verified: the remaining error-family telemetry goldens pass
(fail-log-native, fail-encapsulated, call-failing-dep,
call-bubbling-dep, python-pending, typescript-fail-log-native) with
fail-effect/pending/custom-span/use-exec-service/docker-build-fail
still green, and no traceparent/exec.run/session_complete strings left
in any golden diff.

Signed-off-by: Erik Sipsma <[email protected]>

* dagql,core: fix lint findings from the attribution fixes

go:lint (and ci:bootstrap, which runs it) flagged the previous two
commits: the lazyIsResume branch pushed evaluateOne to gocyclo 31
(limit 30), and the causeCtx edit left container_exec.go misformatted.

Extract the lazy-op span ending into endOTelLazyOp next to its begin
counterpart - which also reads better than a nolint bump - and gofmt
the comment block. go test ./dagql/ stays green.

Signed-off-by: Erik Sipsma <[email protected]>

---------

Signed-off-by: Erik Sipsma <[email protected]>
vito added a commit to vito/dagger that referenced this pull request Sep 27, 2026
Replace the grafted v1 wcprofAnalyze tool with wcprofCapture, which fetches a
wcprof dump once into private module state, and wcprofReport, which slices it
with a wcprof-report helper shipped in the module: per-class self time,
per-parent child breakdowns grouped into shapes, per-client activity over
time, op subtrees, and name-resolved events through jq.

The helper is built at tool-call time against the workspace's engine/wcprof,
so it tracks the dump format; it is grafted into a minimal build tree because
Go import paths can't contain the leading-dot .dagger element. The analyzer
itself stays out of cmd/ and engine/ (dagger#13588); the wcprof README now says so
instead of pointing at the deleted cmd/wcprof-analyze.

Signed-off-by: Alex Suraci <[email protected]>
vito added a commit to vito/dagger that referenced this pull request Sep 28, 2026
Replace the grafted v1 wcprofAnalyze tool with wcprofCapture, which fetches a
wcprof dump once into private module state, and wcprofReport, which slices it
with a wcprof-report helper shipped in the module: per-class self time,
per-parent child breakdowns grouped into shapes, per-client activity over
time, op subtrees, and name-resolved events through jq.

The helper is built at tool-call time against the workspace's engine/wcprof,
so it tracks the dump format; it is grafted into a minimal build tree because
Go import paths can't contain the leading-dot .dagger element. The analyzer
itself stays out of cmd/ and engine/ (dagger#13588); the wcprof README now says so
instead of pointing at the deleted cmd/wcprof-analyze.

Signed-off-by: Alex Suraci <[email protected]>
vito added a commit to vito/dagger that referenced this pull request Sep 28, 2026
Split nested anonymous struct declarations in the node load cost test so
gofmt accepts them, and rewrap the wcprof README so "dagger#13588." no longer
starts a line (MD018 read it as a heading).

Signed-off-by: Alex Suraci <[email protected]>
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.

2 participants