Skip to main content

pylinxi

Durable, self-healing workflows and AI agents in plain Python.

CI PyPI version Python versions License: MIT

Documentation · Getting started · Examples · Changelog


pylinxi makes long-running Python code survive anything that can stop a process. A flow is an ordinary async function; every call to a step is recorded in a signed journal. When a process crashes, is redeployed, or waits days for a human, the run resumes exactly where it stopped: finished steps return their recorded result instantly and are never executed twice.

Status: beta. The API is stable within 1.x and journals stay readable across 1.x releases. Test pylinxi against your own failure modes before relying on it in production.

Contents

Features

  • Plain Python control flow. Branch with if, loop with for, run work in parallel with asyncio.gather or TaskGroup. There is no graph or DSL to learn.
  • Crash-proof execution. Resume any run by id, from any process; completed steps replay from the journal and side effects are not repeated.
  • Self-healing steps. One declarative policy per step: retry with backoff, per-attempt timeout, output validation, input repair between attempts, fallback, and a shared circuit breaker.
  • Durable waits. ctx.sleep() and ctx.wait_for(signal, timeout=...) free the worker and survive restarts; signals can be sent from any process.
  • Lightweight state. The journal stores per-step deltas instead of full snapshots; rebuild state at any point in a run's history.
  • Tamper-evident audit trail. HMAC-signed hash chain with key rotation, automatic redaction of secret-looking keys, retention deletes, and a verify command for audits.
  • Production backends. In-memory, file, SQLite and PostgreSQL journals. PostgreSQL supports many concurrent workers with per-run locking and fencing.
  • Observability. Structured events for every step and an optional OpenTelemetry exporter.
  • Zero core dependencies. Fully typed, Python 3.9–3.13.

Installation

pip install pylinxi

Optional extras:

pip install "pylinxi[postgres]"   # PostgreSQL journal (psycopg 3)
pip install "pylinxi[otel]"       # OpenTelemetry tracing

Quick start

import asyncio
from pylinxi import SQLiteJournal, flow, step

@step
def fetch_order(order_id: str) -> dict:
    print("fetching", order_id)              # runs once, then replays from the journal
    return {"id": order_id, "total": 42}

@step
def send_receipt(order: dict) -> str:
    print("emailing receipt for", order["id"])
    return "sent"

@flow(journal=SQLiteJournal("runs.db"))
async def receipt(ctx, order_id: str) -> str:
    order = await fetch_order(order_id)
    return await send_receipt(order)

result = asyncio.run(receipt.run("A-1001", run_id="receipt-A-1001"))
print(result.status, result.output)          # completed sent

# Later, from any process: nothing is executed again.
result = asyncio.run(receipt.resume("receipt-A-1001"))

How it works

  1. Every call to a @step inside a flow is journaled with its result.
  2. resume(run_id) runs the flow function again from the top. Steps that already finished return their recorded result without executing; execution continues at the first step that did not finish.
  3. The one rule: code outside steps must be deterministic. Put I/O, model calls, randomness and clocks inside steps, or use await ctx.now() and await ctx.uuid().

If flow code changes so that replay no longer matches the journal, the run stops with ReplayDivergence before executing anything new. Use ctx.patched() to change code safely while runs are in flight. See Concepts for the full list of replay guarantees.

Usage

Self-healing steps

from pylinxi import CircuitBreaker, Policy, Retry, step

billing = CircuitBreaker(threshold=5, reset_after=30)      # share one per dependency

@step(policy=Policy(
    retry=Retry(attempts=4, backoff=0.5, on=(ConnectionError, TimeoutError)),
    timeout=20,                                            # seconds per attempt
    validate=lambda out: "intent" in out,                  # False -> retried
    repair=lambda err, args, kwargs, attempt: ((args[0] + f"\nFix: {err}",), kwargs),
    fallback=lambda prompt: {"intent": "unknown"},
    breaker=billing,
))
def classify(prompt: str) -> dict:
    ...

Human approval and deadlines

@flow(journal=journal)
async def expense(ctx, expense_id: str, amount: float):
    decision = await ctx.wait_for("decision", timeout=86_400, default="rejected")
    if decision == "approved":
        return await pay(expense_id, amount)
    return "rejected"

await expense.run("EXP-1", 120.0, run_id="EXP-1")         # status: "suspended"

# From a web handler or any other process:
journal.send_signal("EXP-1", "decision", "approved")       # a Worker resumes the run

Parallel branches

@flow(journal=journal)
async def enrich(ctx, customer_id: str):
    profile, orders = await asyncio.gather(get_profile(customer_id), get_orders(customer_id))
    scores = await ctx.map(score_order, orders, concurrency=8)   # each item is its own checkpoint
    return {"profile": profile, "scores": scores}

Idempotent side effects

from pylinxi import idempotency_key

@step
def charge(order: dict) -> str:
    # "<run_id>:<step_key>", identical across retries and resumes
    return payments.charge(order["total"], idempotency_key=idempotency_key())

More patterns — streaming steps, long-lived loops with continue_as_new, sensitive steps, events — are covered in the Flow API guide.

Running in production

Journal Use it for
MemoryJournal() Tests
FileJournal(directory) A single process; one JSONL file per run
SQLiteJournal(path) One machine, several processes
PostgresJournal(dsn) Many workers sharing one database
from pylinxi import Worker
from pylinxi.postgres import PostgresJournal

journal = PostgresJournal("postgresql://app@db:5432/agents", secret={"2026-q4": KEY})
worker = Worker(journal, [expense, enrich], retry_failed=True, max_failures=5)
await worker.run_forever(interval=5)

A Worker resumes runs whose timers are due, runs that received a signal, runs left open by a crashed process, and (optionally) runs that failed, with backoff. Run as many workers as you need: each run executes on one worker at a time.

Audit and operate journals from the command line:

export PYLINXI_JOURNAL=postgresql://app@db/agents PYLINXI_KEYS_FILE=/run/secrets/pylinxi-keys

pylinxi runs --status failed
pylinxi show EXP-1               # every entry: step, attempts, healing, state changes
pylinxi state EXP-1 --seq 3      # state as of entry 3
pylinxi verify --all             # exit code 1 if any run fails verification
pylinxi delete EXP-1 --yes       # retention and erasure requests

See Going to production for deployment, tracing and a pre-launch checklist, and Upgrading from 1.0 if you are moving from an earlier release.

Documentation

Full documentation is available at karawash-projects.github.io/pylinxi:

Runnable, self-checking examples are in examples/.

Contributing

Contributions are welcome. Please read CONTRIBUTING.md for the development setup, checks and guidelines. Planned work is listed in ROADMAP.md.

git clone https://github.com/karawash-projects/pylinxi && cd pylinxi
pip install -e ".[dev]"
python -m unittest discover -s tests -t .

Security

Please report vulnerabilities privately as described in SECURITY.md. Do not open public issues for security reports.

License

pylinxi is released under the MIT License.

Metadata

Release files for pylinxi 1.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pylinxi 1.1.1
File Size Uploaded Provenance Actions
pylinxi-1.1.1.tar.gz 90.3 kB With provenance Details for pylinxi-1.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pylinxi 1.1.1
File Interpreter ABI Platform Actions
pylinxi-1.1.1-py3-none-any.whl Python 3 none any Details for pylinxi-1.1.1-py3-none-any.whl

Total release size: 151.9 kB

Release files / pylinxi-1.1.1.tar.gz

Download URL pylinxi-1.1.1.tar.gz
Size 90.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b2ca47ece7b9b02036324a09f21d0490dbb0f696e3a670b92059247837a80be2
BLAKE2b-256 checksum
How to use checksums
b426ab8047863e9c112ea7611babae1da3050187b427fae4cf7cb29390f6c75d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 6, 2026.

Transparency log

Release files / pylinxi-1.1.1-py3-none-any.whl

Download URL pylinxi-1.1.1-py3-none-any.whl
Size 61.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
41622c5e1d17399f1182e5ef684b68c7db4289713e10eaad165ae5eb60c45397
BLAKE2b-256 checksum
How to use checksums
e49f6616fb6e676a151c6d5de4002bf4acaeafb95caa278dbc06f1cb725bdf20
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 6, 2026.

Transparency log

Security for pylinxi 1.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pylinxi-1.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 6, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page