Repository navigation
core, dagql: evaluate lazy containers one part at a time - #14043
Merged
Merged
Conversation
sipsma
force-pushed
the
sipsma/remote-cache-track7-per-part-evaluation
branch
from
September 9, 2026 22:09
0941b8f to
55ce450
Compare
sipsma
force-pushed
the
sipsma/remote-cache-track7-per-part-evaluation
branch
from
September 9, 2026 23:12
55ce450 to
1d85bd3
Compare
sipsma
force-pushed
the
sipsma/remote-cache-track7-per-part-evaluation
branch
from
September 18, 2026 18:42
1d85bd3 to
38e0bf8
Compare
grouville
self-requested a review
September 18, 2026 18:51
sipsma
force-pushed
the
sipsma/remote-cache-track7-per-part-evaluation
branch
from
September 18, 2026 18:52
38e0bf8 to
c979b2a
Compare
grouville
approved these changes
Sep 18, 2026
Base automatically changed from
sipsma/remote-cache-track6-session-resources
to
main
September 18, 2026 19:15
Design for per-part evaluation of local results: the part taxonomy and its target-keyed mount identity, the single-level group-attempt structure that replaces the sketched two-level part/group exclusion, the declaration/delegation mechanism with its two operation templates, the per-group attempt lifecycle carried over from the existing lazy machinery, the initial refined operation set, the model plan with the measured budget evidence for re-scoping attach_release_reader, and the sequenced implementation plan with tonight's cut line. Signed-off-by: Erik Sipsma <[email protected]>
Fix the object-side lock discipline: per-group mutexes held across only their own group's body, LazyMu never across a body, and group bodies never demand sibling groups of their own op - self-metadata settles in the resolution phase, so the metadata-first ordering lives before the attempt and the model's GroupNeeds relation guards lead/join instead of body completion. State the result-level completion latch's precondition (all-groups resolution after metadata settled) and the per-group callback-re-read precedence rule (commit 20642c1, per group). Note Erik's overnight ruling on the model run discipline. New ledger entry S2-17; S2-13 reworded. Signed-off-by: Erik Sipsma <[email protected]>
…-budget breach
The attach_release_reader configuration had grown to ~863M distinct
states, nearly two hours of TLC wall time alone. Naive re-bounding is
ruled out by measurement: at MaxInvocations=2 the classification-drop
re-break PASSES with the identical state count (666,999), so the
mechanism under test is unreachable there and the invocation bound is
load-bearing (the scenario needs a dependency producer, the publisher,
and the parked cross-session reader).
The reduction comes from scenario scope instead, via two new constants
in the existing configuration style (configurations select scenarios,
never implementations):
- ReleaseSessions: which sessions may release. attach_release_reader's
question is about the PUBLISHER's release; the reader session's
release interleavings are not part of it. A proper subset breaks
session interchangeability, so such a configuration must not declare
session symmetry (SymmCalls is provided for that case).
- PersistableIntent: whether Spawn may choose persistable requests.
Persisted edges play no role in the scenario.
Defaults (all sessions, TRUE) preserve every existing configuration's
state space exactly; verified by identical distinct-state counts on
lazy (6,398,997), release_steal (35,565), orphan_edges (267), and
flush_roundtrip (53,818 - exercises the persistable machinery).
Scoped to ReleaseSessions={s1}, PersistableIntent=FALSE, the
configuration completes in 26,213,049 distinct states, under three
minutes. Both evidence arms were re-verified at the reduced scope:
dropping the barrier-error classification (attachErrRefusal forced
FALSE) violates NoSpuriousErrors, the classified barrier error stays
reachable (probe run), and the companion unreachability check (a live
session's selected attachment target is never found collected) stays
green over the complete scoped space. The one-time exhaustive bound is
recorded in the configuration comment, per the lazy.cfg convention.
Signed-off-by: Erik Sipsma <[email protected]>
Stage 2 makes evaluation per part: every part of a result maps to exactly one evaluation group and an attempt is per (result, group). The spec's eight per-result lazy fields become functions over a new LazyGroups constant; the eval record gains the demanded part and the group it is currently acting on. The existing attempt machinery - singleflight, waiter-count cancellation, retry-after-bookkeeping- failure, foreign-cancellation retry, per-attempt operation tokens - is extended by indexing, not re-derived: the action bodies are unchanged. Isomorphism anchor: with the singleton shape (one group, one part) the re-encoding is one-to-one, and the lazy configuration reproduces exactly 6,398,997 distinct states (33,885,579 generated), byte-identical to the pre-change baseline measured on the same jar. Every other existing configuration gains only inert constants; the full quick set passes with counts unchanged. New machinery, each piece mapped to the code it models: - GroupNeeds: an acyclic prerequisite relation (metadata before snapshot groups). The ordering is enforced at lead/join (GroupNeedsMet) - i.e. before a group's attempt exists, never inside a body - and the resolution phase (EvalResolveDemand) lets an evaluator settle a prerequisite group first, then re-enter demand for its own group. - EvalDelegateDemand: with ModelPartDelegation, a running group body spawns an internal evaluator for a part of a dependency - what real delegation bodies do and what the model never covered. Internal evaluators take an operation token on the callback token's session and need no session edge on their target; a body cannot finish while its internal evaluator is pending. - Invariants generalized per (result, group) under their existing names, plus PartServedByItsGroup (an evaluator only ever acts on its part's group or that group's prerequisites - the stable-mapping invariant stage 6 will deliberately relax) and GroupOrderRespected (no group attempt exists before its prerequisites completed). New configurations (state counts and wall times on this box, 2026-08-31): lazy_parts (3,821,617 / 65s), lazy_parts_prereq (8,251,257 / 62s), lazy_parts_liveness (145,457 / 33s), lazy_parts_release (238,825 / 30s), lazy_parts_delegate (37,417,395 / 4m54s; scoped to the singleton group shape and PersistableIntent=FALSE after multi-group shapes blew the run budget - see its header). Recorded evidence (all runs 2026-08-31): - Reachability probes violated as required: two groups of one result running bodies concurrently; a group failing while its sibling is complete; the resolution phase exercised; an internal delegation evaluator completing. - Re-breaks: EvalNoWork trusting the consumed callback while its own group's bookkeeping is pending (returning done unlatched) trips EvalDoneComplete; a stale any-group fast path (returning done off a sibling's completion) trips EvalDoneComplete; dropping the GroupNeedsMet lead guard trips GroupOrderRespected. Signed-off-by: Erik Sipsma <[email protected]>
Behavior-preserving refactor ahead of per-group evaluation: the four per-result lazy fields (stored callback, completion latch, published attempt, pending bookkeeping) move into a lazyGroupState record, held inline on sharedResult as lazyWhole - the implicit whole-result group of values that do not split their deferred work. The result-level lazyEvalComplete latch stays alongside as the fast path; for the single group it is set exactly where the group's completion is. evaluateOne, HasPendingLazyEvaluation, and registerLazyEvaluation read and write through the group record; no control flow changes and no allocation is added (the inline record replaces the scalar fields). Test: the dagql suite passes unchanged (also under -race). Signed-off-by: Erik Sipsma <[email protected]>
A value may now split its deferred work into independently evaluable groups (HasLazyEvaluationParts): every part maps to exactly one group, a group's single body fills all its parts, and an attempt is per (result, group). Values that implement only HasLazyEvaluation keep exactly one group, the inline whole-result group, on the code path the previous commit isolated - no behavior or allocation change for them. The new surface: - PartKey / LazyGroupKey / LazyGroupWhole and HasLazyEvaluationParts (ResolveLazyEvalGroups maps parts to groups and may settle the value's own metadata part via the cache; LazyEvalFuncForGroup is the per-group consumption contract). - Cache.EvaluateParts(res, parts...) forces only the named parts; Evaluate is unchanged and forces everything. On a non-parts value both degenerate to the whole-result group. - evaluateGroup is the former evaluateOne loop with every lazy-state access through the group record: singleflight, waiter-count cancellation, foreign-cancellation retry, pending-bookkeeping precedence, and the per-attempt operation token all carry over per group by indexing, not re-derivation. - The recursion stack is keyed by (result, group) and pushed at group entry: the resolution phase legitimately re-enters the same result for its metadata group before the requested group is entered; re-entering the same (result, group) is still refused. - The result-level completion latch is set only by a whole-value pass that resolved the full group set after metadata settled and observed every returned group complete; a parts-scoped pass never sets it. - registerLazyEvaluation skips parts values: their per-group callbacks are re-read at attempt start, and a stored whole-result callback would leave a stale pending signal after per-group completion. - syncResultSnapshotLeases is serialized per result (leaseSyncMu): concurrent group attempts make concurrent lease syncs routine, and two interleaved read-diff-write passes can transiently drop a stored link. - Named groups get their own resume spans, named with the group key. Tests (cache_parts_test.go, a fake parts value mirroring the model scenarios): a metadata read leaves the sibling snapshot group pending; a joint group fills all member parts with one body run; sibling groups run concurrently; per-group failure leaves siblings complete and the failed group retryable; whole-result evaluation runs groups metadata-first and latches the fast path; same-(result, group) self-demand is refused as recursion; body-success bookkeeping-failure retries only that group's bookkeeping; a healthy joiner retries a foreign-cancelled group attempt. Suite green under -race. Teeth (mechanism disabled, test observed red, then restored): - routing every demand to the whole group fails TestEvaluatePartsMetadataLeavesSiblingGroupPending with 'whole-result body ran for a parts value'; - collapsing named groups onto one shared state fails TestEvaluatePartsFailureIsolatedPerGroup with 'first output evaluation returned <nil>, want output body exploded'; - dropping the per-group pending-bookkeeping precedence fails TestEvaluatePartsSyncFailureRetriesOnlyBookkeepingPerGroup with 'timed out waiting for retried bookkeeping attach'. Signed-off-by: Erik Sipsma <[email protected]>
…layer Scaffolding for per-part container evaluation; no operation is refined yet, so every container keeps whole-result behavior byte-for-byte. - Container part keys: metadata, fs, execMeta, and mount:<target>. Mount parts are keyed by target path, not index: targets are unique within a mount list (ContainerMounts.With) and survive add, remove, and replace, so delegation needs no per-op index translation. - LazyState.EvaluateGroup: per-group run-once latching. Each group gets its own mutex held across only that group's body; LazyMu guards the latch map and is never held across a body - carrying the whole-op hold-across-the-body shape to groups would serialize sibling groups of one op. A direct caller racing a cache attempt on the same group serializes on the group mutex and the loser observes done, exactly the existing direct-versus-cache coordination, per group. - LazyContainerParts: the contract refined ops implement (part-to-group mapping from settled metadata, one body per group). Container implements dagql.HasLazyEvaluationParts by routing: an unrefined op maps every part to the whole-result group; a refined op settles its own metadata part first - the only self-demand anywhere, run in the resolution phase before any requested group's body starts, so bodies read plain fields directly and never demand sibling groups. - container.Lazy is cleared only when the op's last group is consumed, keeping LazyEvalFunc() != nil meaning 'something is still deferred' and persistence's ready-form selection meaning 'fully materialized'. - materializeContainerMetadataFromParent and delegateContainerPart: the split-out halves of materializeContainerStateFromParent. The metadata copy carries the mount list shape from the parent while preserving the child's existing source accessors by target (parts are written once, so a pre-seeded accessor already holds the final value); delegation clones exactly one part from the parent's settled accessor and skips an already-set destination for the same reason. Test: the dagql, core, and core/schema suites pass unchanged. Signed-off-by: Erik Sipsma <[email protected]>
… (template A) The 29 metadata-only mutations (entrypoint, default args, user, workdir, env and volatile/system/env-file variables, labels, image-config metadata, healthcheck, GPUs, annotations, secret variables, service bindings, exposed ports, default terminal cmd, and the volatile-exec cache-hit restore) become refined ops: their metadata group copies the parent's metadata and applies the op's field edit - the code that previously sat after materializeContainerStateFromParent, unchanged - and each snapshot part (fs, execMeta, mount:<target>) is its own delegation group copying the parent's settled part. Ops touching only the Secrets, Sockets, or Services lists are metadata: the resources are dependency results, not parts. The conversion is mechanical: each op's Evaluate routes through evaluateAllLazyGroups, ContainerLazyGroups is the shared template-A mapping, and EvaluateContainerGroup dispatches metadata-edit versus delegation through evaluateTemplateAContainerGroup. The one body wrinkle: withEnvFileVariables evaluated its env-file source alongside the parent; the source evaluation stays in its metadata body (a dependency read) while the parent evaluation narrows to the metadata delegation. Test (core, no engine needed): a pending chain of a refined base op (standing in for an exec: separate metadata and fs bodies) plus withWorkdir answers a metadata demand with the base's fs body never run, the child's fs accessor untouched, and both results still pending; a later fs demand runs exactly the base's fs group and fills the child by delegation; full evaluation consumes the rest and clears Lazy. The direct object-side path (Container.Evaluate, which metaFileContents uses) runs a refined op's groups end to end. Teeth (mechanism disabled, test observed red, then restored): making container resolution ignore the requested parts (resolve everything on any demand) fails the chain test at 'base fs body ran 1 time during a metadata read, want 0'. Signed-off-by: Erik Sipsma <[email protected]>
The exec (ContainerExecLazy) becomes template B, static: metadata and
each read-only mount delegate from the parent - the run does not change
or produce them - and fs, execMeta, and every writable mount are filled
jointly by the one process run (the execOutputs group). The body no
longer copies parent state wholesale: run inputs are the parent's
settled fs and mount parts (EvaluateParts on exactly the parts the run
mounts - the parent's own exec metadata is not among them and stays
pending), the mount list shape is the child's settled metadata, and the
output bindings keep writing the child's own accessors. Metadata
questions (args/env expansion, working directory, secrets, sockets,
services) read the child's plain fields, settled by the resolution
phase before the body starts.
The one body impurity this uncovers is resolved: the run resolved the
session's volatile variables and wrote the result back to
container.VolatileEnv, a metadata write from a snapshot body. The
resolved values now stay local to the run (metaSpec takes them as a
parameter; its other two callers never wanted them and pass nil), and
the child's VolatileEnv delegates from the parent as names. Audit of
every VolatileEnv reader (grep -rn VolatileEnv core/): the only
consumer of resolved values was metaSpec inside the same body; the next
exec re-resolves by name against its own session, expandEnvVar and
WalkEnv walk names, with/without-volatile-variable edit by name, and
persistence stores the list verbatim. One behavioral corner moves: the
old write also FILTERED the list to session-resolvable names, so an
expand=true reference to a volatile name whose session binding is gone
now errors ('expand cannot be used with volatile env variable') where
it previously expanded to the empty string - only reachable through an
evaluated exec followed by an expand of an unbound volatile name.
ImageRef keeps the previously evaluated-state behavior: WithExec clears
it on the shell, and the metadata delegation restores the parent's
value exactly as the old whole-body copy did (the pre-existing quirk
the stage-2 design flags for a separate ruling).
withRootfs (ContainerWithRootFSLazy) is the static writer: the write
group evaluates its source directory and sets fs; the metadata group
delegates with the ImageRef clear as its one edit; execMeta and mounts
delegate.
Tests (core, no engine needed): a metadata read on an exec child of a
refined base settles metadata with the base's fs body never run and the
exec pending, while demanding an exec output attempts the run (which
fails without an engine, stays retryable, and leaves settled metadata
alone) and whole-result sync fails on the same run - the deliberate
user-visible edge: withExec(false-cmd).workdir() succeeds, .sync()
fails. A read-only mount whose source is pending stays pending across
metadata reads, and demanding that one mount part runs exactly the
parent's mount group - not its rootfs, not the exec.
Signed-off-by: Erik Sipsma <[email protected]>
The read side of wave 1:
- ContainerRootFSLazy evaluates exactly the parent's fs part.
- ContainerDirectoryLazy / ContainerFileLazy settle the parent's
metadata (the mount list and working directory are all locating a
path needs), then evaluate only the located part: the rootfs branch
goes through the rootfs selector (which is now fs-only itself), and
the mount branches evaluate that one mount's part before reading it.
- The 12 metadata resolvers (entrypoint, defaultArgs, user, workdir,
envVariables, envVariable, labels, label, mounts, healthcheck,
platform, exposedPorts) demand only the metadata part.
- The 4 exec-meta resolvers (stdout, stderr, combinedOutput, exitCode)
demand only the exec-meta part, and metaFileContents' internal force
narrows from full evaluation to the exec-meta part via a direct
object-side EvaluateParts equivalent (evaluatePartsDirect) - which
also covers the legacy reader variants and every other internal
caller that holds the container value rather than its result.
Tests (core, no engine needed): ctr.directory('/a') on a container with
mounts /a and /b runs the parent's /a mount group only - /b and the
rootfs stay pending; the rootfs view runs exactly the parent's fs
group; Stdout on an exec attempts the run (parent fs and mounts
materialize for mounting) but never runs the child's read-only mount
delegation.
Signed-off-by: Erik Sipsma <[email protected]>
Sweep result recorded here for the log: every non-engine unit package under ./core/... and ./dagql/... passes unchanged after the wave-1 conversion (the only exclusion is dagql/idtui's golden suite, which shells out to the dagger CLI against a prebuilt engine and cannot exercise this diff; the behavior-sensitive integration cases - metadata reads on failing exec chains - live in core/integration and run in CI with an engine build). Signed-off-by: Erik Sipsma <[email protected]>
The second configuration over the ~20-minute run budget (~114M distinct states, ~28 minutes on a dev box). Its question - a hit's stored requirement set growing between lookup-filter selection and the serve, and the generation-keyed re-validation converting the stale hit to a miss - involves no persisted edges, so PersistableIntent = FALSE removes the persistable branching from Spawn and the persisted-edge machinery from the space: 11,403,800 distinct states, 1m45s. The re-break stays live at the reduced scope: dropping the ReadBarrierOk hit-path re-validation disjunct violates ReturnedGated (the attach-window data growth is served stale). The one-time exhaustive bound is recorded in the configuration comment. The remaining configuration near the budget line, resources_restart (~110M distinct states), cannot be scoped with these constants honestly: its scenario IS persistence (flush, restart, import), so persistable intent is load-bearing and its one session makes release scoping vacuous. Left for a follow-up ruling (split, or a new scenario switch). Signed-off-by: Erik Sipsma <[email protected]>
Close the two contract holes the implementation review exposed. First: resolution enumerates groups by shape, never by remaining work, and the result-level completion latch additionally requires no allocated group state with a published attempt, pending bookkeeping, or incomplete status - an op that consumed its last body can no longer enumerate its shape while that group's lease sync is still owed, and trusting the empty answer latches permanent false completion. Second: construction- time pre-seeds are not productions - delegation and the metadata copy always evaluate the parent part and overwrite, because a shell cloned through an unevaluated snapshot-writing ancestor carries the pre-copy value for the parts that ancestor will write. Also: require a synchronized holder for the container op pointer on parts paths (the per-group clear races sibling readers on a plain interface field), and record the model-budget outcomes (resources_restart left for Erik, delegate configuration accepted at the singleton-group shape). Signed-off-by: Erik Sipsma <[email protected]>
Council round-1 blocker. Cache-side group state outlives the value's own
view of its deferred work: a body that succeeds consumes the object-side
work (and the container clears its op entirely once the last group is
consumed) while the attempt's bookkeeping is still in flight or failed
and pending retry. A resolver can then no longer name any group, and
evaluateResolved evaluated nothing: a demand reported success over
unfinished bookkeeping, and the whole-value pass latched
lazyEvalComplete vacuously over an empty group list - permanently
swallowing a failed owner-lease sync. Reachable for unrefined ops (body
clears Lazy, sync fails, retry resolves zero groups) and equally for
refined ops (all groups consumed object-side, one group's sync pending),
and concurrently while a final attempt is still in its sync stage.
Fix, in two halves:
- When resolution returns zero groups, the demand is routed to every
group with live cache-side state (published attempt, pending
bookkeeping, or armed callback). Those evaluations join the in-flight
attempt or lead a bookkeeping-only retry - their bodies are consumed,
so no body ever runs from this path and no narrow demand widens onto
sibling bodies.
- The result-level completion latch additionally requires every KNOWN
group state settled (no attempt, no pending bookkeeping, nothing
armed), not just the resolved set complete, so completion can never be
recorded over live state regardless of what resolution reported.
Model correspondence, per the design author's fix-round ruling: no spec
change. The spec's demand routing is total (every part always maps to a
group and EvalNoWork consults that group's cb/syncPending/phase), so the
bypass never existed there; the bug lived in the resolution indirection
below the model's abstraction, and this fix restores the code to the
behavior EvalDoneComplete and LazyCompleteSettled already assert - the
lazy_parts re-break (EvalNoWork trusting a consumed callback while its
group's bookkeeping is pending trips EvalDoneComplete) is exactly this
bug family's model witness.
Test: TestEvaluatePartsEmptyResolutionRetriesPendingBookkeeping - a fake
parts value whose resolver under-reports zero groups after consumption,
with the group's lease sync failing: whole-result evaluation retries
only the bookkeeping, propagates a repeated failure, stays pending, and
settles on a successful retry with the body still run exactly once.
Red on the pre-fix code ('timed out waiting for retried bookkeeping
attach'); green with the fix; suite green under -race.
Signed-off-by: Erik Sipsma <[email protected]>
…oves nothing Council round-1 blocker; the skip-if-set judgment call is revoked as unsound. Schema shells clone whatever accessor value is currently visible WITHOUT forcing the parent (cloneContainerForSchemaChild), so a shell can inherit a stale set accessor from an evaluated ancestor while an unrefined snapshot writer in between will replace that part when its body runs: A (fs set) -> A.withDirectory(...) (unrefined; shell keeps the cloned pre-copy fs) -> refined metadata op above it. Demanding the child's fs hit the skip and served the ancestor's rootfs with the written directory observably absent. The same flaw applied to the exec-meta and mount delegation arms. delegateContainerPart now always evaluates the parent's part and copies it, for all three part kinds. The overwritten pre-copy's reopened ref is dropped without an explicit release, exactly as the whole-op parent-state copy always did when it replaced construction-time clones - equal, not worse. The metadata-merge keeps carrying the child's accessor RECORD by target (pointer stability for the filling group), with its comment corrected to say the carried value is stale-until-overwritten rather than final. Test: TestContainerDelegationOverwritesStalePreCopiedAccessor builds the reviewer's chain - materialized base (fs /old), an unrefined writer op standing in for withDirectory (shell keeps the cloned /old pre-copy, body writes /new), a real refined withEnvVariable above it - and demands the child's fs. Red on the pre-fix code (expected /new, actual /old); green with the fix; every parts suite and the core/schema/dagql suites green, container tests green under -race. Signed-off-by: Erik Sipsma <[email protected]>
Council round-1 should-fix. clearLazyWhenConsumed released LazyMu between observing full consumption and writing container.Lazy = nil, so two sibling groups finishing concurrently raced write/write on the interface word. The check and the clear now happen under one LazyMu hold, serializing concurrent completions. Readers stay lock-free by the ordering argument the whole-op body's clear always relied on, now written at the site: cache paths that re-read object-side lazy state only trust it with no attempt in flight, and attempt retirement under the cache's lazyMu (after the body and the clear returned) orders the clear before those reads; persistence encode runs at flush quiescence; attach-time reads precede evaluability; HasPendingLazyEvaluation's fallback read is advisory and self-corrects. Test: TestContainerConcurrentGroupCompletionClearsLazyOnce rendezvouses the op's last two group bodies so both completions race the all-consumed check. Red under -race on the pre-fix code (DATA RACE on the Lazy write); green for 30 -race iterations with the fix; container tests and core/schema suites green. Signed-off-by: Erik Sipsma <[email protected]>
…he design flag Council round-1 ruling (accepted, no code change): the exec's old body rewrite filtered VolatileEnv to session-resolvable names as a side effect; with resolved values now local to the run, the delegated metadata keeps names verbatim and an expand=true reference to a stale volatile name errors explicitly instead of silently expanding to empty. TestContainerExecMetadataKeepsVolatileNamesAndExpandErrors asserts the new contract on purpose: the name survives the exec's metadata settle unfiltered and ExpandContainerInput returns the explicit volatile-env error. The design document's section-13 flag gains the audit outcome and the ruling so the change is recorded where Erik reads it. Signed-off-by: Erik Sipsma <[email protected]>
Align the pre-seed rule with the as-built metadata merge (carry the accessor record by target and kind, value stale-until-overwritten, never clone parent values from the metadata body - the load-bearing property is the unconditional delegation overwrite, which landed). Replace the blanket synchronized-holder requirement for the op pointer with the narrowed form the fix round's evidence supports: the write/write clear race is serialized under the op's LazyMu; the attempt-guarded readers are safe by the consumed-implies-visible-state ordering argument; the resolution-phase and direct narrow-force reads have no guard, race a concurrent refined clear, and must share a synchronization point with it; the baseline direct whole-value read race is recorded as inherited, not widened. Signed-off-by: Erik Sipsma <[email protected]>
…ss under lazyOpMu Council round-3 convergence item (design revision 4): the split between lock-covered and ordering-covered accesses of container.Lazy is retired for the uniform rule - after construction, the op pointer is only ever read or cleared under lazyOpMu, each a short hold with no body ever under it. Construction-time sets (schema shells, WithExec, persisted decode) precede publication and stay plain. - Finding A: every unrefined op body's inline 'container.Lazy = nil' (16 sites: the withDirectory/withFile/withNewFile/withoutPaths/ symlink writers, the mount and socket mutations, import, and from in container_image.go) now consumes through the locked-store helper consumeLazyOp, closing the race against the locked routing reads. Directory/File inline clears stay as they are per the designer's verification (no routing reads exist for those types). - Finding B: Container.LazyEvalFunc reads the pointer through lazyOpForRouting and captures the op in its closure (a concurrent consumption between closure creation and call becomes a no-op through the op's own latch instead of a nil-interface call), covering HasPendingLazyEvaluation's fallback against the direct-path clear. - Uniformity: LazyEvalFuncForGroup, AttachDependencyResultsKinds, and the persistence encode form selection read through the same helper; clearLazyWhenConsumed stores through consumeLazyOp; the comments state the one rule instead of the per-reader ordering derivation. Lock order is unchanged and one-way (an op's LazyMu, then lazyOpMu; lazyOpMu is never held across anything). Tests, both red under -race on the pre-fix code and green for 10 -race iterations with the fix: TestContainerRoutingReadsRaceUnrefinedClear (an unrefined body's clear racing the cache-resolver and direct narrow-force routing reads) and TestContainerHasPendingFallbackRacesDirectClear (all groups consumed through the direct path so the cache carries no lazy state, the HasPendingLazyEvaluation fallback read racing evaluatePartsDirect's final-group clear - the stdoutLegacy-versus-schema-clone interleaving). The pre-fix runs flagged container.go:1098 (LazyEvalFunc) and the inline clears directly. core, core/schema, and dagql suites green, full -race passes green across all three packages. Signed-off-by: Erik Sipsma <[email protected]>
The as-built code went beyond revision 4's minimum set to one rule: every post-construction access of the container op pointer under lazyOpMu, construction-time sets plain because they precede publication. Adopt it as the design's final form: it retires the per-reader ordering derivation as load-bearing text (kept only as the reason the interim states were observed safe), records the closure capture in LazyEvalFunc, exempts Directory/File clears with the reason, closes the baseline-inherited direct-path pair for free as the G24 limit sanctioned, and blesses the atomic whole-op latch that the required race tests made observable. Signed-off-by: Erik Sipsma <[email protected]>
…sign record Design, mechanism, status, deferred-work assessment, open decisions, and review trail for evaluating lazy containers one part at a time. Supersedes the stage-2 Markdown revisions as the human-facing record; the Markdown working artifact is kept. Signed-off-by: Erik Sipsma <[email protected]>
Separate image metadata from rootfs materialization. Metadata demands now apply the stored image config, reference, and platform without pulling layers. Snapshot parts not produced by from delegate to the parent. Signed-off-by: Erik Sipsma <[email protected]>
Convert cache, temporary, volume, secret, mount-removal, and socket mutations to metadata edits with per-part delegation. Resolvers now return eager children for evaluated parents. For withMountedCache on an evaluated parent, cache snapshot initialization now occurs during the resolver call instead of deferred evaluation. Pending parents retain deferred initialization. Signed-off-by: Erik Sipsma <[email protected]>
Separate mount metadata from directory and file source materialization. Mount source writes update the stable accessor on the real mount entry. Resolvers keep eager behavior when the parent is already evaluated. Signed-off-by: Erik Sipsma <[email protected]>
Resolve each target from settled metadata and map all affected snapshots to one write group. Copy parent snapshots before applying directory, file, removal, and symlink edits. Keep unrelated mounts deferred. Signed-off-by: Erik Sipsma <[email protected]>
Cover image snapshot delegation, named ownership timing, shadowed mounts, and full lazy consumption. Share Dockerfile bind-source classification between eager and deferred paths and test its path normalization. Direct schema tests cover eager mount removal and temporary mounts. Cache and snapshot-backed eager resolver branches are not unit-tested here because the schema test server has no snapshot manager; focused integration tests exercise their helpers. Signed-off-by: Erik Sipsma <[email protected]>
Evaluate only container metadata and rootfs for publish, export, tarball, manifest, and layer preparation. Settle metadata before reading each variant platform and leave mount and exec metadata parts deferred. Signed-off-by: Erik Sipsma <[email protected]>
Evaluate each export container in its own errgroup worker while retaining metadata and rootfs-only evaluation. Add concurrency, resolver, path routing, and full-consumption coverage. Document the pending-rootfs and unsupported mount assumptions. Signed-off-by: Erik Sipsma <[email protected]>
The stack this record ships with has been rebased once and will be again; hashes cited in the record stop resolving after each rebase. Name the commits by title instead, and describe how the reviewed commits were carried onto the rebased branch. Signed-off-by: Erik Sipsma <[email protected]>
Regenerate the Go SDK clients after the per-part API changes. Document intentional file and directory symmetry for the duplicate-code check, and exempt the shared test setup unused results. Signed-off-by: Erik Sipsma <[email protected]>
After a refined group succeeds, copy sibling delegation parts whose parent parts are already complete. This clears image and exec recipes without starting deferred parent work. Signed-off-by: Erik Sipsma <[email protected]>
Parts resolution completes metadata prerequisites before returning the group list. Run multiple groups with one worker each while retaining the direct path for one group. Path writers now materialize parent parts and their source in parallel before applying the write. The parts model already treats each part demand as an independent evaluator, so no model update is needed. For a multi-group call, the surfaced error is now the first group to fail rather than the first group in resolution order. This matches Evaluate(a, b, c). Signed-off-by: Erik Sipsma <[email protected]>
Mark a successful parts resume when the result still has outstanding work. The UI ignores that continuation when deciding whether the creating call remains pending. Signed-off-by: Erik Sipsma <[email protected]>
Directory and file selectors now materialize the located rootfs part before selecting its nested view. Parent failures surface without creating a nested call in the trace. Signed-off-by: Erik Sipsma <[email protected]>
Mark resume spans blocked when all waiters abandon an attempt and its callback returns that cancellation. The attempt remains retryable without presenting the canceled callback as a call failure. Compute parts partial state only after retiring the current attempt. Concurrent completions now leave a non-partial resume once the result is complete. Treat an unexpected parent part mapping as unfinished so the opportunistic delegation sweep skips it. Signed-off-by: Erik Sipsma <[email protected]>
Inspect the exported spans from one multi-group evaluation and require at least one completed resume without the partial attribute. Signed-off-by: Erik Sipsma <[email protected]>
Keep evaluateGroup below the cyclomatic complexity limit while preserving lock-held callback selection and completion bookkeeping. Signed-off-by: Erik Sipsma <[email protected]>
A delegated copy now runs as soon as the parent's part is final; the groups of one call run concurrently; a partial resume span does not clear a call's pending state and an abandoned attempt reads as blocked; the selectors evaluate the located part before a nested call. Records the telemetry findings that led to these, the fix-round review trail, and the closed decision items. Signed-off-by: Erik Sipsma <[email protected]>
Run sibling delegation bodies after a group succeeds. Each copy takes its own group exclusion and demands its parent's part. Keep the initiating callback active through the sweep and bookkeeping. Track object consumption separately from cached callbacks. Reread consumed object state on a later demand, as Go does. Model cache callers waiting for a direct copy's group mutex. Require parent metadata consumption before reading the part mapping. Check sweep entry finality and the initiating callback's lifetime. Preserve the cache prerequisite rule for ordinary attempts. Re-break: removing parent finality from SweepCandidates trips SweepStartsFinal in lazy_parts_delegate. The delegation configuration passes at 22,518,204 distinct states in 6m53s. Its continuation with release and failures passes both liveness properties at 456,983 states in 4m48s. The quick set and both existing parts checks pass. The lazy configuration still has exactly 6,398,997 distinct states. Signed-off-by: Erik Sipsma <[email protected]>
The five lazy_parts configurations this branch adds predate main's DelegatedReleaseOnly constant and did not set it; each sets it to FALSE. The two configurations inherited from main (orphaned_lease and release_wait) did not assign the seven part-model constants this branch declares (ReleaseSessions, PersistableIntent, LazyGroups, LazyParts, PartGroupOf, GroupNeeds, ModelPartDelegation); each takes the whole-parts, no-delegation values every other non-parts configuration uses, so their scenarios are unchanged. A two-direction audit of the spec's 29 constants and 10 variables against all 40 configurations now reports nothing. Signed-off-by: Erik Sipsma <[email protected]>
The per-part edits in this branch shifted lines in main.go; the generated bindings' SourceMap coordinates are regenerated once on the rebased tree with `dagger generate -y go-sdk:generate`. Source-map lines only. Signed-off-by: Erik Sipsma <[email protected]>
golangci-lint's gocyclo limit is 30 and evaluateGroup reached 31 once main's changes were merged into it. Move the callback-body closure (take the operation lease, run the callback, sync snapshot leases, release the lease) into runLazyEvalBody, which returns the leased context, whether the body consumed its object-side state, and the first error. Behavior is unchanged; evaluateGroup is at 26. Signed-off-by: Erik Sipsma <[email protected]>
The leased context runLazyEvalBody returned was never read by its caller (the closure it replaced only used the lease inside itself), so golangci-lint's ineffassign rejected the assignment. Return bodyDone and the error only; the lease still scopes the callback body and the snapshot-lease sync exactly as before. Signed-off-by: Erik Sipsma <[email protected]>
sipsma
force-pushed
the
sipsma/remote-cache-track7-per-part-evaluation
branch
from
September 18, 2026 19:15
7b3a3d5 to
4a09602
Compare
sipsma
added a commit
that referenced
this pull request
Oct 5, 2026
When an exec fails and opens a terminal on its output, the terminal shows each writable mount's failed output. It did so by writing through the input mount's accessors, but since #14043 execInputMounts shares those with the exec's parent container, which is a cached result. The cached container then pointed at the failed output snapshots, which only the failed operation holds. That silently gave the next exec from the cached container the failed run's files instead of its inputs. Since #14470 collects released snapshots on every GC pass, the output is usually gone by then, and the exec fails with "parent snapshot ... does not exist", as in TestModule/TestDaggerTerminal/on_failure. Install the failed output on the terminal's own cloned mount with a new accessor, and leave the input mounts alone. Signed-off-by: Erik Sipsma <[email protected]>
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
A lazy container used to be evaluated all at once. Reading its working directory ran every exec in its chain and materialized every snapshot, including uploads of mounted host directories the question did not need. This PR evaluates a container one part at a time.
A container has four kinds of parts: the metadata (config, ports, mount list, and every other plain field), the root filesystem, the exec-metadata snapshot (stdout, stderr, exit code), and one part per mounted directory or file. Each part is produced on demand.
workdir,envVariable,entrypoint,labels,platform,exposedPorts,mounts, and the rest) runs no exec and materializes no snapshot.container.directory("/out")materializes only the part that/outlives in.stdout()runs the exec, because the run produces the output, but does not copy the container's read-only mounts.publish,export,asTarball,manifest, andlayerevaluate metadata plus rootfs only. Platform variants are still evaluated concurrently.This is layer seven of the cache remediation stack. It is stacked on #13969 and depends on #13969 and #13962. It contains no changes to lookup, hit selection, cache identity, session-resource enforcement, release, prune, shutdown, or persistence formats.
How it works
The unit of work is a group: one function that runs at most once per container and fills one or more parts. The cache keeps one in-flight attempt per (container, group), using the existing attempt machinery indexed by group: singleflight, waiter-count cancellation, retry after a bookkeeping failure, one operation token per attempt. A part is complete exactly when its group is complete; there are no per-part attempts.
A part an operation does not produce is filled by delegation: a group whose body evaluates the parent container's same part through the cache and copies the value into this container. Chains of copies end at the ancestor whose operation produces the part. Delegation always evaluates the parent and always overwrites, because a shell's construction-time accessor value can be stale.
Metadata is settled before any other part is mapped, so mount parts can be keyed by target path and a writer's target part can be computed from settled metadata. The exec's rootfs, exec metadata, and writable mounts form one joint group, because one process run produces all three.
Converted operations: 29 metadata-only mutations, the exec,
withRootfs,from, every mount mutation, every rootfs and mount content writer, the three selectors, 16 readers, and the export family. Every mutation resolver applies its edit eagerly on an evaluated parent and installs an op only on a pending parent. Still whole-value:import,dockerBuild, services, terminals. Directory and File keep one unit.Model changes
The lazy section of
dagql/tla/CacheLifecycle.tlais generalized per (result, group): the eight per-result lazy fields become functions over a newLazyGroupsconstant, and the attempt actions are indexed rather than rewritten. With a single group the encoding is one-to-one, and thelazyconfiguration reproduces exactly 6,398,997 distinct states, identical to the baseline.New:
GroupNeeds(the metadata-first prerequisite relation, enforced before a group's attempt exists),EvalResolveDemand(the resolution phase settling a prerequisite group),EvalDelegateDemand(a running body demanding a part of a dependency, which real delegation bodies do and the model had never covered), and two invariants,PartServedByItsGroupandGroupOrderRespected. Five new configurations:lazy_parts,lazy_parts_prereq,lazy_parts_liveness,lazy_parts_release,lazy_parts_delegate. Each header records its reachability probes and its re-break evidence.Run-budget work:
attach_release_readerandresources_gated_growthwere scoped to their scenarios with two new constants,ReleaseSessionsandPersistableIntent, whose defaults preserve every prior state space exactly.resources_restartremains over the 20-minute budget and needs a ruling; it is unchanged here.Observable changes
withExec(["/bin/false"]).workdir()succeeds; the failure surfaces at the first demand of an exec output (sync,stdout,directory). A test asserts this on purpose.withMountedCacheon an evaluated parent initializes the cache volume's snapshot at the call instead of at first evaluation.withMountedSecretandwithUnixSocketreads/etc/passwdfrom the parent's rootfs during a metadata demand.Known problems, deliberately not fixed here
stdout()ordirectory(path), because its read-only mount copies are separate groups those demands never touch. After a restart the exec runs again. Before this PR the same demand kept the run. Fix options are in the design record, section 18.9.withoutFilesandwithFilesstay chains of single-path operations; coalescing them changes the persisted shape (section 18.10).Design record
hack/designs/remote-cache/per-part-evaluation.html: model, mechanism, the state layout field by field, traced scenarios, invariants and locks, persistence, model work, deferred-work assessment, open decisions, review findings, and the review trail. It has no external assets; open it locally.Validation
Unit and race suites, run at the branch tip:
All pass.
Integration suites, each run against a dev engine with
dagger api call engine-dev test --pkg ./core/integration --run='<pattern>', all passing:TestContainer/TestFrom$(2)TestContainer/TestWithMounted(Cache|Temp)$(5)TestContainer/TestWithMounted(Directory|File)$(3)TestDockerfile/TestDockerBuild/run-mount-bind-(readonly|file)$(11)TestContainer/Test(WithDirectory|WithFile|WithFiles|WithNewFile|WithoutPath|WithoutPaths|Symlink)$(32)TestContainer/Test(Publish|Export|AsTarball|Manifest|Layer)$(15)TestContainer/TestMultiPlatform(Export|Publish)$(5)TestContainer/Test(ExecSync|ExecStdoutStderr|ExecWithWorkdir|ExecWithEnvVariable|ExecExpect)$(13)TLA+: the five new configurations and the re-scoped ones were run when they were introduced, with state counts recorded in the configuration headers. The rebase onto #13969's current head produced no conflicts in any model file, so the model was not re-run for the rebase.
Known validation gaps:
Review: every commit was reviewed by two reviewers against the rules in the design record, built and tested in a clean worktree under the race detector. No defect producing a wrong result was found. One wall-time regression (serialized multi-platform export) was found and fixed before this PR.