# Runbook: the database Postgres is the only supported store (ADR-0021). This is what an operator does with it. ## First start **If you are deploying the desk, use `docs/runbooks/deploy.md` instead** — `docker-compose.yml` now exists and starts Postgres, migrations, `serve` and `runner` together. The literal commands below are the manual path: what the 2026-11-30 drill actually ran on `-p 55440:5432`, next to a live desk on 55434 so it could not touch it. Use them when you want a database without the whole stack, or when you are reproducing that drill. ```bash docker run -d --name tapebook-postgres \ -e POSTGRES_PASSWORD=change-me -e POSTGRES_DB=tapebook \ -p 5432:5432 postgres:16-alpine docker exec tapebook-postgres psql -U postgres -d tapebook \ -c "CREATE ROLE tapebook_app LOGIN PASSWORD 'app-password';" export TAPEBOOK_DATABASE_URL="postgresql://postgres:change-me@localhost:5432/tapebook" uv run tape migrate ``` `tape migrate` connects as the **owner** (here `postgres`); the application role exists before the first migration so `0001_ledger.sql` can grant it the append-only privileges. Migrations live in `migrations/` as numbered `.sql` files and are applied in order. They are plain SQL on purpose: read one before you run it. `tape migrate --dry-run` prints what would run. ## Roles Two roles, and the difference is the whole append-only guarantee: | Role | Privileges | Used by | |---|---|---| | owner (e.g. `tapebook`) | owns the tables, can migrate | `tape migrate` only | | `tapebook_app` | `SELECT`, `INSERT` on the ledger tables | the runner, the API | The application cannot `UPDATE` or `DELETE` a booked event. If a code review ever proposes "just fix the row", the answer is a new correcting event, and the database will enforce that. ## Backup ```bash uv run tape backup ./backup-$(date +%F).json ``` A logical JSON export of the **desk**, not just the ledger (ADR-0030). The artefact carries every table the desk writes, under a versioned schema (`schema_version: 2`): | Section | What is in it | |---|---| | `ledger_events`, `ledger_legs` | the book, including rational share quantities (ADR-0025) | | `orders` | every order's status, broker id, filled quantity and fee components | | `sleeve_halts` | what is stopped, since when, by whom, why | | `sleeve_snapshots` | one valuation per sleeve per cycle | | `decisions` | targets, inputs digest, model, token counts, evidence | | `capital_moves`, `capital_move_steps`, `approvals` | money in flight and the decisions that let it move | | `withdrawal_plans`, `withdrawal_days` | approved withdrawals and each day's raised/withdrawn amounts | | `chat_conversations`, `chat_turns`, `chat_tool_calls` | the transcript and the provenance of each answer | | `instruments`, `ohlcv`, `strategy_instances` | the cached master, the candles, and the schedule | | `marketplace_installs`, `marketplace_ratings`, `desk_install_id` | what this desk installed, what it rated and whether that reached the registry, and the id the marketplace counts it by | | `llm_cache` | paid completions, so a restore does not re-buy them | | migrations, counts, `state_hashes` | the schema it came from, per-section row counts, and one ledger digest per currency | It does **not** contain two tables, by decision rather than omission: - `broker_tokens` — a live credential in a file that is copied off the host is a leaked secret. Tokens are minted again by the token service; an expired one is worthless anyway. - `leases` — a claim held by a process that no longer exists. Restoring one delays a runner until its TTL and makes `doctor` report a phantom owner. There is no Redis-style cache in this deployment. `llm_cache` is a Postgres table and *is* included; bars (`ohlcv`) are included too, because they are evidence the decision digest was computed from. **Completeness is checked, not promised.** Before writing the file the exporter compares its table and column list with the database catalogue *and* with the migration lineage. If a migration added a table or a column the exporter does not know, `tape backup` **refuses** — it will not write a file that would silently drop the new evidence. If that happens, teach `app/backup.py::TABLES` about it (or add it to `EXCLUDED_TABLES` with a reason); do not work around it. ### Encryption at rest `tape backup` writes a **sealed** artefact by default (ADR-0040). The whole JSON document is encrypted with `TAPEBOOK_MASTER_KEY` and wrapped in a `v1::` envelope, so the file that leaves the host carries no readable ledger, orders, decisions, transcripts or audit reviews. The plaintext document inside is the same `schema_version: 2` artefact, so the completeness check and the restore comparison are unchanged — encryption wraps the check, it does not weaken it. ```bash export TAPEBOOK_MASTER_KEY=$(openssl rand -hex 32) # once, then keep it in .env at 0600 uv run tape backup ./backup-$(date +%F).json # sealed: v1::... ``` - The key is 32 bytes, hex (64 characters) or base64. It must **not** live in the database, in `.env` inside the backup, or in the repository. Store a copy somewhere other than the disk that holds the backups: losing the key loses every sealed backup. - A missing, short or obviously weak key **refuses the write**. There is no silent plaintext fallback. - `--no-encrypt` writes plaintext and prints the warning that the artefact contains the whole book. Use it only for a scratch copy that never leaves the host. - `tape restore` detects the envelope and decrypts. A wrong key refuses **before** connecting to a database and names the key id; it cannot partially restore. A plaintext artefact still restores, with the same warning. - Old backups need the key they were sealed with. Rotation is in [credential-rotation.md](credential-rotation.md#rotating-the-master-key): add the old key to `TAPEBOOK_MASTER_KEY_PREVIOUS` while you re-seal live rows and re-take backups. The broker token table is sealed the same way (ADR-0040). `tape` reads it transparently; a row written before the change is upgraded in place on its first read, and every write is ciphertext. The key is the same `TAPEBOOK_MASTER_KEY`, so protect it as the broker credential it now is. ### A second key, for a different purpose The master key lives on the host, so the host can open its own artefact. A second, outward-facing envelope is addressed to an **age recipient** whose private key is held offline, and the push step moves the file to a destination the desk does not control: ```bash uv run tape backup ./backup-$(date +%F).json.age \ --url "$OWNER_URL" --encrypt-to "$TAPEBOOK_BACKUP_RECIPIENT" uv run tape backup push ./backup-$(date +%F).json.age --to s3://my-backups/tapebook/ ``` - `--encrypt-to` wraps the sealed `v1:` text in an `age` envelope for a recipient (`age1...`). The host can write it and **cannot** open it; only the offline identity can. The inner envelope stays inside, so the file still needs `TAPEBOOK_MASTER_KEY` as well. - The recipient is public and lives in `.env` as `TAPEBOOK_BACKUP_RECIPIENT`. The identity is generated with `age-keygen` **on another machine** and never copied to the desk. Losing it makes old off-site artefacts unrecoverable; losing `TAPEBOOK_MASTER_KEY` makes the inner payload unreadable; losing both loses the history. - `tape backup push` accepts `s3://bucket/prefix` (rclone), `scp:user@host:/path` (scp) or a local path, prints size and SHA-256, and re-reads the destination where it can. It never deletes the local artefact, and never prints credentials. - If `age` is absent, `--encrypt-to` refuses but still writes the master-key sealed file — with a non-zero exit code saying that file is *not* safe off-host. A missing `rclone`/`scp` refuses the push with the install line instead of succeeding silently. - `tape restore --check .age --identity ` opens the outer envelope first, then the inner one, still before any database connection. The full ceremony (identity generation, the nightly cron/systemd timer, the restore drill with expected output, and the key-loss matrix) is in [backup-offsite.md](backup-offsite.md). Take a backup **before every migration** and after every trading day you care about. It is written to the path you give it, which is on the same disk as the database until you push it. **A backup beside `pgdata` is not a backup**: the failure you are recovering from takes both (GAP-079). ### Prove the backup opens, then prove it restores `tape restore --check` — an alias for `--dry-run` — opens the artefact, unwraps the `v1:` envelope with `TAPEBOOK_MASTER_KEY`, and checks every section's declared count. It connects to nothing: ```bash uv run tape restore --check ./backup-2026-12-01.json ``` A wrong or missing key refuses here and names the key id, before any database is involved. This is the cheap check to run on the file you just wrote; it does not prove the rows land in a schema. That comparison is `tapebook.app.backup.verify`: it creates a throwaway `tapebook_verify_*` schema on the same server, applies the migrations this code ships, restores the artefact, compares every table's rows and the per-currency state hash, then drops the schema. Nothing touches the live schema. It has no CLI wrapper yet, so call it directly (owner role, as `tape migrate`): ```bash uv run python - <<'PY' import asyncio, os import psycopg from tapebook.app.backup import load_artefact, verify async def main(): artefact = load_artefact(open("backup-2026-12-01.json").read()) async with await psycopg.AsyncConnection.connect( os.environ["TAPEBOOK_OWNER_URL"], autocommit=True ) as connection: report = await verify(connection, artefact.backup) print(report.summary()) raise SystemExit(0 if report.ok else 1) asyncio.run(main()) PY ``` It doubles the book's size on that server while it runs, so run it on the desk host or a copy — not on a disk that is already the constraint. `load_artefact` reads `TAPEBOOK_MASTER_KEY` for a sealed file and needs no database; the connection is only opened for the scratch-schema restore. For a whole-database backup before a Postgres upgrade, `pg_dump`/`pg_basebackup` is still the right tool (ADR-0026, GAP-079). That is the physical path for PITR; this is the desk-level restore. ## Restore Restore into an empty, migrated database. Create one rather than dropping the live one: ```bash docker exec tapebook-postgres createdb -U postgres tapebook_restore export RESTORE_URL="postgresql://postgres:change-me@localhost:5432/tapebook_restore" uv run tape migrate --url "$RESTORE_URL" uv run tape restore --dry-run ./backup-2026-12-01.json # validates, prints counts, connects to nothing uv run tape restore ./backup-2026-12-01.json --url "$RESTORE_URL" ``` Restoring over a non-empty database is refused: half-merging two histories is worse than a failed restore. The API override is `restore(..., allow_non_empty=True, operator="NAME")`; both are required, because "who restored over the live book" is asked after the next incident. The CLI does not expose an override yet, so a `tape restore` is always into an empty database. Even with the API override, a primary-key collision aborts the whole transaction; the flag records an intentional decision, it does not make two histories compatible. An artefact with a missing section, an unknown section, or a section whose declared count does not match its rows is refused when it is loaded, not skipped. A restore that skips the table it does not understand is the failure this format exists to prevent. A restore keeps the same `desk_install_id`, so the marketplace counts this desk once; if you restore onto a different desk, say so. Artefacts written in **schema version 1** — the old ledger-only export — are refused with a message naming GAP-080. They have a different section list and carry no orders, halts or snapshots, so accepting one would restore a laundered book. Take a fresh backup; there is no upgrade path that invents the missing evidence. After the restore, run `uv run tape migrate --url "$RESTORE_URL"` and `uv run tape doctor --url "$RESTORE_URL"` (see `recovery.md`, step 3 and 4) before pointing a runner at it. ## Leases One runner drives one sleeve at a time. A lease is a row with an owner and an expiry, so a runner that dies stops renewing and the desk recovers on its own after the TTL. ```bash uv run tape leases ``` | Situation | What you see | What to do | |---|---|---| | Healthy | one owner per sleeve, expiry in the future | nothing | | A runner is stuck | you keep seeing the same owner across cycles while it is idle | wait for the TTL, or `DELETE FROM leases WHERE name = ''` if you know it is dead | | Two owners, same sleeve | should be impossible; acquisition is atomic | stop the runner you trust least and record it — this is a bug, not an operator error | Set the TTL to a few times the expected cycle duration. Too short and a slow cycle is taken over while it is still working; too long and a crashed runner blocks the sleeve. ## The schedule ```bash uv run tape instances ``` Each row is a strategy instance: an id, the strategy it runs, its cadence, when it is next due, and whether it is enabled. Claiming is one statement — take the earliest due row with `FOR UPDATE SKIP LOCKED` and push `next_run_at` forward — so two runners take different work instead of one waiting for the other. A claim with no registered action is an error, not a skip: the claim has already advanced `next_run_at`, so quietly continuing would lose the run. If you see that, the runner's action map is missing an instance. ## Halts A sleeve that halts stays halted. It stops before authenticating, so it neither trades nor re-halts, and `tape halts` is the only place that state lives outside the database. ```bash uv run tape halts # what is stopped, since when, and why uv run tape halts --clear momentum --by ops ``` Clearing is an operator action with a name attached, because "who decided this was fine" is the question asked after the next incident. Do not clear a halt until the disagreement is actually resolved — the halt is the message. ## If the book and the broker disagree The cycle halts on drift; it does not trade through it. The full procedure, with the drill's actual outputs, is `reconciliation-mismatch.md`. The short version: 1. Do not restart the runner to "clear" the halt. 2. `uv run tape positions ` is the book; `uv run tape reconcile --broker SYMBOL:QTY` compares it against the broker's own statement. 3. If the broker is right and the book is wrong, append a correcting event with `tape adopt` (outside shares, into `UNMANAGED`) or `tape adjust` (a sleeve quantity change) — never update history. 4. Record what happened in the gap ledger if the cause was a defect, then clear the halt.