Skip to content

API reference

Everything below is importable from pylinxi directly (Postgres and OpenTelemetry from pylinxi.postgres and pylinxi.otel).

Flows and steps

pylinxi.flow.flow

flow(fn: Optional[Callable] = None, *, journal: Optional[Journal] = None, on_event: Union[None, Observer, List[Observer]] = None, strict: bool = True, drain_timeout: float = 10.0, name: Optional[str] = None) -> Any

Decorate an async def f(ctx, ...) to make it a durable flow.

pylinxi.flow.step

step(fn: Optional[Callable] = None, *, policy: Optional[Policy] = None, name: Optional[str] = None, sensitive: bool = False) -> Any

Mark a function as a durable, self-healing step.

Works on sync/async functions and sync/async generators (streamed steps). Inside a running flow, calling it is checkpointed automatically. Called from inside another step, or outside any flow, it is a plain call (the outer step's result is the checkpoint). sensitive=True keeps the result out of the journal; it is recomputed on resume.

pylinxi.flow.idempotency_key

idempotency_key() -> str

Stable key for the step currently executing (":").

Identical across retries and resumes, so pass it to external APIs (payments, email, ticketing) to make side effects exactly-once from their side.

pylinxi.flow.Flow

__init__

__init__(fn: Callable[..., Awaitable[Any]], journal: Optional[Journal] = None, on_event: Union[None, Observer, List[Observer]] = None, strict: bool = True, drain_timeout: float = 10.0, name: Optional[str] = None)

name -- the flow's identity in the journal (default: the function's name). Runs belong to one flow; set a stable name if you might rename the function. strict -- stop with ReplayDivergence before running a new step where the journal recorded a different one (default). False only reports a divergence event. drain_timeout -- when one branch suspends, how long (seconds) other branches may keep running to their own suspension point or end.

run async

run(*args: Any, run_id: Optional[str] = None, state: Optional[dict] = None, signals: Optional[Mapping[str, Any]] = None, on_event: Optional[Observer] = None, _must_exist: bool = False, **kwargs: Any) -> RunResult

Start a run, or continue it if run_id already has history.

For an existing run, inputs are taken from the journal: passing different args/kwargs/state raises RunExists, and a run id that belongs to another flow raises FlowMismatch. Use resume() to continue a run that must already exist.

resume async

resume(run_id: str, signals: Optional[Mapping[str, Any]] = None, on_event: Optional[Observer] = None) -> RunResult

Continue an existing run. Raises UnknownRun if run_id doesn't exist.

signal async

signal(run_id: str, name: str, value: Any = True, resume: bool = True) -> Optional[RunResult]

Deliver a signal durably. Safe while the run is executing elsewhere: the signal is journaled first, then (resume=True) the run is resumed if nobody else is executing it. Returns the resume result, or None if it was busy.

stream async

stream(*args: Any, **kwargs: Any) -> AsyncIterator[dict]

Run (or resume, with run_id=) and yield events live -- including "chunk" events from streaming steps. The last item is {"event": "result", "result": RunResult}.

async for ev in agent.stream("hi", run_id="chat-1"):
    if ev["event"] == "chunk": await websocket.send(ev["chunk"])

pylinxi.flow.Context

Handed to every flow as its first argument.

replaying property

replaying: bool

True while recorded history remains that the flow has not reached yet.

step

step(fn: Callable, *args: Any, policy: Optional[Policy] = None, name: Optional[str] = None, sensitive: bool = False, **kwargs: Any) -> Awaitable[Any]

Run any callable as a checkpointed step. The key is allocated now (synchronously), so steps launched together with asyncio.gather replay deterministically. (Use @step if your function has parameters named name/policy/sensitive.)

now async

now() -> float

Deterministic wall clock: recorded on first run, identical on replay.

uuid async

uuid() -> str

Deterministic random id: recorded on first run, identical on replay.

sleep async

sleep(seconds: float, inline_max: float = 1.0) -> None

Durable sleep. Short waits (<= inline_max s) sleep in-process; longer ones suspend the run and free the worker. A Worker (or journal.pending_timers()) resumes it once due; resuming early simply suspends again.

wait_for async

wait_for(signal: str, timeout: Optional[float] = None, default: Any = None) -> Any

Wait for signal, delivered via flow.run/resume(..., signals={signal: value}) or journal.send_signal(run_id, signal, value).

Signals are journaled when delivered, so one sent before the flow reaches this point is not lost; repeated deliveries queue up in order. With timeout (seconds), returns default if nothing arrives by then.

patched

patched(change_id: str) -> bool

Safely change flow code while runs are in flight.

Returns True for runs that reach this point on the new code, False for runs that were already past it (they keep their old behaviour on replay):

if ctx.patched("v2-extra-check"):
    await new_check()

continue_as_new

continue_as_new(*args: Any, **kwargs: Any) -> None

End this run and continue in a fresh journal with new inputs and the current state. Use in long-lived loops (chat sessions, monitors) to keep replay short. Inputs and state are journaled in clear for the next generation, so they may not contain secret-looking keys (checked here, at the call).

route async

route(label: Any, routes: Mapping[Any, Callable], *args: Any, default: Optional[Callable] = None, **kwargs: Any) -> Any

Dispatch to a step by label -- a one-liner replacement for conditional edges.

map async

map(fn: Callable, items: Iterable[Any], concurrency: int = 8) -> List[Any]

Fan out fn over items in parallel (bounded), each item its own checkpoint.

pylinxi.flow.RunResult dataclass

Outcome of run()/resume().

state -- the flow's live state when this call executed the flow; when the run had already completed earlier, it is rebuilt from the journal instead (secret keys redacted) and from_journal is True.

Policies

pylinxi.policy.Policy dataclass

How a step heals itself.

retry -- attempts/backoff for transient errors (see Retry.on) timeout -- per-attempt timeout in seconds. Async steps are cancelled; a sync step's thread can't be killed, so before the next attempt pylinxi waits up to timeout more for it, uses its result if it finished, and otherwise stops retrying (AttemptStillRunning) rather than run the step twice at once. validate -- fn(result) -> bool; False triggers ValidationError (retried) repair -- fn(error, args, kwargs, attempt) -> (args, kwargs) | None; lets you mutate inputs between attempts (e.g. feed the parse error back into an LLM prompt). May be async. fallback -- fn(*args, **kwargs) used when attempts are exhausted, an error is not retryable, or the breaker is open. May be async. breaker -- CircuitBreaker instance (share one per dependency) aggregate -- for generator (streaming) steps: turns the chunk list into the journaled result. Default: "".join for str chunks, else the list. thread -- run plain sync steps in a worker thread (default True) executor -- thread pool for sync steps (default: a dedicated pylinxi pool, so slow steps never starve asyncio's default executor)

pylinxi.policy.Retry dataclass

attempts/backoff for transient errors. Errors that aren't instances of on are not retried, but still go to the fallback and the circuit breaker.

pylinxi.policy.CircuitBreaker

Shared across runs and concurrent calls: after threshold consecutive failures, short-circuit calls for reset_after seconds, then let exactly one trial call through (half-open). Failures reported while already open (from calls that started earlier) don't extend the outage. A trial that is cancelled gives its slot back, so the breaker can never get stuck half-open.

acquire

acquire() -> Optional[str]

'closed' or 'trial' if a call may go ahead, None if the breaker is open.

release_trial

release_trial() -> None

Give back a half-open trial slot without counting success or failure.

Journals

pylinxi.journal.Journal

Base journal. Backends implement _rows, _append_locked, runs and _delete.

__init__

__init__(secret: Union[None, bytes, Dict[str, bytes]] = None, codec: Codec = default_codec, redact_pattern: Optional[Pattern] = DEFAULT_REDACT, active_kid: Optional[str] = None, verify_on_load: bool = True, require_signed: Optional[bool] = None, error_redactor: Optional[Callable[[str], str]] = None)

secret: one HMAC key, or {key_id: key} for rotation. New entries are signed with active_kid (default: the last key in the dict); old entries keep verifying as long as their key id is still present.

verify_on_load -- check every run's chain and signatures each time it's loaded (default). Forged, copied or edited rows raise JournalCorrupt. require_signed -- refuse unsigned entries on load; defaults to True whenever keys are configured. Set False while migrating a journal that was written before you added keys. error_redactor -- optional fn(str) -> str applied to error text before it is journaled (e.g. to mask card numbers or emails).

prepared_delta

prepared_delta(encoded: Dict[str, Any]) -> Dict[str, Any]

A delta built from already-encoded values (state keys -> Codec.encode trees): redacted and decoded in one pass, into fresh objects that share nothing with the caller's live state. Flows build deltas this way on the event loop thread, so a write on a worker thread never touches objects flow code may still change.

load

load(run_id: str) -> List[Entry]

All entries of a run, oldest first, after checking the chain (and, by default, every signature). Raises JournalCorrupt if anything doesn't check out.

last_row

last_row(run_id: str) -> Optional[Tuple[str, str]]

The run's newest stored (payload, sig) row, cheaply (not chain-verified).

head

head(run_id: str) -> Optional[str]

Signature of the newest entry: store it elsewhere as a truncation anchor.

verify

verify(run_id: str, require_signed: bool = False, anchor: Optional[str] = None) -> bool

Check the whole chain against the stored bytes. Never raises; False for a run that doesn't exist.

require_signed -- unkeyed (plain SHA-256) entries fail too; use when keys are configured so a run can't be rewritten as an unkeyed chain. anchor -- a sig previously returned by head(); fails if it's missing, which detects truncation of newer entries.

heads

heads(kinds: Optional[Sequence[str]] = None) -> List[Head]

The newest entry of every run (optionally only those of these kinds).

runs_where_last

runs_where_last(kind: str, key: Optional[str] = None) -> List[str]

Run ids whose most recent entry has this kind (and key, if given).

pending_timers

pending_timers(due_before: Optional[float] = None) -> List[Tuple[str, float]]

[(run_id, wake_at)] for runs currently suspended with a deadline (ctx.sleep, wait_for(timeout=)), soonest first. Pass due_before=time.time() for the ones ready to resume.

state_at

state_at(run_id: str, seq: Optional[int] = None) -> dict

Rebuild flow state as of entry seq (time travel) by folding deltas.

lock

lock(run_id: str) -> Iterator[None]

Exclusive ownership of a run while it executes; raises RunLocked otherwise. Covers other tasks/threads in this process, and other processes for file-backed stores (POSIX). PostgresJournal overrides this with database locks.

chain

chain(run_id: str) -> List[str]

Every generation of the continue-as-new chain run_id belongs to, root first.

send_signal

send_signal(run_id: str, name: str, value: Any = True) -> str

Durably deliver a signal without executing the run (safe while it runs).

The signal is appended to the run's inbox; a waiting ctx.wait_for(name) gets it on the next resume (a Worker resumes such runs automatically). Signals to a run that continued as new go to its newest generation. Returns that run id. Raises UnknownRun, or ValueError if the run already completed.

delete

delete(run_id: str, chain: bool = True) -> List[str]

Permanently remove a run -- by default with every generation of its continue-as-new chain -- for retention policies and erasure requests.

Takes each run's lock first, so it raises RunLocked (and deletes nothing) while any of them is executing. Lock files are removed too. Returns the deleted ids.

close

close() -> None

Release connections/handles. Safe to call more than once.

pylinxi.journal.MemoryJournal

Bases: Journal

pylinxi.journal.FileJournal

Bases: Journal

One JSONL file per run. Appends hold an exclusive file lock, repair a torn final line left by a crash, and fsync (optional). POSIX gives cross-process safety; on Windows locking is per-process only.

Any run id works: lowercase ids made of [a-z0-9_.-] are stored as <id>.jsonl; others get a readable prefix plus a hash (ticket-a1~3f2c….jsonl), so ids that differ only by case never share a file on case-insensitive filesystems.

pylinxi.journal.SQLiteJournal

Bases: Journal

SQLite store (WAL). Appends run in IMMEDIATE transactions, so several processes can share the database file. A heads table indexes each run's newest entry, so scheduling queries don't scan history.

pylinxi.postgres.PostgresJournal

Bases: Journal

runs

runs(kind: Optional[str] = None) -> Iterable[str]

All run ids, or only runs whose latest entry has this kind.

pylinxi.journal.open_journal

open_journal(url: str, create: bool = True, **kw: Any) -> Journal

Open a journal from a URL: memory:// file:///abs/dir file:rel/dir sqlite:///rel.db sqlite:////abs.db postgresql://...

create=False refuses to create a missing file or directory (the CLI uses this, so a mistyped path is an error rather than an empty journal).

pylinxi.journal.Entry dataclass

pylinxi.journal.Codec

Lossless JSON codec.

Round-trips str/int/float/bool/None, lists, dicts (including non-string keys and dicts that happen to contain the tag key), tuples, sets, bytes, datetime, date, time, timedelta, Decimal and UUID out of the box, plus classes you register(): dataclasses, model classes with model_dump(), plain classes with a dict, and Enums. Registered classes are identified by module + qualified name, so two classes called Config in different modules never collide. Unregistered custom objects (and unregistered Enums) raise TypeError instead of silently changing type on replay.

register

register(cls: Type) -> Type

Register a class (usable as a decorator). Registering a new class under the same module + name (e.g. after a reload) replaces the old one.

Worker

pylinxi.worker.Worker

__init__

__init__(journal: Journal, flows: Union[Iterable[Flow], Mapping[str, Flow]], retry_failed: bool = False, max_failures: int = 5, backoff: float = 30.0, max_backoff: float = 3600.0, on_event: Optional[Observer] = None, concurrency: int = 8, resume_stale_after: Optional[float] = 60.0, on_error: Optional[Callable[[BaseException], None]] = None, on_tick: Optional[Callable[[TickReport], None]] = None)

concurrency -- runs resumed in parallel per tick resume_stale_after -- seconds (default 60); resume open runs -- crashed mid-execution -- whose last entry is older than this. Runs still executing elsewhere hold their lock and are skipped. None turns this off (do that for file/SQLite journals shared across processes on Windows, which has no cross-process file locks). on_error / on_tick -- callbacks for tick failures and per-tick reports (errors are also logged to the "pylinxi" logger).

pylinxi.worker.TickReport dataclass

Exceptions

pylinxi.policy.StepFailed

Bases: Exception

pylinxi.policy.ValidationError

Bases: Exception

Raised when a step's output fails its validator. Always retryable.

pylinxi.policy.CircuitOpen

Bases: Exception

Raised when a step's circuit breaker is open and no fallback exists.

pylinxi.policy.AttemptStillRunning

Bases: Exception

A sync step timed out and its thread was still running when the next attempt was due, so the outcome of that attempt is unknown; pylinxi does not start another attempt alongside it (that could repeat a side effect).

pylinxi.policy.PriorAttemptRunning

Bases: BaseException

An earlier execution of this run left an attempt of the step running (it was cancelled by a drain, a crash of the caller, a timeout) and it is still running. Its outcome is unknown, so the step must neither fail nor run again: the flow suspends until retry_at and then picks up that attempt's result. A BaseException so except Exception / except StepFailed in flow code can't turn it into a permanent, journaled failure.

pylinxi.flow.Suspended

Bases: BaseException

Raised inside a flow when it must pause (signal and/or timer).

A BaseException (like CancelledError) so except Exception in flow code can't swallow it by accident.

pylinxi.flow.ContinueAsNew

Bases: BaseException

Raised by ctx.continue_as_new(); ends this run and starts a fresh journal.

pylinxi.flow.ReplayDivergence

Bases: BaseException

Replay no longer matches the journal: the flow's code changed in a way that would run a different step at a point where the run already recorded one. Raised before the new step runs, so nothing new happens. A BaseException so except Exception in flow code can't swallow it. Use ctx.patched() for intentional changes, or strict=False to only report it.

pylinxi.flow.ReplayedError

Bases: Exception

Stands in for the original exception when a caught step failure is replayed.

pylinxi.flow.ResultNotJournaled

Bases: Exception

A step ran but its result can't be journaled (unsupported type). It is not run again on resume -- that could repeat its side effect -- so replay raises this.

pylinxi.flow.FlowMismatch

Bases: ValueError

The run id belongs to a different flow.

pylinxi.flow.RunExists

Bases: ValueError

run() was given inputs for a run id that already exists with different inputs.

pylinxi.journal.RunLocked

Bases: Exception

Another worker currently owns this run.

pylinxi.journal.LockLost

Bases: RunLocked

This worker lost ownership of the run while executing it (for example its database lock connection dropped); it must stop, another worker may take over.

pylinxi.journal.JournalCorrupt

Bases: Exception

Stored data can't be trusted: tampering, rows copied from another run, a bad manual edit, a missing signing key, or disk damage.

pylinxi.journal.UnknownRun

Bases: LookupError

No run with this id exists in the journal (never started, or deleted).