Skip to content
Pyrula
Pre-release: the packages are not on PyPI yet, so pip install does not resolve. Build from source to try it today.

Starting and talking to runs

from pyrula.workflows import ValkeyStore, WorkflowClient
client = WorkflowClient(ValkeyStore(url="valkey://localhost:6379"))
run = await client.submit("charge", {"amount_cents": 500}, idempotency_key="order-7")
result = await run.result(timeout=60)

The client needs only the workers’ store. submit returns a RunHandle; rebuild one with client.handle(name, run_id). Everything is async and follows a continue_as_new chain to the live run. The same operations over HTTP are in Serving over HTTP.

RunHandle method Does
signal(signal, payload, *, signal_id) Wake ctx.wait_for_signal; returns "delivered" or "buffered"
query(query, *args, **kwargs) Read state through ctx.on_query; writes nothing
update(update, payload, *, update_id, timeout=30.0) Apply ctx.on_update and return its value
resume(action, value, *, wait_id) Answer ctx.interrupt
cancel(*, reason) Request cancellation and queue parked runs for cleanup
terminate(*, reason) End the run now with no worker; returns TerminateResult
retry() New run that reuses a failed run’s recorded steps (Replay and recovery)
status() Current RunStatus
result(*, timeout, on_interrupt) Wait for the run to finish
events() The run’s events, oldest first
WorkflowClient method Does
submit(name, params, *, idempotency_key, owner, metadata, user_id, thread_id, allow_unregistered=True, start_at, delay) Queue a run, optionally for later; returns its handle (metadata, users and threads)
trigger(name, event) Feed a Collect/Debounce buffer; returns a handle when a batch fires
handle(name, run_id) A handle to an existing run

result(on_interrupt=handler) calls handler(payload, run_id) for each ctx.interrupt and resumes with the return value: an InterruptResponse(action, value) with action one of approve, reject, respond or edit.

  • submit with idempotency_key returns the first run on a repeat. owner tags the tenant for fair claims. Version and flow control are stamped from the decorator.
  • start_at and delay hold the body back (Starting a run later); POST /{name}/runs takes no start time yet.
  • update waits for whichever worker applies it. Past timeout it raises UpdateTimeout; the update stays queued, so retry with the same update_id.
  • resume answers the interrupt the run is waiting on unless you pass wait_id.

Keep the start id submit returned; it reaches the live run through a continue_as_new chain. ctx.run_id is only the current run’s id.

Client calls raise specific errors, all importable from pyrula.workflows (see the API reference): RunNotFoundError, RunFinishedError, RunNotWaitingError, UpdateRejected, UpdateError, UpdateTimeout and DurableInvocation* from result.

worker.client is a client on the worker’s store.

import asyncio
from pyrula.workflows import MemoryStore, WorkerConfig, WorkflowWorker, workflow
@workflow(name="cart")
async def cart(ctx) -> list[str]:
items: list[str] = []
async def add(sku: str) -> int:
items.append(sku)
return len(items)
ctx.on_update("add", add)
ctx.on_query("items", lambda: items)
await ctx.wait_for_signal("checkout")
return items
async def main() -> None:
worker = WorkflowWorker(
workflows=[cart], store=MemoryStore(), config=WorkerConfig(claim_poll_interval=0.05)
)
loop = asyncio.create_task(worker.run())
client = worker.client
run = await client.submit("cart")
while await run.status() != "signal_waiting":
await asyncio.sleep(0.05)
assert await run.update("add", {"sku": "A-1"}) == 1
assert await run.query("items") == ["A-1"]
await run.signal("checkout")
assert await run.result(timeout=30) == ["A-1"]
worker.stop()
await loop
asyncio.run(main())

pyrula.workflows.sync has a blocking WorkflowClient and RunHandle for Django and Flask views, Celery tasks and RQ jobs. They are named like the async ones, as with httpx.Client and httpx.AsyncClient. Workflow bodies stay async def; only the caller changes.

import asyncio
import threading
from pyrula.workflows import MemoryStore, WorkerConfig, WorkflowWorker, workflow
from pyrula.workflows.sync import WorkflowClient
@workflow(name="sync_greeting")
async def sync_greeting(ctx, who: str) -> str:
return await ctx.step("greet", lambda: f"hello {who}")
store = MemoryStore()
worker = WorkflowWorker(
workflows=[sync_greeting], store=store, config=WorkerConfig(claim_poll_interval=0.05)
)
threading.Thread(target=lambda: asyncio.run(worker.run()), daemon=True).start()
with WorkflowClient(store) as client:
run = client.submit("sync_greeting", {"who": "ada"})
assert run.result(timeout=30) == "hello ada"
rows, _ = client.list_runs("sync_greeting")
assert [row["run_id"] for row in rows] == [run.run_id]

Create one client per process and reuse it; it owns one event loop on a daemon thread. result(timeout=) raises DurableInvocationTimeout. Signatures are in the sync client reference, plus list_runs.

  • A call cut short may still have taken effect. After Ctrl+C, retry with the idempotency parameters: idempotency_key on submit, signal_id on signal, update_id on update.

delay (seconds or timedelta) or start_at (timezone-aware datetime) holds the body until then. One of them, not both.

import asyncio
from datetime import timedelta
from pyrula.workflows import workflow
from pyrula.workflows.testing import WorkflowTestEnv
@workflow(name="send_receipt")
async def send_receipt(ctx, order: str) -> str:
return f"receipt for {order}"
async def main() -> None:
env = WorkflowTestEnv()
run = await env.client.submit("send_receipt", {"order": "o-1"}, delay=timedelta(hours=2))
assert await run.result() == "receipt for o-1" # the two hours are virtual
asyncio.run(main())
from datetime import UTC, datetime, timedelta
await client.submit(
"send_receipt", {"order": "o-1"}, start_at=datetime.now(UTC) + timedelta(days=30)
)

The wait is the run’s first sleep: no worker or concurrency slot held, and it survives restarts. The run reads pending until armed, then sleeping.

  • Bounds. A negative or non-finite delay, a naive start_at, or a time more than 365 days out raises ValueError. A past start_at or zero delay starts now.
  • Lateness. The body can start late by timer_poll_interval_s plus the claim.
  • Idempotency. Same idempotency_key and same timing returns the first run; different timing raises IdempotencyConflict.
  • Before it starts. cancel and terminate end the run without running the body. Signals are buffered. An update raises RunNotStartedError.
  • Retries and successors. A retry does not inherit the delay, and a continue_as_new successor starts at once. Schedules and Kafka records take no start time.

InlineWorkflowRunner and WorkflowTestEnv have a client whose handles drive the run in your process. WorkflowTestEnv (from pyrula.workflows.testing) keeps a virtual clock and skips to a sleep’s wake time and to the deadline of a wait_for_signal or interrupt with timeout=. A wait with no deadline stays parked until the test answers it.

import asyncio
from datetime import timedelta
from pyrula.workflows import workflow
from pyrula.workflows.testing import WorkflowTestEnv
@workflow(name="trial")
async def trial(ctx, user: str) -> str:
await ctx.sleep(timedelta(days=30))
return f"{user}: trial over"
async def main() -> None:
env = WorkflowTestEnv()
run = await env.start(trial, {"user": "ada"})
assert await run.result() == "ada: trial over" # the 30 days are virtual
asyncio.run(main())

await env.advance(timedelta(...)) moves the clock by hand; env.run_until_complete(run) drives a run until it ends or waits on a signal.

await client.cancel(name, run_id) records a graceful request that needs a worker; see Cancel and terminate.

View this page as Markdown