# Backup and restore

> What can be recovered in a self-hosted cairnflow, and how to use cairn-ctl to verify, back up, restore and recover from the trash.

Source: https://cairnflow.dev/docs/self-hosting/backup-restore

## What can be recovered

| You lost | Where it is | How to get it back |
|---|---|---|
| A finished invocation that was purged | The archive, under `archive/<tenant>/<date>/` | Read it with `GET /archive/{id}` (journal and final state). It is not restored as a live invocation. |
| Data that cairnflow deleted itself: retired range data, ownership records, write-ahead logs of dead nodes | The trash, for `--trash-keep-s` (default 7 days) | `cairn-ctl trash restore` |
| The range table, deleted from outside cairnflow | History copies of the table kept in the bucket | `cairn-ctl table restore`, see [Rebuilding the range table](#rebuilding-the-range-table) |
| A tenant marked for deletion | Held in place for `--tenant-purge-keep-s` (default 7 days) | Set the tenant's state back to `active` before the hold ends |
| The whole bucket | A backup at another provider | `cairn-ctl restore` |
| Low-level storage deletions that do not use the trash | Only in bucket versioning, if enabled | Your store's version history |

Purging an invocation by hand (`POST /invocations/{id}/purge`) or by retention removes it from the
live data; it is not undoable beyond reading the archive. Archiving is on unless you run with
`--no-archive`.

## cairn-ctl

`cairn-ctl` reads and writes the bucket directly. No node needs to be running, but it needs the
bucket credentials (the same `AWS_*` environment as the nodes), so it is a separate binary: do not
hand it to people who only need an API key. Point it at the bucket exactly like a node:

```sh
cairn-ctl --main-store s3://bucket/prod verify
cairn-ctl --data-dir ./data table show
```

Commands that change something run **dry** by default: they print the before and after and write
nothing. Add `--apply` to write. Each applied change leaves an audit record in the bucket with who
ran it (`--who`, default `$USER@$HOST`), the command, and the before and after.

Exit codes: `0` done (or `verify` clean), `1` `verify` found problems, `2` bad arguments,
`3` refused, `4` store error. `--json` prints machine-readable output.

Use a `cairn-ctl` with the same `knows=` as your nodes (`cairn-ctl --version`).

## Verify

```sh
cairn-ctl --main-store s3://bucket/prod verify
```

`verify` only reads. It checks that the range table covers the whole key space, that every range
in the table has data that opens, that references between ranges point to data that exists, that
no range directory is orphaned, and that no split or merge has been stuck for more than 100 seconds.
By default it also looks for cross-range calls that lost a message. It exits with `1` when it finds
a problem.

`verify --deep` also checks that every sorted file named by the current manifest and live
checkpoints of each live range is still in the bucket (finding `sst_missing`). It costs one listing
per range and is not part of the background check, so run it on a schedule: it finds a file deleted
from outside cairnflow before a read does.

Other read-only commands: `table show` (range table), `owners` (ownership record of every range and
whether its session is alive), `ranges retired`, `range dump <id>` (raw rows of a range), `wal
floors`, `trash list`, `cluster status`.

## Backups

A backup copies the cluster to another store, ideally at **another provider**, so that losing the
source account does not take the backups with it.

```sh
cairn-ctl --main-store s3://source-bucket/prod backup --to s3://backup-bucket/prod
cairn-ctl --main-store s3://source-bucket/prod backup list --to s3://backup-bucket/prod
```

A backup:

1. places a guard against garbage collection on the source and checkpoints every range in the
   range table. The guard lasts 10 minutes and the command renews it every 2 minutes, so a backup
   that is killed stops holding back garbage collection within 10 minutes. If renewals keep failing
   until the guard may have expired, the command fails instead of finishing an incomplete copy;
2. copies every object those checkpoints reference, plus the cluster's own objects, 16 at a time.
   Temporary checkpoints of the source (the compactor's, readers', other backups') are not copied
   and are removed from the copy;
3. writes a manifest with the size and SHA-256 of every object **last**;
4. removes its checkpoints and the guard.

A backup without its manifest is incomplete: `restore` ignores it and `backup list` marks it. The
source is not modified, apart from an audit record.

The whole run uses one snapshot of the range table. If a split or merge commits while the backup
runs, the run is abandoned and started again with a new id, at most three times; after that the
command fails, and you run it again when splitting is quiet.

Not included: the cluster secret, the bootstrap key and the identity master secret (keep them in
your secret store), and per-node runtime state such as sessions and node write-ahead logs.

Remove old backups on a schedule. The command runs dry first:

```sh
cairn-ctl --main-store s3://source-bucket/prod backup prune --to s3://backup-bucket/prod \
  --keep-daily 7 --keep-weekly 4
cairn-ctl --main-store s3://source-bucket/prod backup prune --to s3://backup-bucket/prod \
  --keep-daily 7 --keep-weekly 4 --apply
```

Incomplete backups older than 24 hours are removed too.

### Credentials for a backup store at another provider

`--backup-env-prefix P` builds the backup store's client **only** from variables named `P` +
`AWS_*`, while `--main-store` keeps using `AWS_*`:

```sh
# source, as for the nodes
export AWS_ENDPOINT_URL_S3=https://source.example.com AWS_REGION=auto \
       AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=...
# backup store, its own set
export CAIRN_BACKUP_AWS_ENDPOINT=https://backup.example.com \
       CAIRN_BACKUP_AWS_REGION=auto \
       CAIRN_BACKUP_AWS_ACCESS_KEY_ID=... CAIRN_BACKUP_AWS_SECRET_ACCESS_KEY=...
cairn-ctl --main-store s3://source-bucket/prod --backup-env-prefix CAIRN_BACKUP_ \
  backup --to s3://backup-bucket/prod
```

The access key and secret are required; an unknown `P...AWS_<X>` variable is an error. With wrong
backup credentials the command fails at its first listing, before touching the source. Pass
secrets only through the environment: the command line is recorded in the audit record. A backup
destination with the same bucket and prefix as the source is refused.

### Limits

- **Each range contributes what had reached its sorted files.** Commits still only in the
  write-ahead log at backup time are not included. Idle ranges flush after `--wal-age-flush-ms`
  (default 60 s), so each range lags the backup time by at most about that.
- **Recovery point** = time between backups + up to about 60 seconds per range.
- **Ranges are not cut at one instant.** Under load, a call between two ranges that was in flight
  during that window can lose its request or its reply; the caller then waits forever.
  `backup check-restore` finds these cases (see below).
- Clusters with a separate `--wal-store` are not supported by backup yet.

## Restoring a cluster

1. **Create a new, empty bucket.** The new `--main-store` must use the **same prefix** as the
   source (`prod` in the examples). `restore` refuses a different prefix and says why.
2. **Copy the backup back:**

   ```sh
   cairn-ctl --main-store s3://new-bucket/prod restore --from s3://backup-bucket/prod
   ```

   Without `--id`, the newest complete backup is used; pick another with `--id <id>` from
   `backup list`. Objects are copied 16 at a time, every object's size and SHA-256 are checked, and
   the marker that makes the bucket openable is written last, so nodes refuse a half-restored
   bucket. If the restore fails midway, empty the destination and run it again. With a backup store
   at another provider, add the same `--backup-env-prefix` as for `backup`.

   `restore` refuses, before writing anything, a backup whose range table lists a range with an
   ownership record but no data in the backup (possible with backups taken during a split by older
   binaries): restoring it would open that range empty. Choose another backup.
3. **Check, before starting any node:**

   ```sh
   cairn-ctl --main-store s3://new-bucket/prod backup check-restore
   ```

   Continue only on exit code `0`, or when the only findings are lost cross-range messages
   (`restore.lost_call`, `restore.lost_reply`), which name the caller and the callee. For any other
   finding, choose another backup.
4. **Start the nodes** on the new bucket, with the cluster secret and bootstrap key from your secret
   store.
5. **Handle the reported calls.** For each caller, either restart it from just before the call,
   `POST /invocations/{id}/restart?from=<index of the Call entry>`, which replays earlier
   `ctx.run` results and sends the call again (the callee may then run a second time, so use this
   only when that is safe), or cancel it with `POST /invocations/{id}/cancel` and settle the
   business side by hand.
6. **Delete again** any tenant you deleted after the backup was taken: restoring an older backup
   brings it back.
7. Point clients at the new cluster. Stop the old cluster completely: two clusters taking the same
   work run it twice.

Rehearse this on a scratch bucket before you need it.

## Recovering from the trash

Cairnflow does not delete its own data directly. Retired range data, the leftovers of a rolled-back
split or merge, and the logs of dead nodes are **moved** to a trash area in the bucket. One node
deletes a trash entry for good only once it is older than `--trash-keep-s` **and** a fresh check
shows nothing needs it; when in doubt it keeps the entry.

```sh
cairn-ctl --main-store s3://bucket/prod trash list
```

Before restoring, stop anything that could clean up again: stop the cluster if you can, or restart
the nodes with `--retire-orphans-every-s 0 --reconcile-intents-every-s 0 --trash-keep-s 0` and
without `--gc-retired-dbs`. Then:

```sh
cairn-ctl --main-store s3://bucket/prod trash restore --range 7            # dry run
cairn-ctl --main-store s3://bucket/prod trash restore --range 7 --apply    # data and owner record of range 7
cairn-ctl --main-store s3://bucket/prod trash restore <entry-id> --apply   # one entry by id
cairn-ctl --main-store s3://bucket/prod verify
```

Restoring copies objects back with "create only if absent", so it **never overwrites** anything; a
conflicting object is reported and the entry is kept. It refuses (exit code `3`) when the range
already has data in place. Restoring brings objects back but does not change the range table.

An entry you had to restore means a deletion was wrong. Keep the `trash list --json` output and the
node logs, and report it.

## Rebuilding the range table

After every change to the range table, nodes write a history copy of the new table to the bucket
and keep the 16 newest. If the range table object is deleted from outside cairnflow (an operator, a
lifecycle rule), `table restore` rebuilds it from the newest copy, **only** when the rest of the
bucket proves that copy is the last table: no ownership record, range directory or operation record
carries a newer range id, every live range of that table has an ownership record without a
tombstone, and the operation records agree. Otherwise it refuses and prints the mismatches.

```sh
cairn-ctl --main-store s3://bucket/prod table restore            # dry run
cairn-ctl --main-store s3://bucket/prod table restore --apply
```

The table is written only if absent. `--apply` refuses while any node session is still live: stop
every node first, and add `--force` only once you are sure they are all stopped.

## Reports for automation

`--report-to-bucket <id>` on `backup`, `backup list`, `backup prune`, `restore`, `cluster status`,
`cluster enable-*` and `table restore` also writes the command's JSON result to the cluster's bucket,
with the command name, exit code, `cairn-ctl` version and timings, even when the command fails. It
carries no secrets. A service holding a `provision` key reads it with
`GET /admin/ops-reports/<id>` (or lists them with `GET /admin/ops-reports`), so it can run
`cairn-ctl` as a one-off job without ever holding bucket credentials itself.

The id is yours to choose and must be new each time: 1 to 128 characters from `A-Z a-z 0-9 - _ .`,
starting with a letter or digit. An id that already has a report makes the command refuse (exit
code `3`) without running. The 256 newest reports are kept, and reports more than 30 days older than
the newest are removed.

## Investigating on a copy

`cairn-ctl fork --to <prefix>` makes a copy of the cluster under another prefix **in the same
bucket**, from a checkpoint, without stopping the cluster. Start a node with
`--main-store s3://bucket/<prefix>` to investigate on real data without touching it. The copy
shares sorted files with the source; the fork places a 24-hour guard against garbage collection on
the source for the data it relies on. Ranges contribute only what had reached their sorted files.
