Repository navigation
fix(engine): take session teardown off the client shutdown path - #13681
Merged
Merged
Conversation
sipsma
marked this pull request as ready for review
July 21, 2026 17:35
The main client's /shutdown POST could exceed the CLI's shutdown budget
(default 10s) even though the run itself succeeded, failing CI jobs at
cleanup with:
shutdown: do shutdown: Post "http://dagger/shutdown": context deadline exceeded
The mechanism: serveShutdown's beginClosing() cancels the main client's
session-attachables request, so the /shutdown POST is usually the main
client's last active connection. Its per-request cleanup then ran the
entire removeDaggerSession synchronously — in the request handler,
before the response is flushed. Teardown is unbounded: the dagql cache
release alone walks every session-owned result and runs their release
funcs sequentially (one production trace showed ~11.8k buildkit ref
releases consuming the whole budget on an engine with ~188k live cache
entries). The symptom disappears on a fresh cache and scales with
parallelism, matching user reports on 0.21.7.
Schedule teardown on a background reaper instead of running it in the
request's cleanup. The reaper re-makes the teardown decision under
lifecycleMu (state still initialized, main client still at zero active
connections), so a reconnect that lands between the last disconnect and
the reap abandons the reap, duplicate reaps no-op via the removed
state, and GracefulStop coordinates through lifecycleMu exactly as
before. The removed-tombstone machinery already keeps same-id
reconnects safe during background teardown (retryable error until the
tombstone drops).
The client-critical drain (workspace lock flush, service stop,
session-wide telemetry flush) still runs synchronously in serveShutdown
before the response; only the engine-internal reclamation moves off the
ACK path.
Adds -race regression tests: last-disconnect cleanup returns while
teardown is blocked mid-drain, same-id connects during background
teardown fail retryable and the tombstone survives until teardown
completes, a reconnect abandons a scheduled reap, and concurrent reaps
tear down exactly once.
Signed-off-by: Erik Sipsma <[email protected]>
sipsma
force-pushed
the
shutdown-async-teardown
branch
from
July 21, 2026 17:45
ec1cfa2 to
b395309
Compare
vito
approved these changes
Jul 21, 2026
This was referenced Jul 22, 2026
sipsma
added a commit
that referenced
this pull request
Aug 13, 2026
…tdown path (#13884) * fix(engine): decouple active-clients API from session lifecycle locks (#13542) The active-clients API (engine.clients, polled by the cloud keepalive) and the client-DB GC ticker acquired each session's stateMu. That lock is held across the entire session/client initialization and across removeDaggerSession teardown (which has a 60s safeguard). A single session stuck initializing or tearing down therefore stalled the active-clients enumeration for ALL sessions, so the keepalive could age past the cloud's 15s inactivity timeout and the consolidator would suspend a live engine, crashing connected clients. Hard-cut the session/client lock model so observer paths never touch a per-session lifecycle lock: - Session identity (sessionID, mainClientCallerID) is immutable, set at construction before the session is published into the registry. - Session state is an atomic, read lock-free by observers. - The per-session lock (renamed stateMu -> lifecycleMu) serializes only init and teardown; no observer path acquires it. - Clients / activeClientIDs / clientFromIDs read atomic state + immutable identity (plus a brief clientMu for the client map), never lifecycleMu, so they can never stall on a session in init or teardown. - Teardown stores state=removed first, leaves the session in the registry as a tombstone during cleanup, and pointer-conditionally deletes it only after lifecycleMu is released. This also fixes a latent same-id resurrection race in the old code, which deleted the session from the registry before releasing its session-scoped cache. - getOrInitClient fast-path returns a retryable error for a removed tombstone without taking lifecycleMu; the new session locks lifecycleMu before publication (init-owner guarantee); clients are inserted only after full initialization; the client DB is opened outside clientMu. - GracefulStop snapshots session pointers into a slice before iterating. Adds -race regression tests for the active-clients stall, the same-id fast-return on a removed tombstone, clientFromIDs state gating, and a lifecycle/observer concurrency stress test; adapts the #13474 concurrent-map and init-window race tests to the new field types. Signed-off-by: Erik Sipsma <[email protected]> (cherry picked from commit 0e21927) Signed-off-by: Matias Pan <[email protected]> * fix(engine): take session teardown off the client shutdown path The main client's /shutdown POST could exceed the CLI's shutdown budget (default 10s) even though the run itself succeeded, failing CI jobs at cleanup with: shutdown: do shutdown: Post "http://dagger/shutdown": context deadline exceeded The mechanism: serveShutdown's beginClosing() cancels the main client's session-attachables request, so the /shutdown POST is usually the main client's last active connection. Its per-request cleanup then ran the entire removeDaggerSession synchronously — in the request handler, before the response is flushed. Teardown is unbounded: the dagql cache release alone walks every session-owned result and runs their release funcs sequentially (one production trace showed ~11.8k buildkit ref releases consuming the whole budget on an engine with ~188k live cache entries). The symptom disappears on a fresh cache and scales with parallelism, matching user reports on 0.21.7. Schedule teardown on a background reaper instead of running it in the request's cleanup. The reaper re-makes the teardown decision under lifecycleMu (state still initialized, main client still at zero active connections), so a reconnect that lands between the last disconnect and the reap abandons the reap, duplicate reaps no-op via the removed state, and GracefulStop coordinates through lifecycleMu exactly as before. The removed-tombstone machinery already keeps same-id reconnects safe during background teardown (retryable error until the tombstone drops). The client-critical drain (workspace lock flush, service stop, session-wide telemetry flush) still runs synchronously in serveShutdown before the response; only the engine-internal reclamation moves off the ACK path. Adds -race regression tests: last-disconnect cleanup returns while teardown is blocked mid-drain, same-id connects during background teardown fail retryable and the tombstone survives until teardown completes, a reconnect abandons a scheduled reap, and concurrent reaps tear down exactly once. Signed-off-by: Erik Sipsma <[email protected]> (cherry picked from commit b395309) * chore: add v0.21.9 release note for #13681 Signed-off-by: Erik Sipsma <[email protected]> * test(engine): adapt teardown fixtures for v0.21 Signed-off-by: Erik Sipsma <[email protected]> * test: use project deploy tokens for GitLab (#13849) GitLab automatically revokes user PATs when it detects that they were leaked. That is what these private repository tests used, and both tokens were revoked. GitLab does not document the same automatic response for project deploy tokens. Replace the PATs with read-only deploy tokens scoped to the test project. Deploy tokens use a username and token pair, so pass the matching username through each Git authentication path. These credentials are intentionally committed for end-to-end tests. They can only read one disposable test repository, which contains no private code or data, so exposing them does not grant access beyond the test fixture. Keep both credentials in the shared VCS fixture so future rotations happen in one place. The second token is still needed to test two different credentials for the same repository. Signed-off-by: Guillaume de Rouville <[email protected]> (cherry picked from commit 66337ba) Signed-off-by: Erik Sipsma <[email protected]> --------- Signed-off-by: Erik Sipsma <[email protected]> Signed-off-by: Matias Pan <[email protected]> Signed-off-by: Guillaume de Rouville <[email protected]> Co-authored-by: Guillaume de Rouville <[email protected]>
This was referenced Aug 31, 2026
social4hyq
pushed a commit
to social4hyq/homebrew-core
that referenced
this pull request
Sep 20, 2026
dagger 0.21.9 Created-by: HarmonybrewBot Commit-by: HarmonybrewBot Merged-by: HarmonybrewBot Description: Created by `brew bump` --- Created with `brew bump-formula-pr`.<details> <summary>release notes</summary> <pre>## v0.21.9 - 2026-08-25 ### Added - Added SSHFS-backed volumes, allowing remote filesystems to be mounted into containers without copying their contents into Dagger's content store by @sipsma in dagger/dagger#13462 ### Fixed - `Container.withDirectory` and `Directory.withDirectory` no longer restore by @sipsma in dagger/dagger#13848 \ deleted nested files after execs remove and recreate an ancestor directory. - Engine client enumeration no longer blocks behind another session's by @sipsma in dagger/dagger#13542 \ initialization or teardown, preventing Cloud keeper heartbeats from stalling and live engines from being suspended. - Session teardown now runs in the background after the main client disconnects, by @sipsma in dagger/dagger#13681 \ preventing shutdown responses from timing out while the engine releases session-owned cache results. - The engine now bounds retained DAGQL cache metadata independently of disk by @sipsma in dagger/dagger#13846 \ usage by pruning cold persisted results when the structural estimate exceeds its configured limit. This may mitigate metadata growth at scale while preserving active and engine-lifetime cache roots. - Registry protocol probes no longer appear as scary errors in progress output by @vito in dagger/dagger#13410 \ when image pulls or publishes succeed, while genuine registry failures remain visible. - Registry authentication no longer invalidates downstream container cache reuse across sessions when applied before or after `Container.from` by @sipsma in dagger/dagger#13901 ### What to do next? - Read the [documentation](https://docs.dagger.io) - Join our [Discord server](https://discord.gg/dagger-io) - Follow us on [Twitter](https://twitter.com/dagger_io) </pre> <p>View the full release notes at <a href="https://github.com/dagger/dagger/releases/tag/v0.21.9">https://github.com/dagger/dagger/releases/tag/v0.21.9</a>.</p> </details> <hr> See merge request: Harmonybrew/homebrew-core!17786
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follow-up to #13670 (now merged; this is rebased on main and down to a single commit).
Problem
This is the user-facing flavor of
shutdown: do shutdown: Post "http://dagger/shutdown": context deadline exceeded— reported on v0.21.7 in #fastly and #nine after upgrading from 0.20.x. It's worse with parallel pipelines, disappears on a fresh engine, and for one reporter a 20s shutdown budget still failed while 60s passed. (Distinct from, and complementary to, the CI telemetry-flush burst the latest #13670 commit fixes.)Root cause
The main client's
/shutdownresponse can be blocked on the entire session teardown:serveShutdowncallsbeginClosing(), which cancels the main client's long-lived session-attachables request (wrapped inwithClosingCancel); that request's per-request cleanup decrements the client'sactiveCount./shutdownPOST is now usually the main client's last active connection, so its own deferred cleanup hitsactiveCount == 0and runsremoveDaggerSessionsynchronously — inside the request handler, before the 200 is flushed (the success path never writes to the ResponseWriter, so the client sees nothing until the handler fully returns).engineCache.ReleaseSessionwalks every session-owned result and runs the release funcs sequentially. Trace-level engine logs from the #nine report show the entire 10s budget consumed by ~11.8k sequential ref releases (Cache.ReleaseSession→Container.OnRelease→immutableRef.Release) on an engine with ~188k live dagql cache entries.Whether the POST or the attachables connection ends up "last" is a race — when the attachables cleanup loses it, teardown runs on that goroutine instead and nobody times out. Hence intermittent, load-dependent, and hard to catch in CI.
Fix
The last-disconnect cleanup now only schedules teardown on a background reaper; nothing user-visible waits on it. The reaper re-makes the teardown decision under
lifecycleMu(state stillinitialized, main client still at zero active connections), so:removedstate;GracefulStopcoordinates throughlifecycleMuexactly as before (it waits out an in-flight background teardown, then skips the tombstone);The client-critical drain in
serveShutdown(workspace lock flush, service stop, telemetry flush) is untouched — only engine-internal reclamation moves off the ACK path.Deliberately not done, to keep this minimal: parallelizing/batching the cache-release walk. Once it's off the client path its duration is an engine-internal concern; worth revisiting only if profiles show cross-session
egraphMucontention.Validation
-raceregression tests: last-disconnect cleanup returns while teardown is deterministically blocked mid-drain; same-id connects during background teardown fail retryable while the tombstone survives; a reconnect abandons a scheduled reap; concurrent reaps tear down exactly once.engine/serverpackage green under-racelocally and in the engine-dev harness (99/99 passed).