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.

Workflows and reproducibility

A workflow scope derives the key of each random draw from its seed and the structure of the calls, so entering a scope again with the same seed and the same calls reproduces its draws. replay_run replays one recorded call from its provenance. This page also documents the orchestration modes, and the settings config.prefect and config.sampling are on Settings.

Workflow scopes

Set a default once to continue a random stream across bare calls in a script or IPython session. Setting it again restarts the stream. Clear the default to restore independent anonymous scopes for bare calls.

from probpipe import Normal, sample, workflow_run

law = Normal("x", loc=0.0, scale=1.0)
workflow_run.set_default(seed=42)
first = sample(law)
second = sample(law)
with workflow_run(seed=7):
    separate = sample(law)
third = sample(law)
workflow_run.clear_default()
print("Default stream draws:", first, second, third)
print("Independent scope draw:", separate)

Open explicit workflow scopes and manage the current context's default scope.

workflow_run(seed=None)

Return a synchronous context manager for an explicit workflow scope.

Re-entering a seeded scope with the same stochastic structure reproduces its workflow-owned random events. An anonymous scope reads system entropy at its first random event. A nested scope extends its parent's structural positions and inherits its root unless it supplies a seed. An explicit scope entered between bare calls preserves the default stream's next position.

The scope fixes provenance mode for its whole block at entry. Draws supplied with explicit keys preserve the scope's random positions.

Parameters:

Name Type Description Default
seed int or None

Non-boolean unsigned 64-bit root seed. None creates an anonymous scope. The context manager validates the seed when entered.

None

Returns:

Type Description
context manager

A synchronous workflow execution scope.

Raises:

Type Description
TypeError

If seed is not an integer or is a boolean, or the scope opens during a JAX transformation that forbids workflow-owned randomness.

ValueError

If seed is outside [0, 2**64 - 1].

UnmanagedConcurrentWorkflowEntryError

If the active scope belongs to another process, thread, or asyncio task, or a copied scope has already closed.

ReplayCompatibilityError

If the scope opens inside replay_run.

RuntimeError

If the context manager is entered while already active, exits out of nesting order, or its block changes provenance mode.

workflow_run.set_default(*, seed=None)

Create or replace the current context's continuing default random scope.

Return None. Successive bare calls use the same keys as successive calls in one explicit scope with the same seed. Setting the default again restarts the stream. Invalid seeds leave the current default intact. A failed call keeps the random positions it consumed.

Explicit scopes entered between bare calls and replay_run preserve the default stream's next position. Draws supplied with explicit keys preserve its positions too. config.reset() leaves the default intact.

Each top-level call fixes its provenance mode at entry. Changing the mode between calls preserves the stream's root and positions.

The default belongs to its configuring process, thread, and asyncio task. In an IPython notebook or terminal session, cells continue the configured stream, including cells with top-level await. Changes made in child tasks stay local to those tasks. A new thread without a copied context starts with no default. Using an inherited default from another owner raises UnmanagedConcurrentWorkflowEntryError. Set or clear the default, or open an explicit scope, in the new context. ProbPipe evaluation points carry their calling workflow's assigned random events.

Parameters:

Name Type Description Default
seed int or None

Non-boolean unsigned 64-bit root seed. None creates a continuing anonymous stream that reads system entropy at its first random event.

None

Raises:

Type Description
TypeError

If seed is not an integer or is a boolean.

ValueError

If seed is outside [0, 2**64 - 1].

RuntimeError

During a Function call, a workflow_run or replay_run block, a check of whether JAX can trace a Function, or a caller-owned JAX transformation. Set the default before entering these contexts.

workflow_run.clear_default()

Remove the current context's default scope and return None.

Subsequent bare calls each open their own anonymous scope. Clearing an absent default is a no-op. Clearing an inherited default affects the current context. In an IPython cell, clearing also removes the default for later cells.

Raises:

Type Description
RuntimeError

During a Function call, a workflow_run or replay_run block, a check of whether JAX can trace a Function, or a caller-owned JAX transformation. Clear the default before entering these contexts.

UnmanagedConcurrentWorkflowEntryError

Bases: RuntimeError

An unmanaged thread or task attempted to enter a copied workflow context.

Run the work through a ProbPipe call, such as one that names an executor, to take part in the parent run, or start an independent workflow_run in the concurrent worker.

Async tasks and threads

An IPython cell's top-level await continues in that cell's execution task. asyncio.create_task, asyncio.run, and asyncio.to_thread can instead copy settings into another task or thread. Bare calls there cannot use an inherited default stream: they raise UnmanagedConcurrentWorkflowEntryError. Set a default inside the new task, clear its inherited default to use fresh anonymous scopes, or open an explicit scope inside the worker.

import asyncio
from probpipe import Normal, sample, workflow_run

law = Normal("x", loc=0.0, scale=1.0)

def worker():
    with workflow_run(seed=7):
        return sample(law)

async def main():
    workflow_run.set_default(seed=42)
    try:
        first = sample(law)
        separate = await asyncio.to_thread(worker)
        second = sample(law)
        print("Task's default stream draws:", first, second)
        print("Worker's independent draw:", separate)
    finally:
        workflow_run.clear_default()

asyncio.run(main())  # In a notebook, use await main() instead.

Replay

replay_run(provenance)

Replay one recorded workflow-owned stochastic invocation.

Parameters:

Name Type Description Default
provenance Provenance

Provenance from a successful workflow-owned stochastic result. The record must contain a compatible RNG recipe and replay anchor.

required

Returns:

Type Description
context manager

A synchronous scope in which exactly one top-level Function.__call__ <probpipe.Function.__call__> must run.

Raises:

Type Description
ReplayCompatibilityError

Raised by the returned context manager if the record, stochastic plan, execution capability, or observed events are incompatible with the replay attempt. Validation can fail when the scope is entered or while its Function call runs; an absent required call is reported when the scope exits.

ReplayUnsupportedCallableError

Raised by the returned context manager if the recorded or supplied callable lacks a strong replay anchor.

Notes

Replay restores ProbPipe's structural RNG root and validates the current call before deriving keys. It does not load user code or inputs from the provenance record. The caller must invoke the same supported Function definition with compatible arguments inside the scope.

The definition matches when the code, the signature, and the types of the declarations do. A new label for the function or its output, or new names for its outputs, change no value, so the function replays the call to the same draws under them (V.8). Replay validates the definition, the stochastic plan, and the events the call consumes, and not the values of its arguments, so an accepted replay of a call with other arguments of the same structure runs on the recorded draws.

Source code in probpipe/functions/_replay.py
def replay_run(provenance: Provenance) -> _ReplayRunScope:
    """Replay one recorded workflow-owned stochastic invocation.

    Parameters
    ----------
    provenance : Provenance
        Provenance from a successful workflow-owned stochastic result. The
        record must contain a compatible RNG recipe and replay anchor.

    Returns
    -------
    context manager
        A synchronous scope in which exactly one top-level
        :meth:`Function.__call__ <probpipe.Function.__call__>` must run.

    Raises
    ------
    ReplayCompatibilityError
        Raised by the returned context manager if the record, stochastic plan,
        execution capability, or observed events are incompatible with the
        replay attempt. Validation can fail when the scope is entered or while
        its Function call runs; an absent required call is reported when the
        scope exits.
    ReplayUnsupportedCallableError
        Raised by the returned context manager if the recorded or supplied
        callable lacks a strong replay anchor.

    Notes
    -----
    Replay restores ProbPipe's structural RNG root and validates the current
    call before deriving keys. It does not load user code or inputs from the
    provenance record. The caller must invoke the same supported Function
    definition with compatible arguments inside the scope.

    The definition matches when the code, the signature, and the types of the
    declarations do. A new label for the function or its output, or new names
    for its outputs, change no value, so the function replays the
    call to the same draws under them (V.8). Replay validates the
    definition, the stochastic plan, and the events the call consumes, and not
    the values of its arguments, so an accepted replay of a call with other
    arguments of the same structure runs on the recorded draws.
    """
    return _ReplayRunScope(provenance)

ReplayCompatibilityError

Bases: RuntimeError

Recorded workflow controls are incompatible with a replay attempt.

ReplayUnsupportedCallableError

Bases: TypeError

A callable lacks the strong definition anchor required for replay.

Orchestration

config.prefect.workflow_kind takes one of these modes, as Settings states.

WorkflowKind

Bases: Enum

Orchestration mode for Function instances.

Members

DEFAULT Inherit from global config; the shipped global default is OFF unless overridden via PROBPIPE_WORKFLOW_KIND or explicit assignment to config.prefect.workflow_kind. At the per-instance level, DEFAULT means "inherit from global config". OFF No Prefect orchestration. Plain Python execution. TASK Wrap execution in a Prefect task (via task.map()). Raises ImportError if Prefect is not installed. FLOW Wrap execution in a Prefect flow. Raises ImportError if Prefect is not installed.