Repository navigation
fix(engine): decouple the connected-clients API from per-session lifecycle locks - #13542
Merged
Merged
Conversation
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]>
sipsma
force-pushed
the
session-lock-investigator-55be06f3
branch
from
June 23, 2026 23:37
3228a5a to
236acb6
Compare
matipan
approved these changes
Jun 25, 2026
matipan
pushed a commit
to matipan/dagger
that referenced
this pull request
Aug 10, 2026
…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]>
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.
What was happening
On Dagger Cloud, live engines with actively-connected clients were sometimes being suspended out from under those clients, crashing runs mid-execution.
This surfaced via a report in
#engine. The cloud's "keeper" polls each engine for its list of connected clients — theengine { clients }GraphQL field — roughly every couple of seconds and treats the response as a keepalive; the consolidator suspends an engine after ~15s with no successful keepalive. The observed symptom was that, even with clients genuinely connected, the engine would occasionally take longer than 15s to answer that poll, the keepalive would lapse, and a perfectly healthy engine would be suspended.Root cause
The
engine { clients }resolver (and the internal client-DB GC ticker) enumerated sessions while taking each session'sstateMu. That lock is held across a session's entire initialization, and across its teardown (removeDaggerSession— which stops the session's services, releases its dagql cache, drains in-flight work, and flushes/closes telemetry, all under a 60s safeguard).Because the enumeration acquired
stateMuper session, a single session that happened to be mid-init or mid-teardown would block the connected-clients enumeration for all sessions, for as long as that one session's lifecycle work took. Under churn (clients constantly connecting and disconnecting), a poll that coincided with a slow teardown could blow past the 15s keepalive budget. A GoRWMutexread lock is also not context-cancellable, so the keeper timing out client-side did not unblock the engine goroutine.This per-session-lock coupling on the read path was introduced relatively recently (#13474, which fixed a real concurrent-map panic), which is why the symptom was new.
The fix
Restructure the session/client locking so that the read-only observer paths never acquire a per-session lifecycle lock. Listing connected clients becomes a cheap, lock-free read that cannot be blocked by any session's init or teardown.
Technical details
sessionIDandmainClientCallerIDare now set at construction, before the session is published into the registry, and never mutated — so observers can read them with no per-session lock.uninitialized/initialized/removed) is an atomic, so liveness can be read lock-free.stateMu→lifecycleMuand now serializes only initialization and teardown. The three observer paths —Clients()(the resolver),activeClientIDs()(the GC ticker), andclientFromIDs()— read the atomic state plus immutable identity (and, where they need the client map, a briefclientMu), and never takelifecycleMu. A session parked in init or teardown is therefore invisible to stalls.removeDaggerSessionnow storesstate = removedfirst (so a concurrent observer or reconnect sees it immediately), keeps the session in the registry as a tombstone while it cleans up, and the registry entry is pointer-conditionally deleted only afterlifecycleMuis released. As a side benefit this closes a latent same-session-ID resurrection race that existed before: the old teardown removed the session from the registry at the start of teardown, so a reconnect with the same ID could create a fresh session while the old one was still releasing its session-scoped cache.getOrInitClientdoes a lock-free fast-path return for a removed tombstone (so a same-ID reconnect during a slow teardown doesn't block onlifecycleMu); the creating goroutine lockslifecycleMubefore publishing a new session (guaranteeing it is the initializer); a client is inserted into the session only after it is fully initialized (so observers never see a half-built client); the per-client SQLite DB is opened outsideclientMu; andGracefulStopsnapshots session pointers into a slice before iterating.Tests
Adds
-raceregression coverage:clientFromIDsstate gating; andThe existing #13474 concurrent-map and init-window race tests are adapted to the new field types (atomic state,
clientMu-guarded client map).