# Runbook: the runner `tape runner` is the process that turns a database into a desk: it claims due strategy instances, runs one cycle per sleeve, and writes what happened. `tape serve` is the read-only view of what it wrote. Without this process the page is a snapshot of history, not a trading record. ## What it needs 1. A migrated database: `uv run tape migrate` (the runner checks `ledger_events`, `leases`, `strategy_instances`, `orders`, `sleeve_halts`, `sleeve_snapshots`, `decisions`, and `ohlcv`/`instruments` when the bar source is a stored table). A missing table refuses startup and names `tape migrate`. 2. A runner config (`kind: Runner`), like `examples/india-runner.yaml`. 3. `TAPEBOOK_DATABASE_URL`, or `--url`. 4. `INDSTOCKS_ACCESS_TOKEN` only when `broker.adapter` or `market_data.adapter` is `indstocks`. The token is read from the environment, never from the config file, and never logged. 5. Book capital already booked in the ledger: `tape deposit ` puts outside money into a sleeve, and `tape allocate ` moves it between sleeves. A sleeve with no allocation records zero-equity snapshots and places no orders (`cycle_unfunded`). ## Fund the book (first run, step 2) A migrated database has an empty ledger, and the runner will not invent capital. Before the first cycle, put money in: ```console $ tape deposit india-discretionary 200000 --reference first-funding deposited INR 200000.00: india-discretionary event: deposit:INR:india-discretionary:first-funding (seq 0) india-discretionary: cash before INR 0.00 cash after INR 200000.00 ``` With a second registered sleeve, `tape allocate` moves booked cash between them: ```console $ tape allocate india-discretionary value-sleeve 50000 --reference rebalance-1 allocated INR 50000.00: india-discretionary, value-sleeve event: allocate:INR:india-discretionary:value-sleeve:rebalance-1 (seq 1) india-discretionary: cash before INR 200000.00 cash after INR 150000.00 value-sleeve: cash before INR 0.00 cash after INR 50000.00 ``` `tape deposit` records `FUNDS_DEPOSITED` against the sleeve with an `EXTERNAL` counterpart, so the book still conserves. `tape allocate` is a **book-internal** move between sleeves; it is not a real capital movement between venues — ADR-0019 governs those, and no broker or bank is contacted. Both commands are idempotent on their `--reference`: running the same command twice prints `already recorded — no change` and the book is not doubled. When `--reference` is omitted it defaults to the amount, so two genuinely identical deposits need two different references (bank references, usually). Both print the event id and cash before/after; if you cannot see the effect, do not run it again — read the report. A typo in the sleeve name is refused with `unknown sleeve ''` and the names the book knows. Sleeves are known from the ledger and from `strategy_instances`, so a newly configured sleeve must have had one runner pass before it can be funded. The first deposit on a completely empty book is the exception: it creates that sleeve, because there is nothing yet to compare the name against. ## Config ```yaml apiVersion: tapebook/v1 kind: Runner metadata: name: india-desk version: 0.1.0 currency: INR # one book currency per runner; every strategy must match it broker: adapter: simulated # simulated | indstocks # ₹2,00,000 in paise. Simulated only: the paper account's cash, in minor units. It must be # large enough for a target to reach one share — see the example-cash note below. cash_minor: 20000000 venue: NSE market_data: adapter: stored # stored | indstocks interval: 1d # the ohlcv key: 1d, 1h, 1w ... strategies: # paths resolve relative to this file - india-book-mandate.yaml sleeves: - id: india-discretionary # the ledger sleeve, the lease name and the schedule row strategy: india-discretionary # metadata.name inside the strategy file cadence_seconds: 86400 # optional; daily/weekly defaults come from the strategy ``` `stored` reads bars a data job already ingested (`tape bars fetch`). `indstocks` fetches and caches bars itself, and needs the token. The broker adapter decides execution, not the bar source: a `simulated` broker with `indstocks` bars is paper trading on real prices. Startup refuses, naming the key, when: `broker.adapter` or `market_data.adapter` is missing or unknown; no strategy file loads; a sleeve names a strategy nobody declared; a strategy's universe is in a different currency from `currency`; a strategy is declared in a different currency; a table is missing; or `strategy_instances` holds an **enabled** instance this config does not list (claiming it would advance `next_run_at` and silently lose that run). ### The example cash figure `broker.cash_minor: 20000000` is ₹2,00,000. That number is not decoration: a 20% target must exceed the cheapest close in the universe, or the first cycle sizes every order to zero and logs `intents: 0, traded: false` — indistinguishable from a strategy that chose to hold. The cheapest name in this example's universe closed at ₹857.25 (2026-11-27); ₹2,000 of paper capital made a 20% target ₹400 and traded nothing (GAP-078). Keep `cash_minor` and the `tape deposit` amount the same figure for a paper desk: the broker's cash is what can be spent, and the book's capital is what the strategy intends to spend. ## Run it ```bash # the loop TAPEBOOK_DATABASE_URL=postgresql://… uv run tape runner examples/india-runner.yaml # one pass, for a cron/systemd timer TAPEBOOK_DATABASE_URL=postgresql://… uv run tape runner examples/india-runner.yaml --once ``` Options: `--interval SECONDS` (default 5, the gap between passes), `--ttl SECONDS` (lease TTL, default 300), `--owner LABEL` (default `desk:hostname:pid`; this is what `tape leases` shows), `--url`. The first pass registers every configured sleeve in `strategy_instances`. Re-registering does not reset the clock. Instances are due immediately on registration. ### Two runners Safe by construction, not by convention: `strategy_instances` is claimed with `FOR UPDATE SKIP LOCKED` and `next_run_at` is advanced in the same statement, and each sleeve is then driven under a named lease (`leases`). A second process either claims different work or is skipped with `held by another runner`. It never double-executes a sleeve. The exception an operator will hit: if the lease holder is **dead** (killed mid-cycle), the skip is not retried. The claim has already moved `next_run_at` a full cadence forward, so the pass is lost until the lease expires *and* the next cadence comes due (GAP-077). The recovery is to force the row due: `UPDATE strategy_instances SET next_run_at = now() WHERE id = ''`. ## What a healthy first run looks like Measured end to end on 2026-11-30 against a throwaway Postgres 16, the real INDstocks instrument master and real daily candles, with `broker.adapter: simulated`. Four names in the universe, one sleeve, ₹2,00,000 of paper capital. Abridged to the lines that matter: ```console $ tape migrate applied: 0001_ledger, … 0013_bars $ tape deposit india-discretionary 200000 --reference first-funding # step 2: fund the book deposited INR 200000.00: india-discretionary event: deposit:INR:india-discretionary:first-funding (seq 0) india-discretionary: cash before INR 0.00 cash after INR 200000.00 $ tape instruments --refresh refreshed: 23220 instruments $ tape instruments INFY NSE:INFY security_id=1594 lot=1 freeze=85222 isin=INE009A01021 $ tape bars fetch INFY RELIANCE TCS HDFCBANK --venue NSE INFY@NSE: 138 bars, last 2026-11-27T00:00:00+00:00 RELIANCE@NSE: 138 bars, last 2026-11-27T00:00:00+00:00 TCS@NSE: 138 bars, last 2026-11-27T00:00:00+00:00 HDFCBANK@NSE: 138 bars, last 2026-11-27T00:00:00+00:00 $ tape runner examples/india-runner.yaml --once {"event": "cycle_start", "sleeve": "india-discretionary", "cycle": "india-discretionary:137"} {"event": "cycle_done", "sleeve": "india-discretionary", "cycle": "india-discretionary:137", "intents": 4, "traded": true, "halted": false, "drift": 0, "rejections": 0} {"event": "tick", "claimed": ["india-discretionary"], "ran": ["india-discretionary"], "skipped": [], "error": null} ``` If the deposit is skipped, the same first pass logs `cycle_unfunded` and `intents: 0, traded: false`; the runner is right — it will not invent capital. Fund the book and run again (forcing the row due if the cadence has already advanced), and the first cycle that trades looks like this: ```console $ tape positions SLEEVE india-discretionary cash INR 64699.00 34 HDFCBANK@NSE 34 INFY@NSE 28 RELIANCE@NSE 11 TCS@NSE $ tape orders india-discretionary cycle side qty filled status booked client id india-discretionary:137 BUY 34 34 FILLED yes india-discretionary:137:HDFCBANK:NSE:BUY … three more, all FILLED and booked … 4 order(s); 0 FILLED with no matching ledger event $ tape instances india-discretionary india-discretionary every 86400s next 2026-11-30T20:13:07+00:00 last 2026-11-29T20:13:07+00:00 enabled ``` The numbers that must agree, and did: | Where | cash | positions | equity | |---|---|---|---| | `tape positions` / ledger | ₹64,699.00 | ₹1,35,301.00 (34 HDFCBANK @857.25, 34 INFY @1151.30, 28 RELIANCE @1382.60, 11 TCS @2572.50) | ₹2,00,000.00 | | `sleeve_snapshots` (last row) | 64,699,00 paise | 1,35,301,00 paise | 2,00,000,00 paise | | `GET /api/sleeves` | `"INR 64699.00"` | the same four quantities | `"INR 200000.00"` | And `5` ledger events (one `FUNDS_DEPOSITED` — written by `tape deposit` — and four `TRADE_FILL`s), `4` orders all `FILLED` and all `booked: yes`, one snapshot per pass (`3` at this point), and `1` decision row — the decision is keyed by sleeve and cycle, so a repeat pass over the same bar writes nothing new. The **second** pass, with the schedule forced due, logged `paper_account_replayed orders=4` and then `intents: 0, traded: false, drift: 0` — a delta, not a duplicate: no new events, no new orders, one more snapshot at the same equity. ### Traps that cost time on a first run - **A repeated deposit is a no-op, not a second deposit.** `tape deposit` is idempotent on `sleeve + amount + --reference`; the second run prints `already recorded — no change` and the book is unchanged. If you intend two identical deposits, give them two bank references. The corollary: an operator who "re-runs to be sure" must read the report, not the exit code. - **`intents: 0, traded: false` on a funded book is usually a sizing floor.** A 20% target must exceed the cheapest close in the universe. The shipped example now uses ₹2,00,000 (`cash_minor: 20000000`); with the old ₹2,000, a 20% target was ₹400 against a cheapest close of ₹857.25, so every intent floored to zero (GAP-078). If you change `cash_minor`, fund the book with the same figure — the paper account's cash is what can be spent, and the book's capital is what the strategy intends to spend. - **`cycle` in the logs is a bar index**, not a date: `india-discretionary:137` is the 138th bar. It does not change while no new bar arrives, which is why a second pass over the same bar is a delta. - **A first fetch goes back 200 calendar days, not to the vendor's limit.** With nothing stored, `fetch_plan.plan` starts each symbol at `now − 200 days`, which returned 138 daily candles (2026-05-12 → 2026-11-27) — enough for the 50-day average in this strategy, and not enough for a 200-day one, which would silently evaluate on a shorter history. `tape bars fetch` has no flag to ask for more; re-running it fetches only the delta. - **The paper account is rebuilt from `orders`, not from the book.** A `tape adjust` of a sleeve holding therefore shows up as drift on the next cycle and halts the sleeve — correct, and the halt will read as "book and broker disagree". ### Why the first restart would halt `SimulatedBroker` keeps cash and holdings in memory. Before this was handled, every new process started flat while the book still held shares; reconciliation reported each holding as drift and the sleeve halted on its second cycle — safely, but permanently, because the halt is written to `sleeve_halts` and checked before anything else. `build_desk` now replays the filled `orders` rows into the fresh simulator (`paper_account_replayed`) before the first cycle. Replay uses the quantity and price the broker reported, so a partial fill replays as what it did, and it re-registers each `client_order_id`, so a retried cycle stays a no-op at the broker as well as at the ledger. ## What it writes | Table | What it records | |---|---| | `strategy_instances` | registration, `last_run_at`, `next_run_at` | | `leases` | which runner currently drives which sleeve, until when | | `ledger_events` / `ledger_legs` | every booked fill, append-only | | `orders` | the broker conversation: intent, acknowledgement, fill, rejection | | `sleeve_snapshots` | one valuation per cycle: cash, positions value, equity, halted flag | | `decisions` | the targets a cycle decided, with the spec version and inputs digest | | `sleeve_halts` | a drift or business halt raised by the cycle itself | One JSON object per line on stdout (all times UTC): ``` {"ts":"…","level":"info","event":"order_egress","detail":"order egress: direct — …"} {"ts":"…","level":"info","event":"paper_account_replayed","orders":4} {"ts":"…","level":"info","event":"runner_start","desk":"india-desk","owner":"…","broker":"simulated","market_data":"stored","currency":"INR","sleeves":["india-discretionary"]} {"ts":"…","level":"info","event":"tick","claimed":["india-discretionary"],"ran":["india-discretionary"],"skipped":[]} {"ts":"…","level":"info","event":"cycle_start","sleeve":"india-discretionary","strategy":"india-discretionary","cycle":"india-discretionary:250"} {"ts":"…","level":"info","event":"cycle_done","sleeve":"india-discretionary","cycle":"india-discretionary:250","intents":2,"traded":true,"halted":false,"drift":0,"rejections":0} ``` `paper_account_replayed` appears only on a `simulated` broker with fills in `orders`: the paper account lives in memory, so the runner rebuilds it from its own filled orders before the first cycle. Without that, a restart sees a broker holding nothing against a book holding shares, calls it drift, and halts (see [Why the first restart halts](#why-the-first-restart-would-halt)). `cycle_unfunded` means the ledger is empty for this currency: the sleeve has no capital and a zero snapshot was written. `cycle_failed` carries the sleeve, the cycle label and the exception. ## Is it healthy? ```bash uv run tape instances # last_run_at advances, next_run_at stays ahead uv run tape leases # only this runner's owner, with an expiry in the future uv run tape positions # the book side uv run tape orders uv run tape halts # should be empty unless something is actually wrong ``` A healthy loop emits a `tick` line every interval and a `cycle_done` (or `cycle_halted` / `cycle_unfunded`) per claimed sleeve. No `tick` lines at all means the process is not running, not that nothing is due. `next_run_at` equal to `last_run_at` means no runner has claimed the instance. ## Stopping it `SIGTERM` or `SIGINT` (Ctrl-C). The handler sets a flag; the loop waits on that flag between cycles, so the current cycle always finishes and the next pass does not start. The process exits 0. If it is killed with `SIGKILL` (or the host dies) **mid-submit**, the order store row is the record, not memory: the broker's `client_order_id` makes a re-submit the same order, and the next start reloads the ledger and reconciles against the broker *before* trading, halting the sleeve if the two disagree. Nothing is lost; something may be counted twice if it is retried without checking, which is why reconciliation runs first. Exit codes: `0` clean stop; `1` a configuration, schedule or cycle error it cannot recover from (the message names the sleeve and cycle); `2` no database URL. ## The honest limit: supervision is yours This process has **no supervision and no restart policy of its own**. The repository ships no systemd unit or container policy for it. If it exits, nothing brings it back, and nothing pages you. That is deliberate: a restart policy is a property of the deployment, and hiding one half of it in the application makes the other half impossible to reason about. A minimal unit (an example, not a shipped file): ```ini [Service] ExecStart=/usr/local/bin/tape runner /etc/tapebook/runner.yaml Environment=TAPEBOOK_DATABASE_URL=postgresql://… Restart=on-failure RestartSec=10 KillSignal=SIGTERM TimeoutStopSec=60 ``` Also unhandled here, and recorded as gaps: - **No database reconnect.** A dropped connection raises, the process exits non-zero, and the supervisor restarts it. Cycles are idempotent, so this is safe; it is not seamless. - **No market-hours or calendar gate.** The runner runs whatever the database says is due. A daily strategy on a 1-hour cadence re-decides on the same last bar; deterministic cycle ids and ledger idempotency keys make the repeats no-ops, but it is not the same as a trading calendar. - **No token refresh schedule** (GAP-059) and no instrument-master refresh schedule (GAP-060). - **The `indstocks` broker adapter has never placed a live order** (GAP-057). Paper (`simulated`) is the only proven execution path. - **Funding does not reconcile against a bank or broker.** `tape deposit` records what the operator says arrived; it does not verify a statement, and `tape allocate` moves no real money (ADR-0019 governs venue moves). Nothing here replaces a bank reconciliation.