Skip to content

AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.

Labels and provenance

A label names a tracked term. A provenance record names the operation that produced a term and its parents. print(x.provenance) prints the lineage of x, one step per line from the loaded data or other roots down to x, as Provenance.__str__ states. The settings config.provenance and config.notation are on Settings. Replay from a provenance record is on Workflows and reproducibility.

Labels and annotations

TrackedTerm

Bases: Immutable

Identity mixin: a label and a write-once provenance.

A TrackedTerm object carries, alongside its mathematical content, the two pieces of identity every ProbPipe object needs: a human-readable label and an optional provenance describing how it was produced. Any such object is a tracked term — the kind of object ProbPipe operations consume and produce.

The label is set at construction, either supplied by the caller or derived from the inputs. Every transform preserves it; only with_label replaces it, returning a copy. rename on the named-tree types renames the fields within an object and preserves the object's label.

The label is read from the term's expression, a private immutable tree that states what the term is: a term constructed directly carries its label alone, and an operation's result carries the expression the operation builds from its operands', as 𝔼[(y, mu) ~ model] for the mean of a law model. with_label replaces the expression with the new label, so the label hides the derivation, which provenance still records.

Provenance is write-once: it is attached at most once via with_provenance, and a subsequent attempt raises. Transformations that build a new object attach fresh provenance to the result instead of rewriting the input's.

A tracked term is immutable (Immutable): assignment and deletion raise once its constructor has returned, and an operation that changes anything returns a new term. Construction assigns inside the window the metaclass opens, so a host's __init__ is written normally.

raw is the one access to the representation, and it is an abstract property: each kind defines it, as its section of the design states. A subclass on which raw resolves to anything but a property raises TypeError when the class is created.

Attributes:

Name Type Description
label str

Human-readable label of this object.

provenance Provenance or None

How this object was produced, or None if no provenance has been attached (an original user-constructed object, or provenance tracking disabled).

Notes

The mixin holds no per-instance storage of its own (__slots__ = ()); the state is stored in the _expression / _label / _label_collapse / _provenance attributes, which a host class declares in its __slots__ (when it uses slots) and initializes via _init_tracked. All writes go through object.__setattr__ so the mixin also works on immutable hosts that block normal attribute assignment.

The non-empty-label guarantee is enforced at construction by the mixin's metaclass (_TrackedTermMeta): finishing __init__ without a non-empty _label raises TypeError. Host classes therefore never need their own label check.

label property

Human-readable label of this object.

The label is rendered from the term's expression once, when the term is built, and shows at most the config.notation.max_depth levels set then. A later setting changes the labels of terms built afterwards, and the notation of a law, a kernel, or a function, which is rendered each time it is shown.

raw abstractmethod property

The term's representation, detached from the workflow.

Detachment removes the provenance, the annotations, and any reference to a container or a parent, and it keeps the spec and the label. A kind represented by an object from outside ProbPipe returns that object, such as a backing array or a wrapped callable, and a kind represented by a ProbPipe object returns that object detached.

provenance property

Provenance describing how this object was produced, or None.

A raw form, such as the standalone law a law's raw returns, has none.

__init_subclass__(**kwargs)

Refuse a subclass on which raw is anything but a property.

Parameters:

Name Type Description Default
**kwargs Any

The class keywords, passed on to the next class in the MRO.

{}

Raises:

Type Description
TypeError

If raw on the class is anything but a property.

Source code in probpipe/core/tracked.py
def __init_subclass__(cls, **kwargs: Any) -> None:
    """Refuse a subclass on which ``raw`` is anything but a property.

    Parameters
    ----------
    **kwargs : Any
        The class keywords, passed on to the next class in the MRO.

    Raises
    ------
    TypeError
        If ``raw`` on the class is anything but a property.
    """
    super().__init_subclass__(**kwargs)
    _check_raw_is_a_property(cls)

with_label(label)

Return a copy of this object under a new label.

The copy is shallow: it shares its data with the original but has label set to label. The copy's provenance records the relabeling, with the original as parent, so the lineage chain is preserved. On an Annotated host the annotations container is its own (its entries are shared), so annotations written after the relabeling appear on one object and not on the other — _shallow_copy does that, from the host's own _decoupled_state declaration.

This relabels the object itself. To rename the named fields inside a structured object, use rename on the named-tree types.

Parameters:

Name Type Description Default
label str

The new label. Must be a non-empty string.

required

Returns:

Type Description
Self

A shallow copy with the new label; the original is unchanged.

Raises:

Type Description
TypeError

If label is not a non-empty string.

Source code in probpipe/core/tracked.py
def with_label(self, label: str) -> Self:
    """Return a copy of this object under a new label.

    The copy is shallow: it shares its data with the original but has
    ``label`` set to *label*. The copy's :attr:`provenance`
    records the relabeling, with the original as parent, so the lineage
    chain is preserved. On an ``Annotated`` host the annotations
    *container* is its own (its entries are shared), so annotations
    written after the relabeling appear on one object and not on the
    other — :meth:`_shallow_copy` does that, from the host's own
    ``_decoupled_state`` declaration.

    This relabels the object *itself*. To rename the named fields inside a
    structured object, use ``rename`` on the named-tree types.

    Parameters
    ----------
    label : str
        The new label. Must be a non-empty string.

    Returns
    -------
    Self
        A shallow copy with the new label; the original is unchanged.

    Raises
    ------
    TypeError
        If *label* is not a non-empty string.
    """
    clone = self._with_label(label)
    clone.with_provenance(
        Provenance.create(
            "with_label",
            parents=[self],
            metadata={"old_label": self._label, "new_label": label},
        )
    )
    return clone

with_provenance(provenance)

Attach provenance to this object (write-once) and return it.

Passing None (e.g. the result of Provenance.create when provenance tracking is off) is a no-op, so call sites can pass the result of Provenance.create(...) without a guard.

Parameters:

Name Type Description Default
provenance Provenance or None

The provenance to attach, or None for a no-op.

required

Returns:

Type Description
Self

This object (not a copy), for call chaining.

Raises:

Type Description
RuntimeError

If provenance is already set (provenance is write-once), or if this object is a raw form, which every reader of raw shares and so carries no provenance.

Source code in probpipe/core/tracked.py
def with_provenance(self, provenance: Provenance | None) -> Self:
    """Attach provenance to this object (write-once) and return it.

    Passing ``None`` (e.g. the result of :meth:`Provenance.create` when
    provenance tracking is off) is a no-op, so call sites can pass the
    result of ``Provenance.create(...)`` without a guard.

    Parameters
    ----------
    provenance : Provenance or None
        The provenance to attach, or ``None`` for a no-op.

    Returns
    -------
    Self
        This object (not a copy), for call chaining.

    Raises
    ------
    RuntimeError
        If provenance is already set (provenance is write-once), or if this
        object is a raw form, which every reader of :attr:`raw` shares and so
        carries no provenance.
    """
    if provenance is None:
        return self
    current = getattr(self, "_provenance", None)
    if current is _RAW_FORM:
        raise RuntimeError(
            f"Cannot attach provenance to {self.label!r}: it is the raw form of a term, "
            "which carries none. Use with_label for a copy that can carry it."
        )
    if current is not None:
        raise RuntimeError(
            f"provenance of {self._repr_summary()} is already set; it can be set only once"
        )
    object.__setattr__(self, "_provenance", provenance)
    return self

__getstate__()

Return this object's state, with a raw form's provenance mark cleared.

A copy or an unpickled object is not the raw form every reader shares, so it is a term of its own that can take provenance.

Returns:

Type Description
tuple of (dict or None, dict or None)

The instance dictionary and the assigned slots, as Immutable.__getstate__ returns them.

Source code in probpipe/core/tracked.py
def __getstate__(self) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
    """Return this object's state, with a raw form's provenance mark cleared.

    A copy or an unpickled object is not the raw form every reader shares,
    so it is a term of its own that can take provenance.

    Returns
    -------
    tuple of (dict or None, dict or None)
        The instance dictionary and the assigned slots, as
        :meth:`Immutable.__getstate__` returns them.
    """
    instance_dict, slots = super().__getstate__()
    if instance_dict is not None and instance_dict.get("_provenance") is _RAW_FORM:
        instance_dict = {**instance_dict, "_provenance": None}
    if slots is not None and slots.get("_provenance") is _RAW_FORM:
        slots = {**slots, "_provenance": None}
    return (instance_dict, slots)

Annotated

Metadata mixin: free-form annotations.

An Annotated object can carry auxiliary information beyond its mathematical content — diagnostic summaries, validation results, backend reports, or any other metadata supplied by the user or an algorithm. The store is a free-form string-keyed mapping (any Mapping[str, Any], including an xarray.DataTree), or None when nothing has been attached.

Attributes:

Name Type Description
annotations Mapping[str, Any] or None

The attached annotations, or None if there are none.

Notes

Annotations are the one documented exception to object immutability: the _annotations store is designed to be written after construction by inference backends, validators, and diagnostic operations, and mutated in place. Treat the channel as append-only — a writer should add its results under its own key and never overwrite mathematical state or another writer's entries.

Like TrackedTerm, the mixin holds no storage of its own (__slots__ = ()); the state lives in the _annotations attribute, which a slotted host class declares in its __slots__.

annotations property

Annotations attached to this object, or None.

A free-form string-keyed mapping of auxiliary information. The value may be any Mapping[str, Any] — in particular, an xarray.DataTree (the layout inference backends and the diagnostics subsystem use) is a valid value.

probpipe.core.tracked.auto_label(label, default)

Resolve an optional label against its construction-time default.

Parameters:

Name Type Description Default
label str or None

The caller-supplied label, or None to use default.

required
default str

The label to use when none was supplied.

required

Returns:

Type Description
str

The supplied label or its default.

Source code in probpipe/core/tracked.py
def auto_label(label: str | None, default: str) -> str:
    """Resolve an optional label against its construction-time default.

    Parameters
    ----------
    label : str or None
        The caller-supplied label, or ``None`` to use *default*.
    default : str
        The label to use when none was supplied.

    Returns
    -------
    str
        The supplied label or its default.
    """
    return default if label is None else label

Provenance records

Provenance(operation, parents=(), metadata=dict(), inputs=dict(), controls=dict(), diagnostics=dict()) dataclass

How a tracked term was produced: an operation plus call descriptors.

Attached write-once to a tracked term via with_provenance. print(term.provenance) prints the term's lineage, one step per line from its roots, in the format that __str__ states. The repr is the short form, which names the operation and the labels of the parents.

Attributes:

Name Type Description
operation str

The operation that produced the object (e.g. "broadcast", "condition_on", "with_label", or "&" for a merge).

parents tuple of ParentInfo

Descriptors of tracked terms the operation consumed. Only these descriptors participate in ancestry traversal.

metadata dict

Optional scalar/string metadata about the operation (e.g. the old and new labels of a relabeling). Serialized alongside the operation by to_dict. The record of a managed call whose route returned a term with a record of its own, as an inference method's posterior under condition_on is, lists the positions of those terms among parents under "route_results".

inputs mapping of str to ParentInfo

Descriptors of resolved plain inputs, keyed by stable parameter label. These descriptors preserve call-defining values without turning them into lineage nodes.

controls mapping of str to JSON-native values

Exact replay/control data. Unlike metadata, values are never stringified.

diagnostics mapping of str to JSON-native values

Exact non-semantic execution observations and drift information.

__str__()

The lineage of the term this record describes, one step per line from its roots.

A step is an ancestor that records provenance. The steps run in the order of computation, so each step follows every step it consumed, and the last line is this record's own step. A line has three parts:

  1. the step's number, followed by a period, as 3.;
  2. the call, as condition_on(1, 2): the operation, without the prefix workflow. that a managed function call records, applied to its parents and then to the names of its plain inputs. A parent that is a step shows its number, and a parent that records no provenance shows its label, or its class name when it has no label. The first parent of a managed call is omitted when it describes a root Function or Operation under the callable's name. A step whose label differs from its call shows the label first, as posterior = condition_on(1, 2), and a label that is the call with literal arguments, as load_data('data.csv'), replaces the call. Inside a label, each parent's label outside string literals shows as the parent's reference. The last line shows the call alone, because a record does not store its term's label;
  3. how the step ran, from its metadata: route and method where it records them, and exact or approximate where it records exact.

A step that several later steps consume is listed once, and each of them refers to its number. The steps of a route fold into the call that ran it: a step that its consumer lists under "route_results" in its metadata, and that no other step consumes, is not a line of its own, and neither is a step whose consumers all fold into the same call. The call leaves the folded steps out of its parents, and its run details name the route and the method that ran, so condition_on(1, 2) is one line where its record also holds the inference target and the sampler's run. A step that a step outside the call also consumes stays a line, and the record keeps every step, so provenance_ancestors and to_dict list the folded steps too. A view, the result of __getitem__, is not a step of its own: each step that consumes it refers to its container indexed by the view's path or position, as 4['beta'].

A merge, which records the operation &, prints by three rules:

  1. it shows its two parents joined by &, as 1 & 4, and never its label, since a merge's label joins its operands' labels;
  2. an operand that records no provenance shows its label grouped as a derived label groups an operand, so a label of several words is bracketed, as [my model] & 2;
  3. a merge whose one consumer is a merge is not a line of its own: the consumer shows it in its place, in parentheses where it is the right operand, so a & b & c is one line, and so is lik & (a & b).

A hexadecimal digest of 32 or more digits shows its first 8, followed by …. The run details of the lines start in one column, after the widest call of at most 48 characters. The steps are the ancestors that provenance_ancestors returns which record provenance, less the folded steps and the merges shown in their consumer's place, and the order and the numbers depend only on the recorded parents, in their recorded order, and on "route_results".

Returns:

Type Description
str

The lines, joined by newlines, with no trailing newline.

Examples:

A model conditioned on the prepared rows of a data file, and the mean of its posterior's beta, print as::

1. load_data('data.csv', '72327ac7…')  route body, exact
2. prepare_inputs(1)                   route body, exact
3. model = build_model(2)              route body, exact
4. posterior = condition_on(3, 2)      method nuts, approximate
5. mean(4['beta'])                     route closed_form, exact

A posterior predictive merged from a renamed likelihood and a posterior conditioned on a model built with &, and a quantile of its y_pred, print as::

1. likelihood = rename(likelihood)
2. likelihood & (prior_K & prior_r)
3. likelihood·prior_K·prior_r = condition_on(2, given)  method nuts, approximate
4. posterior = with_label(3)
5. 1 & 4
6. quantile(5['y_pred'], q, given)                   route monte_carlo, approximate
Source code in probpipe/core/provenance.py
def __str__(self) -> str:
    """The lineage of the term this record describes, one step per line from its roots.

    A step is an ancestor that records provenance. The steps run in the
    order of computation, so each step follows every step it consumed, and
    the last line is this record's own step. A line has three parts:

    1. the step's number, followed by a period, as ``3.``;
    2. the call, as ``condition_on(1, 2)``: the operation, without the
       prefix ``workflow.`` that a managed function call records, applied
       to its parents and then to the names of its plain inputs. A parent
       that is a step shows its number, and a parent that records no
       provenance shows its label, or its class name when it has no label.
       The first parent of a managed call is omitted when it describes a
       root ``Function`` or ``Operation`` under the callable's name.
       A step whose label differs from its call shows the label first,
       as ``posterior = condition_on(1, 2)``, and a label
       that is the call with literal arguments, as
       ``load_data('data.csv')``, replaces the call. Inside a label, each
       parent's label outside string literals shows as the parent's
       reference. The last line shows the call alone, because a record
       does not store its term's label;
    3. how the step ran, from its metadata: ``route`` and ``method`` where
       it records them, and ``exact`` or ``approximate`` where it records
       ``exact``.

    A step that several later steps consume is listed once, and each of
    them refers to its number. The steps of a route fold into the call
    that ran it: a step that its consumer lists under ``"route_results"``
    in its metadata, and that no other step consumes, is not a line of
    its own, and neither is a step whose consumers all fold into the same
    call. The call leaves the folded steps out of its parents, and its run
    details name the route and the method that ran, so
    ``condition_on(1, 2)`` is one line where its record also holds the
    inference target and the sampler's run. A step that a step outside
    the call also consumes stays a line, and the record keeps every step,
    so :func:`provenance_ancestors` and :meth:`to_dict` list the folded
    steps too. A view, the result of ``__getitem__``, is
    not a step of its own: each step that consumes it refers to its
    container indexed by the view's path or position, as ``4['beta']``.

    A merge, which records the operation ``&``, prints by three rules:

    1. it shows its two parents joined by ``&``, as ``1 & 4``, and never
       its label, since a merge's label joins its operands' labels;
    2. an operand that records no provenance shows its label grouped as a
       derived label groups an operand, so a label of several words is
       bracketed, as ``[my model] & 2``;
    3. a merge whose one consumer is a merge is not a line of its own: the
       consumer shows it in its place, in parentheses where it is the right
       operand, so ``a & b & c`` is one line, and so is ``lik & (a & b)``.

    A hexadecimal digest of 32 or more digits shows its first 8, followed
    by ``…``. The run details of the lines start in one column, after the
    widest call of at most 48 characters. The steps are the ancestors that
    :func:`provenance_ancestors` returns which record provenance, less the
    folded steps and the merges shown in their consumer's place, and the
    order and the numbers depend only on the recorded parents, in their
    recorded order, and on ``"route_results"``.

    Returns
    -------
    str
        The lines, joined by newlines, with no trailing newline.

    Examples
    --------
    A model conditioned on the prepared rows of a data file, and the mean
    of its posterior's ``beta``, print as::

        1. load_data('data.csv', '72327ac7…')  route body, exact
        2. prepare_inputs(1)                   route body, exact
        3. model = build_model(2)              route body, exact
        4. posterior = condition_on(3, 2)      method nuts, approximate
        5. mean(4['beta'])                     route closed_form, exact

    A posterior predictive merged from a renamed likelihood and a
    posterior conditioned on a model built with ``&``, and a quantile of
    its ``y_pred``, print as::

        1. likelihood = rename(likelihood)
        2. likelihood & (prior_K & prior_r)
        3. likelihood·prior_K·prior_r = condition_on(2, given)  method nuts, approximate
        4. posterior = with_label(3)
        5. 1 & 4
        6. quantile(5['y_pred'], q, given)                   route monte_carlo, approximate
    """
    return _format_lineage(self)

to_dict(*, recurse=True)

Serialize to a JSON-compatible dict.

Parameters:

Name Type Description Default
recurse bool

If True, recursively serialize parent provenance chains via each parent's .provenance.

True

Returns:

Type Description
dict of str to Any

One entry per field, with each parent and each input as a dict of its descriptor, and each metadata value that is not JSON-native as its str.

Source code in probpipe/core/provenance.py
def to_dict(self, *, recurse: bool = True) -> dict[str, Any]:
    """Serialize to a JSON-compatible dict.

    Parameters
    ----------
    recurse : bool
        If True, recursively serialize parent provenance chains via
        each parent's ``.provenance``.

    Returns
    -------
    dict of str to Any
        One entry per field, with each parent and each input as a dict of its
        descriptor, and each metadata value that is not JSON-native as its
        ``str``.
    """

    def serialize_info(p: ParentInfo) -> dict[str, Any]:
        entry: dict[str, Any] = {
            "type": p.type_name,
            "label": p.label,
        }
        if p.fingerprint is not None:
            entry["fingerprint"] = p.fingerprint
        entry["fingerprint_is_weak"] = p.fingerprint_is_weak
        if recurse and p.provenance is not None:
            entry["provenance"] = p.provenance.to_dict(recurse=True)
        return entry

    parent_dicts = [serialize_info(p) for p in self.parents]
    input_dicts = {label: serialize_info(info) for label, info in self.inputs.items()}

    safe_metadata = {}
    for k, v in self.metadata.items():
        if isinstance(v, (str, int, float, bool, list, dict, type(None))):
            safe_metadata[k] = v
        else:
            safe_metadata[k] = str(v)

    return {
        "operation": self.operation,
        "parents": parent_dicts,
        "inputs": input_dicts,
        "metadata": safe_metadata,
        "controls": copy.deepcopy(dict(self.controls)),
        "diagnostics": copy.deepcopy(dict(self.diagnostics)),
    }

from_dict(d) classmethod

Reconstruct from a dict produced by to_dict.

Original parent and input objects are not available at deserialization time, so parents and inputs are empty. Their descriptors are preserved in metadata under "_parents_info" and "_inputs_info" for inspection.

Source code in probpipe/core/provenance.py
@classmethod
def from_dict(cls, d: dict[str, Any]) -> Provenance:
    """Reconstruct from a dict produced by :meth:`to_dict`.

    Original parent and input objects are not available at deserialization
    time, so ``parents`` and ``inputs`` are empty. Their descriptors are
    preserved in metadata under ``"_parents_info"`` and
    ``"_inputs_info"`` for inspection.
    """
    return cls(
        operation=d["operation"],
        parents=(),
        metadata={
            **d.get("metadata", {}),
            "_parents_info": d.get("parents", []),
            "_inputs_info": d.get("inputs", {}),
        },
        inputs={},
        controls=d.get("controls", {}),
        diagnostics=d.get("diagnostics", {}),
    )

of_view(container, source=None, *, metadata) classmethod

The provenance of a view of container, with source the term stored at the view.

Its parents are the container and the source term where one was supplied (II.4), each as an identity-tier descriptor, so the cost of reading a field or an element is independent of what the container holds. metadata states where the view is, such as a record's path or a batch's position. The active provenance mode applies as for create.

Source code in probpipe/core/provenance.py
@classmethod
def of_view(
    cls, container: Any, source: Any = None, *, metadata: dict[str, Any]
) -> Provenance | None:
    """The provenance of a view of *container*, with *source* the term stored at the view.

    Its parents are the container and the source term where one was
    supplied (II.4), each as an identity-tier descriptor, so the cost of
    reading a field or an element is independent of what the container
    holds. *metadata* states where the view is, such as a record's path or
    a batch's position. The active provenance mode applies as for
    :meth:`create`.
    """
    from ..functions import _context

    mode = _context._active_provenance_mode()
    if mode is ProvenanceMode.OFF or _context._workflow_side_effects_forbidden():
        return None
    from ._fingerprint import _identity_fingerprint

    keep = mode is ProvenanceMode.FULL
    parents = tuple(
        ParentInfo(
            type_name=type(parent).__name__,
            label=_term_label(parent),
            provenance=_term_provenance(parent),
            fingerprint=_identity_fingerprint(parent),
            parent=parent if keep else None,
            fingerprint_is_weak=True,
            identity=id(parent),
        )
        for parent in (container, source)
        if parent is not None
    )
    return cls(_VIEW_OPERATION, parents=parents, metadata=metadata)

create(operation, parents=(), metadata=None, inputs=None, controls=None, diagnostics=None) classmethod

Build provenance respecting the active workflow's provenance mode.

Call sites can pass the result directly to with_provenance() without an extra guard, since with_provenance(None) is a no-op.

Parameters:

Name Type Description Default
operation str

Provenance operation label (e.g. "broadcast").

required
parents tuple or list

Raw tracked parent objects, already ordered and deduplicated by the caller.

()
metadata dict

Optional mapping of scalar/string metadata.

None
inputs mapping of str to Any

Resolved plain inputs keyed by stable parameter label.

None
controls mapping of str to Any

Exact JSON-native replay and execution controls.

None
diagnostics mapping of str to Any

Exact JSON-native non-semantic execution observations.

None

Returns:

Type Description
Provenance or None

The node, with one descriptor per parent and per input; None when the mode is OFF or the call runs inside a side-effect-free probe or a JAX body.

Source code in probpipe/core/provenance.py
@classmethod
def create(
    cls,
    operation: str,
    parents: tuple | list = (),
    metadata: dict[str, Any] | None = None,
    inputs: Mapping[str, Any] | None = None,
    controls: Mapping[str, Any] | None = None,
    diagnostics: Mapping[str, Any] | None = None,
) -> Provenance | None:
    """Build provenance respecting the active workflow's provenance mode.

    Call sites can pass the result directly to ``with_provenance()`` without
    an extra guard, since ``with_provenance(None)`` is a no-op.

    Parameters
    ----------
    operation : str
        Provenance operation label (e.g. ``"broadcast"``).
    parents : tuple or list
        Raw tracked parent objects, already ordered and deduplicated by the
        caller.
    metadata : dict, optional
        Optional mapping of scalar/string metadata.
    inputs : mapping of str to Any, optional
        Resolved plain inputs keyed by stable parameter label.
    controls : mapping of str to Any, optional
        Exact JSON-native replay and execution controls.
    diagnostics : mapping of str to Any, optional
        Exact JSON-native non-semantic execution observations.

    Returns
    -------
    Provenance or None
        The node, with one descriptor per parent and per input; ``None`` when
        the mode is ``OFF`` or the call runs inside a side-effect-free probe or
        a JAX body.
    """
    from ..functions import _context

    mode = _context._active_provenance_mode()
    if mode is ProvenanceMode.OFF:
        return None

    if _context._workflow_side_effects_forbidden():
        return None
    keep = mode is ProvenanceMode.FULL

    from ._fingerprint import _fingerprint_with_strength

    def _make_parent(p: Any) -> ParentInfo:
        fp: str | None
        fingerprint_is_weak = False
        try:
            fp, fingerprint_is_weak = _fingerprint_with_strength(p)
        except Exception as exc:
            logger.warning(
                "fingerprint() failed for %s %r: %s",
                type(p).__name__,
                _term_label(p),
                exc,
            )
            fp = None
        return ParentInfo(
            type_name=type(p).__name__,
            label=_term_label(p),
            provenance=_term_provenance(p),
            fingerprint=fp,
            parent=p if keep else None,
            fingerprint_is_weak=fingerprint_is_weak,
            identity=id(p),
        )

    refs = tuple(_make_parent(p) for p in parents)
    input_refs = {label: _make_parent(value) for label, value in (inputs or {}).items()}
    return cls(
        operation,
        parents=refs,
        metadata=metadata or {},
        inputs=input_refs,
        controls={} if controls is None else controls,
        diagnostics={} if diagnostics is None else diagnostics,
    )

ParentInfo(type_name, label, provenance=None, fingerprint=None, parent=None, fingerprint_is_weak=False, identity=None) dataclass

Descriptor for a provenance parent, used in all non-OFF modes.

Always carries enough information to describe lineage and traverse the ancestry DAG. In FULL mode it additionally retains a live reference to the parent object via parent.

Attributes:

Name Type Description
type_name str

Class name of the tracked parent or plain input (e.g. "EmpiricalDistribution" or "ArrayImpl").

label str or None

Label of the tracked parent. None for plain inputs, a class such as the target of convert among them, and unlabeled tracked terms.

provenance Provenance or None

The parent's own provenance node, and None for a plain input or a tracked term that records none. Kept in both LIGHTWEIGHT and FULL modes so the ancestry DAG remains traversable without holding the parent's data arrays alive. Excluded from hashing (Provenance holds an unhashable metadata dict) but included in equality so that two descriptors for the same ancestor compare equal.

fingerprint str or None

Best-effort 16-character digest populated by Provenance.create. None only when fingerprinting raises an unexpected error. Consult fingerprint_is_weak before treating it as part of a portable cache key. Excluded from equality and hashing: descriptor identity is structural (type_name / label / provenance), so a digest must not perturb ancestor-set dedup.

parent Any or None

The live tracked parent or plain input object. Set in FULL mode; None in LIGHTWEIGHT so the object's data can be garbage-collected. Excluded from equality and hashing.

fingerprint_is_weak bool

Whether the digest contains a process-local object identity. Weak fingerprints remain useful for distinguishing live objects in one process but must not be reused as portable content keys. Excluded from equality and hashing.

identity int or None

The id of the parent object when the descriptor was made, which tells apart two parents that share a type and a label, as two laws under a family's default label do. Excluded from equality and hashing.

provenance_ancestors(node)

Return all ancestor nodes reachable via provenance chains.

Traverses node.provenance.parents recursively (breadth-first) and returns a flat list of unique ancestors, ordered by discovery. The input node is not included in the result.

Returns ParentInfo descriptors. In FULL mode the live parent object is accessible via ancestor.parent; in LIGHTWEIGHT ancestor.parent is None.

Source code in probpipe/core/provenance.py
def provenance_ancestors(node: ProvenanceNode) -> list[Any]:
    """Return all ancestor nodes reachable via provenance chains.

    Traverses ``node.provenance.parents`` recursively (breadth-first) and
    returns a flat list of unique ancestors, ordered by discovery.
    The input *node* is **not** included in the result.

    Returns :class:`ParentInfo` descriptors.  In FULL mode the live parent
    object is accessible via ``ancestor.parent``; in LIGHTWEIGHT
    ``ancestor.parent`` is ``None``.
    """
    visited: set = {id(node)}
    ancestors: list = []
    queue: deque[Any] = deque()

    def _enqueue(p: Any) -> None:
        key = _parent_key(p)
        if key not in visited:
            visited.add(key)
            queue.append(p)
            ancestors.append(p)

    if node.provenance is not None:
        for p in node.provenance.parents:
            _enqueue(p)

    while queue:
        current = queue.popleft()
        current_provenance = current.provenance
        if current_provenance is not None:
            for p in current_provenance.parents:
                _enqueue(p)

    return ancestors

provenance_dag(node)

Build a Graphviz Digraph of the provenance chain rooted at node.

Each node is labelled with its type and label. Edges point from parent to child and are labelled with the operation that produced the child. Works in all modes that attach provenance (FULL and LIGHTWEIGHT).

Requires the graphviz package. Returns a graphviz.Digraph instance that can be rendered or displayed in a notebook.

Source code in probpipe/core/provenance.py
def provenance_dag(node: ProvenanceNode):
    """Build a Graphviz ``Digraph`` of the provenance chain rooted at *node*.

    Each node is labelled with its type and label. Edges point from parent
    to child and are labelled with the operation that produced the child.
    Works in all modes that attach provenance (FULL and LIGHTWEIGHT).

    Requires the ``graphviz`` package.  Returns a ``graphviz.Digraph``
    instance that can be rendered or displayed in a notebook.
    """
    try:
        from graphviz import Digraph
    except ImportError as e:
        raise ImportError(
            "graphviz is required for provenance_dag(). Install it with: pip install graphviz"
        ) from e

    dot = Digraph(comment="Provenance DAG")
    dot.attr(rankdir="BT")  # bottom-to-top: parents below children

    visited: set = set()

    def _label(type_name: str, label: str) -> str:
        return f"{type_name}\n'{label}'" if label else type_name

    def _stable_nid(p: Any) -> str:
        """Graphviz node ID that is the same for all ParentInfo of the same ancestor."""
        key = _parent_key(p)
        if isinstance(key, tuple):
            return ":".join(str(x) for x in key)
        return str(key)

    def _visit_parent(p: Any, child_nid: str, operation: str) -> None:
        """Render a parent (ParentInfo or live object) and recurse."""
        key = _parent_key(p)
        nid = _stable_nid(p)
        if key not in visited:
            visited.add(key)
            dot.node(nid, _label(p.type_name, p.label))
            if p.provenance is not None:
                for pp in p.provenance.parents:
                    _visit_parent(pp, nid, p.provenance.operation)
        dot.edge(nid, child_nid, label=operation)

    def _visit_node(value: ProvenanceNode) -> str:
        nid = str(id(value))
        if id(value) in visited:
            return nid
        visited.add(id(value))
        dot.node(nid, _label(type(value).__name__, value.label or ""))
        if value.provenance is not None:
            for p in value.provenance.parents:
                _visit_parent(p, nid, value.provenance.operation)
        return nid

    _visit_node(node)
    return dot

Provenance modes

config.provenance.mode selects the data retained by new provenance records. Workflow scopes determine when each call's mode is fixed.

ProvenanceMode

Bases: Enum

Choose the data retained by new provenance records.

A top-level call fixes its mode when it starts, and the outermost workflow_run fixes the mode for its block when entered. Changing the mode while such a call or block is open raises RuntimeError. Existing records retain their original contents.

Members

FULL Store parent and input descriptors and retain references to their objects. LIGHTWEIGHT Store ParentInfo descriptors with links to existing provenance. The descriptors contain the object's type and label and an optional fingerprint with its strength classification. This is the default mode. OFF Create no provenance records.