Repository navigation
dagql: retry canceled lazy evaluations - #13938
Conversation
2612398 to
12ff2f6
Compare
28eb2e5 to
cd3ed0e
Compare
…ending lease sync The persisted-decode singleflight in ensurePersistedHitValueLoaded ran entirely on the decode leader's request context and latched a cancellation like a broken payload: every parked joiner woke, read the latched context error, and returned it as its own failure. A cancellation that landed in syncResultSnapshotLeases after the payload install additionally left the owner-lease set incompletely synchronized with nothing retrying it, because later readers took the decoded fast path and never joined. The lazy singleflight had this class fixed in waitForLazyEvaluation (#13938); the decode singleflight did not. Port the same two mechanisms: - finishPersistDecode latches a retry classification next to the error (persistDecodeRetry, computed by lazyEvalErrorCausedByContext against the leader's context). A woken joiner with a healthy context treats a departed leader's cancellation as retryable and loops - leading or joining afresh - instead of failing. Its own cancellation still returns its own cause, and a genuine decode failure still propagates. - A failure after the payload install sets persistLeaseSyncPending (computed inside the finish as installed-and-failed, mirroring lazySyncPending). The fast path does not serve a value while the flag is set; the next demand leads a sync-only attempt that skips the decode and retries just the lease reconciliation. Retrying the sync is safe because syncResultSnapshotLeases stores the reconciled link set only on full success, so a retry re-diffs from the previous stored state. The decode attempt itself stays on the leader's context. The fuller port - a detached attempt context with waiter refcounting, as the lazy path has - was considered and deliberately not done: retrying the bounded decode is enough for correctness, and the detached-attempt machinery would be a much larger change for an efficiency gain only. Tests cover the four shapes: a leader canceled mid-decode with a parked joiner (the joiner succeeds by re-leading; the decoder runs twice), a leader canceled inside the post-install lease sync (the next demand runs a sync-only retry, the desired lease ends attached, and the payload is decoded exactly once), a joiner's own cancellation (returns its own cause), and a genuine decode failure (propagates to callers, no retry). fakeSnapshotManager's attach block is now one-shot and context-aware so a canceled attach returns the context cause and a retried sync proceeds unblocked. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Erik Sipsma <[email protected]>
cd3ed0e to
f6c563d
Compare
| // safe to read. A nil object-side callback with no pending bookkeeping | ||
| // means nothing deferred remains anywhere; a nil callback with pending | ||
| // bookkeeping leads an attempt that retries only the bookkeeping. | ||
| currentLazyEval := lazyEvalFuncOfResult(res) |
There was a problem hiding this comment.
🤖 Would it make sense to let lazySyncPending take precedence before re-reading LazyEvalFunc() here?
The pending bit means the callback body already succeeded, but this path can repopulate shared.lazyEval if a generic HasLazyEvaluation implementation continues returning a non-nil function. The interface does not currently require implementations to clear that function. I reproduced this by leaving it non-nil, failing the first snapshot-lease attach, and retrying Evaluate; the callback body ran twice. The existing regression avoids the case by setting obj.lazyEval = nil.
This also seems slightly out of step with the model, where body success consumes lazyCb and a pending attempt starts directly in syncing. For example, could this be structured as:
var currentLazyEval LazyEvalFunc
if !shared.lazySyncPending {
currentLazyEval = lazyEvalFuncOfResult(res)
}That would make a pending attempt bookkeeping-only regardless of whether the result keeps exposing its callback. A small regression test with a generic implementation that continues returning the same function would pin this down.
There was a problem hiding this comment.
Sorry if these are slop - still getting my bearings with the TLA+ stuff
There was a problem hiding this comment.
Agreed, good catch. Fixed in 3dcb95a: the preflight now only re-reads LazyEvalFunc() when no bookkeeping is pending, so a pending attempt is bookkeeping-only no matter what the value exposes. The consumption contract is now documented on HasLazyEvaluation, and there is a regression test whose callback never clears itself (it fails with two body runs without the gate).
| shared.lazyEval = nil | ||
| shared.lazySyncPending = false | ||
| } else if bodyDone { | ||
| shared.lazySyncPending = true |
There was a problem hiding this comment.
🤖 Could we clarify or preserve the cleanup obligation when this error came from release(...)?
Once bodyDone is true, a release error sets lazySyncPending, but the failed release closure is local to this attempt and is then discarded. The next bookkeeping-only attempt obtains and releases a new operation lease, so it can mark evaluation complete without retrying release of the original lease. A focused fake provider left lease 1 open after its release failed; the second Evaluate returned nil while that lease was still open and its release had only been called once.
One possible shape would be to retain the failed closure alongside the other pending state:
type cacheMapShared struct {
// ...
lazyReleasePending func(context.Context) error
}A retry could consume that closure before acquiring a new operation lease, and restore it if cleanup fails again.
The production lazyLeaseScope.release would also need to leave a failed deletion retryable. Roughly:
if s.lease == nil {
s.released = true
return nil
}
if err := s.lm.Delete(ctx, s.lease.l); err != nil {
return err
}
s.released = true
return nilThe exact state shape may differ, but could we retain a genuinely retryable cleanup obligation here, or otherwise handle release failures separately from snapshot-sync failures?
There was a problem hiding this comment.
You are right that a failed release is never retried and the original lease can outlive the retry. We are leaving this one as is: these leases are created with a 1-hour expiration and the buildkit temporary label (cleaned up at engine startup), so the leak is bounded to at most an hour of extra retention, and it only happens when Delete fails while lease creation, the body, and the snapshot sync all succeeded. Carrying a retryable cleanup obligation across attempts is not worth that, given the existing mitigation.
…ending lease sync The persisted-decode singleflight in ensurePersistedHitValueLoaded ran entirely on the decode leader's request context and latched a cancellation like a broken payload: every parked joiner woke, read the latched context error, and returned it as its own failure. A cancellation that landed in syncResultSnapshotLeases after the payload install additionally left the owner-lease set incompletely synchronized with nothing retrying it, because later readers took the decoded fast path and never joined. The lazy singleflight had this class fixed in waitForLazyEvaluation (#13938); the decode singleflight did not. Port the same two mechanisms: - finishPersistDecode latches a retry classification next to the error (persistDecodeRetry, computed by lazyEvalErrorCausedByContext against the leader's context). A woken joiner with a healthy context treats a departed leader's cancellation as retryable and loops - leading or joining afresh - instead of failing. Its own cancellation still returns its own cause, and a genuine decode failure still propagates. - A failure after the payload install sets persistLeaseSyncPending (computed inside the finish as installed-and-failed, mirroring lazySyncPending). The fast path does not serve a value while the flag is set; the next demand leads a sync-only attempt that skips the decode and retries just the lease reconciliation. Retrying the sync is safe because syncResultSnapshotLeases stores the reconciled link set only on full success, so a retry re-diffs from the previous stored state. The decode attempt itself stays on the leader's context. The fuller port - a detached attempt context with waiter refcounting, as the lazy path has - was considered and deliberately not done: retrying the bounded decode is enough for correctness, and the detached-attempt machinery would be a much larger change for an efficiency gain only. Tests cover the four shapes: a leader canceled mid-decode with a parked joiner (the joiner succeeds by re-leading; the decoder runs twice), a leader canceled inside the post-install lease sync (the next demand runs a sync-only retry, the desired lease ends attached, and the payload is decoded exactly once), a joiner's own cancellation (returns its own cause), and a genuine decode failure (propagates to callers, no retry). fakeSnapshotManager's attach block is now one-shot and context-aware so a canceled attach returns the context cause and a retried sync proceeds unblocked. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Erik Sipsma <[email protected]>
3dcb95a to
20642c1
Compare
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
At callback finish the published attempt pointer always names the finishing attempt: publishing a successor requires the pointer to be nil, and the finish path is the only code that clears it. Replace the conditional pointer comparison with an unconditional clear, matching the model's unconditional retirement. Signed-off-by: Erik Sipsma <[email protected]>
The Go retry decision is per-error, not per-phase: a callback whose attempt was canceled can still fail for its own reason, and that genuine failure propagates to every waiter instead of being retried. The canceled-finish action previously latched only success or foreign cancellation, so this real behavior was unexplored. It can now latch a genuine failure when LazyCanFail is enabled. Also widen lazy invariant coverage: the lazy configuration now checks NoStaleCancelError (its foreign-cancellation machinery was enabled but unchecked there; a probe invariant confirms those states are reached), and the now-green lazy_stale_cancel configuration checks TypeOK, LazyMutualExclusion, LazySuccessPermanent, and OwnershipExact alongside its designated invariant, since only expected-red configurations must violate exactly one invariant. In the lazy configuration the new transition adds explored arcs but no new distinct states: every state it produces is also reachable through a running-phase genuine failure followed by abandonment. The full matrix passes. Signed-off-by: Erik Sipsma <[email protected]>
Callback bodies (Directory, File, Container) clear their object-side Lazy pointer while the attempt is still running its cache-side bookkeeping: snapshot-lease sync and lease release. evaluateOne's fast path consulted that object-side state before the published attempt, so during the bookkeeping window a second caller observed the nil callback and reported success while snapshot ownership was still unsettled. If the bookkeeping then failed, the error was delivered once and the next caller converted the nil object-side callback into lazyEvalComplete, silently swallowing the failure with the owner lease never attached. The object-side write also raced the fast-path read. evaluateOne now consults the published attempt before any object-side lazy state and joins it. With no attempt in flight the object-side read is ordered after the previous callback's writes, because retirement happens under lazyMu after the body returns. A failed attempt whose body already succeeded records lazySyncPending, and the next attempt retries only the bookkeeping instead of treating the consumed callback as completed evaluation. HasPendingLazyEvaluation applies the same order. The model now mirrors the two stages: a running attempt's body finishes into a syncing stage, bookkeeping finishes into completion or a pending retry, and a bookkeeping-only attempt starts directly in syncing. Two new invariants gate the fixed behavior in the lazy configurations: EvalDoneComplete (a successful Evaluate return implies completed evaluation) and LazyCompleteSettled (completion is only recorded with every stage settled). Weakening the fast path back to the old shape violates them within seconds. Probes confirm foreign-cancellation and pending-bookkeeping states are explored in the checked configurations. A deterministic regression holds an attempt open inside AttachLease, proves a second Evaluate joins instead of bypassing, proves a failed attach stays retryable without re-running the body, and proves the retry settles completion. Signed-off-by: Erik Sipsma <[email protected]>
EvalSpawn allowed an evaluator to demand a result whose attachment barrier was still open, an interleaving no Go caller can produce: every result-returning API waits at the barrier and returns errors instead of values, and lazy callbacks are registered only at attachment completion. Spawning now requires a barrier that is neither open nor errored, removing model-only interleavings while the reachability probes for the lazy gates stay violated, so the gates remain non-vacuous. Signed-off-by: Erik Sipsma <[email protected]>
registerLazyEvaluation read the value's object-side lazy state before taking lazyMu. It runs on the ordinary cache-hit path (a hit's value load re-registers the callback), so that read raced a concurrent callback body clearing the same object-side pointer, which bodies do without holding lazyMu. Registration now takes lazyMu first and returns without touching object-side state when a callback is already stored, evaluation is complete, bookkeeping is pending, or an attempt is published. Only with no attempt in flight is the object-side state read, which is ordered after the previous callback's writes because attempt retirement happens under lazyMu after the body returns. Skipping while an attempt is published loses nothing: a lead stores the callback before publishing, and a bookkeeping-only attempt has nothing left to register. The regression test drives cache hits concurrently with a running callback; with the old ordering the race detector reports the pair at registerLazyEvaluation. Also corrects the EvalSpawn comment to name the hit-load registration site; the spec change is comment-only, so model outcomes are unchanged and the matrix was not rerun. Signed-off-by: Erik Sipsma <[email protected]>
Persisted payloads can carry deferred work: a lazy container persists its recipe (persistedContainerFormLazy), and on first value load after import ensurePersistedHitValueLoaded registers it, arming the shared result's callback. The model could not produce that transition: imported results initialized with no callback, decode changed only payload state, and no configuration combined lazy evaluation with persistence, so lazy work on store-produced results was entirely unexplored. Result records now carry an imported flag, and a new ImportedLazyArm action arms a decoded imported result while nothing is stored, running, pending, or complete, mirroring registerLazyEvaluation's guards. Whether a given row carries lazy work is payload data the model does not track, so arming is optional. After a restart every kept row is imported again and may re-arm, matching a store row whose payload still carries its recipe. Fresh results still arm only at publication; the flag keeps the unreal late-arming of fresh results out of the state space, and the existing lazy configurations are unchanged (identical state counts). Restart now drops all evaluator records instead of retaining terminal ones: a restart kills the process and no evaluator goroutine survives it. Invocations stay retained with epoch bookkeeping because the refusal properties must judge pre-restart refusals; no evaluator property needs that, and a retained done evaluator would pair with a rebuilt incomplete result and falsely trip EvalDoneComplete across the epoch boundary. The new lazy_import configuration starts from imported graphs with lazy evaluation and release enabled - release solely so flush and restart are reachable - and checks the lazy safety invariants alongside ownership accounting: 4,137,947 distinct states, green. Probes confirm it reaches imported-result arming, body execution into the bookkeeping stage, foreign cancellation on imported results, pending bookkeeping, and post-restart re-arming. The full 24-configuration matrix passes. Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
lazySyncPending means a previous attempt's body already succeeded and consumed the value's deferred work. evaluateOne's preflight nonetheless re-read LazyEvalFunc from the value and armed whatever it returned, so a HasLazyEvaluation implementation that keeps returning a non-nil function after success would get its body run a second time by the bookkeeping retry. Nothing documented a clearing requirement, and the model already makes the armed-plus-pending state unreachable (body success consumes lazyCb before bookkeeping can fail). Give the pending bit precedence: only consult the object-side callback when no bookkeeping is pending, making pending attempts bookkeeping-only regardless of what the value exposes. Document the consumption contract on HasLazyEvaluation and pin the behavior with a regression test whose callback deliberately never clears itself, which fails without the gate (body runs twice) and passes with it. Reported-by: vito Signed-off-by: Erik Sipsma <[email protected]>
20642c1 to
6ad4134
Compare
…ending lease sync The persisted-decode singleflight in ensurePersistedHitValueLoaded ran entirely on the decode leader's request context and latched a cancellation like a broken payload: every parked joiner woke, read the latched context error, and returned it as its own failure. A cancellation that landed in syncResultSnapshotLeases after the payload install additionally left the owner-lease set incompletely synchronized with nothing retrying it, because later readers took the decoded fast path and never joined. The lazy singleflight had this class fixed in waitForLazyEvaluation (#13938); the decode singleflight did not. Port the same two mechanisms: - finishPersistDecode latches a retry classification next to the error (persistDecodeRetry, computed by lazyEvalErrorCausedByContext against the leader's context). A woken joiner with a healthy context treats a departed leader's cancellation as retryable and loops - leading or joining afresh - instead of failing. Its own cancellation still returns its own cause, and a genuine decode failure still propagates. - A failure after the payload install sets persistLeaseSyncPending (computed inside the finish as installed-and-failed, mirroring lazySyncPending). The fast path does not serve a value while the flag is set; the next demand leads a sync-only attempt that skips the decode and retries just the lease reconciliation. Retrying the sync is safe because syncResultSnapshotLeases stores the reconciled link set only on full success, so a retry re-diffs from the previous stored state. The decode attempt itself stays on the leader's context. The fuller port - a detached attempt context with waiter refcounting, as the lazy path has - was considered and deliberately not done: retrying the bounded decode is enough for correctness, and the detached-attempt machinery would be a much larger change for an efficiency gain only. Tests cover the four shapes: a leader canceled mid-decode with a parked joiner (the joiner succeeds by re-leading; the decoder runs twice), a leader canceled inside the post-install lease sync (the next demand runs a sync-only retry, the desired lease ends attached, and the payload is decoded exactly once), a joiner's own cancellation (returns its own cause), and a genuine decode failure (propagates to callers, no retry). fakeSnapshotManager's attach block is now one-shot and context-aware so a canceled attach returns the context cause and a retried sync proceeds unblocked. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Erik Sipsma <[email protected]>
…ending lease sync The persisted-decode singleflight in ensurePersistedHitValueLoaded ran entirely on the decode leader's request context and latched a cancellation like a broken payload: every parked joiner woke, read the latched context error, and returned it as its own failure. A cancellation that landed in syncResultSnapshotLeases after the payload install additionally left the owner-lease set incompletely synchronized with nothing retrying it, because later readers took the decoded fast path and never joined. The lazy singleflight had this class fixed in waitForLazyEvaluation (#13938); the decode singleflight did not. Port the same two mechanisms: - finishPersistDecode latches a retry classification next to the error (persistDecodeRetry, computed by lazyEvalErrorCausedByContext against the leader's context). A woken joiner with a healthy context treats a departed leader's cancellation as retryable and loops - leading or joining afresh - instead of failing. Its own cancellation still returns its own cause, and a genuine decode failure still propagates. - A failure after the payload install sets persistLeaseSyncPending (computed inside the finish as installed-and-failed, mirroring lazySyncPending). The fast path does not serve a value while the flag is set; the next demand leads a sync-only attempt that skips the decode and retries just the lease reconciliation. Retrying the sync is safe because syncResultSnapshotLeases stores the reconciled link set only on full success, so a retry re-diffs from the previous stored state. The decode attempt itself stays on the leader's context. The fuller port - a detached attempt context with waiter refcounting, as the lazy path has - was considered and deliberately not done: retrying the bounded decode is enough for correctness, and the detached-attempt machinery would be a much larger change for an efficiency gain only. Tests cover the four shapes: a leader canceled mid-decode with a parked joiner (the joiner succeeds by re-leading; the decoder runs twice), a leader canceled inside the post-install lease sync (the next demand runs a sync-only retry, the desired lease ends attached, and the payload is decoded exactly once), a joiner's own cancellation (returns its own cause), and a genuine decode failure (propagates to callers, no retry). fakeSnapshotManager's attach block is now one-shot and context-aware so a canceled attach returns the context cause and a retried sync proceeds unblocked. Signed-off-by: Erik Sipsma <[email protected]>
Summary
A new healthy
Cache.Evaluatecaller could join a lazy callback attempt after every earlier waiter had abandoned and canceled it. When that callback finished with the shared cancellation, the new caller inherited an error it did not cause. A second form occurred when a completed canceled attempt remained published after its last waiter selected its own cancellation arm, allowing a later caller to drain the stale error.This change makes cancellation caused by abandoned shared work transparent to healthy callers while preserving lazy-evaluation mutual exclusion. Reworking the coordination also exposed two adjacent defects in the same code, both fixed here: evaluation could be reported complete before an attempt's cache-side bookkeeping settled, and cache-hit lazy registration raced the callback body's object-side state.
Runtime design
Each lazy callback execution has an attempt-scoped record containing its completion channel, cancel function, waiter count, outcome, cancellation provenance, and telemetry wait targets.
The shared result publishes one current attempt while its callback runs. Callback completion stores the outcome and retires that attempt under the lazy mutex before closing its completion channel. Existing waiters retain the retired record, so they cannot read or decrement a newer attempt's state.
A healthy waiter retries when the callback error is attributable to cancellation of that attempt's shared callback context. A waiter's own cancellation still returns its own cause, and genuine callback failures still propagate to every waiter. A new callback can begin only after the preceding callback has returned, so retries never overlap.
Evaluation preflight consults the published attempt before any object-side lazy state. Callback bodies (Directory, File, Container) clear their object-side
Lazypointer while the attempt is still running its cache-side bookkeeping (snapshot-lease sync, lease release), so object-side state is only trustworthy once no attempt is published; attempt retirement under the lazy mutex orders the body's writes before such a reader. A second caller arriving during the bookkeeping window therefore joins the attempt instead of observing the cleared pointer and reporting success early.A failed attempt whose body already succeeded records pending bookkeeping. The next
Evaluateleads a bookkeeping-only attempt that retries just the snapshot-lease sync instead of treating the consumed object-side callback as completed evaluation, so a bookkeeping failure is no longer reported once and then silently swallowed. Cache-hit lazy registration applies the same attempt-first order under the lazy mutex, closing a data race between the hit path's read and the callback body's write.Telemetry
Native-profiler and OpenTelemetry wait targets are fresh per attempt. They are minted, or deliberately left invalid, under the lazy mutex before the attempt pointer is published. OpenTelemetry waits remain gated by the result producer's profile-skip state, never the forcing waiter's state.
Behavior and cost
Retry happens only after a real callback attempt completes. A genuinely canceled attempt can therefore cause one additional callback execution for a healthy caller. The object-side lazy state remains idempotent, no two callbacks for one result run concurrently, and a bookkeeping-only retry never re-runs the callback body.
Tests and model
The deterministic standard-library
testing/synctestcoverage exercises:A separate regression drives cache hits concurrently with a running callback and is meaningful under the race detector: with the old registration ordering,
-racereports the object-side write against the hit path's read.The five-second timeout guards use the synctest bubble's fake clock and remain active when all goroutines are durably blocked.
The TLA+ model separates callback retirement, completion-channel observation, and waiter wake-up, and now also separates the callback body from the attempt's cache-side bookkeeping: body success moves the attempt into a syncing stage, a bookkeeping failure records a retryable pending obligation, and a bookkeeping-only attempt starts directly in that stage. Cancellation is a flag that composes with both stages, and the canceled-finish action can latch a genuine failure, matching the per-error retry decision in the Go. Evaluators can only demand results whose attachment barrier is neither open nor errored, matching what callers can actually hold. Two new invariants gate the fixed behavior in the lazy configurations:
EvalDoneComplete(a successful Evaluate return implies completed evaluation) andLazyCompleteSettled(completion is only recorded with every stage settled); weakening the preflight back to its old shape violates them within seconds. The model also covers lazy work on imported results: persisted payloads can carry deferred work (a lazy container persists its recipe), which arms on first value load after import or restart, and a newlazy_importconfiguration exercises the full lazy protocol against store-produced results interleaved with flush and restart. Thelazy_stale_cancelconfiguration is a green regression gate,lazy,lazy_liveness, andlazy_importare green, and reachability probes confirmed that foreign-cancellation, retry-cycle, pending-bookkeeping, imported-arming, and post-restart re-arming states are explored within the configured bounds.Validation
go test ./dagql -count=1go test ./engine/server -count=1go test -race ./dagql -run '^(TestCacheHitRegistrationDoesNotRaceLazyCallback|TestCacheEvaluateSettlesBookkeepingBeforeReportingComplete|TestCacheEvaluateRetriesForeignCancellation|TestCacheEvaluateRetiresFinishedAttemptBeforeWaitersDrain|TestCacheEvaluateOwnCancellationOnlyCancelsOwnWait|TestCacheEvaluatePropagatesCallbackFailure)$' -count=1go vet ./dagqldagger check tla-check:cache-lifecycle— all 24 configurations, every expected outcome matchedlazy,lazy_liveness, andlazy_stale_cancel, plus re-break runs proving the new invariants catch the old preflight and probe runs proving the gated states are reachabledagger check dagger-go-sdk:generateStack
This is layer three of the cache-remediation stack. It depends on #13936, which depends on #13934, and relies on the engine-lifetime-unique numeric result IDs introduced at the base of the stack.