Repository navigation
fix(engine): fix session shutdown Close flake (flush scoping + DB pool) - #13670
Conversation
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]>
There was a problem hiding this comment.
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.
|
@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. |
|
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. |
@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:
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. |
|
@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. |
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]>
dbccbd5 to
9ec2919
Compare
🤖:
Summary
Fixes the intermittent
test-split:test-workspaces(and occasionally other splits) flake where otherwise-passing tests failed at cleanup: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-workspacestrace 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.publishResultalone 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/poolWaitDeltain the tens of seconds while individual statements stayed sub-second.The fix
fix(telemetry): skip live emit for internal spans). The per-client DBs wrote every span twice — a live start snapshot plus the final span. Fordagger.io/ui.internalspans that snapshot renders nothing, so it is pure write volume. Skipping it (and reclassifying the childlessdagql.publishResultleaf 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):
beginWaitmaxbeginWait>9s / >5s writesThe 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-rowresource/instrumentation_scopeblobs, and scoping the local-disk flush outside the networkPost /shutdowndeadline.Rejected approaches (documented so we don't relitigate)
busy_timeout== the 10s budget), so one contended write could eat the whole budget. Superseded by the reader/writer split.Commits
chore(engine): instrument shutdown drain and client DBsfix(engine): scope shutdown telemetry flushfix(clientdb): bump connection pool cap to 10— now a no-op, fully superseded by Fix crash #4 (squash candidate)fix(clientdb): split pools and batch writesfix(telemetry): skip live emit for internal spans🤖 Generated with Claude Code