> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Reference app

> The order service reference implementation: Python handlers over CockroachDB, a regression suite, and cross-table accounting checks.

The reference implementation lives in [`blueprints/order-management/reference/`](https://github.com/cockroachlabs/cockroach-cookbook/tree/blueprints/order-management/v1.0.0/blueprints/order-management/reference) in the Cockroach Cookbook repository. It implements the core path end-to-end as Python handlers over CockroachDB, with a regression suite and cross-table accounting checks. It was executed against CockroachDB v26.2.8: 12 regression tests pass and all accounting checks return zero rows. See its `VALIDATION.md` for the exact environment and what was and was not verified.

## Layout

```
reference/
├── README.md            # prerequisites, setup, and scope
├── VALIDATION.md        # what was and was not verified, with results
├── requirements.txt     # psycopg 3
├── schema.sql           # all tables, constraints, indexes, Row-Level TTL
├── seed.sql             # SKU-HOT (1 unit), SKU-1 (100 units)
├── reference.py         # transaction handlers (below)
├── test_reference.py    # the regression scenarios (acceptance criteria)
└── verification.sql     # cross-table accounting checks (must return zero rows)
```

## Handlers

Every write runs through a `@serializable_retry` wrapper that retries the whole transaction on `40001` with bounded backoff and jitter (see [Transactions & SQL](https://docs.cockroachlabs.com/docs/cookbook/order-management/transactions-and-sql.md)).

* **`create_order`**: idempotent create. Stores the request fingerprint and cached response in `idempotency_keys` in the same transaction as the effect. Reserves each line with a guarded `UPDATE inventory SET reserved = reserved + :qty WHERE sku = :sku AND on_hand - reserved >= :qty`. If any line matches zero rows, the whole transaction rolls back, so there is no partial hold.
* **`capture_payment`**: deduplicates callbacks through the `payment_events` inbox, locks the payment row with `FOR UPDATE`, and advances state monotonically. A capture that arrives after cancellation or expiry records the outcome and requests one compensating refund rather than reviving released stock. See [Payments & callbacks](https://docs.cockroachlabs.com/docs/cookbook/order-management/payments-and-callbacks.md).
* **`expire_reservation`** and **`cancel_order`**: release an unpaid hold exactly once. See [Inventory & reservations](https://docs.cockroachlabs.com/docs/cookbook/order-management/inventory-and-reservations.md).
* **`ship`** and **`return_items`**: guarded per-line writes that enforce `shipped + cancelled <= ordered` and `returned <= shipped`; a resellable return increases `on_hand` once. See [Fulfillment & returns](https://docs.cockroachlabs.com/docs/cookbook/order-management/fulfillment-and-returns.md).
* **`claim_outbox`**: claims unsent `outbox` rows with `FOR UPDATE SKIP LOCKED`, with a note on sharding for high volume. See [External integration](https://docs.cockroachlabs.com/docs/cookbook/order-management/external-integration.md).

> [!NOTE]
>
> **No partial hold, no savepoint after retry**
> An out-of-stock line rolls back the entire transaction rather than a nested savepoint. CockroachDB does not allow `ROLLBACK TO SAVEPOINT` after a `40001` restart, so the full rollback is the correct pattern and still guarantees no partial allocation.

## The core transaction

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
POST /orders   Idempotency-Key: <uuid>
withRetry:                                 # see Transactions, isolation & retries
  BEGIN
    INSERT INTO idempotency_keys(key, request_fingerprint)
      VALUES (:key, :fp) ON CONFLICT (key) DO NOTHING
    if replay: return stored response; COMMIT
    for each line:
      UPDATE inventory SET reserved = reserved + :qty
        WHERE sku = :sku AND on_hand - reserved >= :qty   # 0 rows -> OUT_OF_STOCK, roll back
      INSERT INTO reservations(...)
    INSERT INTO orders(...), order_lines(...)
    INSERT INTO order_events(... 'created')
    INSERT INTO outbox('order','order_created', ...)
    UPDATE idempotency_keys SET response = :resp WHERE key = :key
  COMMIT
```

Every column and table name here matches the [Data model](https://docs.cockroachlabs.com/docs/cookbook/order-management/schema-design.md) page and `schema.sql`.

## Running it

From [Setup](https://docs.cockroachlabs.com/docs/cookbook/order-management/setup.md) steps 1 and 2 you have a cluster and the `ordermgmt` database. Then:

```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
cockroach sql --insecure -d ordermgmt -f reference/schema.sql
cockroach sql --insecure -d ordermgmt -f reference/seed.sql
export DATABASE_URL="postgresql://root@localhost:26257/ordermgmt?sslmode=disable"
cd reference
pip install -r requirements.txt
python -m pytest
cockroach sql --insecure -d ordermgmt -f verification.sql
```

Each test maps to an [evaluation task](https://docs.cockroachlabs.com/docs/cookbook/order-management/evaluation-tasks.md) and asserts the expected outcome from [Verification](https://docs.cockroachlabs.com/docs/cookbook/order-management/verification.md). For a browser-based walkthrough against your own cluster, use the `agent-demo/` app.
