Skip to content

engine: explicit client lifecycle and quiescent runtime reclamation - #13999

Closed
vito wants to merge 27 commits into
dagger:mainfrom
vito:extract/client-lifecycle
Closed

vito wants to merge 27 commits into
dagger:mainfrom
vito:extract/client-lifecycle

Conversation

@vito

@vito vito commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Extracted from llm-workspace-dev-env. Independent of the other extraction PRs (#13997, #13998).

What this does for a user

Long-lived engine sessions — an interactive dagger shell, an agent loop, a CI job that spawns many nested module clients — gradually leak: every nested client (module runtime, container proxy, in-engine Dang evaluation) retained its parent runtime, its own trace/log/metric providers, and clientdb handles for the life of the session, and nothing ever unpublished a client that had finished. This PR makes client lifetime explicit so the engine reclaims a nested client's runtime once it is quiescent, while keeping everything that legitimately outlives a request (detached services, lazy cache evaluation, shared DagQL work) alive on a typed lease instead of a captured pointer.

Concretely:

  • Quiescent nested clients are reclaimed. Request admission is serialized with transport closure; once a closed client's typed leases drain, its runtime is unpublished and the parent-retention lease is released (engine/server/session.go, engine/server/client_scope.go).
  • Telemetry is session-owned. Trace, log, and metric providers/processors/readers live on daggerSession, records carry an immutable origin client ID, and export fans out through the validated ancestry route. Session teardown stops producers, then force-flushes and shuts down once (daggerSession.shutdownTelemetry / FlushTelemetry, engine/server/telemetry.go). This is what stops the per-client provider pile-up.
  • Detached work holds a typed lease, not a runtime pointer. engine.ClientScope + engine.DetachClientScope are consumed by: running services (core/services.go, clientScopeLease), lazy/arbitrary cache initializers (dagql/cache_arbitrary.go, ClientLeaseSharedWork), and result-snapshot cleanup in dagql/cache.go.
  • Nested transports must register before serving. Container proxies (engine/engineutil/executor_spec.go) and in-engine Dang proxies (core/sdk/dang/shared/shared.go) call RegisterNestedClientTransport, which validates session authority, parent identity, and ancestry, and closes idempotently from proxy exit or /shutdown.
  • Client metadata is sealed at bootstrap. Registration and init requests reconcile under the session lock and seal one snapshot; conflicts and late completion are rejected; lookups return copies.
  • In-engine Dang clients get inert attachables. Host-backed secret/service lookups from an in-engine Dang client fail with PermissionDenied instead of proxying to the main client (inertAttachables on clientRecord; test DangSuite/TestSDKClientAttachables). Synthetic nested clients resolve attachables through their host-service proxy chain rather than waiting forever.
  • Debuggability. GET /debug/client-lifecycle (cmd/engine/debug.go → Server.ClientLifecycleDebugSnapshot) reports records, retained runtimes, active requests, lease owners, and provider topology.
  • CLI side. engine/client: telemetry subscriptions are bound to the client lifetime, so a failed init or rejected shutdown cancels them and the SSE reconnect loop doesn't hang.

Design and per-step status: hack/designs/client-lifecycle.md.

Extraction notes

Cherry-picked with -x; hunks touching core/agent.go / core/agent_telemetry_test.go (the async agent runtime, coming in a later PR) were dropped from three commits, along with staged-commit helpers (Server.Agents, workspaceGitIdentity) and the harness ServeExecHTTP interface method that belong to other stacks. core/llm: pin object tools to the composed schema is included for its workspaceHostRoutingContext rename and doc updates only; its agent-test changes travel with the agent PR.

Two commits on top of the cherry-picks:

  • engine,dagql: satisfy golangci-lint — the six findings from the first CI run (unparam/unused/dogsled/gocyclo).
  • client: drain telemetry before cancelling it on close — the first CI run failed every integration split the same way: a failed module call exited 1 without printing the error, because Close() cancelled the telemetry consumers (bound to the client lifetime by client: bind telemetry consumers to the client) right after /shutdown returned, before the server streamed the rows the shutdown flush had written. The source branch tip reproduces this too; the fix drains the consumers after a successful /shutdown and keeps cancel-first for a failed one.

Testing

  • go build ./core/... ./engine/... ./dagql/... ./internal/... ./cmd/...
  • go test ./engine/server/ ./engine/ ./engine/client/ ./engine/clientdb/ ./engine/engineutil/ ./engine/telemetry/ ./dagql/ ./core/ ./core/sdk/dang/shared/ ./core/schema/ — all pass.
  • Against a dev engine built from this branch: TestCall/TestArgTypes/*/invalid_output, TestModule/TestCurrentModuleAPI/workdir/error_on_escape (failing before the drain fix) now pass; further representative failures from the other splits re-run locally before pushing. Full suites are on CI.

🤖 Generated with Claude Code

https://claude.ai/code/session_01KHM5ZGg7oCyU9ExQ3upRjC

vito and others added 24 commits August 27, 2026 13:32
Resetting invalid local cache state (unclean shutdown, schema mismatch,
corrupt DBs) deleted the entire worker root dir inline with os.RemoveAll
before the engine came up. On a warm cache that is tens of GB across
millions of inodes: startup blocked for the whole delete, and the unlink
storm saturated the disk queue hard enough to stutter the host for about
a minute.

Rename the discarded state aside to a sibling worker-trash-<unique> dir
instead — an O(1) rename on the same filesystem — so startup proceeds
immediately, and remove the tree from a background sweeper at a bounded
duty cycle (50ms of unlinks, 200ms of rest) so the filesystem journal
drains between bursts instead of monopolizing the disk. The sweeper runs
at full speed when the disk is under the same free-space pressure that
triggers cache GC, resumes leftover trash dirs on the next startup if
interrupted, and detaches stale mounts left behind by the crashed engine
(recursively up front, plus an EBUSY fallback per path) rather than
failing the reset.

The unclean-shutdown integration test now also polls the state volume
until the trash dir is swept, so discarded state cannot silently leak
across resets.

Signed-off-by: Alex Suraci <[email protected]>
Remove discarded worker state synchronously when the configured GC policy
reports disk pressure. This ensures startup reclaims enough space for the
engine to operate before it begins creating files again.

Signed-off-by: Alex Suraci <[email protected]>
…tory-module-wiring

core: wire files, directories, and workspaces between modules
…13916)

* engine/server: sweep discarded cache state slowly

Resetting invalid local cache state (unclean shutdown, schema mismatch,
corrupt DBs) deleted the entire worker root dir inline with os.RemoveAll
before the engine came up. On a warm cache that is tens of GB across
millions of inodes: startup blocked for the whole delete, and the unlink
storm saturated the disk queue hard enough to stutter the host for about
a minute.

Rename the discarded state aside to a sibling worker-trash-<unique> dir
instead — an O(1) rename on the same filesystem — so startup proceeds
immediately, and remove the tree from a background sweeper at a bounded
duty cycle (50ms of unlinks, 200ms of rest) so the filesystem journal
drains between bursts instead of monopolizing the disk. The sweeper runs
at full speed when the disk is under the same free-space pressure that
triggers cache GC, resumes leftover trash dirs on the next startup if
interrupted, and detaches stale mounts left behind by the crashed engine
(recursively up front, plus an EBUSY fallback per path) rather than
failing the reset.

The unclean-shutdown integration test now also polls the state volume
until the trash dir is swept, so discarded state cannot silently leak
across resets.

Signed-off-by: Alex Suraci <[email protected]>

* engine/server: block trash sweep under pressure

Remove discarded worker state synchronously when the configured GC policy
reports disk pressure. This ensures startup reclaims enough space for the
engine to operate before it begins creating files again.

Signed-off-by: Alex Suraci <[email protected]>

---------

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]>
Mark in-engine Dang clients with inert attachables, so that host-backed
secret and service lookups fail with PermissionDenied instead of a proxy to
the main client. Keep explicitly delegated graph resources. Let a Go SDK
dependency build treat ambient Git configuration as optional. Remove the
stale LockMode test setup.

Signed-off-by: Alex Suraci <[email protected]>
(cherry picked from commit 61048a8)
vito added 2 commits August 28, 2026 21:22
Drop the always-nil error from releaseClientConnection and the unused
bool from clientAttachableCaller, blank the pointer-identity byte in
ClientScopeAuthority, and annotate the lifecycle snapshot and two tests
whose shape the linters cannot see past.

Signed-off-by: Alex Suraci <[email protected]>
Binding the telemetry consumers to the client lifetime lets a failed
initialization cancel them, but Close cancelled that lifetime right after
/shutdown returned, before the server had streamed the rows the shutdown
flush wrote. The final spans, including the error that ended the run,
never reached the frontend, so the CLI exited 1 without printing why.

After a successful /shutdown wait for the consumers to drain first; the
server ends the streams itself once it has sent everything. A failed
shutdown keeps cancelling first so a rejected request cannot hang Close.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the extract/client-lifecycle branch from 44c5e3a to b227acb Compare August 29, 2026 01:35
A local generate run had modified it; it is not part of this change.

Signed-off-by: Alex Suraci <[email protected]>
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