Skip to content

fix(engine): fix session shutdown Close flake (flush scoping + DB pool) - #13670

Merged
tiborvass merged 5 commits into
mainfrom
fix-shutdown-flake
Jul 21, 2026
Merged

tiborvass merged 5 commits into
mainfrom
fix-shutdown-flake

Conversation

@vito

@vito vito commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

🤖:

Summary

Fixes the intermittent test-split:test-workspaces (and occasionally other splits) flake where otherwise-passing tests failed at cleanup:

cleanup failed: "close dagger session": shutdown: do shutdown:
Post "http://dagger/shutdown": context deadline exceeded

The CLI gives session shutdown a 10s budget. At teardown the engine force-flushes each client's buffered telemetry to per-client SQLite DBs; under a parallel-teardown storm those writes convoy on SQLite's single writer and blow the budget. Several contention sources compounded; this PR fixes them and keeps the instrumentation that let us attribute each one.

Why now

The flake appeared mid-July. Querying span volume per test-split:test-workspaces trace over time (Dagger Cloud / ClickHouse) shows it isn't gradual — median spans/trace doubled overnight on Jul 14–15, ~60k → ~120k, coinciding with #13588 (wall-clock OTel profiling emission). That change (a) added new profiling spans — dagql.publishResult alone is ~22% of a trace — and (b) enlarged the per-client DB span queue 128× (2048 → 256Ki), so bursts CI used to silently shed are now all retained and must be flushed at teardown. More teardown write volume on the same single-writer sink is what tipped a latent contention into an active flake.

Root cause (two compounding contention sources)

1. An O(n²) flush storm. Every client shutdown called sess.FlushTelemetry, which ForceFlushes every client in the session. N clients tearing down = N whole-session flushes (instrumentation showed up to 30 concurrent, each fanning out to ~69 providers).

2. A single-writer DB convoy. SQLite permits one writer per DB file. A shared single-connection pool funneled every reader and writer through it; the hot main-client DB — the session-wide sink the CLI drains — serialized all writes, and flushes queued behind each other: beginWait/poolWaitDelta in the tens of seconds while individual statements stayed sub-second.

The fix

  • Scope the shutdown flush. A nested client's providers already export to its own DB and every ancestor DB, so it only needs to flush itself; only the main client keeps the session-wide sweep. Removes concurrent contenders without lengthening any single hold — the axis a tail-latency budget cares about.
  • Split the DB pools + batch writes. A single-connection write pool (respecting SQLite's one-writer limit and the modernc thread-pinning tripwire) plus a multi-connection read pool (WAL readers run concurrently with the writer); each export batched into one transaction. Per-statement and commit costs drop to trivial, leaving only queue-for-the-writer time.
  • Skip the live double-emit for internal spans (fix(telemetry): skip live emit for internal spans). The per-client DBs wrote every span twice — a live start snapshot plus the final span. For dagger.io/ui.internal spans that snapshot renders nothing, so it is pure write volume. Skipping it (and reclassifying the childless dagql.publishResult leaf from passthrough → internal so it is covered) removes ~20% of DB writes, directly attacking the volume Wall-clock time: OTel profiling emission, truthful TUI durations, analyzer moved out of tree #13588 added. The final span is still written, so nothing is lost from the completed trace or Cloud.

Validation

Engine logs on comparable load (337 vs 330 total sessions; largest session 68 vs 73 clients):

metric before (RED, timed out) after (this PR)
canceled / failed shutdowns 1 (the flake) 0
max client shutdown 9.998s (killed at budget) 4.12s (completed)
client shutdown >9s / >5s 1 / 9 0 / 0
DB-write beginWait max 11.55s 7.13s
beginWait >9s / >5s writes 13 / 71 0 / 7

The failure mode — a flush killed at the 10s ceiling — is gone, with ~2.4× headroom under budget. A process-global counter logs suppressed live-emits for auditing; the capture dropped 80k internal live-emits (~39% of all live emits, ~20% of DB writes). Nested-client span delivery is preserved (TestTelemetry/TestGolden/trace-function-calls). Green across repeated CI re-runs.

The single-writer floor still produces multi-second holds under peak concurrent teardown (7 writes at 5–7s beginWait), so two levers remain in reserve if it regresses: normalizing the redundant per-row resource/instrumentation_scope blobs, and scoping the local-disk flush outside the network Post /shutdown deadline.

Rejected approaches (documented so we don't relitigate)

  • Bump the client shutdown budget to 60s — papers over legitimate contention; a healthy shutdown should never need >10s.
  • Pool cap = 10 on a shared pool — reintroduced the modernc sqlite busy-wait (busy_timeout == the 10s budget), so one contended write could eat the whole budget. Superseded by the reader/writer split.
  • Batching writes on a shared pool — long transactions starved SSE reads (tail 10s, 903 slow fetches); only safe once writes have a dedicated connection. Tail latency, not throughput, is the metric the budget cares about.
  • Dedupe span double-emission during the run — would cripple the live TUI; the double-emit predates the regression and isn't the cause.

Commits

  1. chore(engine): instrument shutdown drain and client DBs
  2. fix(engine): scope shutdown telemetry flush
  3. fix(clientdb): bump connection pool cap to 10 — now a no-op, fully superseded by Fix crash #4 (squash candidate)
  4. fix(clientdb): split pools and batch writes
  5. fix(telemetry): skip live emit for internal spans

🤖 Generated with Claude Code

vito added a commit that referenced this pull request Jul 17, 2026
Workspace.withModule and withSDK resolve their module source and settings
hints under withWorkspaceLookupLockOverride, which salts every per-client
cache key with a fresh random scope. The override lock rides in context,
invisible to dagql cache keys, so the salt is what keeps results resolved
under one lock from being served to another - but it also means every
evaluation of an install chain redoes the full module fetch, SDK load,
and codegen. The common SDK pattern of evaluating one workspace chain
several times (changes, then export) re-resolved multi-minute installs
from scratch, which is the engine load behind the shutdown flakes that
#13670 instrumented.

Git refs do not need the pessimism: their resolution depends only on the
ref and the base lock contents. Route them through a hidden per-client
field, __workspaceInstallResolution(ref, baseLock), whose args content-
address the resolution. Its value carries the resolved module name,
constructor-arg hints, and the lock recordings of both phases as deltas
(resolve, and the hints module load), computed with Lock.Diff. Callers
replay the deltas onto their overlay lock - the resolve delta always, the
hints delta only when the config entry is actually added - so a cache hit
reproduces bit-for-bit what a live resolution would have recorded.

Local, external, and ambiguous refs keep the live path: they read host or
workspace state that the base lock cannot content-address. The random
scope also stays, both for that path and as the intra-resolution scope
inside the cached unit.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the fix-shutdown-flake branch from 455c3d4 to 264705c Compare July 17, 2026 18:01
@vito vito changed the title fix(engine): make session shutdown drain fast and attributable engine: instrument session shutdown drain to attribute CI flake Jul 17, 2026
@vito
vito force-pushed the fix-shutdown-flake branch from 264705c to db1d6c3 Compare July 17, 2026 18:33
@vito vito changed the title engine: instrument session shutdown drain to attribute CI flake fix(engine): batch client DB telemetry writes to fix shutdown flake Jul 17, 2026

@sipsma sipsma 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.

EDIT: the below was written by claude, it was more enthusiastic about posting the comment here than I wanted before I had actually reviewed, but it lgtm so no harm

Details

Read through the full diff — this is genuinely instrumentation-only: every change is timing capture + leveled logging (the FlushTelemetry clientMu snapshot and the ExportSpans break-then-return are behavior-equivalent). The phase/provider/pool-stat breakdown is exactly what's needed to attribute the drain; it also lines up with what users hit in the wild (the #fastly and #nine reports of shutdown: ... context deadline exceeded on 0.21.7), so this will help beyond the CI flake.

The one red check (test-split:test-local-cache) is unrelated: TestLocalCachePruneSpaceOverrides/reservedSpace failed on a dagger-cli session connect error against the nested engine right after a Received signal terminated on the runner — a known-flaky prune/disk-pressure suite, untouched by this diff. The failing run's own logs show the new instrumentation reporting ~45ms drains, i.e. it's already doing its job. Worth a rerun; good to merge from my side.

FWIW I root-caused the user-facing flavor of this timeout separately: when the main client POSTs /shutdown, beginClosing() cancels its session-attachables request, so the POST usually becomes the last active connection and the deferred cleanup runs the entire removeDaggerSession — including engineCache.ReleaseSession's sequential ref-release walk — before the response is flushed. On big caches that alone blows the 10s budget (the #nine trace logs show ~11.8k sequential ref releases filling the window). I'm prototyping moving session teardown off the shutdown-ACK path on top of this branch; your instrumentation stays load-bearing for the telemetry-flush flavor.

@vito
vito force-pushed the fix-shutdown-flake branch from 02dda22 to db1d6c3 Compare July 17, 2026 19:13
@vito

vito commented Jul 17, 2026

Copy link
Copy Markdown
Contributor Author

@sipsma I'm still chasing down what to fix, really - the instrumentation-only phase was just to try to get some failed CI runs with logs captured, but none of them failed. The logs showed telemetry DB contention, which made me suspicious of #13632 but without it actually failing I'm still flying blind.

@vito vito changed the title fix(engine): batch client DB telemetry writes to fix shutdown flake fix(engine): scope shutdown telemetry flush to fix Close flake Jul 17, 2026
@sipsma

sipsma commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

@sipsma I'm still chasing down what to fix, really - the instrumentation-only phase was just to try to get some failed CI runs with logs captured, but none of them failed. The logs showed telemetry DB contention, which made me suspicious of #13632 but without it actually failing I'm still flying blind.

Yeah makes sense. Sorry about the comment, I forgot to explicitly ask it to have me review before posting so its very much Fable jargon slop.

That fable claims to have a fix by further making shutdown async in some places. I will send out a stacked draft pr on top of this one if you want to look.

@sipsma

sipsma commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Stacked draft with the fix for the user-facing flavor is up at #13681 (teardown was running inside the /shutdown request handler before the response flushed; it now runs on a background reaper). Based on your commits here incl. the flush scoping; will rebase down once this merges.

@vito vito changed the title fix(engine): scope shutdown telemetry flush to fix Close flake fix(engine): fix session shutdown Close flake (flush scoping + DB pool) Jul 17, 2026
@vito

vito commented Jul 17, 2026

Copy link
Copy Markdown
Contributor Author

Yeah makes sense. Sorry about the comment, I forgot to explicitly ask it to have me review before posting so its very much Fable jargon slop.

@sipsma np! figured as much 😄

btw - did you end up investigating shutdown timesouts because of a user-facing issue? I started looking into this because I was seeing a lot of CI flakes, which I figured was from a recent change. Never found a smoking gun though. My guess at the situation is that shutdown timeouts were already a risk, and maybe our CI just sat beneath the 10s threshold enough to not notice most of the time, until #13632 came in and added a moderate perf penalty to telemetry I/O which pushed it over the edge.

I think at this point I'll land what's here:

  • fixing ForceFlush storms - this definitely isn't a new thing, but seems sensible regardless, as long as it doesn't introduce any draining issues (seems OK so far)
  • bumping client DB pool from 1 to 10 - this was unbounded before Engine & TUI fixes: clientdb writes, dagql fan-out, high-verbosity traces #13632 but 1 is pretty aggressive considering we'll need to at least read and write, even ignoring parallel writers. 10 seems as good of a random number as any. 🤷‍♂️

Worth noting that I also tried using a transaction to batch span inserts, and that improved write throughput but ultimately made everything else worse. (Didn't try that with the pool bumped to 10 though...)

My one question is whether we should keep the logging instrumentation. Leaning yes for now, but waiting for a run to finish to make sure it doesn't 2x the logs or something.

@vito
vito force-pushed the fix-shutdown-flake branch from 7f28140 to 8966d9d Compare July 18, 2026 00:43
@sipsma

sipsma commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Yeah makes sense. Sorry about the comment, I forgot to explicitly ask it to have me review before posting so its very much Fable jargon slop.

@sipsma np! figured as much 😄

btw - did you end up investigating shutdown timesouts because of a user-facing issue? I started looking into this because I was seeing a lot of CI flakes, which I figured was from a recent change. Never found a smoking gun though. My guess at the situation is that shutdown timeouts were already a risk, and maybe our CI just sat beneath the 10s threshold enough to not notice most of the time, until #13632 came in and added a moderate perf penalty to telemetry I/O which pushed it over the edge.

I think at this point I'll land what's here:

  • fixing ForceFlush storms - this definitely isn't a new thing, but seems sensible regardless, as long as it doesn't introduce any draining issues (seems OK so far)

  • bumping client DB pool from 1 to 10 - this was unbounded before Engine & TUI fixes: clientdb writes, dagql fan-out, high-verbosity traces #13632 but 1 is pretty aggressive considering we'll need to at least read and write, even ignoring parallel writers. 10 seems as good of a random number as any. 🤷‍♂️

Worth noting that I also tried using a transaction to batch span inserts, and that improved write throughput but ultimately made everything else worse. (Didn't try that with the pool bumped to 10 though...)

My one question is whether we should keep the logging instrumentation. Leaning yes for now, but waiting for a run to finish to make sure it doesn't 2x the logs or something.

Yeah there are user reports of this. The fix in the other pr I sent out is a best guess and hopefully should squash the issue generally just by making more of the shutdown async.

I am totally fine with leaving the logging instrumentation in.

@vito

vito commented Jul 20, 2026

Copy link
Copy Markdown
Contributor Author

@sipsma Looks like the latest CI run caught lightning in a bottle (the shutdown timeout this PR is meant to help) - having an agent investigate some more now that we have instrumented engine logs with the failure happening.

vito added 5 commits July 21, 2026 06:49
CI flaked with nested clients failing at Close: the shutdown POST's 10s
budget expired ("do shutdown: context deadline exceeded") while the
engine drained the session. The engine logs from that run could not
attribute the time: the drain phases (workspace lock flush, service
stop, session-wide telemetry flush) logged nothing on success, and the
suspected bottleneck — every client-DB now shares a single SQLite
connection (1629d02), serialized against SSE drain reads and every
sibling exporter targeting the same parent DB — was invisible.

Add timing logs at each boundary, with no behavior changes: per-phase
durations in serveShutdown (start lines too, so an uncancellable wedge
leaves a breadcrumb), per-provider durations in client telemetry
flush/shutdown, session-flush duration with an engine-wide inflight
gauge and a reason tag, per-lock workspace flush timing, and per-batch
client-DB write timing that pairs each batch with the pool's
WaitCount/WaitDuration delta to separate queuing on the single
connection from statement execution. Slow SSE fetches and slow OTLP
fan-outs log at Warn with the same 1s threshold.

Signed-off-by: Alex Suraci <[email protected]>
Every client shutdown flushed telemetry for the entire session, not just
itself. Under a parallel teardown storm this self-inflicted an O(n^2)
burst: instrumentation on a loaded run showed up to 30 concurrent
whole-session flushes, each fanning out to as many as 69 clients'
providers, all convoying on the per-client-DB single connection. That
burst is what pushed session shutdown past the client's 10s budget and
flaked otherwise-passing tests at Close.

A client's own providers already export its spans to its own DB and to
every ancestor DB, so a nested client only needs to flush itself; the
main client (which shuts down last and whose DB the CLI ultimately
drains) still does a session-wide flush to sweep up stragglers from
clients that had not shut down yet. This removes concurrent contenders
from the hot connection without lengthening any single hold, so it cuts
the shutdown tail rather than trading throughput for it. Validated that
nested-client spans still reach the trace via the trace-function-calls
golden test.

Signed-off-by: Alex Suraci <[email protected]>
The pool was capped at a single connection to stop a burst of concurrent
writers from each pinning an OS thread in modernc.org/sqlite's nanosleep
busy handler and exhausting the Go runtime's thread limit. But a cap of
1 funnels every reader and writer of a client DB through one connection,
and under a parallel-teardown storm that convoy blew the client shutdown
budget: instrumentation showed poolWaitDelta in the tens of seconds on
hot main-client DBs while individual statements stayed sub-second, i.e.
the time was spent queued for the connection, not executing.

The pool was unbounded before the single-connection cap and that was
fine until a specific high-contention tripwire; 1 overcorrected. Cap at
a small bound instead: WAL keeps reader/writer concurrency, writes drain
in parallel, and the worst-case pinned-thread count per DB stays far
below the runtime limit. Pairs with the shutdown flush scoping, which
removed the O(n^2) teardown amplifier; this widens the connection so the
residual live-export write contention drains instead of convoying.

Signed-off-by: Alex Suraci <[email protected]>
The client shutdown timeout kept recurring even after scoping the flush
and bumping the pool, and the engine logs finally pinned why. Every span
was written as its own auto-commit transaction, and each was fanned out
to its own DB plus every ancestor DB and live-emitted twice, so a run
issued ~340k write-lock acquisitions concentrated on hot main-client
DBs. The INSERTs themselves are trivial (~0.5ms, append-only schema, no
secondary indexes); the cost was purely the number of transactions
serializing on SQLite's single writer. Bumping the pool to 10 made it
worse, not better: extra connections can't write in parallel, they lose
the BEGIN IMMEDIATE race and busy-wait for the write lock up to
busy_timeout, which is 10s == the shutdown budget, so one contended
write could consume the whole budget.

Fix the write path two ways. First, give each client DB separate read
and write connection pools: one write connection (SQLite is single
writer, so one avoids all cross-connection busy-waiting) and a small
read pool so SSE drains and log reads run concurrently with the writer
under WAL instead of queuing behind it on a shared connection. Route all
Select* reads through DB.Read(). Second, insert each export batch under
one transaction, which takes the write lock once per batch instead of
once per row (~55x fewer acquisitions); this is safe now only because
the batch holds the dedicated write connection and no longer blocks
reads, which is why the same batching regressed earlier on a shared
pool.

Also decompose the per-batch write log into beginWait (queuing for the
write connection), maxStmtDuration (the INSERTs), and commitDuration
(the WAL commit), so a slow "write N spans" is attributable to the
writer convoy vs. actual SQLite work.

Signed-off-by: Alex Suraci <[email protected]>
The per-client telemetry DBs write every span twice, a live start
snapshot plus the final span, so a running span is visible before it
ends. For dagger.io/ui.internal spans that snapshot is pure write
volume: they are hidden from the UI, so the live copy renders nothing.
Under a parallel-teardown burst those doubled writes convoy on SQLite's
single writer and blow the 10s shutdown budget.

Skip the live snapshot for internal spans on the per-client DB
processors; the final span is still written, so nothing is lost from the
completed trace or Cloud. Reclassify dagql.publishResult from passthrough
to internal so it is covered too: it is a childless leaf, by far the
highest-volume profiling span, so passthrough bought nothing. call_exec
and the other passthrough profiling spans keep their live emit because
they parent real work.

A process-global counter logs how many live emits were suppressed so the
reduction can be measured from a CI capture.

Signed-off-by: Alex Suraci <[email protected]>
@tiborvass
tiborvass force-pushed the fix-shutdown-flake branch from dbccbd5 to 9ec2919 Compare July 21, 2026 13:52
@tiborvass
tiborvass merged commit 1080371 into main Jul 21, 2026
87 checks passed
@tiborvass
tiborvass deleted the fix-shutdown-flake branch July 21, 2026 14:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants