# Quickstart

> Scaffold a durable workflow, run it, and watch it survive a suspend.

Source: https://docs.pyrula.io/getting-started/quickstart/

Scaffold a workflow, run it on a local SQLite store, open its event stream. No broker, key or account.

```bash
pip install "pyrula[workflows]"
pyrula init --workflow
pyrula dev app.py --open
```

Not on PyPI yet: build from source ([Install](https://docs.pyrula.io/getting-started/install.md)) and prefix the other
two with `uv run`.

## Generated workflow

`pyrula init --workflow` writes `app.py`, a small checkout workflow:

```python
from pyrula.workflows import WorkflowContext, step, workflow

# Counts real executions so the result payload can show what was not repeated.
CALLS = {"reserve": 0, "charge": 0, "receipt": 0}


@step
def reserve_inventory() -> dict:
    CALLS["reserve"] += 1
    return {"sku": "widget", "qty": 2}


@step
def charge_card() -> dict:
    CALLS["charge"] += 1
    return {"amount": 4200}


@step
def send_receipt(order: str) -> dict:
    CALLS["receipt"] += 1
    return {"order": order, "calls": dict(CALLS)}


@workflow(name="checkout")
async def checkout(ctx: WorkflowContext, order: str = "A-1042") -> dict:
    await reserve_inventory()
    await charge_card()

    # A durable sleep, not asyncio.sleep: the run suspends, the worker slot is
    # freed, and the run resumes later from the journal.
    await ctx.sleep(2)

    return await send_receipt(order)
```

`@step` records a function's result. `CALLS` is a process-local counter, not durable state: a
different worker process that resumes the run starts it at zero.

## Run the workflow

`pyrula dev app.py --open` starts a local server, runs the workflow once and opens the dev UI:

```
=== Pyrula Dev Server ===
Target: app.py:checkout
Using SQLite store .pyrula/dev.db - runs survive a restart; --fresh starts empty
Cloud: off (no PYRULA_CLOUD_API_KEY) - running locally only
UI: http://127.0.0.1:7978/ui

Press Ctrl+C to stop

  reserve_inventory  done
  charge_card  done
  suspended - worker slot freed
  resumed from journal
  send_receipt  done
  completed - {'order': 'A-1042', 'calls': {'reserve': 1, 'charge': 1, 'receipt': 1}}
Saved the last run as .pyrula/last/checkout.case.
```

The run suspends at `ctx.sleep(2)` and resumes at `send_receipt`. Each step ran once: the card was not charged twice.

## Inspect the event stream

`http://127.0.0.1:7978/ui` lists runs; opening one shows its result and event stream:

```
complete    started 27s ago    0 ms (last attempt)
{'order': 'A-1042', 'calls': {'reserve': 1, 'charge': 1, 'receipt': 1}}

  run:init
  step:pending   reserve_inventory
  step:done      reserve_inventory
  step:pending   charge_card
  step:done      charge_card
  run:sleeping   suspended until 17:54:43
  run:woken      resumed at 17:54:43
  step:pending   send_receipt
  step:done      send_receipt
  run:complete   result: {'order': 'A-1042', 'calls': {...}}
```

Every row expands to its payload. This is the journal the engine replays from.

`pyrula dev` loads your code once: edit `app.py`, Ctrl-C, start again, and each start submits a
fresh run. Runs live in `.pyrula/dev.db`, so history survives a restart:

```bash
pyrula dev --fresh                          # delete the file first
pyrula dev --store valkey://localhost:6379
```

## Prove recovery

`pyrula init` in a fresh directory also writes `crash_resume.py`, a two-step workflow that kills
its own process between the steps. Run it twice:

```bash
python crash_resume.py
python crash_resume.py
```

The first pass runs step one, then kills the process:

```text
  step one: RAN (this line should appear exactly once, ever)
  killing this process now - run the script again
```

The second pass waits about five seconds for the dead process's lock to lapse, replays step one
from the journal and runs step two:

```text
  step two: RAN
result: {'first': 'one', 'second': 'two'}
```

`step one: RAN` appears once across both passes. The run lives in `.pyrula/dev.db`, which outlives
the process, and `.crash_resume_run` holds the run id until the run completes.

A step that finished before the crash isn't run again, but an external effect isn't exactly-once:
if the process died before the result was recorded, the step runs again, so give the provider an
idempotency key ([details](https://docs.pyrula.io/getting-started/existing-app.md#wrap-the-function)). To crash a real worker, see [Crash handoff between workers](https://docs.pyrula.io/workflows/guides/worker.md#crash-handoff-between-workers). If something misbehaves, see
[Troubleshooting](https://docs.pyrula.io/getting-started/troubleshooting.md).

Next: [Running a worker](https://docs.pyrula.io/workflows/guides/worker.md) for production, and
[Connect to Pyrula Cloud](https://docs.pyrula.io/getting-started/cloud.md) to watch runs outside the dev UI.

## Minimal workflow

For a script or test that does not suspend, use `InlineWorkflowRunner`:

```python
import asyncio
from pyrula.workflows import step, workflow, InlineWorkflowRunner, MemoryStore


@step
def build(name: str) -> str:
    return f"hello, {name}"


@workflow(name="greet")
async def greet(ctx, name: str) -> str:
    return await build(name)


async def main() -> None:
    runner = InlineWorkflowRunner(store=MemoryStore())
    run = await runner.client.submit("greet", {"name": "ada"})
    print(await run.result())  # hello, ada
    for event in await run.events():
        print(event.kind, event.payload)


asyncio.run(main())
```

`submit` queues, `result()` runs it in this process, `events()` returns the journal. `MemoryStore` is for tests; `SQLiteStore("pyrula.db")` and Valkey survive restarts ([Choosing a store](https://docs.pyrula.io/getting-started/choosing-a-store.md)).

<span id="parameters"></span>

Params are validated against the body's annotations, and a dataclass, Pydantic model or `list[Order]` arrives as that type. Bad or missing input ends the run with `run:error` code `invalid_request`.

<span id="options"></span>

Decorator options are in the [`@workflow` reference](https://docs.pyrula.io/reference/workflows.md#workflow).

## Connect to Pyrula Cloud

Copy the environment's key from **Setup** and restart `dev`:

```bash
export PYRULA_CLOUD_API_KEY="<key>"
pyrula dev app.py
```

[Connect to Pyrula Cloud](https://docs.pyrula.io/getting-started/cloud.md) covers capture settings and worker setup.
