Skip to content

[backport-0.21] fix(engine): take session teardown off the client shutdown path - #13884

Merged
sipsma merged 5 commits into
dagger:backport-0.21from
sipsma:backport-13681-0.21
Aug 13, 2026
Merged

sipsma merged 5 commits into
dagger:backport-0.21from
sipsma:backport-13681-0.21

Conversation

@sipsma

@sipsma sipsma commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

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 /shutdown response 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:

GitLab CI-fixture backport:

Dependency / 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 targets dagger/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.21 as 269c47d7708b4623c3fbfdcd2440d19a055dc7e0, 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:

  • The production engine/server/session.go change cherry-picked cleanly; its patch is identical to the source commit's production patch.
  • The source regression-test helper relied on a dagql import and wcprofSpanCount fixture already present on main. v0.21 needs an explicit dagql import and has no wcprofSpanCount field, so the fixture omits that main-only field. The four regression scenarios and assertions are unchanged.
  • Added the v0.21.9 unreleased change entry at .changes/unreleased/Fixed-20260812-212429.yaml, attributed to source PR fix(engine): take session teardown off the client shutdown path #13681.

GitLab CI fixture:

  • Cherry-picked the proven v0.21 commit without conflict or adaptation; the resulting commit has the same stable patch ID as becaa3a33542ccc7e96dbf3f430d887f41958e52.
  • The delta is exactly six existing integration-test files: cross_session_test.go, git_test.go, gitcredential_test.go, module_config_test.go, module_test.go, and proxy_test.go.
  • No engine/product code, diagnostics, local-worktree workaround, or release note was added by the fixture backport.

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 (trace 886bbe0b885eadd71e68918a20194ccd)
  • dagger --progress=plain call engine-dev test --pkg=./engine/server --count=1 — 56/56 passed (trace ac8e829ffe4a031b53a25e5176e4c983)
  • dagger --progress=plain call engine-dev test --pkg=./engine/server --race --count=1 — 56/56 passed (trace 63c38bec3799ed278a72b79ff5305185)
  • dagger --progress=plain check go:lint changelog:generate — passed (trace 52c8f0caf2bfebc849034933083594a8)

GitLab fixture validation and provenance:

  • Canary PR [backport-0.21] fix: hide registry HTTP probe errors #13885 passed all 75 applicable checks on becaa3a33542ccc7e96dbf3f430d887f41958e52, including all five formerly failing shards and TestPrivateGitRepoArgCaching in real CI.
  • Fresh CI on this PR's current head passed all 75 applicable checks: 74 Dagger Cloud contexts plus DCO. The five formerly failing shards passed with traces: test-base (2460fc75505f4043c73494f2f9504ba4), test-call-and-shell (6a40c909805c2ca65b8733650c2daa63), test-cli-engine (09c7f1aaa19a385f71b973f574042f59), test-container (4fb6d68d4ea869e4065304ecb7e36cb2), and test-modules (2eea881d02a2065a40344008d4612f4f).
  • Stable patch IDs for becaa3a33542ccc7e96dbf3f430d887f41958e52 and da8c39fb37947ffb4ee304e799b5e09e4c3e3b16 match: c5ece8f8d50919d36bdb6abad1e312d65ae8a2bf.
  • The post-cherry-pick delta is exactly six files with 35 insertions and 30 deletions.
  • gofmt -d produced no diff for all six fixture files.
  • git diff --check passed for both the six-file cherry-pick and the complete stacked PR diff.

Release note

The unreleased v0.21.9 Fixed entry 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

sipsma and others added 3 commits August 10, 2026 12:14
…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)
@sipsma sipsma added this to the v0.21.9 milestone Aug 12, 2026
@sipsma
sipsma force-pushed the backport-13681-0.21 branch from 2e020a0 to a75c147 Compare August 12, 2026 22:45
@grouville
grouville self-requested a review August 12, 2026 22:46
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]>
@sipsma
sipsma marked this pull request as ready for review August 13, 2026 02:58
@sipsma
sipsma merged commit 67425bb into dagger:backport-0.21 Aug 13, 2026
76 checks passed
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