Fingerprinting¶
Pivot fingerprints your stage functions so it knows when code changes. Unlike file-level hashing (which triggers on whitespace or comment edits), Pivot's fingerprinting is Abstract Syntax Tree (AST) based — it captures the structure of your code, ignoring cosmetic changes.
What Gets Tracked¶
When Pivot builds a stage, it computes a manifest: a dict mapping logical keys to hashes:
| Manifest key | What it represents |
|---|---|
self:<name> |
The stage function's own AST |
func:<module>.<qualname> |
Helper functions called by the stage |
class:<module>.<qualname> |
User-defined classes referenced by the stage |
const:<module>.<name> |
Immutable module-level values, read as a global or as module.NAME; a helper read as module.helper is a func: entry, a library function an ext: entry |
const:<module>.<qualname>.<name> |
Immutable values in a closure cell, keyed under the function that holds the cell, so two closures from one factory (h2 = make(2), h5 = make(5)) keep their own values |
default:<module>.<qualname>.<parameter> |
Default argument values the AST does not record |
ext:<module>.<name> |
Library functions and classes a stage reads (agg = np.mean), recorded by name (numpy.mean); Pivot does not hash their code (a library installed from git or a local path is hashed by its installed files instead: dist:) |
byname:<module> |
A module the stage's worker imports by name and whose code is not hashed: a library module the stage reads as a global (np.mean(x) with import numpy as np) or imports in its body, the module that defines each ext: callable, and the library module of a base class of your class, of a class in a type hint or a class annotation, of a class, instance, enum member or exception inside a value (a partial, a default, a loader's config), of a pivot loader class, of a stage function that a library defines, and of a library callable whose __module__ is not a string. In those places Pivot records no standard-library module and none of its own. Pivot checks it is the module the worker will import (Same module in the worker); the lock file does not record it |
dist:<name> |
The installed files of a library installed from git, from a local directory or from a local wheel or sdist, not editable, that owns one of the stage's byname: modules, and of each library installed that way that such a library depends on, directly or through other libraries. <name> is the library's distribution name in lower case, each run of -, _ and . made one - (PEP 503): Fix_Lib gives dist:fix-lib. The lock file records it. See Libraries Installed from Git or a Local Path |
schema:<module>.<qualname> |
Pydantic model JSON schemas |
wire:<parameter> |
Call-site artifact wiring: a direct identity, or a collection's kind and ordered identities; input path bindings use wire:<parameter>:path or :paths |
dep:…:loader:<module>.<class>:…, out:…:loader:<module>.<class>:…, out:…:tag |
Reader/Writer method ASTs and config for each input and output, plus each output's placement and write semantics |
How It Works¶
For each stage function, Pivot:
- Parses the AST —
inspect.getsource()→ast.parse()→ normalize (strip docstrings, renamedeftofunc) →ast.dump()→xxhash64 - Walks closure variables —
inspect.getclosurevars()finds globals and nonlocals the function references - Recurses transitively — every user-code callable found in step 2
gets the same treatment, and its dependencies are merged into the
manifest. A user class the stage reaches has its callable members walked:
methods, descriptors such as properties, partial members, nested user classes,
and methods bound to another user class (
Holder.fn = Other.cm). A held classmethod tracks its function and its original receiver class:cls.VALUEreadsOther.VALUE, notHolder.VALUE, even throughHolder().fn(). A module value or helper read only inside a method (ScopeWalk().step(...)reading a module-level regex) is tracked. So is the class of an instance afunctools.partial, a loader's config, a dataclass field default or aStageParamsdefault holds (partial(run, Scorer())): its class is walked as if the stage named it, so an edit toScorer.scorere-runs the stage. A scalar class attribute a member reads throughself,cls,type(self),self.__class__, or literalgetattris tracked by value just asClass.NAMEis. Library value forms preserve complete values: pandas timestamps/timedeltas, supported dateutil/pytz datetime zones, and numpy integers/booleans remain accepted. Arbitrary user timezone implementations remain unsupported.types.DynamicClassAttributeon a reached user class is refused by member name rather than silently omitting its executable getter. Ordinaryenum.propertygetters are tracked like property getters; enum redirects for members namednameorvalueremain supported. - Follows imports in the function body — a user module discovery already
loaded is walked like a module-level dependency, together with its packages
and a submodule a
fromimport names (import pkg.sub,from pkg import sub). A body import of a user module discovery did not load is refused when the pipeline is defined, without running it: Pivot would have to execute the module to fingerprint it. The error names the module; import it at module level (or inpipeline.py) so discovery loads it, or move the value into the stage'sStageParams - Inspects type hints — user-defined classes in annotations (including Pydantic models) are fingerprinted
- Hashes Pydantic schemas —
model_json_schema()captures field types, defaults, and validators
The manifest is stored in the per-stage lock file. On the next run, Pivot computes the manifest again and compares it key-by-key against the locked version. Any difference triggers re-execution.
While a stage runs, its worker records the user modules it imports through
Python's __import__ and importlib.import_module entry points, including a
module a warm worker already holds, and compares the sys.modules keys before
and after the stage to catch a newly registered user module loaded from a
source file. What a covered module's first import starts belongs to that
import, as it would for a module-level import: every import on the thread
running it, every hooked import on a thread it started (and on threads those
start) for the rest of the stage, already resident or not, and every module
any thread registers without the hooks while such an import or thread runs.
Every thread Python starts counts: each start function _thread exposes
(start_new_thread, start_new, start_joinable_thread), which
threading.Thread, threading.Timer and ThreadPoolExecutor start through.
A thread native code starts outside _thread is not covered.
A hooked import on any other thread is counted, already resident or not, and
so is a module registered without the hooks at any other time, even when a
covered import later imports it. A stage that imported a user module its
fingerprint does not cover still succeeds, with one warning naming the module,
but its result is never reused:
Pivot files no run-cache entry, removes any entry an earlier run filed for the
same inputs, never restores one for that stage, and writes a lock the next run
cannot match; pivot status --explain and pivot repro --dry-run --explain
show the stage as stale with that reason, and pivot verify reports it as
failed with that reason until it reruns without an uncovered import.
pivot commit keeps that mark when it
records the same outputs, so the stage still reruns. A user class reached only
through a loaded input (an object in a loaders.Pickle() input whose class the
stage never names) counts as a module the stage imported; name the class in the
parameter's annotation (Annotated[Box, loaders.Pickle()]) to cover it. To
clear the warning, import the module statically and read it by name in the
stage's own code (import pkg.mod, then pkg.mod.NAME, or pass pkg.mod
itself to the call that needs it), so the walk covers it, or move the value
into StageParams. An import in pipeline.py alone does not cover a module
for a stage that never reads it, and a body import that only silences the
warning while the stage still reads values through the object a dynamic import
returned leaves those values untracked. A @no_fingerprint stage is not
checked: its declared code_deps are its code.
That check does not see every way a stage can reach code. In most of these
cases Pivot reuses a result whose fingerprint missed the code, as it would
without the check. In three it reruns a stage it could have reused: a thread
that existed before a covered import, a thread left from an earlier stage (a
covered thread of that stage included) that imports while a later stage runs,
and a thread native code starts outside _thread:
- a read of a module already in
sys.moduleswithout an import, orimportlib.reload: import the module where the stage reads it; - a warm
EntryPoint.load()orimportlib.__import__of a user module another stage already made resident: it creates no newsys.moduleskey, and the loader may hold an importer before the hook, so it is not fingerprinted, as on main; import the module statically; - private import machinery, or a loader that replaces a module already in
sys.modulesor never registers one, such asrunpy.run_path("helpers/lib.py")orrunpy.run_module("toplib")for a top-level module: import it statically, or move the value intoStageParams; - an import in a child process: declare the code the child runs as an input,
or list it in
@no_fingerprint(code_deps=[...]); - an import from a thread that outlives its stage: the import is charged to whichever stage is running when it happens, which then warns and reruns, or to none; a covered thread still running in a later stage is not covered for it; join the thread before the stage returns;
- a covered module that hands work at import time to a thread that existed before its import, such as a pool an earlier import created: that thread is not covered, so its imports are counted and the stage reruns. When an earlier stage in the same worker started the thread, whether the stage warns depends on which stage ran first there: where the covered import itself starts the thread, the thread is covered and the stage caches. Start the thread or pool inside the module, or import the module statically;
- a thread native code starts outside
_thread, such as one a C extension starts orpthread_createcalled throughctypes: no start hook sees it, so its imports are counted and the stage warns and reruns; import the module statically; - a user module a covered thread imports that has nothing to do with the covered module: it is excused and not fingerprinted, as on main, so an edit to it is seen only through values the stage reads from the covered module, or when the covered module changes; import user modules statically;
- a user module another thread registers without the hooks while a covered import or covered thread runs: it is excused with that import's own, so an edit to it is seen only through values the stage reads from the covered module, or when the covered module changes; import user modules statically, or before starting threads;
- a user module a covered module loads at import time through
importlib.utilandexec_module,EntryPoint.load()orimportlib.__import__: it is excused, as on main, and not fingerprinted itself, so an edit to it is seen only through values the stage reads from the covered module, or when the covered module changes; import it statically; - a package resource read through
importlib.resources(for examplefiles(helpers).joinpath("table.txt")): it is data, not code; declare it withpipeline.input; - a module created without a source file (CPython's
pyexpat.errors, Cython's_cython_3_3_0): it has no source to fingerprint; pivot repro --no-commitfollowed bypivot commitof outputs edited by hand after that run:pivot commitrecords them against the static fingerprint, the "trust me" path. Outputs the run wrote, unchanged since, are recorded with the manifest the run recorded, the mark included;- a result cached by an earlier Pivot version: if its static fingerprint is
unchanged, it may be reused, from its lock, which Pivot reads as it is, or
from its run-cache entry, which Pivot finds under the key that version filed
it under (each directory the stage reads whole hashed from its listing the
way that version hashed it), because
_CACHE_SCHEMA_VERSIONkeys only the fingerprint caches in state.lmdb, not the lock or the run cache. A stage whose static walk reaches a user class method or a user module gains entries in its manifest, so it reruns once as Code changed after the upgrade. That accepted one-time rerun writes the current manifest; later runs reuse it until code or inputs change. Runpivot repro --force <stage>once to re-check a stage you know imports dynamically. Upgrading from 0.10.4, a stage that reaches a library installed from git, a local directory or a local wheel or sdist gains that library'sdist:key, so it reruns once as Code changed, and a stage that reaches none keeps its lock, with three exceptions, each of which reruns once as Code changed: a stage in a virtual environment uv built withUV_LINK_MODE=symlink, where 0.10.4 took every library as user code; a stage that reaches a file linked intosite-packagesthat no editable install's RECORD lists (a link you made yourself); and a stage that reads the project's part of a package it shares with an installed library through the package's name (company.local.f()), whose module Pivot now walks, so a value in it that no fingerprint records refuses the stage, as it does in a top-level module (core.unsafe_fingerprintingturns that into a warning). The fingerprint caches' schema goes from 43 to 45, so Pivot computes each stage's manifest once more, which reruns nothing by itself. Upgrading from 0.5.6 or earlier, every stage with outputs reruns once as Code changed, because each output's tag (out:<key>:tag) joined the manifest; that run is checked, so it marks a stage that imports dynamically.
Transitive Tracking¶
If train() calls normalize() which calls clip_outliers(), all three
functions appear in the manifest. Changing clip_outliers triggers a
re-run of train even though train itself didn't change.
Module-level scalars, exact tuples and frozensets of scalars, and compiled
regular expressions are tracked by value. If your stage does from myproject
import config and then accesses config.THRESHOLD, Pivot captures the value
or the called function. A stage reading any other module-level value, such as a
list, dict, set, nested collection, enum member, frozen model, or instance,
raises StageDefinitionError; use StageParams instead.
What Triggers a Re-Run¶
| Change | Triggers re-run? |
|---|---|
| Rename a variable | Yes |
| Change a numeric constant | Yes |
| Add/remove a function argument | Yes |
| Change a helper function your stage calls | Yes |
| Change a Pydantic field type or default | Yes |
| Edit a docstring | No |
| Add/remove comments | No |
| Change whitespace/formatting | No |
| Change an unused import | No |
| Change a library installed from git, a local directory or a local wheel or sdist that your stage uses, or a library installed that way that it depends on, and reinstall it | Yes |
Edit such a library's installed files in place (in site-packages) |
Yes |
| Reinstall the same files of such a library from another commit or path, with pip or uv, into another virtual environment, or with only its version changed | No |
| Upgrade or downgrade a library installed from a package index | No, as before: Pivot records such a library by name (a stage function or a loader's load, save and empty that it defines is still hashed) |
Edit the source of a library installed editable from a directory outside the virtual environment and outside every site-packages directory |
Yes (it is your code) |
Edit the source of a library that flit's install --symlink links into site-packages (an editable install) |
Yes (it is your code). A link into site-packages that no editable install's RECORD lists is a library's to Pivot, so an edit through it reruns nothing, where Pivot 0.10.4 saw it: flit before 3.0 wrote no direct_url.json, so Pivot takes a module file it linked as a package-index library's (reinstall with flit 3.0 or later); an editable install whose RECORD is lost lists none of its links (reinstall it); and Pivot takes a link to your own file made by hand in site-packages as a library's too (install your code editable instead) (Files Linked into site-packages) |
Reinstall the same libraries with uv's UV_LINK_MODE=symlink, which links each installed file into uv's cache, in place of copies |
No: Pivot takes a file linked into site-packages as library code, as it takes a copy there, unless an editable install's RECORD lists it, also when your project reaches it through a link of its own, and refuses a broken install there as it refuses a copied one (Files Linked into site-packages) |
Surprises and Pitfalls¶
Lambdas¶
A lambda in a source file is hashed by its AST like any function. One created
dynamically (via eval, exec, or an interactive session) has no source, so
Pivot hashes its code object (__code__: bytecode and constants, without the
source path). Its fingerprint is the same from run to run, and editing the
expression re-runs the stage. Only a callable with neither source nor a code
object falls back to id(), which changes every run; Pivot warns when it does.
Prefer named, module-level functions, whose AST hash ignores comments and
formatting:
# Works, hashed by its code object
normalize = eval("lambda df: df / df.max()")
# Better - AST fingerprint
def normalize(df):
return df / df.max()
Module-Level Values¶
A stage may read a module-level bool, int, float, str, bytes or
None, a tuple or frozenset of such values, or a compiled regular
expression; editing it re-runs the stage. A regex is tracked by its pattern and
flags. Reading any other module-level value (list, dict, set, a tuple holding a
tuple, list or object, enum member, class instance, or a method bound to an
instance such as np.random.default_rng(SEED).normal), directly or as
module.NAME, is a StageDefinitionError that names the variable:
COLUMNS = {"score": float} # Module-level dict
@stage
def process(data: pd.DataFrame) -> pd.DataFrame:
return data.astype(COLUMNS) # Error!
The same rule covers a default argument that reads a module value, such as
def process(data, cols=COLUMNS), on the stage or on a helper it calls. A
default is evaluated when the module loads, so Pivot checks its value: a scalar,
a tuple or frozenset of scalars, or a compiled regex is tracked, and anything
else is refused. A literal default such as cols=("a", "b") is part of the
function's code and is tracked with it. A default that is a pipeline input
handle (raw=RAW with RAW = pipeline.input("t.csv")) is wired as an input
and tracked by its content.
A dataclass's class-level field default (rng: Any = make_rng(), a
ClassVar) is evaluated when its class is created, so Pivot hashes its value
for each stage that reaches the class: a string, bytes or a path by its
content, including text that looks like a memory address, an exception by its
arguments, attributes and built-in value fields such as OSError.filename, an
object by its attributes and __slots__, and a function or classmethod an
object holds (a callback) with the module values it reads. A callback that reads
its own enclosing class stops at that class. One __wrapped__ follower handles
user helpers, globals, closure cells, partial arguments and keywords, defaults, state,
and loader methods. It stops at a @fingerprint_by_name mark and refuses a loop
or a chain past sys.getrecursionlimit() above that boundary by name, even with
unsafe fingerprinting enabled: break the loop, shorten the chain, or move the
value into StageParams. A terminating user chain inside that limit is walked one
function at a time, including each Python function's own code and reads. Native cache settings
are recorded only for caches over user code, from the stdlib cache_parameters closure,
without calling it. A cache over library code is recorded by name; edits to its typed
or maxsize do not trigger a rerun. For stacked native caches, only the settings visible on
the outermost wrapper are recorded: CPython's functools.update_wrapper copies
the inner cache's cache_parameters, so an edit to the outer typed or
maxsize is not seen. Use the stage's StageParams for cache configuration
that must trigger a rerun. Library helpers and their wrappers, such as json.dumps, are
recorded by name without reading their private closure state. A library-defined stage root
still tracks the project globals, closure values and defaults its body reads; a native cache
on that root follows its terminal Python body. User wrapper code is walked even when
functools.wraps copied a library target's module metadata.
An unmarked class-based decorator under a cache is recorded as a bound value:
its C-readable state and its class's code are tracked. A by-name mark remains
a boundary: the walk adds no settings or body dependencies below it.
Class attributes read through the receiver are analyzed in each Python method
body reached through the chain, including beneath a native cache, a partialmethod or a
forwarding decorator, up to a by-name mark.
An Enum member is hashed with its value, and known exact stdlib type expressions such as
list[int], str | None or collections.abc.Callable[[int], str] by their origin
and arguments. A user subclass of types.GenericAlias is refused: its native
alias fields do not describe its Python behavior or state. A numpy scalar subclass
includes its attributes and slots as well as its native data. A default whose state Pivot cannot
read, such as a random.Random, a numpy Generator or a threading.Lock,
refuses the stage, naming the field. For a field, build the value with
dataclasses.field(default_factory=...); a ClassVar takes no factory, so
create its value in the method that uses it; or move the value into the stage's
StageParams.
A partial argument or loader config that holds a library value whose type has no
supported value form is refused for the same reason. For example,
random.Random keeps its generator state in C, so Pivot cannot safely hash it.
Read such data from a pipeline input or move its configuration into StageParams.
An OrderedDict keeps its logical order, including move_to_end changes. Its
keys must be exact bool, int, float, complex, str, bytes or None
values: Python's native ordered iterator hashes keys, so other key types are
refused before iteration rather than running their hash code. This includes an
OrderedDict subclass or a mapping proxy over one.
Pivot reads the values it fingerprints, and the classes they hold, through
Python's own C-level accessors rather than through their code. Where a value
cannot be read that way, the stage is refused by name: a class whose metaclass
defines __getattribute__ or __getattr__ (reading anything of the class would
run it), a functools.lru_cache wrapper whose cache_parameters was replaced,
or a class attribute that a method reads through self and that is a
descriptor object.
An object whose __getattr__ raises an error other than AttributeError for
a name it does not have (a dict-backed config, an AttrDict, a lazy object)
gets the same decision as any other object of its kind: Pivot takes that error
as a missing attribute rather than stopping the fingerprint on it.
Fix: move a mutable or nested value into the stage's StageParams. Configuration in module-level mutable collections is not supported.
To suppress the check (at your own risk), set
core.unsafe_fingerprinting = true in your Pivot config
(pivot config set core.unsafe_fingerprinting true) or
PIVOT_UNSAFE_FINGERPRINTING=1 in the environment. A stage whose fingerprint
needed that downgrade still runs, but its result is never filed in the run
cache or restored from it: the captured value may differ next time while the
fingerprint stays the same.
Pivot rejects patterns that bypass static analysis:
globals()/locals()— runtime namespace accessgetattr(obj, variable)— dynamic attribute lookupimportlib.import_module()— dynamic imports
All of these silently introduce dependencies that fingerprinting can't
track. Use direct attribute access and static imports instead. Other dynamic
import spellings (__import__, an alias of import_module, exec) are not
refused: a user module one of them loads while the stage runs makes its result
not reusable, as described above, and a library module costs nothing.
Code Edited While Pivot Runs¶
Pivot loads your code once, when it discovers pipeline.py, and the run uses
that code. A stage's fingerprint describes the code that Pivot loaded, not the
file as it is when the stage starts. If you edit a stage or a helper while the
run continues (in an editor, or from an upstream stage), the stages of that run
use the loaded version, and their locks record it. The next run loads your edit
and reruns the stages it changes. This holds for every user module Pivot can
read the source of, whatever loaded it: a module under the project root, one on
PYTHONPATH, an editable install's finder, a zip's .py file (Pivot compiles
and runs it itself), importlib.util.spec_from_file_location, sitecustomize
before Pivot started, or a loader a module calls itself (see below). A module
Pivot cannot read the source of is never reused, as the next paragraphs say.
A worker imports some modules from their files itself: a module outside the
project root (on PYTHONPATH, or a package installed from a source checkout),
a stage's module under the root in a src layout, and a module that a stage
imports in its body. If the worker imports such a file after you edit it, a
stage that uses the module (its code reaches the module's functions, classes or
values, or it imports the module while it runs) runs your edit, which its
fingerprint does not describe. That stage logs a warning that names the module
("imported user modules that changed after pivot loaded them"), and Pivot does
not reuse its result: the next run reruns it ("Previous run imported modules
edited after pivot loaded them"). A stage on the same worker that does not use
the module is not affected. A helper recorded by name only
(fingerprint_by_name) is not a use of its module's code. pivot repro --watch
loads an edit under the project root again. A module outside the root is loaded
once by the watch or server process, so its edit is loaded when Pivot starts
again; until then a worker that imports it after the edit runs the edit, and
the stages that use it warn and rerun on every run.
A library installed from git, a local directory or a local wheel or sdist is
read once per Pivot process (and again if the workers' sys.path changes):
Pivot hashes its installed files when a stage first reaches it. A reinstall
while Pivot runs is not seen by that process, so pivot repro --watch, with
or without --serve, sees it when Pivot starts again. The next process reads
the new files, and a stage whose library changed reruns once.
Pivot hashes such a library's files as they are on each machine, so three cases give a key that differs from machine to machine or from commit to commit. A library with compiled extensions has files whose names carry the platform and whose bytes differ by platform and build, so its key differs between machines. A library whose build writes a version file that holds the commit (setuptools-scm, hatch-vcs) gets a new key at every commit, so every stage that uses it reruns at every commit. A library installed from git on one machine and from a package index on another gets a key on the first and none on the second, so each machine reads the other's lock as stale.
A user module whose source Pivot cannot read (a sourceless .pyc, or a module
from a loader that gives no source) is never trusted: Pivot cannot tell which
code a worker holds. A stage that uses it warns once per run ("uses user
modules whose source pivot cannot read"), reruns on every run, and never files
or reuses a run-cache entry. The same holds for a module from any loader Pivot
cannot show runs the source it reads. Pivot trusts only three: Python's own
source file loader and a zip's .py file, whose source Pivot compiles and runs
itself, and Pivot's own loader run inside another (an import hook that wraps
the loader it finds, as dd-trace-py's ModuleWatchdog does). For that last one
Pivot trusts that the wrapper runs the code Pivot's loader compiled for the
module, and nothing else: a wrapper that asks Pivot's loader for the code and
then runs its own cached bytecode instead is not detected (a known limit; no
known tool does this). Every other loader may run cached bytecode, or text
other than its source, so the file can say one thing while the module runs
another: a subclass of importlib.machinery.SourceFileLoader or another
importlib.abc.SourceLoader (tools that rewrite source as it is imported
install one), a proxy around Python's loader, or a loader that caches its own
bytecode. So can a zip that holds a .pyc beside the .py file, as a zipped
compileall -b tree or an egg does, when Python's own zip importer finds the
module: it picks that .pyc when its header matches the .py file's time and
size. The first stage in each process that uses such a module logs why ("Pivot
cannot trust the code of user module '…'"), naming the loader (the real one,
when an import hook wraps it), and what to do: import the module without that
loader, or accept that the stage reruns on every run. After a run that used
such a module, Pivot never reports the stage as cached, unless you pivot
commit outputs that no run recorded while the stage's lock carries no mark; a
lock written before the loader was installed, or by an earlier Pivot, can
still be reported cached until a run uses the module. Each rerun runs whatever
that loader runs: if the loader runs old bytecode, the output is still the old
code's. Pivot stops claiming the result is fresh; it cannot make your loader
run the current code. A loader with only the old load_module method still
imports as it does without Pivot, and its module is treated the same way.
A module imported before Pivot starts, by sitecustomize or a .pth import
line (in the pivot process and in every worker), was loaded before Pivot
could record its source; a module that a module loads with a loader it calls
itself (SourceFileLoader(...).load_module()) passes no hook that records it.
Pivot reads such a module's file when it discovers the pipeline, and each
worker when it starts and after each stage, and trusts that text only when the
file and its cached bytecode show it is the module's code: CPython's own loader
imported it, and neither the file nor the bytecode it may have run changed
after the process started or in the 2 s before. Otherwise Pivot treats the
module as one whose source it cannot read, and the first stage that uses it in
each process also logs why ("Pivot cannot trust the code of user module '…'":
Pivot did not see it compile). That happens when the file changes while Pivot
starts or in the 2 s before it starts (a stage that uses it reruns once more on
the next run), in a process that loaded a module and then edited it, and for a
module a custom loader imported. A worker whose text differs from the one the
pivot process recorded marks the stage, as above. Import such modules from
the pipeline or a stage instead. A
forward step of the system clock between an edit and the start of a pivot
process can make that edit look older than the start: the 2 s margin covers a
step of about 1 s where the file system keeps whole-second change times, and of
2 s where it keeps exact ones. A file system that keeps change times in
2-second steps (FAT) uses the whole margin, so there an edit made just as a
pivot process starts can be missed. Linux's FAT driver also sets a file's
change time to its modification time whenever it reads the file's entry from
disk again, so there an edit whose modification time a tool put back can look
unchanged; Pivot then catches it only by the file's cached bytecode.
Under pivot repro --no-commit no lock is written. The run records, for
pivot commit, the manifest each stage's lock would have held, warnings' marks
included, and the outputs it wrote. pivot commit writes that manifest when the
outputs on disk are still those, so a stage that ran loaded or edited code
reruns on the next run, as it would without --no-commit. Outputs edited by
hand since that run are recorded against the code on disk now, the "trust me"
path.
Same Module in the Worker¶
A worker imports a module your stage refers to by name (a helper module outside
the project, a library, the module a library function comes from) with the
project root first on its sys.path. A program that runs Pivot in its own
process, such as a notebook or a script calling pivot.executor.run(), may
already hold a module of that name from another file: a notebook's own
helpers.py, or an installed library named like a project file. import in
pipeline.py then returns the program's module, so the fingerprint would
describe it while the worker runs the project's file, and an edit to that file
would read as cached. Pivot fails the stage's fingerprint instead, naming both
files. Rename one of the two modules, or, when the program imported its own
module of that name, run Pivot in a new process (the pivot command).
Every module a stage refers to by name is predicted once per run, without
importing anything. On a 1,000-stage project with three such modules per stage,
pivot status took about 3% longer than before the check. Only when a module
Pivot holds is not the one the prediction finds does Pivot start one
interpreter, as it starts a worker (about a tenth of a second, once per run), to
confirm what a worker would import. That interpreter runs your sitecustomize
and .pth files once more, as every worker does, and imports no project module.
A module that site, a sitecustomize or a .pth file imports in every
interpreter is what the worker imports too, so it is no error. Cases not
checked: a module the program loads by file location while Pivot is loading the
pipeline (from another thread); a finder the program inserted into
sys.meta_path after it started, which Pivot assumes the worker has too; a
package whose __init__ changes its own __path__; and a pipeline object run
again after the program changed sys.path, whose fingerprints Pivot keeps (load
the pipeline again).
Your Module in a Package a Library Shares¶
A stage can read your module through a package it shares with an installed
library: import company.local, then company.local.value(), where company
also has a directory in site-packages (a namespace package, or a library
package whose __init__ calls pkgutil.extend_path). Pivot sends that module
with the stage: a module of your project that Pivot sends by value as itself,
when Pivot can pickle it alone, and any other (a module outside the project
root, say) by its name, which the worker imports before the stage runs. The
worker puts it on the package while the stage runs, so the stage runs as a
plain python run of your code does, and an edit to the module reruns it.
The worker imports each module sent by name before the stage, whether or not
this run of the stage reads it: Pivot records what the stage's code can read,
not what one run reads. When that import fails in the worker after it worked
in Pivot's own process (import-time code that cannot run twice, a file broken
during the run), the stage's output holds one warning that names the module and
the error's type and message, on one line (Could not import module
'company.local', which the stage reads through its package: RuntimeError:
...), Pivot binds nothing for the module, and the stage runs. A stage that
reads the module then fails with
AttributeError: module 'company' has no attribute 'local', as in Pivot
0.10.4, with the warning in its output; a stage that does not read it in that
run runs, as in 0.10.4. Other stages run on.
The limits of sending your module, each of which Pivot 0.10.4 has too, with the same outcome unless the item says otherwise (Imports a Stage Makes While It Runs):
- A module that cannot be pickled (one holding a
threading.Lock) is not sent. A helper outside the project root that reads it through the package finds it only when the helper's module imports it itself (import company.local, notimport companyalone); otherwise the stage fails withAttributeError: module 'company' has no attribute 'local'. A stage whose own code reads it so fails before it runs, as its call to the worker cannot be pickled. - A stage that holds a class of the module (
from company.local import Mode) while a helper outside the project root imports the module itself holds another copy of it than the helper:company.local.run(Mode.FAST)then compares the stage'sMode.FASTwith the helper's copy ofMode. - The module's import-time code does not run in the worker: a class it
registers with a library as it is imported is not registered there. Pivot
0.10.4 fails here earlier, with
AttributeError, as it binds nothing on the package. - A stage body that imports the library's package itself (
import companyinside the stage) gets it without your module. Only a library package whose__init__callspkgutil.extend_pathreaches this: Pivot refuses such an import of a namespace package that has a directory in your project. - A
@no_fingerprintstage's helper module is not read, so a module that only the helper reads through the package is in the worker only where an import there puts it (see@pivot.no_fingerprint()below). - A function of the module that rebinds one of its globals (
global COUNT) changes the copy its functions read: code that then readscompany.local.COUNTthrough the package still sees the old value. Pivot 0.10.4 fails here earlier, withAttributeError, as it binds nothing on the package. - A package of yours below the shared one (
company/proj/__init__.py) one of whose modules a helper outside the project root imports itself (import company.proj.other) is the helper's copy in the worker, which holds only the modules that import loaded: reading another one through it (company.proj.mod) fails withAttributeError. - A module outside the project root that the stage's own code reads through the
package (not inside a lambda) is imported as the worker receives the stage:
if that import fails, every stage running in Pivot's workers at that moment
fails, with
A task has failed to un-serialize.
@pivot.no_fingerprint()¶
For stages where AST fingerprinting doesn't work (C extensions, generated
code, complex metaprogramming), opt out with @no_fingerprint():
from pivot import no_fingerprint, stage
@stage
@no_fingerprint()
def external_model_stage(data: pd.DataFrame) -> pd.DataFrame: ...
@stage
@no_fingerprint(code_deps=["scripts/train.sh", "configs/model.yaml"])
def shell_stage(data: pd.DataFrame) -> dict: ...
With @no_fingerprint(), Pivot falls back to file-level hashing: it
hashes the entire source file containing the function. The optional
code_deps argument lists additional files (relative to the project root)
that are part of the stage's code; editing one marks the stage "Code changed".
Use sparingly. File-level hashing is less precise: any change anywhere in the file triggers a re-run.
A @no_fingerprint stage whose own code reads your module through a package
it shares with an installed library (import company.local, then
company.local.value(), where company also has a directory in
site-packages) finds the module there in its worker. A helper module that the
stage calls is not read for this: a module that only the helper reads so is
missing there, and the stage fails with AttributeError: module 'company' has
no attribute 'local'. A helper outside the project root, which the worker
imports by name, works when it imports the module itself
(import company.local), as that import binds it there
(Imports a Stage Makes While It Runs).
@pivot.fingerprint_by_name¶
A helper function that cannot change a stage's output — process bookkeeping, file locks, log rotation — can carry this mark so Pivot records it by its module and qualified name only, never its body:
from pivot import fingerprint_by_name
@fingerprint_by_name
def process_start():
"""Read /proc for a running process."""
...
A stage that calls a marked helper does not rerun when the helper's body changes. It reruns once when the helper moves to another module, when the helper gets a new name, or when someone removes the mark.
The decorator accepts a module-level function, and a functools.wraps,
contextlib.contextmanager or class-based wrapper of one (an instance whose
__wrapped__ leads to the function, also one with __slots__ and no
__dict__). It refuses a class, a method, a lambda, a
nested function, a functools.partial, a helper that imports a user module in
its body, and a helper that uses importlib.import_module or __import__.
Import the module at the top of the helper's file instead.
The fingerprint walk never reads the body of a marked function. A decorator
above the mark is user code: Pivot adds a function decorator's own code to the
fingerprint and records the marked function inside it by name. This is also
true when functools.cache wraps that decorator. A library wrapper directly
above the mark (functools.cache, functools.lru_cache,
contextlib.contextmanager) keeps the record by name.
Pivot refuses a class-based decorator above the mark, however the stage
reaches the helper (a call, a class member, a partial argument, a default, a
pydantic default_factory) and however the decorator keeps __wrapped__ (in
its __dict__, a slot or a property). Pivot cannot fingerprint the code and
state of a class instance, and the mark records only the function below it.
core.unsafe_fingerprinting does not turn this refusal into a warning. To
clear it, put @fingerprint_by_name above the class-based decorator, so Pivot
records the whole helper by name, or replace the class with a function
decorator built with functools.wraps.
Without a mark below it, Pivot fingerprints each Python function on a
functools.wraps chain by its own code and reads, including module attributes
such as settings.FACTOR. The same admission applies when a C cache or a
partial holds the decorator.
A stage cannot carry @fingerprint_by_name: Pipeline refuses a stage with
the mark above @stage, below it, or below another decorator. Use
@no_fingerprint() to opt a stage out of AST fingerprinting.
Pivot does not walk code that only a marked helper calls. If that code imports a user module in its body, the run-time check counts the import, and the stage warns and reruns each run. Move that import to the top of its module to clear it.
Soundness is the user's choice: if a marked helper can change a stage's output, Pivot does not see the change.
Performance¶
Pivot fingerprints a stage the first time it needs the stage's fingerprint,
and keeps it while that pipeline stays loaded, in the pivot process, never
in a worker: pivot repro when the stage is ready to run, pivot status for
each stage it reports, and a watch for every stage before its first run and
again after each reload. It fingerprints one stage at a time, except in an
engine that serves RPC (--tui, --serve), where a client's explain or
commit request can fingerprint while a run fingerprints its next stage.
Results are cached at two levels:
- In-memory —
WeakKeyDictionarycache avoids re-parsing the same function within a single process - Persistent — AST hashes and full manifests are cached in StateDB, keyed by each source file's path and the digest of its content. If the source file's content hasn't changed, the cached hash is reused without parsing; an edit that keeps the file's mtime, size and inode is still seen
The dist: keys are not cached in StateDB: Pivot reads the installed files of
each library installed from git or a local path once per process, when a stage
first reaches it. When no library on the workers' sys.path is installed that
way, and none has a direct_url.json Pivot cannot classify, Pivot does not look
up where a stage's library modules come from at all.
When a manifest is rebuilt, tracked globals and closure cells are read from their live bindings again, not from the values an earlier walk captured. A deleted binding is recorded as absent and contributes no value entry, rather than being refused as an unsupported captured object.
For a project with 125 stages, fingerprinting typically completes in under 100ms on subsequent runs.
Python Version Dependency¶
AST fingerprinting means the Abstract Syntax Tree — not bytecode — is what gets hashed. AST structure can vary between Python versions (e.g., 3.12 vs 3.13 may parse some constructs differently), so the same source code can produce different fingerprints under different Python versions. This can cause unnecessary stage re-runs when switching versions.
To avoid surprises:
- Pin your Python version in your project (e.g.,
.python-version) - Use uv to manage your Python environment consistently
- All team members and CI should use the same Python version
Relationship to Other Concepts¶
The fingerprint manifest is one of three inputs to the caching skip-detection algorithm, alongside parameters and dependency hashes. A stage skips only when all three match.