Queueing and Counters¶
A shared build (derivation_build) moves from Created to Queued once its queue conditions hold. Counters tell an evaluation to keep waiting. Every queue condition reads maintained columns, so the event that changes a fact must update the column as well. A consistency check acts as the only backstop against missed updates.
flowchart LR
C[Created] -- conditions holding --> Q[Queued]
Q -- condition regressing --> C
Q -- claim --> B[Building]
C -- not needed, no entry point --> S[Skipped]
S -- needed again --> C
A[Aborted] -- needed again --> C
Start Condition Columns¶
All on derivation_build, moved by transitions and never derived by a per-row walk.
| Column | Meaning | Moved by |
|---|---|---|
missing_runtime_deps |
Runtime dependencies (kind IN (1, 2)) leading to a shared build without a complete closure |
runtime_can_start: seeded on a NAR landing, spread up and down through the SQL function ripple_missing_runtime_deps |
fetchable |
Terminal success (Completed, Substituted) with a complete closure |
can_start::became_fetchable, can_start::lost_fetchability |
blocking_deps |
Direct build dependencies (edges of kind Buildtime or Both in derivation_dependency) that are not fetchable or whose unneeded_outputs include an output the edge names. A stored copy in any cache counts, with no trust or subscription term (Trusted Build Outputs) |
One-hop spread from the shared builds a fetchable change returned |
wanted |
Shared build still wanted by some open entry point, unless its evaluation or the build was aborted there. An aborted build on an edge where failure doesn't spread can stay unwanted until an admin starts a retry | can_start::update_need |
- Complete closure (
graph_sql::shared_build_complete_predicate): a shared build counts as complete when every output outsideunneeded_outputsis present in the cache andmissing_runtime_deps = 0. TheEXISTSoverderivation_outputmust stay readable for shared builds without output rows. - An upstream copy never counts as
fetchable. A build that needs a shared build held in an upstream cache must wait for the passthrough, because every build must draw its inputs from the Gradient cache. - A flag change must write the flag with a
RETURNINGclause that reports exactly the changed rows, and only those rows may spread further. A spread driven by a state instead of a transition pushed a counter below zero, and= 0never held for that counter again. - The flag change and the spread ran in one transaction under
can_start::lock_shared_builds, which tookderivation-orderedFOR NO KEY UPDATElocks. The lock must return theSharedBuildLockproof required by both functions. - Complete closures propagate transitively, one level at a time.
blocking_depsmoved a single hop and then halted. Reaching zero queued the waiting build, and it never made that buildfetchable. - A transitive spread ran as one SQL function call (current bodies in
m20261001_000001_plain_concept_names.rs). The function can count, lock in order and advance every level on its own. A chain of 163 levels cost one round trip instead of three per level. Unit tests ingraph/runtime_can_start.rsandgraph/walk_completeness.rsverified that the function bodies match the module predicates. A predicate change demanded a migration.
Queue Conditions¶
graph_sql::gates_predicate act as the single source of truth for these conditions. graph_sql::promotable_predicate can layer status = Created on top.
| Condition | Build | Passthrough (cache_available) |
|---|---|---|
derivation.walked |
Required | Required |
A build_job naming the derivation |
Required | Required |
wanted |
Required | Required |
probed (upstream probe answered) |
Required | - |
blocking_deps = 0 |
Required | - |
Own .drv NAR in the cache (drv_present_predicate) |
Required | - |
Queueing Events¶
Queue every touched shared build through can_start::promote. The call embeds the queue condition, and the candidate list acts only as a bound.
- An imported batch: run
seed_blocking_deps, thenpromoteover the batch and over whatever the needs-build update of the batch gained. - A dependency turned
fetchable:became_fetchablecan queue each build that need the dependency, once its counter reached zero. - A
.drvNAR arrival:gradient-graph/src/nar.rscan queue the.drvowners. - Any newly needed build, through
update_and_settle_need(see Skipped and Thaw). - Stream completion and the graph-stuck heal:
can_start::promote_closureover the evaluation's closure (see the repair pass).
Queued Invariant¶
- The assigner can read the status column alone. It cannot re-check the queue conditions. A
Queuedmark must therefore mean the conditions held at write time. - Every writer of
Queuedmust either embedpromotable_predicateor settle its rows withcan_start::unpromote_ungatedin the same call. unpromote_ungatedcan move onlyQueuedrows with no open assignment. ABuildingshared build can finish undisturbed.lost_fetchabilitymust raiseblocking_depson the builds that need the changed ones. The same statement (RIPPLE_UP) will move theQueuedrows without an open assignment back toCreated. After that, update the needs-build marks from the changed shared builds.assignment_record::claim_assignmentcan insert an assignment row only while the shared build is stillQueuedwith the expectedcache_availablevalue. The claim will drop a regressed job instead of handing it out.can_start::recount_blocking_deps_for_derivation_idsact as the consistency check's backstop for a lost move.
Needs Build¶
A shared build is open (graph_sql::open_predicate) when fetchable is false and its status is not BuildStatus::TERMINAL_FAILURE. Builders, Skipped, Aborted, and Completed shared builds with a missing dependency in the closure all qualify as open.
graph_sql::open_closure_cte_bodydefines one walk behind both the needs-build mark and its naming. Seeds step over runtime dependencies. A builder (builder_predicate: walked, probed, absent from a cache, inBUILDER_STATUSES) can step over build dependencies too. The need walk alone (need_closure_cte_body_until) can also step throughSkippedandAbortedbuilds (BUILDS_ONCE_WANTED). One walk can reach everything a thaw would build. Naming walks stop at them until the thaw. The need walk can enter anAbortedbuild only over an edge where a failure can spread (failure_spreads_predicate). The build can stay aborted on other edges. Only an admin retry can start it again.- Only open shared builds are reachable. A
fetchableor failed shared build ends the walk. - The walk can reach a passthrough but cannot step through it on a build dependency. No job ever builds the input closure of a passthrough output.
- The needs-build mark lives in a column. The mark flows down from the entry points, while the can-start counters flow up from the leaves. A one-hop predicate cannot carry the downward direction.
update_needwalks the region below the given roots (roots included) in one statement.WRITE_NEEDthen writes the answer as a boundunnestarray. Recursive CTEs carry no usable row estimate, and a membership subquery degrades into a sequential scan.- The write returns each changed row with its new value, split into gained and lost sets for the caller.
Partial Substitution¶
An upstream cache filled with nix copy can hold just the outputs referenced by a closure. A shared build can still become a passthrough when its wanted parents need no missing output.
| Parent | Needed outputs of the dependency |
|---|---|
| Builder | The names in derivation_dependency.dependency_outputs (the inputDrvs outputs), every output when unknown |
| Passthrough | The outputs referenced by its own outputs over a runtime dependency |
| Entry point of a live evaluation | Every output |
apply_upstream_hitscan setcache_availablewhen caches contain every needed output. Outputs absent from every cache land inderivation_build.unneeded_outputs.- The substitute job can fetch just the outputs outside
unneeded_outputs. A build job can require only the outputs on its edge. - Edges that reference an unneeded output count toward
blocking_deps. The spread on afetchablechange can skip those edges. - The
needed-output-requeuepass can find unneeded outputs that parents want (UNNEEDED_OUTPUTS_NOW_NEEDED).needed_outputs::forget_unneeded_outputscan then clearcache_availableandunneeded_outputsand turn the shared build into a real build. That function can also recountblocking_depsof the builds above. - An exhausted substitution and a demote clear
unneeded_outputsthrough the same function.
Callers of update_need¶
Follow each call with a settle_need call.
- Status transitions: each entry into and exit from
BUILDS_ONCE_WANTED, plus every move intoAborted, trigger the transition-effects emitter (status/effects.rs). An aborted job mark can change what an entry point wants. Retries leaveAbortedinsideBUILDS_ONCE_WANTEDand callupdate_and_settle_needdirectly. - Unchanged status:
update_and_settle_need, for events that move the needs-build mark without a status change.- Batch import (new builder, new entry point, adopted runtime dependencies, upstream hit)
demote_cached_outputandlost_fetchability- An exhausted substitution
- New runtime dependencies from a NAR
- The per-task evaluation GC and every adoption
Skipped and Thaw¶
Apply each needs-build move in can_start::settle_need in a fixed order.
| Side | Steps |
|---|---|
| Gained | thaw_wanted (Skipped/Aborted -> Created, attempt = 0), then adopt_below_named, then promote |
| Lost | unpromote_ungated, then skip_unwanted (Created, not needed, no entry_point -> Skipped) |
Skippedcounts as settled work. Queue conditions cannot affect a skipped build, and no evaluation waits for one.- A thaw can end at
Created, never atQueued. Read the queue conditions in thepromotecall after the thaw. - An
Abortedshared build can thaw the same way. An abort is no verdict. - An entry point with
build_job.abortedset needs nothing until a retry removes the mark. - Entry points of an
Abortedevaluation need nothing. Otherwise the aborted evaluation keeps its own builds wanted, and the next check thaws them. - Entry points of a
CompletedorFailedevaluation still need the closure below them. The retire step builds a retired output under such an entry point again. - Call
status::release_evaluation_needto update the need below the entry points of an aborted evaluation, inside the abort transition. Every abort sends it: hard aborts after aborting the unshared builds, soft aborts and the stuck-evaluation recovery without touching builds. update_needandsettle_needare crate-private. Other crates callupdate_and_settle_needand every needs-build move can skip and thaw inline. The consistency check'ssettle_skippedacts as the table-wide backstop and reportsskipped_moves.- The batch writer can call
gain_and_settle_needinstead. Its region walk will not enter a shared build already wanted. Its naming walk (adopt_unnamed_below) will stop at a shared build the evaluation already named. Both walks then cost about the batch's own rows, not the whole closure. - Probe responses (
mark_probed) callgain_and_update_and_settle_need. Misses takegain_needbecause misses only add the mark below the build. Builds that become newly available in the cache takeupdate_needbecause they can drop the mark. Both walks end with onesettle_needcall. - Writers of
Createdcallcan_start::settle_createdon the rows they wrote. Unwanted rows go toSkipped, startable rows toQueued. The retire step, the batch writer, the thaws and the retries count as such writers.
Evaluation Verdict¶
graph_sql::blocks_evaluationblocks an evaluation in two cases. Either the status sits inNEED_BUILD_STATUSESwhile the shared build iswanted, or the status isQueuedorBuilding(the assigner hands those out regardless of need).- A pending shared build with no wanters can never block anything. No code path can queue such a build.
Aborteddoes not appear inNEED_BUILD_STATUSES. So no evaluation can wait for an aborted shared build, and a later need can still thaw it.- Once no blocking shared build remains,
check_evaluation_donecan write a verdict. Any named shared build inBuildStatus::REQUEUEABLE(Abortedincluded) or a present error message yieldsFailed. Everything else yieldsCompleted. - A lost needs-build mark leaves every status unchanged. Finalize, in the emitter, the evaluations that name the shared builds which lost the mark.
Evaluation Counters¶
The evaluation table holds five counter columns. They cover the shared builds named through its build_job rows.
| Column | Counts |
|---|---|
named_shared_builds |
Every named shared build |
active_shared_builds |
blocks_evaluation |
failed_shared_builds |
BuildStatus::REQUEUEABLE |
queued_shared_builds |
Queued |
building_shared_builds |
Building |
- Triggers (
m20261031_000000_counter_trigger_per_statement.rsand the baseline hold the current bodies):evaluation_shared_build_moved,evaluation_shared_build_namedandevaluation_shared_build_unnamedfire once per statement. Those statements coverderivation_buildupdate,build_jobinsert andbuild_jobdelete. These triggers sum their transition tables per evaluation, then write one delta row per evaluation. Raw SQL and ORM changes both pass through these triggers. - Triggers append signed rows to
evaluation_shared_build_delta, for live evaluations only, and take no lock. - Membership: the SQL function
evaluation_shared_build_counts(status, wanted)(current body inm20261009_000000_build_job_aborted.rs). Keep its body in sync withgraph/predicates.rsthrough a unit test inevaluations/counters.rs. A predicate change will require a migration. - Fold:
fold_shared_build_deltascan run at the start of every waiting-state pass. One fold is a singleDELETE ... RETURNINGunder advisory lock640. An instance that sees the lock taken can skip the fold. Rows held by another transaction (SKIP LOCKED) get skipped as well, and their deltas wait for the next pass. The fold never blocks on an evaluation row, so it cannot deadlock with the graph writer. - Read:
eval_countersshould return the folded columns plus the unfolded deltas. - Counters answer only "not yet": a naming and a transition in flight together can miss each other. Confirm a zero with
reachability::eval_blocked.recount_evaluationscan recount a contradicted value under the fold lock. The recount, like the fold, will skip an evaluation held by another transaction. The next contradicting read will recount that evaluation. - The consistency check can recount every in-flight evaluation.
eval_counter_driftreports only the evaluations where folded columns plus pending deltas disagree with the recount.
Naming and Adoption¶
- Always name every walked derivation plus the direct inputs in a batch. Stop descending at
walked AND unwalked_inputs = 0. Only the evaluation that walked a cut-off subtree names its interior. - Deleting that evaluation cascades those names away. Start the open-closure walk from every
build_jobof a live evaluation withreachability::adopt_pending_closures. Insert the missing(evaluation, derivation)rows withON CONFLICT DO NOTHING. - Name a build with
reachability::adopt_below_namedat the moment it gains the needs-build mark. Every live evaluation naming a wanted open parent then names the build and the open closure below it. A build below a cut-off subtree can therefore queue during the evaluation. - Further callers: the per-task GC, the repair pass and the consistency check. The GC can call through
settle_after_delete, but only when a cascaded name belonged to an open shared build. The repair pass can calladopt_pending_closurefor one evaluation. The consistency check can scan unfinished shared builds in windows of 20,000. The consistency check can also name each build with nobuild_jobrow under an unfinished parent that running evaluations already name.
Walk Completeness¶
derivation.walked: the derivation carries its own walk record, covering outputs, all edges and the sources of every input. The inserting transaction must add unknown inputs as stubs in the same transaction. The queue never picks up a stub and workers never receive one.derivation.unwalked_inputs: direct build inputs, matched bykind IN (0, 2), with no recorded subtree. The import step seeds these rows. As inputs finish, the SQL functionripple_unwalked_inputsspreads updates. The consistency check (walk_drift) recounts the set.- Two events can clear
walked: the missing-input self-heal and the demote path (can_start::unwalk_derivations). The orphan derivation GC also clearswalkedfor derivations that survive a deleted dependency they require.unpromote_ungatedruns afterwards.
Dependency Failure¶
- A fresh terminal-failure transition lets
cascade_dependency_failedmark everyCreated,QueuedandFailedTransientderivation that wants the failed build asDependencyFailed. repair_dependency_failedcan repeat that walk inside the closure of an evaluation, at stream completion and during the graph-stuck heal. A shared build thawed after its dependency failed gets caught by this repeat.- The repeat can also take each shared build the evaluation aborted (
build_job.aborted) as a starting point. Derivations wanting such a build end asDependencyFailed. - Both walks share one edge rule (
failure_spreads_predicate). A shared build built here can fail with any dependency. - A passthrough can fail only on a dependency output its own outputs reference. That output must also be missing from our cache and from every upstream cache.
- Unknown references of a passthrough output fall back to the edge kind. Runtime dependencies then fail the passthrough.
- Both walks skip a shared build with an open dispatch. The worker report of that dispatch must settle the status, as with an unqueue.
Build Abort and Retry¶
Two endpoints, POST /builds/{id}/abort and POST /builds/{id}/retry, act on a build of an evaluation. Both run inside the graph writer (status::evaluation_build).
| Action | Allowed Status | Effect |
|---|---|---|
| Abort | Created, Queued, Building |
Set build_job.aborted, mark the shared build Aborted, mark dependents in the closure DependencyFailed, send AbortJob to the worker |
| Retry | FailedPermanent, FailedTimeout, Aborted, DependencyFailed |
Move failed builds back to Created and clear their build_job.aborted, move dependents failed through them back to Created (RETRY_BUILD_CLOSURE), repeat the dependency-failure walk, queue the closure |
Rules for aborts:
- The evaluation need to run.
- Shared builds wanted by another evaluation are not abortable.
CompletedandFailedevaluations count, as in the need recount (wanted_by_its_evaluation). - A superuser can abort a build from the board without any evaluation running. The abort can set
build_job.abortedon each finished evaluation wanting the build. - Such builds stay
Aborted. The need recount and the consistency check leave themAborted.
Rules for retries:
- A retry of a
DependencyFailedbuild can also retry each failed dependency below the build. The walk can only passDependencyFaileddependencies. - Retries never reopen a finished evaluation. Build retries for an evaluation in
Completed,Failed, orAbortedreceiveEvaluationFinished. Evaluation retries create a new evaluation of kindRetrywithpreviousset. The graph can reuse finished builds. - Retries wait until the worker confirmed the earlier abort. A late abort report can move a retried build back to
Aborted. - The
EvalandUnstickthaws of the repair pass skip the aborted build and everything above the build in the closure. - Retry thaws skip the deterministic-failure block. The user asked for the rebuild.
Consistency Check¶
The consistency::graph_consistency_report gets built through a sequence of recounts. Each step depends on the previous one.
| Step | Reports |
|---|---|
unwalked_inputs |
walk_drift |
missing_runtime_deps |
runtime_drift |
fetchable (repair_fetchable) |
counter_drift (with blocking_deps) |
wanted (recount_wanted) |
need_drift |
settle_skipped |
skipped_moves |
blocking_deps + queue (recount_blocking_deps_for_derivation_ids) |
counter_drift, unpromoted_startable |
| Adoption | adopted |
| Evaluation counters | eval_counter_drift, wedged_building_evals |