Repository navigation
dagql: fix session resource cache inconsistencies - #13969
Merged
Merged
Conversation
sipsma
force-pushed
the
sipsma/remote-cache-track6-session-resources
branch
from
August 26, 2026 04:30
44842d8 to
c2d89aa
Compare
sipsma
force-pushed
the
sipsma/remote-cache-track6-session-resources
branch
2 times, most recently
from
August 27, 2026 02:09
85a0c95 to
7e1b574
Compare
sipsma
force-pushed
the
sipsma/remote-cache-track6-session-resources
branch
from
August 30, 2026 19:38
7e1b574 to
39ebfe8
Compare
sipsma
force-pushed
the
sipsma/remote-cache-track6-session-resources
branch
from
September 3, 2026 22:16
de3bb48 to
c467516
Compare
sipsma
force-pushed
the
sipsma/remote-cache-track6-session-resources
branch
from
September 3, 2026 23:05
c467516 to
d29ecc3
Compare
sipsma
force-pushed
the
sipsma/remote-cache-track6-session-resources
branch
from
September 3, 2026 23:48
d29ecc3 to
0eb2abd
Compare
sipsma
force-pushed
the
sipsma/remote-cache-track6-session-resources
branch
from
September 9, 2026 22:09
0eb2abd to
891bb15
Compare
sipsma
force-pushed
the
sipsma/remote-cache-track6-session-resources
branch
from
September 9, 2026 23:06
891bb15 to
73234a8
Compare
sipsma
force-pushed
the
sipsma/remote-cache-track6-session-resources
branch
from
September 18, 2026 18:31
73234a8 to
bd79ad1
Compare
grouville
approved these changes
Sep 18, 2026
Base automatically changed from
sipsma/remote-cache-track5-reader-cancel
to
main
September 18, 2026 18:51
The spec cites Go source as file.go:NNN. These were accurate at ecbad98 and drifted as dagql/cache.go changed across the 14 commits of the remote-cache remediation stack. This re-anchors every citation to the enclosing function plus a short textual anchor (the durable anchor) and refreshes each line number once. Comment-only change; no action, invariant, or property is touched. core and persist report identical distinct-state counts (22,443 and 475,901) before and after, as a comment-only change must. Signed-off-by: Erik Sipsma <[email protected]>
Add session-resource requirement checks to the cache model. Every field
and action is a no-op while Handles = {}, which every existing
configuration now sets, so the 28 existing configurations keep their
exact distinct-state counts (verified: core 22,443; persist 553,097).
Per result: handle (mirrors sessionResourceHandle) and required (the
STORED requiredSessionResources set). Per session: a bound handle set in
the sessionRelease record, cleared at ReleaseSessionDelete. New constant
Handles.
Maintenance follows the code exactly:
- PubIndexFresh sets required from its own chosen handle plus its
structural deps' stored sets (initCompletedResult's recompute,
cache.go:556, 5216); the own handle can only be one the publishing
session has already bound, since a leaf's resolver binds before
returning it (core/schema/secret.go).
- PubAttachAddDep recomputes the parent one level deep
(addExplicitDependencyLocked, cache.go:2668).
- Import folds the one-level recompute over the rows in a
nondeterministic order (the Go map loop over c.resultsByID,
cache_persistence_import.go:359) and applies the decode overwrite to
rows imported "decoded"; DecodeInstall applies the same overwrite at
the read barrier (cache_persistence_import.go:679-685). Both are the
defects that let requiredSessionResources drift from the truth.
The lookup filter (required subset-of bound) gates LookupHit,
CanonicalPick, and FnComplete's reuse branch
(selectLookupCandidateForSessionLocked, cache_egraph.go:685 via
sessionSatisfiesResourceRequirementsLocked:671; direction confirmed by
the extra-handle-still-hits case in cache_test.go). The wait path does
not filter: a session keeps what it produced. BindResource models
BindSessionResource (cache.go:588), refused for a released session.
Properties (intent-encoding, listed in the PROPERTIES/PROPERTY-ONLY
headers with provenance):
- RequiredExact: the stored set equals the transitive recount
TrueRequired, the relationship OwnershipExact has to DerivedOwn.
- ReturnedGated: no session is handed a result depending on a handle
leaf it never bound (retGated recorded at the return boundary).
Stated assumption (PROPERTIES header): a result reaches a session only
through a filtered path; the handle-ID load fallback
(loadResultByResultID canonical mode) that can bypass the filter is out
of scope for this model. The PubIndexFresh and PubAttachAddDep dep
choices are restricted by the same assumption, so the model cannot reach
a session structurally depending on a leaf it never obtained.
Signed-off-by: Erik Sipsma <[email protected]>
Two configurations exercise session-resource checks with Handles = {h1}.
- resources: two sessions, two calls in one class, release on, no
persistence, no injections. Green. RequiredExact and ReturnedGated
hold alongside the graph-integrity core, across bind-before-publish,
an unbound session missing and executing its own, bind-then-hit, bind
racing release, adoption respecting the publishing session, and
attachment of a gated leaf reaching the parent's stored set.
14,784,945 distinct states.
- resources_restart: one session, persistence and import on, release on.
ACCEPTED FINDING, expected red on RequiredExact. The STORED
requiredSessionResources set drifts from the true transitive
requirement in two places that also exist unchanged on upstream/main:
importPersistedState recomputes it over c.resultsByID in Go map order,
so a parent visited before its dependency ends with an empty set
(cache_persistence_import.go:359, recompute at cache.go:556); and the
decode install overwrites it from the decoded value, which knows only
its own handle, so a non-leaf loses its dependency-derived requirement
(cache_persistence_import.go:679-685). TLC reports the violation at an
initial state: res[1] is a leaf (handle h1, required {h1}), res[2]
depends on it but was re-imported "decoded" with required {} while
TrueRequired is {h1}. One session suffices for RequiredExact;
ReturnedGated (the harm) would need two, as the config header explains.
Erik decides what to do with the code.
expectedOutcome records resources green and resources_restart red on
RequiredExact, with the Go functions named.
Signed-off-by: Erik Sipsma <[email protected]>
CacheLifecycle started one goroutine, and so one TLC JVM, per configuration with no bound. With 30 configurations, nine JVMs of 3.4 to 5.5 GiB each (43 GiB together) were running when the kernel's OOM killer took the host down. A buffered-channel semaphore of four in the per-configuration loop caps that. The expectedOutcome map, runOne, and One are unchanged; exported signatures are unchanged, so no generated file changes. Signed-off-by: Erik Sipsma <[email protected]>
runOne took the violated invariant's name by stripping " is violated." from TLC's error line. TLC reports a violation in an initial state as "Error: Invariant X is violated by the initial state:", so the name came out as "X is violated by the initial state:" and the check reported a drifted configuration for resources_restart, whose accepted finding is exactly such an initial-state violation (the import-order drift of requiredSessionResources). The name is the first word after the prefix in both forms; take that. Signed-off-by: Erik Sipsma <[email protected]>
The secret-by-ID cross-session isolation test asserted the pre-fix failure surface: the replayed result ID was served to the unbound session and the error came later, at plaintext resolution, as ResolveSessionResource's "no bound resource for session". Result-ID value loads are now gated on the session's bound resources (sharedResultLookupCanonicalEquivalentGated), so both the concurrent session and the post-close session are refused at load time with "session ... has not bound the session resources this result requires". The isolation contract is unchanged and strictly earlier; the test now asserts the refusal message. Signed-off-by: Erik Sipsma <[email protected]>
A retention edge (AddExplicitDependency) lands after its parent has already been published and settled. A dep carrying session-resource requirements would grow the parent's stored requiredSessionResources at a point where sessions already holding the parent, or an ancestor deriving its set from it, have no way to observe the change - the late-dep half of the gated-growth finding. The public entry now refuses such deps; its one caller retains an SDK-generated typedefs module whose dependency closure is pure type metadata (only secrets and host sockets carry handles, and no public Module API can put either on a constructed module), so the refusal is unreachable today and exists to fail loudly if that ever changes. The publication attach path keeps landing requirement-carrying deps through the internal variant; that window is closed separately by re-checking the filter after the attach barrier. With late growth refused, a live result's stored set can only change while its own attachment is in flight, so the ancestor cascade added for the late-dep defect has no remaining caller that can change any set and is reduced back to the parent-only recompute the attach path needs. Signed-off-by: Erik Sipsma <[email protected]>
The lookup filter runs at selection time under egraphMu, but a hit selected while the result's attachment is still in flight parks at the attach barrier outside that lock, and an attached dep can grow the stored requiredSessionResources before the barrier opens. Nothing re-checked, so the session was served a result it no longer satisfies and the failure surfaced later, at exec time, as a wrong-session resource resolution error - the attach-window half of the gated-growth finding. Serve paths that cross the barrier now re-run the filter afterwards: request and digest lookups convert the hit into a miss and fall through to the singleflight (the engine already accepts duplicate execution in the adjacent dedupe race; the recorded session edge stays until session release rather than growing a decrement-and-collect path), and gated result-ID loads refuse with the same error as the selection-time check. Results that never had an attachment phase skip the re-check: with retention edges refusing requirement-carrying deps, a live result's stored set is frozen once its attachment settles, so the selection-time check still covers them. The waiter-return and publication-attach paths serve the producing session's own results and need no re-check for the same reason. Both new tests hold attachment open with a blocking test object, let a second unbound session select the result mid-attach, then land a gated leaf: the lookup test asserts the miss conversion and the load test asserts the refusal. Each fails without the re-check. Signed-off-by: Erik Sipsma <[email protected]>
sharedResultByResultID canonicalized with requireCleanAttachment=false, so an ID load could be redirected onto an equivalence-class sibling whose dependency attachment was still open or had failed. The load then parked on that sibling's attach barrier and inherited its wait or its attachment error, even though the exact result the caller asked for was settled and healthy - a spurious failure on a load that should succeed. Publication adoption already passes requireCleanAttachment=true for the same reason; the load path now matches it. When no clean candidate satisfies the session, the load falls back to the exact result, which stays gated by the session filter. The regression test holds a lower-ID digest sibling's attachment open and loads the settled exact result by ID: with the old flag the load parks on the sibling's barrier and the test times out; now it resolves to the exact result immediately. Signed-off-by: Erik Sipsma <[email protected]>
The model mirrors the three code changes that closed the finding: 1. ReadBarrierOk re-runs the session-resource filter for hit serves (sessionStillSatisfiesResourceRequirements), and the new ReadBarrierGatedMiss action converts a stale hit into a singleflight fall-through, keeping the recorded session edge exactly as the code does. Gated result-ID loads refuse instead; both are non-serves and the model already folds ID loads into LookupHit. 2. AddDepLate carries the entry-point guard: a retention dep with a non-empty stored required set is refused, so only the empty-required edge is modeled and no stored set changes. With late growth refused, a settled result's required set is frozen, the ancestor cascade has nothing left to repair, and CascadeRequired/AncestorClosure are gone; PubAttachAddDep is back to the parent-only recompute the attach path performs. 3. The held-result guards (FnComplete reuse, PubIndexFresh and PubAttachAddDep deps, AddDepLate) pair ownership with current satisfaction. Ownership alone stopped implying possession the moment a denied hit keeps its recorded edge without receiving the value; the freeze makes satisfaction at use equivalent to having been served, so the pair is exactly possession. The PROPERTIES header states the revised contract. resources_gated_growth flips from the accepted red to a passing check at tighter bounds (MaxResults 2; the pre-fix trace used only the leaf and the parent): 15,576,235 distinct states, and resources_latedep absorbs ReturnedGated at 3,840,790. Re-break evidence: dropping the ReadBarrierOk conjunct turns gated_growth red on ReturnedGated in 23 states; dropping AddDepLate's empty-required guard turns it red on RequiredExact in 21; a probe confirms the gated-miss conversion state is reachable in 21. All 30 configurations are green - no tracked finding remains - and 26 counts are unchanged from the previous suite (the growth window needs three invocations, so configs bounded at MaxInvocations 2 are untouched; resources stays at exactly 2,239,409). Citations re-anchored for the code fixes' line shifts. Signed-off-by: Erik Sipsma <[email protected]>
WithSessionResourceHandle allowed an already-attached result to gain or change its handle under egraphMu and recomputed the stored set in place. Serve paths now rely on a registered result's required set being frozen once its attachment settles (the post-barrier re-check skips results that never had an attachment phase, and held-result guards trust satisfaction-at-serve), so a late handle mutation would grow requirements invisibly to sessions already holding the result or an ancestor. Every production caller stamps detached results; the attached branch now permits only the identical no-op and refuses a semantic change, leaving the stored set untouched. The commit also covers the digest-lookup arm of the post-barrier re-check with its own regression: the same blocked-attachment setup drives lookupCacheForDigests directly and asserts the stale hit converts to a miss. Signed-off-by: Erik Sipsma <[email protected]>
Review round blocker: a hit denied at the post-barrier re-check keeps its recorded session edge, and a later BindResource can make that edge satisfy the filter again, so ownership plus current satisfaction passed the held-result guards for a value the session was never handed. The probe supplied by the review (a denied-then-bound edge feeding FnComplete reuse) violates on the previous spec in 25 states. deniedEdges records exactly those pairs: added by ReadBarrierGatedMiss, cleared by a later successful serve of the same pair (ReadBarrierOk), dropped with the session snapshot at release collect and at restart, and constrained under countedEdges by TypeOK. The four held-result guards (FnComplete reuse, PubIndexFresh and PubAttachAddDep deps, AddDepLate) now require a counted edge outside deniedEdges; the satisfaction conjunct stays as the frozen-set corollary every possessed settled result obeys. With the exclusion, the probe is unreachable over the full 15,556,075-state space, and removing the exclusion from FnComplete alone re-breaks it in 25 states. All 30 configurations stay green; 29 counts are unchanged (deniedEdges is constant empty wherever the conversion cannot fire) and resources_gated_growth tightens from 15,576,235 to 15,556,075 as the excluded reuse paths prune. The resources_latedep registry comment now describes the refusal/freeze instead of the deleted cascade. Signed-off-by: Erik Sipsma <[email protected]>
Review round should-fix: freezing the handle of attached results dropped the lock-time registration check with it, so an identical re-stamp silently succeeded even after the result was collected, and the spec header still describes that guard. The attached branch now resolves the engine cache and verifies the ID is still registered under egraphMu.RLock before permitting the identical no-op or refusing a semantic change. The regression gains the collected case: after the owning session releases, even the identical re-stamp reports the collection; it passes nil against the previous commit (re-break verified). Signed-off-by: Erik Sipsma <[email protected]>
Review round blocker: a counted edge recorded at selection is not possession - a hit parked at (or denied by) the read barrier holds an edge for a value the code never handed over, and a sibling invocation could reuse through it. Tracking received edges instead (the previous commit's deniedEdges, or the review's receivedEdges) closes that hole but under-approximates the code: a fn's resolver legitimately receives values mid-call through inner loads, with no completed outer invocation, and requiring one collapsed 24 of 30 configuration state spaces by 20-45%. The faithful reading models the inner load itself. FnComplete's reuse, PubIndexFresh's structural deps, PubAttachAddDep's attachment dep, and AddDepLate's caller loads no longer consult recorded edges at all: each carries the inner serve's own contract - the result is settled, currently satisfied, the session live - and records the session claim exactly as the code's serve does (trackSessionResult in attachResult, the hit claim in lookupCacheForRequest), adding the session ownership unit when the edge is new. deniedEdges is gone; a pending or denied edge can no longer masquerade as possession because nothing reads it. One narrowing is stated in place: the code claims deps during the fn and may publish after release marking begins; collapsing claim into publication skips marking-session publications with cached deps. Evidence, all on resources_gated_growth bounds unless noted: - the review's pending-edge probe violates on the previous spec in 14 states and still names a reachable state here - deliberately: the reuse it flags now IS the inner load of a settled, satisfied result, claim recorded, which the code performs at that moment; - ProbeReuseWithoutClaim and ProbeReuseUnsatisfied are unreachable over the full 31,257,355-state space: reuse always claims and never serves an unsatisfied result, so the unclaimed-reuse artifact and the acquisition-time-only concern from earlier rounds stay dead; - re-breaks: dropping the ReadBarrierOk re-check turns gated_growth red on ReturnedGated in 22 states; dropping AddDepLate's empty-required guard turns resources_latedep red on RequiredExact in 19 states. All 30 configurations are green. Counts grow everywhere the guards bite, and four snap back to their exact pre-ownership-guard values (decode_cancel 229,933; persist 5,875,948; persist_liveness 700,073; decode_cancel_liveness 868,973), recovering breadth the ownership-only guards had silently pruned. resources_gated_growth runs 31,257,355 distinct states in 5m14s solo; ModelLateDeps turns FALSE there for budget, with the late-window guard re-broken in resources_latedep. Signed-off-by: Erik Sipsma <[email protected]>
Review round blocker: collapsing the inner load into the consuming action forced a liveness guard at consumption time, so the model could not represent a code-real ordering - a resolver's inner load claims the session edge while the session is live, release then marks the session and snapshots its edges while the fn is still running, the fn completes holding the value, and the outer operation late-refuses at exit. FnInnerLoad now performs the claim as its own action, mirroring the serve's critical section (trackSessionResult in attachResult / the hit claim in lookupCacheForRequest): settled result, currently satisfied, live session, edge and session unit recorded, possession remembered on the running call (oc.acq). The four consumers - FnComplete's reuse, PubIndexFresh's structural deps, PubAttachAddDep's attachment dep, and AddDepLate (whose caller runs inside a module-load fn) - read acq with no liveness guard and no edge writes: release marking refuses new claims but does not revoke values a running fn already holds, so the claim -> mark -> completion -> late-refusal ordering is representable. No consumer reads recorded edges, so a pending or denied hit edge still cannot masquerade as possession. Erik ruled for this fidelity over CI cost (the check leaves the CI check in a follow-up): the full 30-configuration suite is green in 33 minutes wall on four contended lanes, with inner-load claims - never modeled before - driving every gated and persistence configuration up (resources_gated_growth 59,068,443; resources_restart 38,479,042; persist 37,253,508; lazy_import 28,353,797). resources' header count and the reuse wording move to the acquisition model. Signed-off-by: Erik Sipsma <[email protected]>
Review round blocker: FnInnerLoad collapsed the claim and the successful delivery into one action, but the code separates them - the serve claims the session edge in its own critical section, and the nested operation exit (op.finish) only hands the value to the resolver afterwards, refusing with ErrCacheSessionReleased when release marked the session in between. The collapsed action could not represent that claim -> mark -> refused-delivery ordering. FnInnerLoadClaim now records the edge and unit and parks the load as oc.acqPending (one in-flight load per call; concurrent resolver loads interleave across calls - stated narrowing). FnInnerLoadDeliver moves it into acq on a live exit; FnInnerLoadRefused drops it on a marked exit, keeping the recorded edge with no possession, exactly the state the review named. FnComplete waits for the in-flight load to resolve, and the deliver/refuse pair joins SystemProgress fairness (a nested operation always exits) so liveness configurations stay meaningful. Consumers are untouched: acq-only, no liveness, no edge reads. What a refused resolver does with the error stays fn-internal nondeterminism (FnCanFail's domain). The PROPERTIES header and the NoSpuriousErrors comment now describe the acquisition model instead of the removed counted-edge guards. Evidence: ProbeLateRefusalOfAcquiredReuse - an invocation in "returning" with a non-live session whose reuse source sits in its call's acq - is reachable in 23 states on resources bounds, replacing the earlier mislabeled probe; the full 30-configuration suite is green in 38.5 minutes wall on four contended lanes, with moderate growth over the single-phase split (resources_gated_growth 66,468,891; resources_restart 52,546,488; lazy_import 42,663,176; persist 40,237,408). Signed-off-by: Erik Sipsma <[email protected]>
Erik's ruling alongside the full-fidelity model: the cache-model checks leave per-PR CI entirely and stay easy to run locally. The tla-check module moves to the dev environment overlay (the same mechanism as engine-lab and tui-qa), so CI's default environment never sees its checks while `dagger --env dev check tla-check:...` keeps working; the module's Go build and bindings stay CI-covered through dagger-go-sdk:generate, which regenerates dev-scoped module bindings too (verified by a converged run). The full CacheLifecycle check now documents its cost (~35-40 minutes wall, largest configurations above 40M distinct states) and is required before pushing changes under dagql/tla - the README states that policy, since nothing enforces it in CI anymore. Two smaller runners make pick-and-choose safe: Quick, a curated cheap-subset check (16 configurations, 15.5s measured) as the iteration default, and Some, which runs named configurations with their expectedOutcome still enforced - the middle ground between the full check and One, which enforces nothing. Verified: quick green in the dev env; the module is absent from the default environment. A CI smoke lane was considered and dropped: check registration has no manual/CI-exclusion attribute, so a default-env smoke check cannot coexist with a dev-only full check in one module without duplicating the module or inventing that attribute. Signed-off-by: Erik Sipsma <[email protected]>
Two review round blockers. First, a pending inner load is a counted session operation in the code (beginSessionOperation through op.finish), so release cleanup cannot run under it, and waiter cancellation cannot strand it. FnInnerLoadClaim now increments the session's active count as the admission; delivery and refusal decrement it through FinishSessionOperation and are enabled while the fn is canceled too; FnWindDown waits for the in-flight load; DerivedSessionActive counts pending loads. A refused delivery is resolver-visible without any injection: the fn may propagate it (a new FnComplete branch guarded by loadRefused), and operation exits now classify an errored operation in a non-live session as a refusal - op.finish's released override - so propagation is a release refusal, never a manufactured failure. Second, the attachment hook's attachResult claims cache-backed children after fn completion, so fn-time acquisitions cannot cover them. PubAttachClaim performs that claim during pubState = "attaching" (single-phase: this path runs inside the outer operation), and a claim attempted after release marked the session fails the attachment deterministically - PubAttachFailDropHold now fires for a non-live session without AttachCanFail. Modeling that refusal surfaced a NEW FINDING, documented as a precise exemption in NoSpuriousErrors and in the README, awaiting a ruling: a publisher's own release between fn completion and attachment closes the barrier with an error and fails an innocent cross-session reader parked on it - the same defect family as the fixed decode_cancel joiner finding, with the analogous fix being a retry/miss classification for parked readers. The exemption tolerates a failure only when the failed invocation's result has a publisher whose session is no longer live. Evidence: ProbePendingDefersRelease green over the full 7,306,439-state resources space (a pending operation always defers release); ProbeUninjectedAttachRefusalReachable red in 10 states (the deterministic attachment refusal is reachable); ProbeCanceledFnResolvesPending red in 14 states on drain_orphan (a canceled fn with an in-flight load is reachable, and its load still resolves). Full 30-configuration suite green, 51.5 minutes wall at four lanes (resources_gated_growth 82,830,107; resources_restart 73,371,326; lazy_import 46,842,707); documented cost figures updated to match, and the tla-check bindings regenerated (converged). Signed-off-by: Erik Sipsma <[email protected]>
…ing red Review round, three blockers and a should-fix. Admission is its own step (FnInnerLoadAdmit: the beginSessionOperation CAS increments active before any graph lock), so release can mark between admission and claim: FnInnerLoadPreclaimRefused exits the operation with nothing recorded, FnInnerLoadDone is the unclaimed live completion (a miss or fresh nested execution), and the claimed pair delivers or refuses as before. DerivedSessionActive counts admitted operations; FnComplete and FnWindDown wait for the admission to resolve; the executor's termination assumption moves to strong fairness on FnComplete, because admission/exit cycles toggle its enabledness and defeat weak fairness (both large liveness configurations were red without it and are green with it). Error provenance replaces the too-broad failing-to-refused conversion: op.finish's released override applies only to a value-bearing success, so the exit classification is strict again, and release-caused errors enter the refusing flow where they are observed - a propagated inner-load refusal (fnErrRefusal) and a release-refused attachment claim (attachRefused) route their waiters to refusing; injected errors stay failures. Attachment failure now requires an actual refused attempt: PubAttachTarget selects the child the hook will attach (satisfied, as the value embeds only possessed children), PubAttachClaimOk records the claim, PubAttachClaimRefused fires when release marked in between and arms the deterministic PubAttachFailDropHold; PubFinishOk waits for the in-flight attempt. The surfaced finding is pinned red instead of exempted: NoSpuriousErrors is strict again, attach_release_reader (two sessions, no handles, no injections) holds the expected red in a 23-state trace - a publisher's release between fn completion and the attachment claim fails a live cross-session reader parked at the read barrier - and resources drops the property, since the finding is reachable at its bounds; decode_cancel keeps it green. README and expectedOutcome track the finding, awaiting the ruling. Evidence: ProbePreclaimRefusalReachable red in 7 states; ProbeAdmittedInnerLoadDefersRelease green over the full 14,035,387-state resources space; ProbeArmedAttachRefusalReachable red in 16 states. Full 31-configuration suite: 30 green plus the pinned red, ~62 minutes wall at four lanes (resources_gated_growth 114,297,187; resources_restart 110,470,682; lazy_import 62,492,706; decode_cancel_liveness 6,480,887 and persist_liveness 5,056,595 green under the strong-fairness fix). The resources header, cost figures, and regenerated bindings updated; the malformed generated phrase is gone. Signed-off-by: Erik Sipsma <[email protected]>
Review round, two blockers and two nits. A refused attachment claim can no longer publish cleanly: PubFinishOk requires no armed target AND no claim error, mirroring initCompletedResult closing the barrier with the attachment error. And the claim re-checks registration under the graph lock (acquireSessionResultLocked's guard): the lock-free target selection can race a release that collects the child, so PubAttachClaimGone consumes the target as an ordinary attachment failure - attachGone, not a release refusal - and PubAttachFailDropHold fires for either error. Comment nits: the NoSpuriousErrors preamble now says release-caused errors enter provenance-specific refusing phases where observed while unrelated errors remain failures; the three remaining references to the removed single-phase FnInnerLoad name the split actions; the fairness header describes weak system progress plus the one explicit strong-fairness executor-termination assumption. Evidence: ProbeNoDoneWithRefusedAttach and ProbeNoCountedEdgeToUnregistered are green over the full 12,487,215-state resources space (the pinned attach_release_reader config's green state space exceeds 200M generated states, so the probes run at resources bounds, which exercise the same machinery with two sessions, release, and attachment); the pinned red holds. Full 31-configuration suite: 30 green plus the pinned red, ~73 minutes wall at four lanes; the finish guards prune post-refusal completions (resources 14,035,387 -> 12,487,215, release_prune 24.8M -> 22.0M), everything else stable. Signed-off-by: Erik Sipsma <[email protected]>
Review round: the claim checks the session tombstone before the registration guard in one critical section, so PubAttachClaimGone now requires a live session - a released session with a collected target gets the release refusal, preserving the Go error order - and a latched claim error stops all further attachment work: PubAttachTarget selects no new child and PubAttachAddDep lands no dependency edge after either error, matching the hook returning on its first failure. Comments and the properties header include the registration-error outcome. Evidence: ProbeAttachGoneReachable red in 21 states at resources bounds (the collected-target claim error is exercised, closing the vacuity concern on ProbeNoCountedEdgeToUnregistered); full 31-configuration suite green apart from the pinned attach_release_reader red. Signed-off-by: Erik Sipsma <[email protected]>
Comment-only. The resources header count moves to the ultimate-head value, and this message is the requested before/after addendum for the claim-error ordering and latching commit (0dc808415d), full9 -> full10: flush_inflight 146,732 -> 145,868 release_prune 21,975,055 -> 21,612,619 resources 12,487,215 -> 12,350,115 resources_restart 109,821,554 -> 109,817,150 rollback 40,563,686 -> 40,496,606 rollback_decode 25,633,010 -> 25,632,146 The other 24 complete-space configurations are identical; attach_release_reader stops at its expected violation, so its partial count (25,291,595 -> 16,441,238) is not a complete-space comparison. Verification for this comments-only change: SANY plus one unchanged TLC run (resources green at 12,350,115). Signed-off-by: Erik Sipsma <[email protected]>
…ve time AddExplicitDependency refused deps whose stored requiredSessionResources was non-empty, so a settled result's required set could never grow and serve paths could trust their selection-time check once they had crossed the attach barrier. That refusal broke module loading for any module whose source is private git over SSH: the typedefs result's dependency closure includes the ssh-agent socket handle, so the retention edge from the SDK container to the loaded module was refused and loading failed outright (CI: TestModule/TestContextDirectoryGit/SSH_Private_GitLab and TestModule/TestCustomSDK/Private_GitLab). The refusal is reversed and the stale-serve window it prevented is closed by a cheap serve-time re-validation: - sharedResult carries a requirement generation counter. The one function that mutates a registered result's stored set (recomputeRequiredSessionResourcesLocked) bumps it when the set actually changes, inside the same egraphMu write critical section as the mutation. All three of its callers (publication, the explicit-dependency path, the import recompute) go through it; every other write to requiredSessionResources targets detached or not-yet-published shared results. - Retention edges accept requirement-carrying deps again, and the recompute cascades upward through depParents with a worklist until the sets stop changing, so ancestors of an already-settled parent cannot keep stale stored sets. This resurrects the cascade that the refusal had made unreachable (91cbd77, removed by bf5ceab). - The three serve sites that re-check after leaving the selection critical section (request lookup, digest lookup, result-ID value load) capture the generation inside the same critical section that ran the subset check and compare it with one atomic load at serve time. An unchanged generation serves with no lock: the set the check validated is the set being served. A changed generation runs the full locked re-check and keeps each site's existing failure behavior (the lookups convert to a miss, the ID load refuses). The capture placement is a correctness requirement: captured after the unlock, a concurrent growth's bump could already be reflected in the captured value and the stale serve would pass the comparison. - The attachDepsWaitCh-based skip in sessionStillSatisfiesResourceRequirements is subsumed by the counter: attachment-time growth bumps the generation, results that never had an attachment phase (imported rows) are covered too, and a settled fresh result's serves no longer pay a read lock plus subset check per hit - the common case is one atomic load and no lock acquisition. The refusal test is replaced by TestCacheAddExplicitDependencyAcceptsSessionResourceDepsAndRecomputesAncestors: the edge is accepted, the parent's and ancestor's stored sets and generations grow, an unchanged set does not bump, an unbound session's ID load of the grown ancestor is refused, and the binding session is still served. Three new window tests park a serve between its selection critical section and its re-validation with a test hook, land the requirement-carrying retention edge, and assert the request hit and the digest hit convert to a miss and the ID load refuses; with the re-validation disabled all three fail by serving the stale hit. The three existing attach-barrier re-check tests pass unchanged on the generation comparison. Full dagql package green with -count=1 and -race. Signed-off-by: Erik Sipsma <[email protected]>
…rves by selection capture The code change this mirrors: AddExplicitDependency accepts deps whose stored requiredSessionResources is non-empty again (the refusal broke private-git module loading), the recompute cascades the growth to the parent's ancestors, and serve paths re-validate a selected hit against a per-result requirement generation captured inside the selection critical section - unchanged generation serves lock-free, changed generation re-runs the locked filter. Model changes: 1. LookupHit captures the selected result's stored required set on the invocation (selRequired). The generation bumps exactly when the stored set changes, so "generation unchanged since capture" and "stored set equals the capture" name the same observable, and ReadBarrierOk's hit conjunct becomes the disjunction: set unchanged, or currently satisfied. ReadBarrierGatedMiss is the complement (changed AND unsatisfied). 2. AddDepLate accepts requirement-carrying deps: the empty-required guard is gone, the edge is recorded in a new lateDeps field beside deps, and the action assigns the parent and every registered ancestor its transitive requirement - the fixpoint the code's depParents cascade reaches inside the same critical section, exact because RequiredExact holds before the edge. 3. ReturnedGated now judges the DATA closure (DataRequired: deps minus lateDeps). A retention edge keeps a dep alive without the parent's payload needing it, and it can land after a perfectly valid serve; judged over all edges, the invariant flags sessions that legitimately held or produced the parent before the edge existed. Demonstrated: with the exit-time judgment switched back to TrueRequired, resources_latedep_recheck goes red in a trace where an unbound session is validly hit-served a plain imported parent (empty required set, filter and re-validation both pass) and the retention edge lands only after the serve - nothing could have re-checked it (red at depth 16, 5,384,380 distinct states searched). 4. The new ReturnedHitSatisfied invariant holds every completed hit-path serve to the CONSERVATIVE stored set at the serve instant (retHitSatisfied, captured in ReadBarrierOk). This is the re-validation's contract, and it is the invariant the late-edge window trips when the re-validation is weakened, precisely because a late edge never changes any data closure. Configurations. resources_gated_growth keeps ModelLateDeps FALSE for state-space budget and gains ReturnedHitSatisfied; the retention-edge scenarios get two new small configurations whose imported starting graphs make the windows reachable at two invocations: resources_latedep_recheck (the stale-serve window; an imported parent also proves the generation covers barrier-less results the former attachDepsWaitCh skip never re-checked) and resources_latedep_cascade (the ancestor cascade). resources_latedep is re-pointed at them and keeps cheap accounting coverage. Green runs (14-16 workers): resources 12,352,815 distinct states (header updated; +2,700 over the prior count, the selRequired field), resources_latedep 14,716,634 (up from the refusal-era count: the accepted edges and the cascade), resources_latedep_recheck 27,392,221, resources_latedep_cascade 56,779,748. NOT fully re-run here: resources_gated_growth (a 10-minute bounded prefix found no violation at depth 34 with 68.9M distinct states explored; every historical red in this family sits at depth <= 24) and resources_restart; both fall to the required full suite before push. Re-break and reachability evidence, spec weakenings applied and restored around each run: - Reachability: on the shipped spec, a temporary probe invariant goes red in 19s (depth 14, 1,804,807 distinct states searched) at the exact ReadBarrierGatedMiss enabling state on a late-edge-grown imported parent. - Dropping the ReadBarrierOk re-validation disjunct: gated_growth red on ReturnedGated at depth 24 in 1min01s (attach-window data growth served stale); at the recheck bounds a completed stale late-edge serve is reachable (a late-edge-restricted probe red at depth 16) while a companion probe holds GREEN over the complete weakened space (27,404,573 distinct states): every such stale serve still satisfied its data closure. The late edge is liveness-only; the split between ReturnedGated and ReturnedHitSatisfied is exactly that line. - Restricting AddDepLate's cascade to the parent alone: RequiredExact red at depth 20 through the imported ancestor (4,316,947 distinct states searched). README and the tla-check expectations list the two new configurations; the README's closed-findings note now describes the re-validation instead of the refusal. Signed-off-by: Erik Sipsma <[email protected]>
The requiredGenAtCheck addition made sharedResultByResultID return five values, and four callers that need only the result had to discard three of them with blank identifiers, which the dogsled linter forbids (golang:lint-all red on the merge ref). The outcome is now one sharedResultLookup struct - the resolved result, the requirement generation captured at the pre-check, and the session-tracking bookkeeping - so callers name the fields they use and no call site needs a blank identifier. No behavior change. Signed-off-by: Erik Sipsma <[email protected]>
…ls attachment A publisher's own release could fail an innocent cross-session reader: publication indexes a result with an open attach barrier, another session's lookup selects it and parks at the barrier, the publishing session is released before the attachment hook's claim runs, the claim is refused (acquireSessionResultLocked's released-session check), the attachment fails, and the barrier closes carrying the error. The parked reader - a live session that injected nothing - surfaced the producer's release as its own failure, even though a retry would succeed. This is the attach_release_reader model finding, the same defect family as the fixed decode_cancel leader-cancellation finding. The fix classifies the barrier error at the latch: when the attachment hook's own error chain carries ErrCacheSessionReleased - inside attachment that can only be the publishing session's release - the error stored on the barrier is wrapped with a dedicated sentinel (errAttachRefusedByProducerRelease). Only the hook error decides the classification; the cleanup errors joined into the attachment error cannot reclassify a genuine failure, and the publishing invocation keeps the unclassified attachment error. The two hit-serve paths that park on the barrier (request lookup and digest lookup) convert a classified failure to a miss and fall through to the singleflight, keeping the recorded session edge exactly as their requirement re-validation miss conversion does. Result-ID value loads keep propagating the error: they name one exact result and have no call to re-execute; the classified form stays visible in the chain. The other barrier consumers were audited and left unchanged: attachResult's cache-backed branch re-serves a result the caller already holds, and wait's own-result load runs only after a successful publication whose barrier closed clean. Readers selecting the result after the failure never see the error at all - candidate gathering already skips attachment-failed results. Tests drive the exact window with the blocking-attachment harness: the producing session releases while attachment is parked and a second session is parked at the barrier; the request hit and the digest hit convert to a miss and the reader succeeds by executing its own call, the ID load still fails with the classified error, and the producer's call fails with the claim refusal without the classified form. A control shows a genuine (non-release) attachment failure still propagating to the parked reader unconverted. With the classification disabled, the two conversion tests fail by surfacing "cache session released" for the producer's session as the reader's own error. Full dagql package green with -count=1 and -race. Signed-off-by: Erik Sipsma <[email protected]>
…ications Two changes from the attach_release_reader escalation ruling. First, attachResult's cache-backed branch claims the target before the unlocked refresh (ensurePersistedHitValueLoaded) instead of after it: a successful claim pins the target for the rest of the attachment, so another session's release cannot collect it in between. The claim checks the caller's session tombstone before registration, so the caller's own release still fails with the release refusal and the committed barrier classification for its readers is unchanged. A claim that finds the target already collected fails the attachment loudly, exactly as before the reorder: every production acquisition path claims at acquisition or reaches the result through a claimed one, whose dependency edges pin it, so a collected target here is an invariant violation by the caller rather than a case to handle. TestCacheAttachmentClaimPinsTargetAgainstForeignRelease pins the property on the blocking-attachment harness: session B claims session A's child at acquisition, A releases while B's attachment is parked, the child stays registered, and the attachment completes against the original record. Second, a pre-existing leak in publication's failure handling is fixed. Indexing (indexWaitResultInEgraphLocked) registers the fresh result and makes it lookup-visible, but nothing owns it until the handoff hold is taken later in the same critical section, so the error returns in between - the structural-dep pass's "retain result call ref: missing cached result", the requirement recompute, and indexing's own input-provenance failure - left a registered, digest-indexed record with a zero ownership count: selectable by lookups and reachable by no collection path, with the dependency edges added so far retaining their children forever. Those error paths now roll the partial publication back inside the same critical section (rollbackPartialPublicationLocked): the record leaves the e-graph, the partial edges are unwound with the ordinary decrement-and-collect machinery, and the failed result's release hooks run after the lock drops, matching the attachment-failure path. The error itself still propagates loudly. Adopted results are owned by others and pinned by the handoff hold taken at adoption, so they are not rolled back. The window is race-shaped - the referenced result must be collected between the pre-lock digest derivations and the indexing critical section - so a test hook (testBeforePublicationIndex, following the existing hook idiom) makes it deterministic. TestCachePublicationRollsBackWhenStructuralDepMissing collects the doomed ref's target in that window and asserts the publication fails loudly, no registered record is left behind, the live dep's partial edge is unwound, and a repeated call re-executes instead of hitting a stranded record; with the rollback disabled it fails on the leftover record (one registered result before, two after). Full dagql package green with -count=1 and -race. Signed-off-by: Erik Sipsma <[email protected]>
…amily The model half of the escalation ruling: the republish design is gone entirely, and the family closes through the claim-at-acquisition invariant instead. The attachment claim runs first, under the graph lock, before any unlocked refresh work (PubAttachTarget's block comment names the Go ordering in attachResult's cache-backed branch), and target selection is restricted to results PINNED for the publishing session (PinnedForSession): a counted session edge, or reachability through a claimed result's dependency edges, which retain the target while the claim's edge lives. This mirrors the audited Go invariant - every production acquisition path claims at acquisition - and replaces the pre-fix model's unpossessed target selection, which over-approximated states production cannot produce. A pinned target cannot be collected by another session's release, so the collected-target claim arm (the registration-guard error the pre-fix model carried) is unreachable and its machinery stays gone; the publisher's own release remains the one deterministic attachment error, classified on the barrier so parked cross-session hit readers convert to a miss and execute the call themselves (ReadBarrierRefusalMiss), exactly as the committed window fix behaves. The NoSpuriousErrors preamble documents the final shape of the fixed family, including the Go-side rollback of partially indexed publications. attach_release_reader flips to expected-green and no other configuration changes; README and the tla-check expectations follow. Evidence: - attach_release_reader green over its complete space with a companion unreachability check listed alongside NoSpuriousErrors (a live session's selected attachment target is never found collected): 862,831,124 distinct states, depth 59, 1h48min at 15 workers. The reader-conversion retries opened this space up - it is now the suite's largest by far, recorded in the README's cost note. - Re-break: dropping the barrier-error classification turns the configuration red on NoSpuriousErrors at depth 25 (34,956,931 distinct states searched) with the original reader-victim trace. - Reachability: the ReadBarrierRefusalMiss enabling state (a hit reader parked on a barrier closed with the classified producer-release refusal) is reachable - a temporary probe goes red at depth 23 after 24,276,563 distinct states. - Touched configs all green; the pin restriction prunes states production cannot produce: resources 9,783,983 (from 12,282,639), release_prune 17,658,877 (from 21,479,359), flush_inflight 141,104, flush_closure 119,670, flush_roundtrip 53,818, poisoned_restart 22,650, liveness 5,365; orphan_edges 267, release_steal 35,565, release_inflight 35,565, drain_escape 14,833, drain_orphan 14,833, flush_drained 38,684, and lazy_release 1,505 unchanged. Signed-off-by: Erik Sipsma <[email protected]>
The Quick and Some runners and the expectedOutcome edits in this branch changed the module's API and shifted lines in main.go; the generated bindings are regenerated once on the rebased tree with `dagger generate -y go-sdk:generate`. This replaces the branch's two earlier regeneration commits, which regenerated the same file on the old base. Signed-off-by: Erik Sipsma <[email protected]>
…gurations main's cache model now declares the DelegatedReleaseOnly constant (its orphaned-lease mutation) and every configuration on main sets it. The seven configurations this branch adds (attach_release_reader and the six resources ones) were written before that constant existed and did not set it, so TLC would refuse to load them. Each sets it to FALSE, the non-mutation value. resources also lists SharedLeaseReleasedWhenRetired: it replaced the core configuration, which carried that invariant on main. Signed-off-by: Erik Sipsma <[email protected]>
…rations, drop two stale variable references
The rebase onto main brought two configurations this branch never
knew (orphaned_lease and release_wait); they did not assign the Handles
and ModelLateDeps constants this branch declares, so TLC would refuse
them. Both now set Handles = {} and ModelLateDeps = FALSE; the
orphaned_lease mutation keeps DelegatedReleaseOnly = TRUE. Two UNCHANGED
tuples still named deniedEdges, a variable an earlier commit of this
branch removed; the rebase's merge of FnComplete and FnWindDown kept the
name by mistake. Removed. A two-direction audit of the spec's constants
and variables against all 35 configurations now reports nothing.
Signed-off-by: Erik Sipsma <[email protected]>
sipsma
force-pushed
the
sipsma/remote-cache-track6-session-resources
branch
from
September 18, 2026 18:52
bd79ad1 to
ef14efc
Compare
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.
Summary
Dagger's cache can return a previously computed result instead of re-running work. Some results depend on things that belong to one specific client session, such as a secret or a socket. Those are tracked by a "session resource handle". A session must bind a handle before it is allowed to use any result that depends on that handle.
The cache enforces this with a filter. Every cached result stores a set of the handles it needs, called
requiredSessionResources. When a session looks up a cached result, the cache checks that set against the handles the session has bound. If the session has not bound them, it does not get the result.That enforcement had four holes. In each case, a session could be handed a cached result that depends on a secret or socket handle it never bound.
Import used a random order. On engine start,
importPersistedStaterebuilds the stored handle set for every result read from disk. A result's set is its own handle plus the sets of its dependencies. The rebuild walked results in Go map order, which is random. If it reached a parent before that parent's dependency, the parent read an empty set from the dependency and stored an empty set for itself. The parent then looked like it required nothing, so the filter let anyone have it.Decoding erased the set. Persisted results are stored encoded and decoded on demand. When the decoded value was installed, the code copied
sessionResourceHandleandrequiredSessionResourcesfrom the decoded value onto the cached result. The decoded value only knows about its own handle, not its dependencies' handles. So a result that required a handle through a dependency lost that requirement at decode time. This copy was also a data race: it wrote the field while holdingpayloadMu, but the lookup filter reads the same field while holdingegraphMu, and no lock is common to both.Loading by result ID skipped the filter. A client can ask for a result by its numeric ID.
loadResultByResultIDfiltered candidates by session, but if no candidate passed the filter it returned the exact requested result anyway. A session that saved an ID and used it later, without binding the handle, was served the result.Late dependencies did not propagate.
AddExplicitDependencyattaches a dependency to a result that was already published. The code recomputed the handle set for the direct parent only. Anything that already depended on that parent kept a stale set. Today this happens when generated module types are attached to a published module container.This is layer six of the cache remediation stack. It is stacked on #13962 and depends on #13962, #13940, #13938, #13936, and #13934. The TLA+ model work that found these problems is in the same range.
What changed
payloadMu.depParentswith a work list until no set changes. It runs inside the sameegraphMucritical section as before.Model changes
The cache's concurrency rules are modeled in TLA+ (
dagql/tla/CacheLifecycle.tla) and checked in CI. The model now covers session resource gating: each result has a handle and a stored required set, each session has a set of bound handles, and the lookup filter compares them.Two properties check it:
RequiredExact: every result's stored set equals the set you get by walking its dependencies. This catches bookkeeping drift.ReturnedGated: no session is ever handed a result that needs a handle it never bound. This is the rule users care about.The model found the import and decode bugs, and the model config that reproduced them (
resources_restart) now passes with the fixes in place. A new model action covers late dependencies, and a config (resources_latedep) checks that the upward propagation works.Configuration cleanup, so the suite does not accumulate near-duplicates:
coreconfig was removed. Theresourcesconfig runs the same bounds with more behavior and now checks every invariantcoredid.release_prune,flush_roundtrip, andpersist. It is not enabled inlazy_importandpoisoned_adoption, because those exceeded 23 million states and would not fit in a CI run. That is a cost decision, not a coverage judgment.One known problem, not fixed here
The model still reports one expected failure, in the
resources_gated_growthconfig. The mechanism:The session now holds a result that requires a handle it never bound. A late
AddExplicitDependencycall opens the same window after publication instead of during it.Fixing this needs a decision, so it is not fixed in this PR. The options are to re-check the filter after the wait completes, to prevent requirement-extending changes after a result is indexed, or to decide that gating is defined at lookup time and adjust the property to match. The config keeps the failure visible in the meantime.
Validation
go test -race ./dagql -count=1passes. Four new tests, one per fix. Each was confirmed to fail against the unfixed code.go vetandgofmtare clean.dagger check tla-check:cache-lifecyclepasses on the final commit, 4m8s, all configs run fresh.No integration test suite was run.
🤖 Generated with Claude Code