Dependencies¶
A stage's dependencies are its function parameters. Pivot loads each one before the stage runs, passes the loaded value in, and uses the dependency to build the DAG and to decide when the stage must re-run.
A parameter can receive one of four values at the call site:
| Call-site value | The function receives | Creates a DAG edge |
|---|---|---|
A handle (from pipeline.input() or another stage call) |
The loaded artifact | Yes |
A list or tuple of handles |
A list or tuple of loaded artifacts |
One per handle |
A StageParams instance (at most one) |
That instance, with params.yaml overrides applied |
No (see Parameters) |
pipeline.previous() or pipeline.previous("key") |
The stage's prior tagged incremental output | No |
Anything else (an int, a string, a path) is rejected when the pipeline is
built: parameter 'factor' has unsupported type 'int'. Use ArtifactHandle
(dependency), StageParams (config), or list/tuple of ArtifactHandle. Put such
values in the stage's StageParams.
Previous incremental outputs¶
pipeline.previous() is valid only as an argument to the stage call whose
return type has one output tagged incremental. For a TypedDict result, use
pipeline.previous("key") to select the tagged field. Each marker can bind one
parameter only; it is not a handle and does not add a self-edge to the DAG.
Inputs: pipeline.input()¶
Files that no stage produces are declared once, by name:
| Argument | Effect |
|---|---|
name |
Input name; also the file name under data/raw/ |
external=True |
Read data/external/<name> instead |
path="dir/file.csv" |
Read this path (relative to the project root) |
t=pathlib.Path |
Pass the stage a pathlib.Path instead of loading the file |
t=str |
Pass the stage the file's text |
format=loaders.CSV(sep=";") |
Load with this reader |
Without t or format, the extension picks the loader:
| Extension | Stage receives |
|---|---|
.csv |
pandas.DataFrame (CSV()) |
.jsonl |
pandas.DataFrame (DataFrameJSONL()) |
.json |
parsed JSON (JSON()) |
.yaml, .yml |
parsed YAML (YAML()) |
.txt, .sql, .jinja |
str (Text()) |
.pkl, .pickle |
unpickled object (Pickle()) |
| anything else | pathlib.Path (PathOnly()) |
An input whose file does not exist fails before anything runs:
Stage 'demo/keep' depends on input 'missing.csv' (path data/raw/missing.csv),
which does not exist. pivot repro --all --keep-going is the exception. It
logs a Skipping: warning for each missing input of a stage, excludes that
stage and every stage downstream of it, and runs the other stages. A
missing tracked file has its own rules (see
Files tracked outside the pipeline).
Pivot reads an input only when it is a regular file or a directory, symlinks
followed. A FIFO, a socket or a device, or a symlink to one, is never read.
Such an input fails its stage as unreadable, in every mode, as a file you
cannot read does: unreadable deps: scores.csv (a FIFO, not a file).
For a stage that ran before, --explain shows
Unreadable deps: scores.csv (a FIFO, not a file); a stage with no previous run
is explained as No previous run before any input is read. A symlink to
/dev/null is a device too (a device, not a file). For an empty input, use
an empty file instead. At the path of a tracked file, such an entry counts as a
missing tracked file when pivot repro runs, and in --explain and
--dry-run under --all --keep-going too. Outside that mode, for a stage that
ran before, --explain, --dry-run and pivot status --stages-only show it as
unreadable. Plain pivot status stops with an error that names it
(Error: Is a device, not a regular file: <path>), and pivot track refuses to
track one.
Directory inputs and .pivotignore¶
A directory input (t=pathlib.Path on a directory) is hashed file by file, and
any change to it makes its consumers stale, except for the files and
directories the project's .pivotignore names. pivot init writes a starter
.pivotignore (pivot check-ignore --show-defaults lists it): compiled Python
(*.pyc, __pycache__/), virtual environments, version-control and editor
files, build directories. So a Python process that imports from an input
directory and writes __pycache__/*.pyc there leaves the stage cached.
- Patterns are read and matched as git 2.52 reads and matches a root
.gitignore, with a port of git's own matcher: the same syntax, the same**rules (logs/**names what is insidelogs, notlogsitself, so!logs/.gitkeepbrings that file back;foo**/barnamesfoo/barandfoox/barbut notfoobar, which git before 2.52 also named), and the same bytes (a line that is not valid UTF-8 matches the same bytes in a name; a NUL ends a line). Matching is case-sensitive, as git's is withcore.ignorecaseoff. Each file is matched by its path inside the project (the input's path plus the file's path under it), never by where a symlink points, so a directory linked in from outside the project is treated as a local one. A file under an ignored directory stays ignored, as in git: a later!pattern cannot bring it back. .pivotignoredecides two things: which files of a directory input count for its hash (so whether its consumers rerun), and which changes inside a directory inputpivot repro --watchskips.pivot check-ignoreanswers by the same rules. For an input directory that.pivotignoreignores (below),check-ignorereports its files ignored, as git would, but the input is hashed whole.pipeline.pyand.pivot/at the project root are never ignored, whatever the patterns say, andcheck-ignoretakes a relative path from the project root, not the current directory.- A line may hold at most 256 runs of
*that are tried at more than one place. A run at the end of the line does not count, nor a lone*right before a/(it matches the rest of one name), and consecutive**/count as one. Pivot matches a longer line differently from git, with a warning that quotes it, and always toward hashing more. For a member (a file or directory inside an input) a negation (!...) is taken to match it and any other such line not to, so every file git might keep is kept. For an input directory (the input's own directory, or one above it) it is the other way round: a negation matches none, so an earlierbuild/rule still makes an input atbuildhash whole, and any other such line matches every input directory, so an input is hashed whole unless a later line unignores it and every directory above it. At worst a stage reruns when git's rule would not count the file. - It does not apply to stage outputs, to data you
pivot track, or to the cache: every file in a directory output or a tracked directory is hashed, cached and restored, a.pycincluded. A stage that reads another stage's directory output depends on that output's whole hash. - The listing committed for a directory input
(Listing files) holds the files its hash counts,
so it leaves out what
.pivotignorenames too. A tracked directory's.pvt.listingkeeps every file, andpivot pull <tracked path>fetches every one of them, sopivot checkoutrestores the directory as it was. - An input file you declare by name is always hashed, whatever
.pivotignoresays. An input directory that.pivotignoreignores itself (or that lies in a directory it ignores, such as an input underbuild/) is hashed whole, with a warning: leaving out every file in it would hide every change to it. - Only the project's
.pivotignorecounts: not one in your home directory, since lock files carry input hashes to every machine, and not one in a subdirectory, which is data like any other file. - Changing
.pivotignorechanges the hash of every directory input holding a file whose status it changes, so those stages run once.pivot status --explainshows the input's hash change;git diffon the input's committed listing (.pivot/stages/=inputs/) after the run shows which files entered or left its hash.
Example¶
# pipeline.py
import pathlib
import pandas as pd
from pivot import Pipeline, StageParams, loaders, stage
class ShiftParams(StageParams):
offset: int = 0
@stage
def shift(raw: pd.DataFrame, params: ShiftParams) -> pd.DataFrame:
return raw.assign(value=raw["value"] + params.offset)
@stage
def stack(tables: tuple[pd.DataFrame, pd.DataFrame], lookup: dict) -> pd.DataFrame:
left, right = tables
combined = pd.concat([left, right], ignore_index=True)
return combined.assign(value=combined["value"] + lookup["bonus"])
@stage
def describe(query: str, notes: pathlib.Path, rows: pd.DataFrame) -> dict:
return {"query": query.strip(), "notes_bytes": notes.stat().st_size, "rows": len(rows)}
with Pipeline("deps") as pipeline:
raw = pipeline.input("values.csv")
lookup = pipeline.input("lookup.yaml", external=True)
query = pipeline.input("query.sql")
notes = pipeline.input("notes.md", t=pathlib.Path)
semi = pipeline.input("semi.csv", format=loaders.CSV(sep=";"))
low = shift(raw, params=ShiftParams(offset=1))
high = shift(semi, params=ShiftParams(offset=100))
stacked = stack((low, high), lookup)
describe(query, notes, stacked)
with these files:
mkdir -p data/raw data/external
printf 'id,value\n1,10\n2,20\n' > data/raw/values.csv
printf 'id;value\n3;30\n' > data/raw/semi.csv
printf 'bonus: 5\n' > data/external/lookup.yaml
printf 'select 1\n' > data/raw/query.sql
printf '# notes\n' > data/raw/notes.md
The two calls to shift become the stages deps/shift and deps/shift@1
(see variants). stack receives a tuple of two
DataFrames because it was called with a tuple of two handles.
Outputs of other stages¶
A stage call returns a handle to the stage's output. For a stage that returns a
TypedDict (several outputs), select one field before passing it on, with
attribute or item syntax:
split = split_rows(raw) # returns a TypedDict with fields "train" and "test"
fit(split.train) # or split["train"]
Passing the whole handle fails: Stage 'demo/fit' received handle from
multi-output stage 'demo/split_rows' without selecting an output. Use
handle.key or handle['key']. Available: ['train', 'test'].
A directory output is passed whole, as a
dict from each file's path to its value, or one file at a time by indexing
its handle with that path:
parts = split(raw) # returns Annotated[dict[str, pd.DataFrame], directory]
count(parts) # every file: reruns when any of them changes
fit(parts["train.csv"]) # one file: reruns only when train.csv changes
Objects named by hash¶
A declared input can name another object by its content hash instead of holding
it: a pin file holding the hash of a snapshot another project pushed, an index
naming the hashes of records. The stage reads each such object with
pivot.read_by_hash:
import pivot
from pivot import Pipeline, stage
@stage
def plan(pin: str) -> dict:
snapshot = pivot.read_by_hash(pin.strip()) # a pathlib.Path to the object
return {"taken": snapshot.read_text().splitlines()}
with Pipeline("plan") as pipeline:
plan(pipeline.input("counted.pin", t=str))
- Where the object comes from. Pivot looks the object up in the cache, else
downloads it from the project's default remote into the cache, and checks that
its bytes hash to the hash asked for. The path is the read-only cache object:
read it, never change it. Any file object in the cache can be read this way: a
stage's file output, one file of a directory output, or a tracked file, once
pivot pushhas put it on the remote. - Finding a hash to pin.
pivot.output_hash("pipeline/stage", key)returns the content hash a stage's committed lock records for its outputkey(Nonefor a stage's one unnamed output, aTypedDictfield's name otherwise), read from the lock file alone, so a command that writes a pin can name the output it pins. It raisespivot.exceptions.OutputMissingErrorwhen no lock records it. Call it outside the stage: inside a stage run it raisespivot.exceptions.ObjectReadError, since the lock it reads is not one of the stage's inputs, and a new output there would never rerun the stage. Write the hash into a pin file and declare that file instead. - What reruns the stage. The input that names the hash, as any input does:
a new hash in
counted.pinrerunsplan. - What the lock records. Each hash the run read, once, sorted, under
reads, beside the stage's declared dependencies. A run-cache restore records what the restored run read, andpivot commitafterpivot repro --no-commitrecords what that run read.pivot commit <stage>with no such run records the outputs on disk: when the lock already records those outputs from the same code, params and dependencies, it keeps the lock'sreads, since those outputs came from those objects. Otherwise (edited outputs, or a changed input such as a new pin, even when the outputs' bytes are the same) it records noreads: a fresh run, or a matching--no-commitrecord, records what the stage reads now. A stage that reads nothing by hash has noreads. A pivot older than this one dropsreadswhen it writes the lock: from a run-cache restore, or frompivot commitafter this pivot's--no-commitrun. And when a--no-commitrun of an older pivot follows this pivot's own, the older pivot keeps this pivot'sreadsin the record, sopivot committhen records objects the later run may not have read: that can only make the stage stale orpivot pullfetch an extra object, never skip a run that is needed. - A recorded object that is not at hand.
pivot statusandpivot reprodecide from local state, as they do for outputs, and contact no remote: an object the lock records counts as available when it is in the cache, or when the remote index (filled bypivot push,pullandfetch, and by a run that completed after its read fetched the object) records it on the default remote. Otherwisepivot statusreports the stage stale, naming the objects and why, and suggestspivot pull, which fetches them, when a remote is configured and pulling brings the stage up to date (not beside an edited metric, or below a stage that must run);pivot reproruns the stage: its read fetches the object from the remote, or fails naming it when the remote lacks it too. An object the index records is not checked again, so its later loss from the remote is found by the next read, not bypivot status. - Pulling.
pivot pull <stage>fetches the objects its lock records underreads, beside the stage's outputs, so the stage can run again in the clone;pivot push <stage>sends the same objects. An untargetedpivot pullfetches every object on the remote. - A read that fails raises
pivot.exceptions.ObjectReadErrornaming the hash: a value that is not a content hash (16 lowercase hex characters), an object neither the cache nor the remote holds, or bytes that hash to something else.
pivot.read_by_hash works only inside a stage Pivot runs, from any thread of the
stage's own process, a coroutine's included. A process the stage starts (a forked
child, joblib's processes backend) is refused: only the stage's own process
records what it reads, so read there and pass the path or bytes on.
Testing is natural¶
Outside a with Pipeline block a @stage function is an ordinary function, so
tests pass data directly:
def test_shift() -> None:
df = pd.DataFrame({"value": [1, 2]})
assert shift(df, ShiftParams(offset=1))["value"].tolist() == [2, 3]
Files tracked outside the pipeline¶
pivot track caches files that are not stage outputs (large raw data, for
example) and writes a .pvt sidecar to commit in their place:
The sidecar sits beside its data, and its path: is the data's name
(values.csv in data/raw/values.csv.pvt). pivot checkout, pivot pull and
pivot repro --checkout-missing restore the file that path: names, under the
directory holding the .pvt.
A missing tracked file stops the run. Before any stage runs, pivot repro
and pivot run check that each tracked file exists. With --checkout-missing,
they first restore the files that the cache holds. A missing file stops the run
with the error The following tracked files are missing.
There are two exceptions. A run given target stages without --watch
(pivot repro <stage>, pivot run <stage>) stops only on a missing file that a
loaded stage reads or that is, lies inside or holds a loaded stage's output: a
missing file that no loaded stage reads, such as an input of a pipeline the run
does not load, does not stop it. Its --checkout-missing restore still stops on
a failure. And
pivot repro --all --keep-going without --watch excludes each stage that
reads the missing file, and every stage downstream of it, and runs the other
stages.
A stage reads the file when one of its dependencies is the file, lies inside
it, or is an input directory that holds it, also when the path reaches the file
through a symlink. A Skipping: line names the stage and each missing file
that it reads. When the run excludes a named target, the command exits 1 after
the other targets run.
A missing tracked file that is, lies inside or holds a stage output still
stops the run before any stage runs, also under --all --keep-going. The error
names the output and its stage. Under --all --keep-going, and in a run given
target stages, a mapped stage whose instance output overlaps such a file fails
instead and adds no instance.
A .pvt restores its file only inside the project. A sidecar whose path:
names no file (., ./ or empty), holds .., is absolute, or names a file
whose directory really lies outside the project through a symlink, is skipped
with a warning that names it; the command keeps going and exits 0. Move such a
sidecar beside its data inside the project and set path: to the data's name.
pivot track refuses a path whose directory really lies outside the project, as
from a data -> /mnt/external symlink: the .pvt would be written beside the
data, outside the project, where no Pivot command reads it again.
The check reads "inside the project" from the resolved path, so it does not see
a bind mount inside the project that points outside: resolve() cannot detect a
bind mount, and a .pvt restored under it lands outside the project (git and DVC
share this limit, and setting a bind mount up needs CAP_SYS_ADMIN). The check
and the write are separate steps, so a local process that can already write in
the project can replace a checked directory with a symlink pointing outside
between the two and land the file there.
See also: Artifacts & the DAG | Outputs | Loaders