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.
submitwithidempotency_keyreturns the first run on a repeat.ownertags the tenant for fair claims. Version and flow control are stamped from the decorator.start_atanddelayhold the body back (Starting a run later);POST /{name}/runstakes no start time yet.updatewaits for whichever worker applies it. Pasttimeoutit raisesUpdateTimeout; the update stays queued, so retry with the sameupdate_id.resumeanswers the interrupt the run is waiting on unless you passwait_id.
Ids in a long chain
Section titled “Ids in a long chain”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.
Errors
Section titled “Errors”Client calls raise specific errors, all importable from pyrula.workflows (see the API reference): RunNotFoundError, RunFinishedError, RunNotWaitingError, UpdateRejected, UpdateError, UpdateTimeout and DurableInvocation* from result.
In the same process
Section titled “In the same process”worker.client is a client on the worker’s store.
import asynciofrom 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())From sync code
Section titled “From sync code”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 asyncioimport threading
from pyrula.workflows import MemoryStore, WorkerConfig, WorkflowWorker, workflowfrom 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_keyonsubmit,signal_idonsignal,update_idonupdate.
Starting a run later
Section titled “Starting a run later”delay (seconds or timedelta) or start_at (timezone-aware datetime) holds the body until then. One of them, not both.
import asynciofrom datetime import timedelta
from pyrula.workflows import workflowfrom 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 naivestart_at, or a time more than 365 days out raisesValueError. A paststart_ator zerodelaystarts now. - Lateness. The body can start late by
timer_poll_interval_splus the claim. - Idempotency. Same
idempotency_keyand same timing returns the first run; different timing raisesIdempotencyConflict. - Before it starts.
cancelandterminateend the run without running the body. Signals are buffered. AnupdateraisesRunNotStartedError. - Retries and successors. A retry does not inherit the delay, and a
continue_as_newsuccessor starts at once. Schedules and Kafka records take no start time.
Without a worker
Section titled “Without a worker”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 asynciofrom datetime import timedelta
from pyrula.workflows import workflowfrom 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.
Cancellation
Section titled “Cancellation”await client.cancel(name, run_id) records a graceful request that needs a worker; see Cancel and terminate.