Cache Closure¶
One invariant governs the cache: an output served from the cache must include its full runtime closure, stored alongside it. Per-shared-build counters enforce this invariant across the graph, and every start condition checks those counters. A self-heal can then fix anything a failed build exposed.
flowchart LR
C[CommitNar] -- seed --> W[missing_runtime_deps]
R[retire_outputs] -- reverse spread --> W
W -- "complete + terminal success" --> F[fetchable]
F --> U["blocking_deps of waiting builds"]
U -- 0 --> Q[Queued]
Complete Closure¶
Runtime dependencies live in derivation_dependency alongside build dependencies, with EdgeKind::Runtime = 1 and Both = 2. The predicates live in gradient-db/src/graph/predicates.rs.
| Term | Definition |
|---|---|
Present (present_predicate) |
The shared build has output rows, and each one links to a cached_path row with a set file_hash |
missing_runtime_deps |
Runtime dependencies of the shared build that lack a complete closure |
Complete closure (shared_build_complete_predicate) |
Present, and missing_runtime_deps = 0 |
fetchable (fetchable_predicate) |
Terminal success plus a complete closure. A copy from upstream does not count |
.drv present (drv_present_predicate) |
The build's own .drv NAR exists with a backed cached_path row. This marks presence only, not a complete closure |
- Build start condition:
blocking_deps = 0and.drvpresent.blocking_depscounts direct dependencies without a setfetchableflag. The counter also includes direct dependencies whoseunneeded_outputshold an output the edge names. A stored copy in any cache counts, with no trust or subscription term (Trusted Build Outputs). Thefetchableflags of those dependencies already cover their own closures, so the condition needs no recursion. - Passthrough start condition: shared builds available in a cache can start without either term. Those jobs don't list any direct inputs (
gradient-scheduler/src/loops/build.rs). - Push: jobs upload only their own outputs. Everything below them held a complete closure before assignment. A worker therefore need not push a closure for the invariant to hold.
NAR Commit¶
commit (gradient-graph/src/nar.rs) runs inside the graph writer's transaction for each CommitNar. A pooled handle cannot be used here.
- Upsert the
cached_pathrow underFOR NO KEY UPDATEand readwas_backedwhile holding that lock. No later statement can recover this endpoint. - Overwrite
referenceswith the line the worker reported, in order. From that line alone,references_for_hashcan rebuild the narinfoReferences:line and the signature fingerprint byte for byte. - Insert an add-only runtime dependency for each path in
references, then updatewantedfor the producers. Skip a reference that points to a twin or to a derivation with a direct edge back to the referrer. Real Nix references never form either, and such an edge can block both closures. seed_runtime_deps(gradient-db/src/graph/runtime_can_start.rs): recount the producers from scratch. Paths with no earlier NAR becomefreshly_present; re-pushing a backed path only triggers a recount.- Spread the newly complete closures to the shared builds that need them at runtime.
ripple_shared_builds_completecan count down their missing dependencies level by level in one call ofripple_missing_runtime_deps, a SQL function. Thenbecame_fetchablesetsfetchableand moves theblocking_depscounter. - Run
ripple_shared_builds_incomplete, thenlost_fetchability, on shared builds that a new dependency on a missing path left incomplete. -
Write a
cached_path_signaturerow per target cache and sign each row with the cache's key. These cases leave the row unsigned. No key is in the cache,sign_outputsis off in the subscription, or all producing tasks keep the path private. Mark matchingderivation_outputrows cached. -
Transitions only: Start the spread only from rows with a state change reported by the seed. Spreading from a state can drive a counter below zero, and a negative counter can never read
= 0again. - Deadlocks: the graph writer can retry a transaction that hits
40P01,40001or25P02up toGRAPH_TX_ATTEMPTS(3) times (gradient-graph/src/writer.rs).
Retire¶
retire_outputs in gradient-db/src/graph/runtime_can_start.rs is the only path that removes cached_path rows. The steps:
- Lock the hashes
FOR NO KEY UPDATEin a single hash-ordered statement, with the producers' advisory keys held exclusive. - Read the producers with a complete closure (
complete_among) before the delete can remove that endpoint. - Remove the rows, with a cascade to
cached_path_signature. - Call
ripple_shared_builds_incompletefrom the shared builds that had a complete closure. - Apply
lost_fetchabilityover the producers and every build left incomplete. Reset only the producers of deleted paths toCreated.
| Caller | Trigger |
|---|---|
demote_cached_output (gradient-db/src/caches/demotion.rs) |
Self-heal, operator invalidation, a cache dropping its last claim, a NAR missing from storage |
GcRequest::UnusedCacheClaims (gradient-graph/src/gc.rs) |
Stale-path eviction |
GcRequest::Paths (gradient-graph/src/gc.rs) |
Zombie purge |
- One cache's claim:
Demotion::CacheClaimcan remove only thecached_path_signaturerow of that cache. The retire can follow only after the last signing cache is gone. - Graph writer only: all callers operate inside the graph writer. The GC scans take place on the pool and hand the deletes to the graph writer.
- Lock order:
cached_pathrows (by hash), thenderivation_buildrows (byderivation), with advisory keys ahead of rows. Always write the cache availability flag (cache_available) before the retire indemote_cached_output. Always take both lock passes first. Details are in Shared Builds.
Consistency Check¶
A lost move has one backstop: graph_consistency_report in gradient-db/src/graph/consistency.rs.
recount_missing_runtime_deps: recountmissing_runtime_depsacross the whole table. This also backfills the column.repair_fetchableandrecount_blocking_deps_for_derivation_ids: rewritefetchableandblocking_depsover the start-condition scope. That scope covers pending shared builds and the rows they wait on.recount_walk_completenessandrecount_wanted: recount the walk bit and the needs-build mark across the whole table.settle_skippedthen settles the queue against that mark.
Self-Heal¶
When a build reports InputsUnavailable, the error names the missing paths. repair_missing_inputs (gradient-graph/src/self_heal.rs) can resolve each case in the table.
| Case | Action |
|---|---|
| Reported missing, object gone | demote_cached_output: retire the row, delete the object, clear cache_available. Builds that need the path block again until the producer can push anew |
| Reported missing, object present | Kept. Storage acts as the judge, and a worker with an outdated view of the cache deletes nothing. The failed build retries |
Producer without a build_job (orphan) |
Also unwalk_parents_of: the parents keep their cached outputs, the next evaluation walks them again and names the orphan |
No producer (.drv or source) |
Purged only when the object is truly gone. The failed derivation gets unwalked, so the next evaluation walks it again and pushes its sources |
- Corrupt NAR: Always check every fetched input against its
nar_sizeandnar_hash(verify_nar,gradient-worker/src/proto/nar_daemon_import.rs). A mismatch is aCorruptCachedNar, classifiedInputsUnavailablein prefetch and Substitute alike. The same self-heal can rebuild the producer with consistent metadata. - Requeue:
requeue_failed_shared_buildscan thaw demoted producers in a terminal failure all at once. - Circuit breaker: Without the self-heal, the build failed after
build.inputsUnavailableMaxLoops(GRADIENT_BUILD_INPUTS_UNAVAILABLE_MAX_LOOPS, default 3) priorInputsUnavailableattempts (inputs_unavailable_attempt_count). - Failure text: All failures store the worker's error, capped, on
build_attempt.failure_message.
Garbage Collection¶
The cache-maintenance pass in gradient-cache/src/schedule.rs runs on a schedule. The interval comes from gc.intervalSecs (3600 s). Each run computes a keep-set with reachable_derivations_cte: the closure of all entry_point and build_job derivations over derivation_dependency edges. Rows that carry a build_job of their own do not belong to this set.
| Pass | Reclaimed | Bound |
|---|---|---|
| Evaluation GC | Finished evaluations past task keep_evaluations. Cancelled first, then oldest |
The latest evaluation of the task and the latest successful evaluation remain. Active evaluations remain and don't count toward the limit |
| Derivation GC | derivation rows outside the keep-set, their attempt logs |
Created before gc.orphanDerivationHours (24) |
| Stale-path eviction | Each cache's cached_path_signature rows on paths outside live_cached_paths_cte, then cached_path rows left without a claim and their objects |
That cache's last fetch (or the claim's creation) older than max(gc.narTtlHours, gc.narUploadGraceHours) (336 h). Claims with pinned_at set don't expire, so pinned paths stay valid. |
| Zombie purge | Rows with no object in storage | Storage probe per row. A probe error will preserve the row |
| Orphan NAR files | Objects without any referencing row | Older than gc.narUploadGraceHours (24 h) |
- Derivation re-check: the graph writer can delete a listed derivation only if the current rows still leave it unreachable. Any job, entry point or dependent outside the list will keep the derivation and its listed closure alive.
- Path re-check: re-check each chunk of paths against roots created after the scan (
scanned_at). Remove objects only for rows the graph writer reported as retired. - Live paths: outputs of the keep-set's runtime closure, plus the
.drvNAR andinputSrcsof every reachable derivation. - Fetch time: every NAR download bumps
cached_path_signature.last_fetched_atandfetch_count(gradient-web/src/endpoints/caches/nar.rs). - Per-cache storage use: a cache's use is the sum over its own claims. Evicting a cache's unused claim lowers that cache's use, even while another cache keeps the path.
Access¶
| Endpoint | Rule |
|---|---|
GET /builds/{build}, /log, /graph, /closure, /downloads |
The project must be public, the requester must belong to the build's project, or the requester must belong to any project with a build_job for the same derivation (BuildAccessContext::load, gradient-web/src/endpoints/builds/mod.rs) |
GET /builds/{build}/download/{filename} |
The same rule as above, or a download token for the derivation |
Narinfo, NAR, ls and serve on /cache/{cache} |
The active cache must hold a signed cached_path_signature row for the path. cache_can_sign_content_variant_sql_condition must also hold for that row (cached_path_by_store_hash_subquery_sql, gradient-db/src/store_path_content_variant_reader_choice.rs) |
GET /cache/{cache}/log/{drv} |
The cache can serve the log only if the cache can hand out an output of that derivation under the same rule (build_attempt_that_produced_derivation_output_served_by_cache in gradient-db/src/cached_paths.rs). Requests fall through to the upstream caches (caches/build_log.rs) otherwise |