# Starting and talking to runs

> WorkflowClient: submit runs, signal, query, update, cancel and wait for results.

Source: https://docs.pyrula.io/workflows/guides/client/

```python
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](https://docs.pyrula.io/workflows/guides/http.md#endpoints).

| `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](https://docs.pyrula.io/workflows/concepts/replay-and-recovery.md)) |
| `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](https://docs.pyrula.io/workflows/guides/metadata-and-users.md)) |
| `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](https://docs.pyrula.io/workflows/guides/worker.md#fairness-across-tenants). Version and [flow control](https://docs.pyrula.io/workflows/guides/flow-control.md) are stamped from the decorator.
- `start_at` and `delay` hold the body back ([Starting a run later](#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`.

## 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

Client calls raise specific errors, all importable from `pyrula.workflows` (see the [API reference](https://docs.pyrula.io/reference/workflows.md)): `RunNotFoundError`, `RunFinishedError`, `RunNotWaitingError`, `UpdateRejected`, `UpdateError`, `UpdateTimeout` and `DurableInvocation*` from `result`.

## In the same process

`worker.client` is a client on the worker's store.

```python
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())
```

## 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.

```python
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](https://docs.pyrula.io/reference/workflows-sync.md), 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`.

## Starting a run later

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

```python
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())
```

```python
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](https://docs.pyrula.io/workflows/guides/flow-control.md) 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.

## 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.

```python
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.

## Cancellation

`await client.cancel(name, run_id)` records a graceful request that needs a worker; see [Cancel and terminate](https://docs.pyrula.io/workflows/guides/cancel-and-terminate.md).
