Repository navigation
engine: explicit client lifecycle and quiescent runtime reclamation - #14047
Conversation
508aa3b to
e4c7338
Compare
4f12948 to
be630ff
Compare
|
no comment on the changes but thats one hell of a title |
f8cf08e to
067261c
Compare
| // lease, regardless of how many waiters join it. | ||
| callCtx := context.WithValue(ctx, cacheContextKey{callKey}, struct{}{}) | ||
| callCtx, cancel := context.WithCancelCause(context.WithoutCancel(callCtx)) | ||
| sharedBase, clientScopeLease, err := engine.DetachClientScope( |
There was a problem hiding this comment.
(from 🤖, reviewed by Erik) [P1] Credential refresh still uses the original request’s released scope
The new scope check breaks credential refresh for memoized LLM endpoints. loadLLMRouter saves a SessionScopedContext for later credential lookups, but that context still contains the original request’s lease. Once the request finishes, the reloader cannot start another cached call, even when a new request has a valid scope.
The environment lookup swallows that error, so the SDK keeps sending its original token. I reproduced this with the LLM endpoint fixture: after rotating the token and advancing the refresh clock, both requests sent Bearer token-v1.
Credential refresh needs to retain the credential owner’s identity while using valid execution ownership for each lookup.
| @@ -74,7 +73,7 @@ func (srv *Server) CurrentWorkspace(ctx context.Context) (*core.Workspace, error | |||
| // Epoch 0 (never bumped) maps to "" so untouched sessions keep the client's | |||
| // default namespace and share cache entries as before. | |||
| func (srv *Server) currentWorkspaceReadEpoch(ctx context.Context) (string, error) { | |||
There was a problem hiding this comment.
(from 🤖, reviewed by Erik) [P2] Workspace read epochs need to follow the workspace owner
Workspace host reads replace client metadata with the workspace owner’s metadata, so their cache keys use the owner’s client ID. This change reads the epoch from the executing client’s scope instead.
That splits the cache key and its invalidation counter across two clients. After the owner exports or reloads its workspace, a nested module can still read the owner’s old cached contents. In a focused probe, the owner’s namespace advanced from parent to parent:1, but the nested reader continued using parent.
Both reading and incrementing this epoch need to refer to the owner of the host-read cache.
There was a problem hiding this comment.
Fixed in 9a39db8: both epoch reads and bumps resolve the validated workspace owner, so nested host reads share the owner’s invalidation counter. Added coverage for parent/nested invalidation and scope validation.
| return fmt.Sprintf("Topic{traceID=%s, clientID=%s}", t.TraceID, t.ClientID) | ||
| } | ||
|
|
||
| func telemetryOriginClientID(ctx context.Context, sessionID string) string { |
There was a problem hiding this comment.
(from 🤖, reviewed by Erik) [P2] Host-routing metadata can change the telemetry origin
Client metadata is deliberately rebound to the workspace owner during workspace host access. The operation still runs under the nested client’s scope, but this helper now attributes its telemetry to the workspace owner.
That sends the telemetry to the owner and its ancestors while skipping the nested client that performed the operation. Previously, the nested client’s provider supplied that destination.
I reproduced this by emitting a span under a child scope with parent workspace metadata: the parent received both span snapshots, and the child received none. The log processor uses the same helper. Telemetry origin needs to remain tied to the executing client when host-routing metadata changes.
There was a problem hiding this comment.
Fixed in 52f34c5: span/log origins prefer the client scope over rebound host metadata, including final telemetry after lease release. The regression checks delivery to the child and its ancestors.
| } | ||
| defer unlockScope() | ||
|
|
||
| if !clientExists { |
There was a problem hiding this comment.
(from 🤖, reviewed by Erik) [P2] Removing DB keepalives makes recurring exports replay historical data
Without the client keepalive reference, each export can leave its store in the 32-entry idle cache. If more than 32 destinations without subscriptions receive recurring telemetry, their stores can repeatedly evict one another. Reopening a store decodes its accumulated telemetry history.
A focused exporter probe with 33 destinations and 2,000 existing log rows each took about 145 ms for three rounds of one-row exports. Holding keepalive references, as before this change, reduced that to 0.47 ms.
This makes new telemetry increasingly expensive as those clients accumulate history. We need a way to bound retained stores without repeatedly replaying the full history of actively used destinations.
There was a problem hiding this comment.
Resolved this by tying the telemetry stores to the clientRuntime which is much more natural than arbitrary 32 LRU anyhow
Model typed client leases, runtime reclamation, child ownership, session teardown, and the final telemetry barrier. Extend the cache model with an explicit release-completion wait and expose both suites through project checks. Signed-off-by: Alex Suraci <[email protected]>
Add a context-aware completion barrier for session release so teardown can wait through deferred operations and cleanup hooks. Preserve cleanup errors for all waiters and cover deferred completion, cancellation, and error propagation. Signed-off-by: Alex Suraci <[email protected]>
Record the design that stops the gradual leak in long sessions. Record the agreed rules for transport registration, metadata sealing, strict parent capability, agent ownership, and the final telemetry flush. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit e26b820) Signed-off-by: Alex Suraci <[email protected]>
Add a lock-safe debug snapshot of client records, retained runtimes, active requests, parent retention, and telemetry provider topology. Record the first shutdown signal so that closed runtimes are visible. Do not change reclamation behavior. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit b26a7a8)
Replace retained ancestor runtime pointers with immutable client ID routes that the session owns. Validate roots and nested ancestry at registration, and resolve runtime ancestors only at use sites. Route telemetry through client IDs so that exporters do not retain parent clients. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 85d8520)
Move trace and log providers, processors, and bounded queues from client runtimes to the session. Stamp each record with its origin client ID and resolve the ancestry route at export. Keep metrics per runtime and remove client DB keepalives. Flush and shut down trace and log telemetry only after producers and cleanup stop. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit b902fdf)
Add immutable client identity and metadata snapshots backed by typed, idempotent lifecycle leases. Lease each accepted request and published transport, and reject new root work after close. Report lease kind and owner counts in the lifecycle snapshot. Do not enable runtime reclamation yet. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 56544bb)
Clone explicit client scopes for agent loops, running services, lazy evaluation callbacks, and shared DagQL calls. Keep agent leases in stopped and failed tombstones because their snapshots embed runtime state. Release service scopes on stop or exit, and release durable leases at session teardown. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 6bfb487)
Require container and in-engine Dang proxies to register a unique nested transport from the creating request before they serve. Publish ancestry, parent retention, and transport ownership together. Close reachability once from proxy cleanup or shutdown, and do not let a first request revive it. Record the implemented steps in the design. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 3a4504d)
Reconcile metadata from registration and bootstrap requests under the session lifecycle lock, then seal one snapshot before runtime initialization. Reject conflicts and late completion. Return an independent copy from each lookup. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 260cc42)
Bind telemetry subscriptions to the client lifetime instead of request cancellation, so that a failed initialization or a rejected shutdown can cancel them. Close the event sources when the client context ends, so that the SSE library does not wait in its reconnect loop. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 5dfa47d)
Separate stable identity and routing records from retained runtime state. Route metadata, telemetry, attachables, and scoped execution through purpose-specific lookups. Clone labels before the session adds analytics attributes, so that attachable and shutdown metadata stay identical. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit da2a615)
Give each detached cache initializer one shared-work client scope for its execution lifetime. Clear the cached cancel closure after completion so that it does not retain the detached runtime context. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 803a230)
Move the engine utility gateway and attachable lookup to the session. Resolve workspace owner metadata from sealed records and host-service proxies from record ancestry, so that workspace access does not need the owner runtime. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 04c8b6f)
Keep active object tools on the schema captured when the LLM was composed, so that cached builders cannot retain old client graphs. Do not compile workspace overlays during normal tool schema resolution. Keep strict overlay loading for explicit agent recomposition. Compact the telemetry context of dormant agents while their durable leases stay explicit. Record the seam in the design. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit f837596) Signed-off-by: Alex Suraci <[email protected]>
Move metric aggregation, the meter provider, and the periodic reader from client runtimes to the session. Stamp engine measurements with an origin ID and partition exports through record ancestry. Include metric flush and shutdown in the final telemetry barrier. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 008123e)
Serialize request admission with transport closure. Unpublish a closed runtime after its typed leases drain, and release the parent ownership from the child transition. Keep runtime-backed agent tombstones on an explicit durable lease. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 5d0106c)
Resolve attachable access for a synthetic nested client through its host-service proxy chain. Secret and socket lookups then do not wait for an attachable that the client never registers. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 1ec98a0)
Release the client scope lock while the runtime initializes, so that schema work can clone lifecycle leases without a lock-order cycle. Keep the runtime alive with a provisional request lease and check the transport state again before the request is admitted. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 5ba3c91) Signed-off-by: Alex Suraci <[email protected]>
Keep the effective client metadata when a client scope is cloned for detached work. This keeps the Workspace owner routing and retains the caller runtime through its lifecycle lease. Signed-off-by: Alex Suraci <[email protected]> (cherry picked from commit 6baece0) Signed-off-by: Alex Suraci <[email protected]>
A tWriter routes a process's output through t.Log. When that process outlives the test, as a leaked client session does, the next line it prints panics with "Log in goroutine after test has completed" and takes every remaining test in the binary down with it; CI lost a passing cache-persistence run this way. Mark the writer done from the test's cleanup, flush any partial line there, and redirect later output to stderr with a marker naming the finished test, so the leak stays visible without becoming fatal. Signed-off-by: Alex Suraci <[email protected]>
The unclean-shutdown persistence subtest kills engine A and then drops its client without closing it, so the client's session process stays alive with its stderr bound to the subtest. When the outer client's cleanup later tore down the tunnel that process was still attached to, it logged after the subtest had completed and panicked the whole test binary. Close the client after the kill, ignoring the expected error, so the session process exits before the subtest finishes. Signed-off-by: Alex Suraci <[email protected]>
Session teardown now waits for deferred cache cleanup and for every client scope lease to release before it shuts telemetry down, and those waits deliberately carry no deadline so a reap never cuts off a live producer. Engine graceful stop has a five minute budget for exactly the opposite reason, but it was stripped twice before reaching those waits: main passed a context without cancel to GracefulStop, and removeDaggerSession dropped whatever it received. One producer that ignored cancellation could therefore hold engine shutdown forever, where the previous sixty second teardown budget had bounded it. Keep the caller's deadline while still dropping its cancellation, and pass the stop context through unchanged. Reaps carry no deadline, so their waits remain unbounded as designed; only graceful stop is bounded. Signed-off-by: Alex Suraci <[email protected]>
A shared call's callback releases its operation lease and client scope lease itself only when it finishes with an error or with no waiters left; otherwise it delegates release to the first waiter that publishes the result. If the callback finishes successfully while a waiter is still admitted, and that waiter is then canceled before it observes completion, neither side releases: the callback saw a waiter, and the waiter took the cancellation path. Every in-flight call of a query whose client disconnects can hit this, and a module load has dozens in flight, so one abrupt disconnect left a session with hundreds of orphaned shared-work leases. Teardown waits for those leases and for the operation lease's cache cleanup without a deadline, so the session never finished tearing down. Record callback completion under callsMu, the same lock the waiter uses to leave, so exactly one side observes the other's state. The last waiter leaving after a successful callback now releases the leases. Before this change the same race leaked the operation lease as well. Signed-off-by: Alex Suraci <[email protected]>
Add an integration test that runs module calls on a nested dev engine and kills the CLI at staggered points while each call's SDK runtime is starting, registering its nested client, or running its exec. Every disconnect reaps the session, and teardown waits without a deadline for every client scope lease, so a lease that is never released leaves a removed session in the lifecycle debug snapshot forever. The test polls that snapshot until no session or runtime remains, dumps the engine's goroutines if one does, and then requires a fresh call to succeed. Its first runs found the orphaned shared-lease race fixed in the previous commit: a disconnect during a module load left every in-flight call's lease held on the main client and the session never tore down. This is the empirical net for the lock-order and lease-ownership bugs that the lifecycle model cannot see by construction. Signed-off-by: Alex Suraci <[email protected]>
The cache model already distinguished a fn completing from its waiters leaving, including a last waiter that takes the ctx.Done arm after the fn has finished, but nothing tracked who owned the callback's operation lease and client shared-work lease after completion. That is the seam the orphaned-lease race lived in: the callback delegates release to the waiters when it succeeds with one admitted, and a waiter that then leaves through cancellation never published, so nothing released them. Track the lease on each ongoing call with Go's release rule: the callback releases on error or with no waiters, the publishing waiter's Once releases at unregistration, and the last waiter leaving without a publication releases as well. SharedLeaseReleasedWhenRetired requires a fully retired call to have released it. The DelegatedReleaseOnly mutation restores the old rule and must violate the invariant, so the gate cannot pass vacuously. Signed-off-by: Alex Suraci <[email protected]>
Add hack/heap-repro, which drives one Go SDK session through many module function calls against a running dev engine while sampling its heap profile after a forced GC, its goroutine count, and its lifecycle snapshot, then renders the recorded runs side by side as a stacked area chart bucketed by allocation site. Every call spawns a fresh module runtime, so the chart shows what one nested client leaves behind: at the merge base the per-client log rings, span processor queues, and clientdb spill files grow with every call until the session closes, while on this branch they stay flat and only the shared cache content grows. run.sh rebuilds the dev engine from a worktree with a fresh state volume before recording, so the same command compares any two builds. Parsing the profile promotes github.com/google/pprof to a direct dependency. Signed-off-by: Alex Suraci <[email protected]>
The Dang in-engine SDK named the nested client's parent from the caller's request metadata rather than from the client scope held on the context. Workspace operations such as local-dependency codegen run under a scope whose client differs from the one their metadata names, so the session rejected the registration with a parent-scope mismatch and dagger-go-sdk:generate failed while generating a module's local dependencies. Derive the parent from the held scope, the same authority the container-exec proxy already uses, via a shared NestedClientParentID helper, and drop the now-redundant caller ID threaded through the Dang SDK. A held scope is now required, so a nested client can no longer fall back to an implicit parent from metadata. Signed-off-by: Alex Suraci <[email protected]>
The orphaned_lease gate added to the expected-outcome map pushed every declaration below it down two lines, so the generated client's embedded SourceMap positions no longer matched main.go and dagger-go-sdk:generate reported the client as out of date. Bump the eleven affected SourceMap line numbers to match; no schema, signature, or description changed. Signed-off-by: Alex Suraci <[email protected]>
CallerStatFS reaches clientAttachableCaller directly, bypassing the inert client guard in resolveClientAttachableCaller. During agent reload, parsing scheme-less module refs therefore waits ten seconds for attachables that in-engine Dang clients will never register. Reject these lookups immediately without granting access to an ancestor's filesystem, and cover both blocking and nonblocking direct lookups in the existing inert-client regression. (cherry picked from commit 3735666) Signed-off-by: Alex Suraci <[email protected]>
Exercise the upstream synthetic-client wait regression through session records after the lifecycle rebase. Preserve registered-client precedence and exact-client waits without relying on the removed daggerClient type. Signed-off-by: Alex Suraci <[email protected]>
Use unique IDs for accepted sockets and remove closed upstream connections so address reuse and stale messages cannot target dead sockets. Keep socket failures isolated to their connection and close sockets on cancellation before waiting for forwarding goroutines. Add regressions for ID reuse, peer closure, failure isolation, and shutdown; validate with repeated race tests and tunnel and local-cache integration tests in Dagger Cloud. Signed-off-by: Alex Suraci <[email protected]>
Retain a client lease for each agent loop and addressable snapshot, release them at their lifetime boundaries, and resolve agents through executable client contexts. Move the runtime adaptation and its regression from vitoland commit 19511cee9f now that agent-runtime is on main. Preserve the upstream mailbox-drain and graceful-stop guards. Signed-off-by: Alex Suraci <[email protected]>
Borrow a shared-work scope from the active request or agent turn when an endpoint refreshes its credentials. Keep lookup bounded by its routing session and timeout after the original routing call releases its lease. Move the adaptation and regression from vitoland commit 42d8367be9. Signed-off-by: Alex Suraci <[email protected]>
Document that OpenStats includes idle cached stores after the idle-cache merge. Preserve the upstream opener injection used by its regressions. This replaces the comment adaptation in vitoland merge fa3a23dbe4. Signed-off-by: Alex Suraci <[email protected]>
8761110 to
a38b78b
Compare
Exercise credential expiry through HTTP requests after the endpoint's original request scope is released. Verify rotated authorization headers reach the provider while the endpoint stays memoized and temporary lookup scopes are released. Signed-off-by: Alex Suraci <[email protected]>
Resolve workspace read epochs through the validated workspace owner so nested host reads share the owner's invalidation counter. Cover ancestor routing, reload invalidation, and rejection of unrelated or released scopes. Signed-off-by: Alex Suraci <[email protected]>
Stamp emission origins from the client scope before consulting host routing metadata. Preserve identity after lease release for final telemetry, while rejecting scopes from another session. Cover delivery to the original client and its ancestors after routing metadata is rebound to the parent. Signed-off-by: Alex Suraci <[email protected]>
Keep recovered telemetry stores open for initialized client runtimes and release them after metric reclamation or the final session telemetry drain. Remove the idle LRU so the final reference closes each store immediately; readers retain independent references and late telemetry reopens history. Cover repeated exports to 33 clients without subscriptions, reclamation with an active reader, persisted history, and registry shutdown races. Signed-off-by: Alex Suraci <[email protected]>
Return leases directly from the infallible test factories and adapt them only at the clone callback boundary. This removes always-nil error results and their redundant assertions while preserving the callback contract. Signed-off-by: Alex Suraci <[email protected]>
Provide a telemetry store registry in the client initialization lock test, matching the runtime's store ownership requirement. Verify that failed initialization releases the store reference along with its request lease. Signed-off-by: Alex Suraci <[email protected]>
…en its producer's session is removed Add a test for a failure first seen when a superseded check was cancelled: a php-client/test run of dagger#14627 failed with "acquire shared client scope: session ... is closed", naming the session of dagger#14626's php-client/php-stan check on the same engine (traces 51ab194ff7d2c48ac494ff453b55daf7 and 68db9b2801268c97c90d34fcc9d617f5). dagger#14047 gave client work typed lifecycle leases: a call shared across sessions runs under a lease cloned from the session that started it, and a session marked removed refuses every further clone, even from a lease it still holds. Session removal marks the session removed before it waits for its leases to drain, so shared work can still be running when its producer's session is marked removed. A nested call that work then makes fails to clone the producer's scope, and the call's other waiters receive that error although their own sessions are alive. The test builds two sessions with the client lifecycle tests' harness, a real dagql cache, and a call both share. It waits for the second session to join the call, marks the producer's session removed as session removal begins, then lets the shared work make its nested call, and asserts the desired behaviour: the surviving waiter gets the call's value, whether from the shared work or by taking it over. It fails today with the producer's closure, every run. It covers the early teardown window, before the cache releases the producer's session. Signed-off-by: Erik Sipsma <[email protected]>
…on was removed The cache shares a call, a lazy evaluation, or a result's publication across sessions, and runs it under a lifecycle lease cloned from the session that started it. Since dagger#14047 (the explicit client lifecycle rework), removing a session first marks it removed, then tears down its services, agents, resolver, containers and cache session, and only then waits for its leases to drain. Shared work it started keeps running in between, and fails as soon as it needs any of that: a removed session refuses to clone its scope, the cache refuses its released session, its services are gone. That failure was handed to every waiter, including sessions that are alive. In CI, cancelling a superseded check failed a healthy check from another PR on the same engine with `acquire shared client scope: session "..." is closed`. Record the removal on the session's scope authority, which every lease the session issues already carries, before the removed state is published and before any teardown step runs. A lease now reports whether its session has been removed. When shared work fails after its producer's session was removed, whatever the error, the cache attributes the failure to the removal: - An ordinary call is retired from the ongoing calls, and each waiter still waiting runs the call again with its own callback, under its own scope: the first starts a new call and the others join it. This also covers a failed publication of the call's result. A waiter takes over at most three times, the same budget as lazy evaluation's foreign-session retries, and then fails with the last failure. - Readers waiting on a publication that fails under a removed session's scope, including a dependency published along with the result, treat it as a miss, as they already do when the producer's cache session was released. - A lazy evaluation is marked as failed by its producer's release, so the existing retry for a released producer applies: waiters from other sessions run it again under their own scopes, with the same bound. The lease guard is unchanged. Letting the old work keep cloning would run it against dependencies teardown has already closed. A genuine failure that happens to coincide with its producer's removal is run once more by a survivor and fails again under the survivor's scope. Signed-off-by: Erik Sipsma <[email protected]>
…en its producer's session is removed Add a test for a failure first seen when a superseded check was cancelled: a php-client/test run of dagger#14627 failed with "acquire shared client scope: session ... is closed", naming the session of dagger#14626's php-client/php-stan check on the same engine (traces 51ab194ff7d2c48ac494ff453b55daf7 and 68db9b2801268c97c90d34fcc9d617f5). dagger#14047 gave client work typed lifecycle leases: a call shared across sessions runs under a lease cloned from the session that started it, and a session marked removed refuses every further clone, even from a lease it still holds. Session removal marks the session removed before it waits for its leases to drain, so shared work can still be running when its producer's session is marked removed. A nested call that work then makes fails to clone the producer's scope, and the call's other waiters receive that error although their own sessions are alive. The test builds two sessions with the client lifecycle tests' harness, a real dagql cache, and a call both share. It waits for the second session to join the call, marks the producer's session removed as session removal begins, then lets the shared work make its nested call, and asserts the desired behaviour: the surviving waiter gets the call's value, whether from the shared work or by taking it over. It fails today with the producer's closure, every run. It covers the early teardown window, before the cache releases the producer's session. Signed-off-by: Erik Sipsma <[email protected]>
…on was removed The cache shares a call, a lazy evaluation, or a result's publication across sessions, and runs it under a lifecycle lease cloned from the session that started it. Since dagger#14047 (the explicit client lifecycle rework), removing a session first marks it removed, then tears down its services, agents, resolver, containers and cache session, and only then waits for its leases to drain. Shared work it started keeps running in between, and fails as soon as it needs any of that: a removed session refuses to clone its scope, the cache refuses its released session, its services are gone. That failure was handed to every waiter, including sessions that are alive. In CI, cancelling a superseded check failed a healthy check from another PR on the same engine with `acquire shared client scope: session "..." is closed`. Record the removal on the session's scope authority, which every lease the session issues already carries, before the removed state is published and before any teardown step runs. A lease now reports whether its session has been removed. When shared work fails after its producer's session was removed, whatever the error, the cache attributes the failure to the removal: - An ordinary call is retired from the ongoing calls, and each waiter still waiting runs the call again with its own callback, under its own scope: the first starts a new call and the others join it. This also covers a failed publication of the call's result. A waiter takes over at most three times, the same budget as lazy evaluation's foreign-session retries, and then fails with the last failure. - Readers waiting on a publication that fails under a removed session's scope, including a dependency published along with the result, treat it as a miss, as they already do when the producer's cache session was released. - A lazy evaluation is marked as failed by its producer's release, so the existing retry for a released producer applies: waiters from other sessions run it again under their own scopes, with the same bound. The lease guard is unchanged. Letting the old work keep cloning would run it against dependencies teardown has already closed. A genuine failure that happens to coincide with its producer's removal is run once more by a survivor and fails again under the survivor's scope. Signed-off-by: Erik Sipsma <[email protected]>
Supersedes #13999 with a fresh branch rooted directly at current
main. Builds on #13940 instead of replaying the cache lifecycle that predated it.What this does
https://claude.ai/code/artifact/d9e5af54-5a24-4ae7-ab4e-da06bd625f9b
Long-lived engine sessions create a new engine client for nested SDK invocations. Previously every client runtime—and its DagQL/schema graph, telemetry providers, engine gateway, and client DB handles—remained reachable until the whole session ended. This change splits stable client identity from reclaimable execution state and reclaims a closed runtime once its explicit owners drain.
ClientScopevalues with typed, idempotent leases for transports, accepted requests, services, shared cache work, and child runtimes./debug/client-lifecycleobservability for records, retained runtimes, lease owners, and provider topology.Integration with #13940
#13940 intentionally made
Cache.ReleaseSessiona tombstone-and-handoff operation: when cache work is active, release returns after assigning cleanup to the last operation, before cleanup hooks necessarily run. That contract is useful and remains unchanged.This branch adds
Cache.WaitSessionRelease, a context-aware completion barrier that returns only after deferred operations and per-session cleanup hooks finish. Authoritative session teardown calls it before the final telemetry flush. Teardown then waits for all remaining client-scope leases as a second producer barrier; this covers detached shared/arbitrary callbacks that can briefly outlive their last request waiter without holding a cache operation.The #13999 lazy-evaluation hunk was not replayed. Its client-scope ownership was rebuilt around #13940's newer per-attempt cache token, with cache-operation completion ordered before runtime-lease release.
TLA+ model
The implementation is split across two executable models, matching the code boundary:
dagql/tla/CacheLifecycle.tlaowns operation admission, release handoff, cleanup completion, and successful release waits.CacheLifecycle_release_wait.cfggates the new contract.engine/server/tla/ClientLifecycle.tlaowns request/transport/background/child leases, two-phase metric drain and runtime reclamation, authoritative teardown, and the final trace/log telemetry barrier. Four configurations cover the core lifecycle, shared work, child retention, and teardown.The client model consumes cache phases abstractly instead of duplicating the full cache state space. TLC caught two assumptions while developing the model: cache-release initiation must itself be fair teardown progress, and already-admitted requests/background work must eventually drain. Both are explicit in
LiveSpec.Project checks:
The design and the mapping from modeled transitions to Go serialization points are in
hack/designs/client-lifecycle.md.Validation
go test ./dagql ./engine ./engine/client ./engine/engineutil ./engine/server ./core -count=1go test -race ./engine/server ./dagql -count=1dagger --cloud check tla-check:cache-lifecycle— all 26 configurations passeddagger --cloud check golang:lint-all markdown-lint:lint tla-check:client-lifecycle dagger-go-sdk:generatedagger --cloud api call engine-dev test --pkg ./core/integration --run='TestDang/TestSDKClientAttachables'— 7 tests passed against the dev engineFull integration splits remain for CI.