Execution Model¶
Pivot uses a parallel execution model with warm worker pools for maximum performance.
Execution Flow¶
┌──────────────┐
│ pivot repro │
└──────┬───────┘
│
▼
┌──────────────────┐
│ Engine │ ← Central coordinator
│ (run) │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Build Bipartite │
│ Graph │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Check │
│ Fingerprints │
│ vs Lock Files │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Engine │
│ Orchestration │──────────────┐
└──────┬───────────┘ │
│ │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Worker 1 │ │ Worker N │
│ (Process) │ ... │ (Process) │
└──────┬───────┘ └──────┬───────┘
│ │
▼ ▼
┌──────────────────────────────────────────┐
│ Per-Stage Lock Files │
│ (Parallel writes, no contention) │
└──────────────────────────────────────────┘
Engine Orchestration¶
The Engine uses event-driven orchestration for maximum parallelism:
- Stage States - Each stage has its own state (PENDING → READY → PREPARING → WAITING_ON_LOCK → RUNNING → COMPLETED)
- Scheduler -
Schedulerowns stage state, upstream/downstream sets, and resource permits - Ready Queue - Engine asks Scheduler for eligible stages
- Event Emission - StageStarted/StageCompleted events to sinks
As stages complete, their downstream stages become ready. The Engine handles both batch (exit_on_completion=True) and continuous (exit_on_completion=False) execution through the same orchestration code.
Stage Execution States¶
Stages have individual states tracked by the Engine:
class StageExecutionState(IntEnum):
PENDING = 0 # Not yet considered
BLOCKED = 1 # Upstream failed
READY = 2 # Can run, waiting for worker
PREPARING = 3 # Engine clearing outputs
WAITING_ON_LOCK = 4 # Worker waiting for artifact locks
RUNNING = 5 # Stage function executing
COMPLETED = 6 # Terminal
The IntEnum allows ordered comparisons (e.g., state >= PREPARING means execution has begun).
State Transitions¶
PENDING ──(deps complete)──▶ READY ──(worker available)──▶ PREPARING ──▶ WAITING_ON_LOCK ──▶ RUNNING ──▶ COMPLETED
│ │
└──(upstream failed)──▶ BLOCKED └──(failed)──▶ COMPLETED
Output Filtering by State¶
During watch mode, the Engine filters filesystem events based on stage state:
- PREPARING: Silence events for this stage's outputs (Engine is preparing them)
- WAITING_ON_LOCK: Defer events while worker waits on artifact locks
- RUNNING: Defer events for outputs (collect, don't act yet)
- COMPLETED: Process deferred events, compare output hashes, trigger downstream
Worker Pool¶
Pivot uses loky.get_reusable_executor() with spawn context. WorkerPool owns workers and
the manager process for the Engine lifetime. Each run gets its own manager-backed output queue
and drain shutdown event, so logs cannot cross run boundaries. A manager that cannot be reached
when a run starts (it died, or its socket was removed) is replaced then.
Why ProcessPoolExecutor?¶
- True parallelism - Not limited by Python's GIL
- Isolation - Each stage runs in its own process
- Memory efficiency - Workers can be recycled
Why Spawn?¶
- Safety - Avoids fork() issues with threads (Python 3.13+ deprecates fork in multithreaded contexts)
- Compatibility - Works on macOS and Linux
- Clean state - Each worker starts fresh without inherited state
Pool Size¶
get_width() gives the Engine an upper bound from the run's stage graph, capped by
core.max_workers. It limits admission and the workers that the run's first submission starts.
The worker pool starts processes when the run submits work. The run's first submission starts
the run's resource width: the most of its stages that one replayed schedule runs at once,
within resource capacities (Scheduler.resource_width). The width counts every stage of the
run, including stages that are cached or skipped later. A local_grade: 2 limit therefore
starts at most two workers for an otherwise-wide grade wave, and a chain starts one. The replay
has a step budget: 10,000 steps plus 8 per stage, dependency and requested resource. Below it
the width is exact. A run that needs more starts get_width()'s pool size, the most workers it
may hold at once. Random runs of 400 or more stages whose stages each ask for several small
resources can need more. After the first submission, a dispatch starts a worker when an admitted
stage finds every live worker busy, or for the scheduler-admissible direct consumer wave of the
parent it dispatches. For a parent that runs past half the one-shot idle timeout, the pool pings
idle workers pre-started for that wave. The ping restarts the worker’s idle clock without
blocking it on the parent. When the parent resolves, pings stop and those workers become
ordinary idle workers. A run whose stages all skip in the coordinator starts no workers.
For a one-shot Engine, an idle worker exits after the 10-second idle timeout, or occasionally
after a second one, when loky's worker loses its process-lock race. The timeout is 116 times the
largest coordinator handoff gap of five 100-stage pandas/NumPy chains, 70.959 to 86.164 ms,
measured at 3f72f1f2 on a 32-CPU cloud machine, while remaining short compared with
remote-stage waits. A persistent watch, serve or TUI Engine keeps idle workers alive between its
runs for a warm next run.
Textual Startup¶
Before Textual captures sys.stderr, Pivot starts loky's and multiprocessing's resource
trackers. Textual's captured stream has no valid file descriptor, and those tracker launchers
need one. Workers can start after the TUI begins and use the already-running trackers.
Warm Workers¶
Workers stay alive across runs in one long-lived Engine, so imports from earlier stages remain available. Before a later run reuses workers, Pivot replaces them if a user-code module they imported changed. A watch-mode code reload starts the reloaded run's width of fresh workers together, so that run starts its stages at once.
Stage resources¶
Stages can reserve scheduler-held resources while they execute:
@stage(resources={"gpu": 1})
def train(data: pd.DataFrame) -> Model: ...
@stage(resources={"cpu": "all"})
def compact(data: pd.DataFrame) -> pd.DataFrame: ...
Resource names are case-insensitive. Every scheduled stage, including bare @stage functions, holds one cpu unit. The cpu capacity is the configured worker count (core.max_workers), not the pool size, so cpu: "all" runs without another stage. Other resources default to capacity 1, which serializes stages sharing that resource.
Set a project capacity in .pivot/config.yaml or override it for one command:
The scheduler acquires every permit immediately before submitting a stage and releases them when it completes. A stage waiting for a resource does not consume a worker. Resource declarations tune concurrency only; they are not part of stage fingerprints.
Stage Execution¶
Each stage execution:
- Acquire Execution Lock - Prevent concurrent execution of same stage
- Read Lock Data - Get previous fingerprint and hashes
- Hash Dependencies - Compute current dependency hashes
- Check Skip Conditions - Compare fingerprints, params, deps
- Restore or Execute - Either restore from cache or run function
- Cache Outputs - Store in content-addressable cache
- Write Lock File - Record new fingerprint and hashes
- Release Lock
Three-Tier Skip Detection¶
Pivot uses a three-tier skip detection system to minimize unnecessary work:
Worker receives stage
│
▼
┌────────────────────────┐
│ Lookup dep hashes │
│ (StateDB cache: O(1) │
│ when metadata match) │
└────────────┬───────────┘
│
▼
┌────────────────────────┐
Tier 1: │ Check generation O(1) │──── Match? ──▶ SKIP
│ (StateDB lookup) │
└────────────┬───────────┘
│ No match
▼
┌────────────────────────┐
Tier 2: │ Compare lock file │──── Unchanged? ─▶ SKIP
│ (fingerprint+params+ │
│ dep_hashes) │
└────────────┬───────────┘
│ Changed
▼
┌────────────────────────┐
Tier 3: │ Check run cache │──── Hit? ─────▶ SKIP
│ (input_hash → outputs)│ (restore from cache)
└────────────┬───────────┘
│ No hit
▼
┌──────────────┐
│ EXECUTE │
│ stage func │
└──────────────┘
Dependency Hash Lookup¶
Before skip checks, dependency hashes are looked up via StateDB. Each cached hash entry stores file metadata from a stat() that follows symlinks:
mtime_ns- Modification time in nanosecondssize- File size in bytesdev- The device of the filesystem that holds the fileinode- Filesystem inode number
When all four match the current file's stat() result, the cached hash is returned in O(1) without re-reading the file. The inode check detects file replacement (delete + create with same name), which keeps mtime/size but changes inode. The device check detects a path that now reaches another filesystem (a directory symlink re-pointed at another mount), where an inode number can repeat. The entry holds no ctime: a new hard link changes it, so every hardlink checkout would invalidate the entries of the files it links. Only files with changed metadata require actual hashing.
A dependency is hashed only when it is a regular file or a directory, symlinks followed: storage.cache.hash_file decides from the file's stat, before the StateDB lookup, and never opens a FIFO, a socket or a device (the rule storage.regular_file.open_regular_file states). Such a dependency is unreadable, as a file this user cannot read is, and named with its kind: the stage fails with unreadable deps: data (a FIFO, not a file), and, for a stage that ran before, its explanation says Unreadable deps: data (a FIFO, not a file) (one with no lock is explained as No previous run before any dependency is hashed). The hash reads a file through storage.regular_file.open_regular_file, as a copy into the cache does, so an entry swapped in after the stat is refused at once too.
Tier 1: Generation Check (O(1))¶
The fastest check uses monotonic generation counters to detect changes without comparing hashes:
- Each output has a generation counter in StateDB, keyed by its artifact identity and incremented every time the output is written
- When a stage runs, it records the generation of each dependency at that moment
- On next run: if
recorded_generation == current_generationfor all deps → nothing changed → skip
A dependency on one file of a directory output follows its directory's counter, which moves whenever any of its files are written; when it moved, the file's own hash in Tier 2 decides.
Example: Stage train depends on demo/preprocess's output.
preprocessruns and writes its output → generation becomes 5trainruns, recordsdep_generations: {"demo/preprocess": 5}- Next run: the generation is still 5 → generations match → skip
train preprocessruns again → generation becomes 6- Next run:
trainrecorded 5, current is 6 → mismatch → fall through to Tier 2
This provides instant O(1) skip detection when nothing has changed.
File metadata verification: In addition to generation comparison, Tier 1 optionally verifies that cached file hashes still match the current file metadata (mtime_ns, size, device, inode). This catches external modifications that generation tracking alone wouldn't detect—for example, if an external tool modified a dependency file without going through Pivot.
Tier 2: Lock File Comparison¶
If generations don't match, perform a full comparison:
- Code fingerprint (AST hash of function + dependencies)
- Parameters (Pydantic model values)
- Dependency hashes (content hashes of all input files)
If all match the lock file → skip.
Tier 3: Run Cache Lookup¶
If the current inputs differ from the lock file but match a previous execution:
- Compute
input_hashfrom fingerprint + params + dep_hashes - Look up in run cache:
input_hash → cached_outputs - If found → restore outputs from cache, skip execution
This enables skipping even when switching between branches or reverting changes.
StateDB Architecture¶
StateDB is an LMDB-backed key-value store for all pipeline state. Its key prefixes and the .pvt discovery memo are described in Storage.
Multi-process safety¶
- Workers open StateDB in
readonly=Truemode (no write contention) - Workers collect
DeferredWritesand return them to the coordinator - Coordinator applies all writes atomically in a single LMDB transaction
- One exception: before a worker writes a
*.pvtmember into a directory output (a run or a run-cache restore), it adds that member to the stage'snocommit:record in its own write transaction, so a crash never leaves the stage's member unrecorded. Only a stage that writes such a member pays this write
Generation tracking¶
Generation counters enable the O(1) skip check. If a stage recorded dependencies at generations [5, 3, 7] and current generations are still [5, 3, 7], skip without further comparison. If any generation differs, fall back to full hash comparison.
Concurrency Safety¶
Pivot uses a "check-lock-recheck" pattern to prevent TOCTOU (Time-of-Check-Time-of-Use) race conditions between concurrent pivot processes on one project.
The Problem¶
Without locking, two processes could both read a stage's lock file, both decide the stage must run (or that a missing output must be restored), and conflict on output writes; or one could overwrite an output while another process's stage is reading it.
Artifact Locks¶
Each artifact has a lock file under the stage state directory's locks/, taken with flock (storage/artifact_lock.py): READ is LOCK_SH, WRITE is LOCK_EX. expand_lock_requests turns a stage's deps and outs into requests, one per artifact at the strongest mode asked for, and acquire_many takes them in sorted key order (no lock-order deadlocks), retrying a non-blocking flock until it succeeds.
| Who | Deps | Outs | Held |
|---|---|---|---|
| A worker running a stage | READ | WRITE | for the whole run, through the lock file write |
| The coordinator deciding whether a cached stage skips | READ | READ | for the check |
| The coordinator restoring a cached stage's outputs from the cache | READ | WRITE | for the check and the restore |
A stage lock is read only after its artifact locks are held, so a waiting process evaluates the state committed by the writer ahead of it.
A cached stage's skip check takes READ on its outputs, so it does not wait for the runs reading them as deps: a widely read output is held READ by every running consumer, and WRITE would wait until none is running. When the check finds an output that differs from the lock but is in the cache, it releases its locks, takes WRITE on the outputs, and decides again from the start, since another process may have restored or rebuilt them in between. Locks are never upgraded in place: two processes each holding READ and waiting for WRITE would wait on each other.
Multi-Process Safety¶
Concurrent pivot repro is Safe¶
Multiple simultaneous pivot repro invocations on the same project are safe and supported:
- Each invocation gets its own loky worker pool and StateDB instances
- LMDB enforces at most one writer at a time (via mutex), unlimited concurrent readers
- Read transactions use MVCC snapshots—readers never block or see partial writes
- Writes are per-stage lock files (distinct files) plus centralized StateDB (atomic updates)
State Database Access Pattern¶
The coordinator-worker pattern ensures multi-process safety:
- Worker processes (readonly): Open StateDB in readonly mode, see consistent MVCC
snapshots. Collect deferred writes locally instead of writing directly. The one direct
write is the
nocommit:record of a*.pvtmember, made before the member is written. - Coordinator process (read-write): Applies all deferred writes in a single atomic
transaction after worker completes via
apply_deferred_writes().
This avoids write contention between workers while maintaining consistency.
Concurrent Scenarios¶
| Scenario | Result |
|---|---|
Two pivot repro, same stage |
WRITE on its outputs lets one run it; the other waits, then finds it cached |
Two pivot repro, different stages |
Both execute independently, writes serialize |
pivot repro --no-commit + pivot commit |
Independent operations, no lock needed |
| Cache writes by both processes | Idempotent (check exists before writing) |
Error Handling¶
Two error modes:
| Mode | Behavior |
|---|---|
fail (default) |
Stop on first error |
keep_going |
Continue with independent stages |
See pivot.types.OnError for the enum definition.
Missing inputs¶
Before any stage runs, the engine looks for missing inputs in two steps:
- After the
.pvtdiscovery walk, the pre-flight (executor.core.verify_tracked_files) finds each tracked file (.pvt) that does not exist, as a file or a directory (symlinks followed). One rule decides it, bystatalone (storage.track.present_kind): anything else at the path, such as a socket or a FIFO, is missing, and the path is never opened. With--checkout-missing, it first restores each one that the cache holds. engine.graph.get_runnable_stagesfinds each dependency that no stage produces and that does not exist on disk.
When step 2 finds a missing dependency, a run across all pipelines (Engine(all_pipelines=True), as pivot repro --all builds it) with OnError.KEEP_GOING (engine.graph.skips_missing_dependencies) excludes the stage that has it, and every stage downstream of it. It logs one Skipping: warning for each missing dependency and runs the other stages. When no stage is left, or in any other run, the run stops with the missing-dependency errors. A watch run waits for the input instead (see Watch Mode).
A missing tracked file stops the run at step 1 with TrackedFileMissingError, except in two kinds of run. A run given target stages outside a watch session (no --watch or --serve; pivot repro <stage>, pivot run <stage>), and not in leave-out mode, takes the missing files from the pre-flight as leave-out mode does (tolerate_missing=True). It stops after step 2 with TrackedFileMissingError naming only those that a loaded stage reads (engine.graph.read_tracked_files, by the rule below), before any stage runs. A missing tracked file that no loaded stage reads, such as another pipeline's input, does not stop it. A missing tracked file that overlaps an output of a loaded stage stops it at step 1, as below, and one that overlaps a mapped stage's planned instance output fails that stage at expansion, as in leave-out mode, after its producer may have run. Its --checkout-missing restore stays the one outside leave-out mode (tolerate_failed_restore=False): a restore that fails stops the run, and the restore replaces a socket or a FIFO in a tracked file's place. A run with no target stops on every missing tracked file. The other exception is leave-out mode (engine.graph.is_leave_out_mode, which the engine and pivot repro both call): skips_missing_dependencies is true and the engine has no FilesystemSource (no --watch or --serve). pivot run and executor.core.run never set all_pipelines. In leave-out mode:
- The pre-flight returns the missing files (
tolerate_missing=True) instead of raising. They are the one source of which tracked paths are missing:get_runnable_stagesexcludes each stage with a dependency that is such a file, lies inside one, or is an existing input directory that holds one, by their paths or by their resolved paths (os.path.realpath), so a dependency that reaches the file through a symlink reads it too, and a dependency on a socket or a FIFO where a tracked file belongs is excluded though an entry exists there. A stage gets one error, and oneSkipping:warning, for each missing tracked file it reads. - A
--checkout-missingrestore that fails leaves its path missing, with aCannot restorewarning, instead of stopping the run (executor.tracked_restore). It fails for a tracked directory whose listing is unavailable (exceptions.ListingUnavailableError, whose docstring names the cases): its committed listing is stale, empty or unreadable (a file this user cannot read, or a directory where the file belongs) while the cache holds no copy of that listing (a fresh clone), with the warning thatpivot checkoutgives; or the listing's object in the cache cannot be read, even beside an intact committed listing (the read checks the cache's copy for a collision), with a warning naming the path and the error and no listing remedy. It fails too for a read or write that fails withOSError, naming the path and the error: a write into a read-only directory, or a cache prefix directory this user cannot search, whoseOSErrorthe listing read raises as it is. A refusal (a restore that would replace a user's file or a control path, or link into a cache that refuses this process's links with no copy among the checkout modes) and any other corrupt listing still stop the run: a collision, a cached listing object whose bytes do not hash to its record, and a listing that does not parse or does not match its record. Outside leave-out mode, every one of these failures stops the run too, as in 0.10.4: an unreadable cache prefix directory with its rawPermissionError. In leave-out mode only, the restore also fails, before it reads the cache, where an entry it does not replace stands at the path: a socket, a FIFO or a device, or a symlink to one, which it neither replaces nor opens, and the warning names it (executor.tracked_restore._occupied). Outside leave-out mode the restore replaces such an entry, as in 0.10.4. - A missing tracked file that is, lies inside or holds an output of a loaded stage, by their paths or their resolved paths, still raises
TrackedFileMissingErrorat step 1, naming the output and its stage, and, for a file whose--checkout-missingrestore failed, naming it as one, not as one the local cache lacks (ownership.MissingTracked.failed, which the pre-flight returns). A mapped stage whose planned instance outputs overlap one fails at expansion and adds no instance.ownership.tracked_output_refusalbuilds the error in both places, and in the dry run, which predicts the same failed restores (executor.core.MissingTrackedFiles.missing). One function plans a mapped stage's instances for the run and the dry run (expansion.plan_instances): the keys that instance targets name, the outputs over a missing tracked file, and the incremental outputs that the run would lose. The dry run reads the keys as the run does (under--no-commit, for a producer that the run skips, from the directory in the workspace where no listing is committed or cached,expansion.workspace_keys). It shows a mapped stage that this plan, or any other refusal of its expansion, stops (expansion.Expansion'srefused: the run fails it alike) as one row that would not run (would_run: false,would failin text,WILL FAILin--explain), with the reason the run fails it with. A mapped stage whose producer is current only becausepivot pullwould bring it up to date, and whose listing cannot be read (ListingMissingError,CorruptListingError), is not one: the run, which never pulls, runs that producer again and reads the listing it writes, so the dry run shows the mapped stage as not yet expanded, as 0.10.4 does. Under--no-committoo, the dry run does not read that producer's directory in the workspace, which the run replaces when it runs the producer again. Any other refusal of such a mapped stage is one: it is over the keys of the listing that the dry run reads, which it takes the producer's run to write again, so the run meets that refusal after it runs the producer. Each mapped stage that the run blocks behind a refused one (cli/leave_out_dry_run.py_refused_upstream) is one row that would not run either (would be blocked,WILL BE BLOCKED), whose reason names the refused one. - A named target whose stage, or a stage upstream of it, is excluded does not stop the run. The engine runs the other targets and keeps the excluded ones in
Engine.left_out_targets(expansion.keep_targets, which the dry run calls too).pivot reprothen raisesTargetsLeftOutError(exit 1) after its summary. When every target is excluded, the engine runs no stage. pivot repro --dry-runand--explainmake the same decisions and restore nothing (cli/leave_out_dry_run.pyplan_run, withexecutor.core.find_missing_tracked_files, which finds the missing files with the same walk and existence rule and only reads the walk's memo). First, as the run's registration in the cache does, they refuse a cache whose object store is the root of a mount of its own (naming.require_shared_store). Of the restore, the dry run shares two reads, the check for an entry the restore does not replace (executor.tracked_restore._occupied) and the lookup of what the restore links (executor.tracked_restore._source), and predicts the rest (executor.tracked_restore.check_tracked); the agreement tests, which give a dry run and a run the same tree, guard that prediction.
Cancellation¶
The engine supports graceful cancellation via a CancelRequested event. When set:
- Running stages complete - The currently executing stage finishes normally
- Pending stages are skipped - No new stages are started
- Results include cancellation - Skipped stages report reason "cancelled"
This cancellation is stage-level, not mid-stage. This ensures outputs are always in a consistent state (either fully written or not started).
In watch mode, the Agent RPC cancel command sends a CancelRequested event, allowing external tools to stop execution between stages. The TUI also uses this for Ctrl+C handling.
Stopping mid-stage¶
Ctrl+C at a terminal (outside the TUI), and the death of the Pivot process (SIGKILL, or SIGTERM, which Pivot does not handle outside the pivot command's repro --watch --serve; that serve mode handles SIGTERM as Ctrl+C), stop running stages mid-stage. Each running stage gets pivot.executor.worker.WorkerTerminated, a KeyboardInterrupt, raised where it is, so its except KeyboardInterrupt cleanup, finally blocks and context managers run, as they would for Ctrl+C in a plain Python program. Then:
- The stage fails and nothing it produced is committed: no output enters the cache and no lock is written, even if the stage caught the exception and returned a value.
- The worker exits once the stage has unwound, and no later than
worker.TERMINATION_GRACE_S(10 s) after it was told to stop, whatever the stage does. Before exiting, it kills every process still descended from it. A process that detached (double-forked, a daemon, or orphaned when its parent exited) is not reached; the stage's cleanup must stop it, as it must stop a container, which the Docker daemon runs. - Pivot itself (on
Ctrl+C) waits up to the same 10 s for its workers, then kills any left with their child processes.
A cleanup that must finish therefore has 10 s: remove a container with docker rm --force, which takes about a second, not docker stop, which waits 10 s for the container by default.
Explain Mode¶
Preview what would run and why:
Shows:
- Code changes
- Parameter changes
- Dependency changes
Checkout Missing Mode¶
The --checkout-missing flag restores missing tracked files (.pvt) from the cache before running:
This is useful when:
- A branch switch leaves the data that the new branch's
.pvtfiles name missing from disk - After
git cleanor an accidental deletion of tracked files
Without this flag, a missing tracked file stops the run, except in leave-out mode and, for a file no loaded stage reads, in a run given target stages (see Missing inputs). The error (TrackedFileMissingError) suggests how to restore the files:
- For one missing file:
pivot checkout <path>, orpivot checkout --only-missingto restore all missing files. - For more than one:
pivot checkout --only-missing(restore without running), orpivot run --checkout-missing(restore and run). - After a
--checkout-missingrestore: the error saysThese files are not in local cache.and suggestspivot pull. In leave-out mode, a file whose restore failed is named as one whose restore failed instead, and theCannot restorewarning before the error names the cause.
How it works: the pre-flight restores each missing file from the hash that its .pvt records, and a directory from its listing. It never replaces a file that exists, and no stage runs during the restore. The cache must hold the objects (pivot pull fetches them from a remote). After the restore, the normal execution flow continues and may skip stages if nothing else changed. In leave-out mode, the run then excludes only the stages that read a file that the pre-flight could not restore.
Under repro --all --keep-going, with neither --watch nor --fail-fast, --dry-run and --explain restore nothing. With --checkout-missing, a missing tracked file is restorable when the local cache holds every object that its restore needs, the user can read each of them as the restore reads them (the lookup, then an open for reading, which each checkout of an object makes; a symlink restore of a directory whose whole tree the cache holds opens none once it can stat the tree's files, and restores file by file, opening each object, when it cannot: cache.linked_tree with stat_files, else cache.missing_linked_objects with readable), and the restore can write it: the nearest existing directory above it is one that the user can write in and search (state_dir.nearest_entry_problem, which a state directory is checked with too). A symlink restore of a directory whose whole tree the cache holds makes the directory that holds the path before it reads the tree or looks up any member's object (cache.restore_tree), so where that directory cannot be made it fails whatever the cache holds, and the dry run checks that first. Where that directory exists and the user cannot write in it, the restore's link of the whole tree fails there, and the restore looks up each member's object before it restores file by file: a member that the cache lacks leaves the path absent, with no warning, as in the dry run (executor.tracked_restore.check_tracked), and otherwise the restore cannot stage the directory. Where the run's registration in the cache refuses this process's links (the cache's register is on a filesystem mounted read-only here, which the dry run reads from os.statvfs: naming.register_refuses_links), the restore copies every object, and the dry run opens each one as the copy does. With no copy among the checkout modes (cache.refused_link_modes), the restore refuses where it reaches a link, which stops the run, and the dry run refuses there alone: at the link of a file's object, or of a directory's whole tree that a symlink restore links as it is (cache.linked_tree), once the directory that holds the path exists or can be made; and at the link of the first file of a directory restored file by file, once the restore can stage the directory beside the path. Where the restore cannot make or stage that directory, it fails with a Cannot restore warning, and a directory whose listing holds no file links nothing, so the restore brings it back. executor.tracked_restore.check_tracked predicts the restore for each missing file that executor.core.find_missing_tracked_files finds, sharing with it only the lookup of what it links, so a directory whose listing is unavailable is not restorable, as in the run; a path whose objects or listing the user cannot read (an object, or a directory of the cache, at mode 0o000) gets the warning that the run's restore gives for the error, and a path that the restore cannot write gets one warning naming the directory, where the run's warning names the error that its write meets. Limit: they write nothing, so they do not register the project in the cache. Where the run's registration fails on a writable filesystem (a cache register that this user cannot write), the run stops before any stage runs while they list the stages; whether a registration writes there, and fails, only the write tells. They count as present each path that such a restore creates: the file or directory, and each file and empty directory of the directory's listing, with every directory that holds one. A dependency the restore does not create still excludes its stage, and so does one the restore creates that is a directory holding a missing tracked file that the restore does not bring back, as in the run. The --checkout-missing row of the CLI reference says where the dry run's would_run then comes from the disk. For a mapped stage that they show as not yet expanded, --dry-run and --explain print a Notice: line on stderr only where the run may expand it (cli/leave_out_dry_run.py _log_restore_limits, with status.restore_limits). The mapped stage waits for its producer (status.expand_current gives the stages that are not current). Each stage that runs by its own explanation, the producer or a stage upstream of it, has a dependency that is, holds or lies inside a restorable path, by its path or its resolved path (engine.graph.tracked_overlap, which asks storage.path_forms), and whose hash the explanation does not take from a .pvt (explain.find_tracked_hash, with the explanation's own store and cache). The rule starts from the dependencies that get_runnable_stages found present (engine.graph.RunnableStages.present), resolves their symlinks and reads the listings of the restorable directories. Then it explains each of those stages again with explain.get_stage_explanation, which reads the stage's lock and hashes its other dependencies on disk, giving each such dependency the hash that the lock recorded (assume_restored), as if the restore brought back what the stage last read. The notice is printed when each of those explanations says that the stage would not run, and no stage of the producer and its upstream stages that is current by its own explanation has such a dependency: that stage is current for the disk without the restored path, and the run runs it. So the explanation, not a second rule, decides code, params, other inputs, outputs, --force and a stage with no lock. The restore can bring back other contents, so the notice says that the run may add the instances. The notice is wrong when the restore does not give back exactly what the stage last read: another file of the read directory changed or was added, the file was tracked again with new contents, the restored file's mode differs (a single file's .pvt records no executable bit, and a directory's hash holds each file's), or the stage never read the file (it was tracked after the stage's last run). It names the last of those stages in execution order (the producer itself when it is one of them), with its first such dependency.
Deferred Commit Mode¶
The --no-commit flag runs stages without writing durable state:
# Run stages — outputs land on disk; no locks, no cache, only a record of what each stage ran and wrote
pivot repro --no-commit
# Inspect results, then snapshot current workspace state
pivot commit
How It Works¶
--no-commit: stages execute and outputs are written to disk. No lock files, cache copies, generations or run-cache entries are written. StateDB keeps one record per stage (nocommit:<stage>): the code manifest the run's lock would have held, rerun marks included, and the hashes of the outputs it wrote; and the*.pvtfiles Pivot wrote in its directory outputs since its lock was last written, with their content hashes. Each*.pvtis added before the file is written, as every path that writes a stage's*.pvtmember without writing its lock does (a run-cache restore,pivot getof the stage), so a crash leaves at worst a record without a file. Until a lock is written, each such file that still holds the recorded content is the stage's own: a later run or restore replaces it, andstatusdoes not warn about it. The stat-validated file hashes of dependencies and outputs the run read are also saved best-effort, so a later status need not read them again.pivot commit [stage_names...]: computes current workspace state (hashes deps and outputs), writes production lock files, saves outputs to cache, and updates StateDB. Without arguments, commits all stale stages. With stage names, unconditionally commits those stages. It takes as the stage's own only the*.pvtfiles its lock lists, or that itsnocommit:record lists and that are unchanged since; it refuses, naming it, any other.pvtin an output, which may be a user's sidecar. A refusal fails that stage alone; the other stages are still committed, and the CLI and the RPCcommitboth report the full result. A written lock removes the record. The code manifest it writes depends on the outputs:- The outputs on disk are the ones a
--no-commitrun wrote (its record):pivot commitwrites the manifest that run recorded. The run's code is the code the stage ran, which can differ from the code on disk now (a helper edited while the run continued), and a rerun mark the run set stays. An unmarked record files a run-cache entry under that manifest. A marked record stays non-reusable: it files no entry and deletes one at its static input hash. - No record, a record without a code manifest (one that holds only another feature's key), or outputs that differ from it (edited by hand after the run):
pivot commitfingerprints the code on disk now and records the outputs against it, as below.
Use Case¶
This workflow avoids caching overhead during rapid iteration. pivot commit is also the "trust me" path — if you change code but know outputs are still correct, pivot commit records the current state without re-running stages. For outputs that a --no-commit run wrote and nobody changed since, it records the code that run ran instead, so an edit made during or after that run still reruns the stage.
See Also¶
- Architecture Overview - System architecture
- Fingerprinting - Code change detection