Skip to content

fix(engine): take session teardown off the client shutdown path - #13681

Merged
sipsma merged 1 commit into
dagger:mainfrom
sipsma:shutdown-async-teardown
Jul 21, 2026
Merged

sipsma merged 1 commit into
dagger:mainfrom
sipsma:shutdown-async-teardown

Conversation

@sipsma

@sipsma sipsma commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

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 /shutdown response can be blocked on the entire session teardown:

  1. serveShutdown calls beginClosing(), which cancels the main client's long-lived session-attachables request (wrapped in withClosingCancel); that request's per-request cleanup decrements the client's activeCount.
  2. The /shutdown POST is now usually the main client's last active connection, so its own deferred cleanup hits activeCount == 0 and runs removeDaggerSession synchronously — 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).
  3. Teardown is unbounded: engineCache.ReleaseSession walks 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 still initialized, main client still at zero active connections), so:

  • a reconnect landing between the last disconnect and the reap abandons the reap (the next last-disconnect schedules a fresh one);
  • duplicate reaps no-op via the removed state;
  • GracefulStop coordinates through lifecycleMu exactly as before (it waits out an in-flight background teardown, then skips the tombstone);
  • same-id reconnects during background teardown stay safe via the removed-tombstone machinery from fix(engine): decouple the connected-clients API from per-session lifecycle locks #13542 (retryable error until the tombstone drops).

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 egraphMu contention.

Validation

  • New -race regression 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.
  • Full engine/server package green under -race locally and in the engine-dev harness (99/99 passed).

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
sipsma force-pushed the shutdown-async-teardown branch from ec1cfa2 to b395309 Compare July 21, 2026 17:45
@sipsma
sipsma requested a review from vito July 21, 2026 18:27
@sipsma
sipsma merged commit bd52681 into dagger:main Jul 21, 2026
86 of 87 checks passed
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]>
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
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