Repository navigation
[backport-0.21] fix(engine): take session teardown off the client shutdown path - #13884
Merged
Merged
Conversation
…dagger#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 dagger#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]>
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)
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
sipsma
force-pushed
the
backport-13681-0.21
branch
from
August 12, 2026 22:45
2e020a0 to
a75c147
Compare
grouville
self-requested a review
August 12, 2026 22:46
grouville
approved these changes
Aug 12, 2026
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]>
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.
Summary
Backports #13681 to the v0.21 maintenance line for v0.21.9.
When the main client's final connection closes, engine-internal session teardown is now scheduled on a background reaper. This keeps the
/shutdownresponse from waiting on unbounded cache and resource reclamation, while the client-critical workspace/service/telemetry drain remains synchronous.This draft also carries the exact proven v0.21 private-GitLab CI-fixture backport from #13849. It replaces revoked GitLab user PAT usage with project deploy tokens and their required usernames in six integration-test files; it does not change product behavior.
The shutdown change addresses shutdown-path teardown scheduling. It does not claim to fix the newly reported startup/egraph contention, and it does not redesign cache release or lifecycle locking.
Source PR and commits
Shutdown-path backport:
cherry-pick -xbackport commit:a5eb16e5efb93794ba31eb08b84a81f56590874da75c147aa640348ac3a03b2739e8f60a60ddf56bce47b2b336e49e37302d05e6abe8195c8ac6ff52GitLab CI-fixture backport:
deploy tokensfor GitLab #13849becaa3a33542ccc7e96dbf3f430d887f41958e52on [backport-0.21] fix: hide registry HTTP probe errors #13885da8c39fb37947ffb4ee304e799b5e09e4c3e3b16Dependency / stacked diff
This draft intentionally and temporarily includes and depends on #13865. PR #13681 relies on the lifecycle-state and removed-tombstone behavior backported there.
The branch starts from the exact current #13865 PR head,
35afbde0013e6c40937fedfa67434c801427762f, but this PR still targetsdagger/dagger:backport-0.21. It must be rebased or otherwise updated after #13865 merges so that the prerequisite commits disappear from this PR's diff. The stacked diff is expected while #13865 remains open.Since the fixture was propagated here, #13885 merged into
backport-0.21as269c47d7708b4623c3fbfdcd2440d19a055dc7e0, so the target branch now contains the same six-file fixture patch. A clean local three-way merge against that base collapses the identical fixture content: the effective merge delta contains only the #13865 prerequisite and #13681 backport files. The exact fixture cherry-pick remains in this branch's history for provenance.v0.21 adaptations
Shutdown-path backport:
engine/server/session.gochange cherry-picked cleanly; its patch is identical to the source commit's production patch.dagqlimport andwcprofSpanCountfixture already present on main. v0.21 needs an explicitdagqlimport and has nowcprofSpanCountfield, so the fixture omits that main-only field. The four regression scenarios and assertions are unchanged..changes/unreleased/Fixed-20260812-212429.yaml, attributed to source PR fix(engine): take session teardown off the client shutdown path #13681.GitLab CI fixture:
becaa3a33542ccc7e96dbf3f430d887f41958e52.cross_session_test.go,git_test.go,gitcredential_test.go,module_config_test.go,module_test.go, andproxy_test.go.No teardown, cache-release, or locking behavior was opportunistically redesigned.
Validation
Shutdown-path validation passed locally:
dagger --progress=plain call engine-dev test --pkg=./engine/server --run='^(TestMainClientLastDisconnectDoesNotBlockOnTeardown|TestSameIDConnectDuringBackgroundTeardownGetsRetryable|TestReapAbandonedWhenMainClientReconnects|TestConcurrentReapsSingleTeardown)$' --race --count=1 --test-verbose— 4/4 passed (trace886bbe0b885eadd71e68918a20194ccd)dagger --progress=plain call engine-dev test --pkg=./engine/server --count=1— 56/56 passed (traceac8e829ffe4a031b53a25e5176e4c983)dagger --progress=plain call engine-dev test --pkg=./engine/server --race --count=1— 56/56 passed (trace63c38bec3799ed278a72b79ff5305185)dagger --progress=plain check go:lint changelog:generate— passed (trace52c8f0caf2bfebc849034933083594a8)GitLab fixture validation and provenance:
becaa3a33542ccc7e96dbf3f430d887f41958e52, including all five formerly failing shards andTestPrivateGitRepoArgCachingin real CI.test-base(2460fc75505f4043c73494f2f9504ba4),test-call-and-shell(6a40c909805c2ca65b8733650c2daa63),test-cli-engine(09c7f1aaa19a385f71b973f574042f59),test-container(4fb6d68d4ea869e4065304ecb7e36cb2), andtest-modules(2eea881d02a2065a40344008d4612f4f).becaa3a33542ccc7e96dbf3f430d887f41958e52andda8c39fb37947ffb4ee304e799b5e09e4c3e3b16match:c5ece8f8d50919d36bdb6abad1e312d65ae8a2bf.gofmt -dproduced no diff for all six fixture files.git diff --checkpassed for both the six-file cherry-pick and the complete stacked PR diff.Release note
The unreleased v0.21.9
Fixedentry says that session teardown now runs in the background after the main client disconnects, preventing shutdown responses from timing out while the engine releases session-owned cache results. It attributes the change to source PR #13681.The GitLab fixture update is test-only and does not add a release note.
Remaining risks / work