# Runners and transactions

> Run use cases on Sypnia Data through its API, or on any Postgres with a direct connection, all or nothing.

Applies to: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service).  
Source: https://cases.docs.sypnia.com/sypnorm/runners/

For agents: Two runners from '@sypnia/cases/sypnorm'. Data API runner: createRunner(dataClient, { atomic: true }) with a @sypnia/data client (the person's token, row-level security applies); reads run first, writes commit all or nothing in one POST /rest/v1/transaction; inserted ids travel as references; increment/decrement add in the database; a no-match update/delete or check failure rolls back and retries (max 2); a table already written cannot be read again in the same run; no forUpdate/ctx.db.sql. Direct runner: createRunner({ databaseUrl, cases }) on a server with any Postgres 14+: one real transaction, forUpdate locks, ctx.db.sql; actor passed by your server. runner.run(useCase | name, input, actor) returns { ok: true, outcome, data } | { ok: false, outcome, tell, data }. The Data API runner refuses a case whose outcome some case listens to (it throws: that case runs in its area's service, POST /_cases/<id>, called with the person's Data session and run under row-level security); the outbox is written only on the server, by the direct runner the area's service uses, in the same transaction as the run's rows, then handed on right after the commit. Direct runner option rls: true (or { role }) applies the project's row-level security with the actor's claims. A declared failure undoes the run's own writes on both runners. Runners are what the area service uses; the runtime calls them for in_app, external, scheduled and event starts.

A runner runs use cases against a database. Choose by where your code runs and which database you use; the use cases are the same.

## On Sypnia Data, through its API

```ts
import { createClient } from '@sypnia/data/client';
import { createRunner } from '@sypnia/cases/sypnorm';
import { placeOrder } from './cases/place-order';

const sypnia = createClient('https://<ref>.data.sypnia.com', 'syp_pk_<ref>_…');
const runner = createRunner(sypnia, { atomic: true });

const r = await runner.run(placeOrder, { items: [{ product_id, qty: 1 }], pickup_at }, { signedIn: true });
if (!r.ok) show(r.tell);                        // r.outcome is 'OutOfStock' or 'BakeryClosed'
```

Sypnorm talks to the [Data API](https://data.docs.sypnia.com/data/rest-api/) with the person's token, so every read and write obeys row-level security. It works from a browser, a phone or a server, and on every Sypnia Data project, managed ones included, for every case **nobody listens to**.

With `atomic: true`, a use case is **one transaction over HTTP**:

- Reads run first, as the use case asks for them.
- The writes go in one [Data API transaction](https://data.docs.sypnia.com/data/rest-api/#transactions) and commit all or nothing. An inserted row's `id` can be used by the next insert: it travels as a reference the engine fills inside the transaction.
- `increment()` and `decrement()` add in the database, so concurrent changes are never lost.
- If an update or delete matches no row, or a check constraint fails, the rows changed since they were read: the transaction rolls back and the use case runs again (at most twice). Its own failures (sold out…) then decide.
- Read before you write: a table the use case already wrote cannot be read again in the same run. `forUpdate()` and `ctx.db.sql` need a direct connection.

Without `atomic`, each step is its own request: fine for use cases that only read, or write one row.

A declared failure sends no writes: the run's rows are not saved, only its answer comes back.

### A case someone listens to runs on the server

When some case listens to an outcome of a case, the outcome has to be saved in the outbox with the case's rows, and the outbox lives in the schema `sypnia_cases`, which the Data API never exposes. A row written there with a person's token could also be forged from a browser. So the Data API runner **refuses such a case** with a message that names the listener, and the case runs in its area's service instead:

`src/app/order-for-tomorrow-button.ts`

```ts
// «Plan the bake» listens to «Order for tomorrow»: call the orders area's service
const res = await fetch('https://orders.la-espiga.example/_cases/order-for-tomorrow', {
  method: 'POST',
  headers: { Authorization: `Bearer ${session.access_token}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ items: [{ product_id, qty: 2 }], pickup_at }),
});
```

The service checks the person's Sypnia Data session, runs the case under the project's row-level security, and writes the outbox row in the same Postgres transaction ([Starts](https://cases.docs.sypnia.com/map/starts#in_app), [Delivery](https://cases.docs.sypnia.com/runtime/delivery)). The browser never writes the outbox.

## On any Postgres, with a direct connection

```ts
import { createRunner } from '@sypnia/cases/sypnorm';

const runner = createRunner({ databaseUrl: process.env.DATABASE_URL!, cases: [placeOrder] });
const r = await runner.run('place-order', input, { userId, role: 'customer', signedIn: true });
```

On a server, against Sypnia Data's database or any Postgres 14+: one real transaction, `forUpdate()` row locks and `ctx.db.sql`. Here your server says who the actor is, so it must have checked the person first. With `rls: true` (or `rls: { role: 'authenticated' }`), the run takes that role and the actor's claims, so the project's row-level security applies as it does over the API.

When the schema `sypnia_cases` is in the database, an outcome some case listens to goes into the outbox in the run's own transaction, and is handed on right after the commit. The body runs under a savepoint: a declared failure undoes the run's writes, while the failure's event (when someone listens) still commits. This is the runner each area's service uses ([Running cases](https://cases.docs.sypnia.com/runtime)).

## Which one

|                             | Data API runner                             | Direct runner                                      |
| --------------------------- | ------------------------------------------- | -------------------------------------------------- |
| Database                    | Sypnia Data                                 | any Postgres 14+ (Sypnia Data's included)          |
| Where your code runs        | browser, phone, server                      | server only                                        |
| Cases someone listens to    | refused: they run in the area's service     | yes: the outbox row commits with the data          |
| Who enforces permissions    | row-level security, with the person's token | your server, and the project's policies with `rls` |
| Transactions                | atomic over HTTP                            | real Postgres transactions                         |
| `forUpdate()`, `ctx.db.sql` | no                                          | yes                                                |
