Referencia · §8.30

Backups and subjects' keys

backup, subject_keys, §M14.24 R6

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

BACKUP [FULL] TO 'repo' [KEEP n] (an administrator’s; not in a transaction block, 25001; an absolute path on the server or a URL of a module’s object store, else 22023) writes the database as one snapshot sees it, while others go on writing, into a repository of backups: a new or empty directory, or one BACKUP wrote (anything else in it — a backup of the format before repositories, a stray file — 22023). Each backup is a directory of the repository, 000001-full, 000002-incr, … numbered in order: a full one holds all of the database, an incremental one what changed since the backup before it — the entries written or changed and the keys deleted. BACKUP TO makes an incremental one when it can (the repository’s last backup finished, of the same branch, its kept branch still there and unchanged), else a full one; FULL always a full one, starting a new chain. It returns commit (the snapshot: AS OF COMMIT it reads the same), entries, sealed, omitted, bytes (the parts’, compressed), deleted, kind (full, incremental), backup (its directory) and removed (the older backups KEEP removed).

The snapshot is a branch (§8.26, Kv::create_branch: a checkpoint, then a copy in constant time) named nc-backup-<repository hash>-<number>, read and then kept: the next backup of the repository makes its own, compares the two (Kv::changed_since), and drops the old one. The comparison walks the new branch’s B-tree and skips each subtree whose root page was born by the old branch’s origin (a copy-on-write tree never points to a younger page), then walks the old tree and skips the subtrees it reaches at the same page between the same separators; the leaves left give key ranges, and only there are the two snapshots read side by side — a value differing written, a key gone written as a delete (BTree::diff_ranges, Engine::changed_since; ZFS’s send and btrfs’s compare two snapshots’ trees the same way). It is exact for any two trees of the file and costs what changed plus the pages read to learn their births (a changed leaf’s siblings). Where the two differ in what decides visibility beyond a key’s versions — a spilled transaction’s writes or status, a running transaction’s unlogged ranges (§5.2) — it gives no ranges, and every key is compared (the backup is still only what changed). A kept branch holds on to the pages it shares, as a snapshot does: the data file keeps what was overwritten since the last backup. FORGET SUBJECT drops every kept branch before its scrub (what they share is what the erasure removes): the next backups are full. Branches named nc-backup-… are the backups’; they are listed with the others, and one kept for a backup of a branch other than the main one is that branch’s child — DROP BRANCH of it waits for DROP BRANCH nc-backup-… (its next backup is then a full one).

Where a repository is (backup::Target, §M14.18 O3b): files named by paths within it (000001-full/part-000000), each written whole and seen only whole — list(dir), get, put, delete. Built in: a directory of the database’s file system (each file written as .tmp, synced, renamed, the directory synced). A module registers a URL scheme (register_target, ext::backups): modules/s3 (nucleus-s3) keeps a repository at s3://bucket/prefix — AWS S3, MinIO, R2, B2 —, each request signed with Signature Version 4 (sign, checked against the examples of AWS’s documentation), configured by the AWS SDKs’ variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION, AWS_ENDPOINT_URL[_S3]: another store, addressed by path), one PUT an object (no multipart: a part is about 16 MiB), retried three times on a network error or HTTP 500/503. A scheme no module serves: 0A000.

It is the store’s entries less what is derived from them: every secondary index’s (a B-tree’s, HNSW’s, a text or sparse index’s — table.indexes’ ids under the table’s prefix) and ANALYZE‘s samples (00 04); the catalog, roles, grants, policies, models and their files, secrets (sealed already, §8.24), the audit log, the erasure records, the embedding queue and the column store’s segments travel as they are. Files (through the database’s file system, Kv::files): parts part-000000, … of about 16 MiB, each a sequence of entries — 0 key, value; 1 a sealed one: the row’s table id (or none), its keys’ ids, a nonce, the sealed key and value; 2 an audit record: key, the record with its detail blank, keys’ ids, nonce, the sealed detail; 3 a key deleted; 4 a key of a row of subjects deleted, sealed under the keys of its subjects as the backup before saw them (a subject forgotten since: left out, its rows’ entries are too) — and a manifest written last (manifest.tmp, synced, renamed, the directory synced): nucleus backup 2, the kind, the backup an incremental one follows (base), the branch kept, the branch backed up, the commit, the time, the counts, the tables that had statistics, compression lz4-block, and each part’s length and SHA-256 as stored. No manifest, no backup (a directory without one is skipped, its number not reused).

Compression and encryption (§M14.18 O3c). A part is stored as its entries’ length (u32) and them compressed in LZ4’s block format (the storage’s own compressor, nucleus_kv::lz, §M14.20 V5): about a third of the bytes on rows of text, and faster to write and read than the bytes it saves (docs/benchmarks.md). With a backup key — 32 bytes, nucleus server --backup-key FILE (or NUCLEUS_BACKUP_KEY_FILE; nucleus sql <dir> and nucleus restore read the same), the file holding 64 hexadecimal digits (openssl rand -hex 32), backup::set_backup_key in an application — each part is then sealed by ChaCha20-Poly1305 under it, its nonce (a random base a backup, counted up) first and its path in the repository (000002-incr/ part-000000) authenticated with it, and the manifest names the key by its id (encryption chacha20-poly1305 <id>: SHA-256 of nucleus backup key and the key, its first 8 bytes) and ends with mac, HMAC-SHA-256 under the key of all before it: the parts’ hashes are in it, so the whole backup is authenticated. Nothing of the database is then in the repository in the clear, whatever store keeps it. A restore with no key refuses an encrypted backup, with another key refuses it by id, and with a key refuses an unencrypted one — whoever can write to the repository could otherwise slip one in (22023); a manifest altered, its MAC not matching: 22000; a part that does not decrypt or decompress: 22000. A backup continues a chain only made with the same key (or both without): a new key starts a new chain. The key must be kept apart from the repository — lost, its backups are; the subjects’ sealing (below) is independent of it.

Under the key hierarchy (§M14.30 K1c). Without --backup-key, a backup is encrypted with the hierarchy’s data key backup (made at the first backup) when the owner’s --encrypt-backups says so — by default when the root key was given explicitly (--root-key, a variable, a passphrase, a KMS), or once the keyring holds a backup key; not with the database-managed root alone, which a lost disk takes with it. A --backup-key given is taken into the keyring as that data key (the user’s file, never removed), so the backups made without it later go on with the same key and chain. The manifest then carries the data keys wrapped by the root — key backup <root id> <wrapped> and the secrets’ key secrets …, and key subjects …, the key the subject keys’ table is sealed with (never the subject keys themselves: FORGET must reach every backup) — under its MAC, so the root alone restores it: nucleus restore <repo> <dir> --root-key FILE (or the other root options) unwraps the backup’s key, refuses another root naming both ids, and takes the wrapped keys into <dir>.keyring before it restores — so the sealed table --subject-keys names opens, and the restored database its secrets, with that root (backup::carried_keys; the backup’s --backup-key still opens it as before). While backups are encrypted, an unencrypted backup is refused as with a key set (--encrypt-backups no restores it).

Retention and schedule (§M14.18 O3c). KEEP n (backup::prune) removes, once the backup is made, the repository’s backups older than its last n full ones — whole chains, oldest first, each backup’s manifest before its parts (a removal cut short leaves no half backup: it is skipped as unfinished), a directory left empty removed (FileSystem::remove_dir). nucleus server --backup-to <repository> --backup-every <duration> [--backup-full-every <n>] [--backup-keep <n>] (nucleus_server::backups::start) backs up on a thread of its own: at the start if the repository’s last backup is older than the interval, then each interval after the last; every n-th backup a full one (default 7: with 1d, a weekly full one and daily incremental ones), a failed one tried again within five minutes, each logged. Every backup — BACKUP or scheduled — is counted in the metrics: nucleus_backups_total, nucleus_backup_failures_total, nucleus_backup_failing (1 while the last failed), nucleus_backup_last_success_timestamp_seconds (the schedule reads the repository’s last at its start), nucleus_backup_last_bytes, nucleus_backup_duration_seconds, and the schedule’s nucleus_backup_interval_seconds — the alerts NucleusBackupOverdue and NucleusBackupFailing (§8.39) watch them.

Restore tests (§M14.18 O4). A backup is good when it restores: backup::restore_test(kv, scratch, registry, repo) restores the repository’s last backup (its chain) into scratch, a new database, and checks what it made as the crash tests check a recovery — check::check (catalog, rows and indexes agree, every foreign key holds, no stray keys) and audit::check (the audit chain holds); a restore that fails (a part missing, its SHA-256 differing, a manifest’s MAC, a part that does not decrypt or decompress) is a problem found too. The result, Tested (backup, restored, problems), is left in the backup as restore-test (when, the commit, result ok or failed, the problems), in the database’s audit log (kind restore test, ok, the backup and the problems as its detail; not when the database tested is the scratch one, as nucleus restore --test‘s) and counted: nucleus_restore_tests_total, nucleus_restore_test_failures_total, nucleus_restore_test_failing, nucleus_restore_test_last_success_timestamp_seconds, nucleus_restore_test_duration_seconds, nucleus_restore_test_interval_seconds. nucleus server --restore-test-every <duration> [--restore-test-dir <dir>] (with --backup-to; nucleus_server::backups::start_restore_tests) runs one an interval after the repository’s last (last_restore_test reads the last 50 backups’ records), in <dir>.restore-test by default — a directory of its own, marked .nucleus-restore-test (one holding anything else is refused: its files are never thrown away), the database restored in its db and removed after; room for a copy of the database is needed there while it runs. nucleus restore <repository> --test runs one by hand, in the temporary directory (exit status 1 and the problems when it fails). The alerts NucleusRestoreTestFailing and NucleusRestoreTestOverdue watch them.

What is sealed. An entry about a subject (§8.29): a row of a table with subject columns (a partition’s are its parent’s) whose subject columns are not all NULL, and — with the subjects of the row it references — a row of a table referencing one by a key that does not set itself to NULL or a default when it goes (CASCADE, RESTRICT, NO ACTION: what FORGET deletes with it, or what would stop it), transitively, referenced tables first (a self-reference is not followed); for each such row also its values stored out of line (LARGE_INDEX), its embedding jobs (00 17) and next model’s vectors (00 18). A row’s subjects are its subject columns’ values cast to text, as FORGET names them; the entry is sealed by ChaCha20-Poly1305 under SHA-256 of the subjects’ keys in id order (forgetting any one of them makes it unreadable, as it deletes the row), its kind, table and keys’ ids as associated data; nonces are a random base a backup, counted up. An audit record of version 2 whose detail holds, as a literal, a subject’s text or the head of a text of a subject’s rows (8 bytes or more, FORGET’s rule) has its detail sealed and its fields in the clear. A table with rows of subjects stored as columns (column, row, column: a segment mixes subjects) is refused (0A000); a database with subject columns and no store of keys is refused (55000): its backups could not be forgotten.

Subjects’ keys (subject_keys::SubjectKeys, set for the process by set_subject_keys). A subject’s id is HMAC-SHA256 of its text under a pepper kept with the keys — a backup shows neither whose rows it holds nor, by guessing names, whether someone’s are there. Each subject has a 32-byte random key under a 16-byte random key id, which a backup names it by; BACKUP makes the missing ones before it writes. FORGET SUBJECT destroys, after its commit, the keys of the subject as text in each subject column’s type, and marks each with its commit: a backup whose snapshot is older (begun before, still running) gets no new key for it and leaves those entries out (omitted), one taken after gets a new key, under a new id, for the subject’s new rows — the old backups still name the old one. The server’s store is nucleus_server::subject_keyfile::SubjectKeyFile: nucleus server --subject-keys FILE, by default <dir>.subject-keys beside the data directory (nucleus sql <dir> and nucleus mcp <dir> use it too), made with mode 0600 when first needed, a table (nucleus subject keys 1, pepper …, k id key-id key, d id commit) rewritten — new file, synced, renamed, the directory synced — before each change returns. Sealed (§M14.30 K1d): on disk the table is nucleus subject keys sealed 1 and, in hex, a random nonce and the table sealed by ChaCha20-Poly1305 under the key hierarchy’s data key subjects — a copy of the file alone opens nothing. A table in the clear (before the hierarchy) is sealed at the next start, rewritten in place so no copy in the clear stays (a kept copy would keep the keys FORGET destroys); with --old-key-files keep or manual it stays in the clear, warned of at every start, until nucleus keys <dir> import. It must be kept, and backed up, apart from the data and its backups; restoring it needs the root that wraps subjects too (a backup carries that key wrapped, so the root and the file suffice). subject_keys::MemoryKeys keeps them in memory (tests, an application holding its own). The old file’s blocks may remain on the disk until overwritten; a key management service is a module’s to add.

Restore (backup::restore_to(kv, registry, repo, until); nucleus restore <repository | s3://…> <dir> [--at <commit|backup|time>] [--subject-keys FILE] [--backup-key FILE], keys by default <dir>.subject-keys) makes a new database (one holding data: 55000) of the repository’s last backup — or, by --at, the last of commit n or before, the one in directory 000003-incr, or the last made by a time ('2026-11-15 14:05:00+01'; UTC without a zone) —, from a directory or a module’s store: that backup’s full one and the incremental ones after it, each following the one before (one missing or unfinished: 22000). A directory holding a manifest of its own (a backup of the format before repositories, nucleus backup 1) is restored by itself. Each manifest is checked against the backup key (above); each part against its length and SHA-256 (22000), then decrypted and decompressed, and the entries each backup’s parts hold against its manifest’s count (entries and deleted; 22000); the entries are written in transactions of about 4 MiB, backup after backup — a sealed one opened with its keys (one that does not open: 22000, the backup changed or another database’s keys), left out when one of them is destroyed (omitted), an audit detail then blanked with erasure u64::MAX (KEY_DESTROYED; the chain still holds, §9), a delete applied (deleted) —; then every index rebuilt from the rows (dml::backfill_index), the keys of tables referencing rows left out by SET NULL / SET DEFAULT set so (nulled), and the tables the last backup had statistics of analyzed again. It returns Restored (commit, backups, entries, opened, deleted, omitted, blanked, indexes, nulled). A restore that fails removes the directory nucleus restore made.

The time a restore reaches is a backup’s: point-in-time restore is as fine as the backups are frequent — incremental ones cost what changed, so they can be taken often. Not the WAL archived: the log holds every entry in the clear, and a subject’s rows in an archived log could not be forgotten (§M14.24), while a backup’s are sealed. Tests: tests/backup.rs (a restore is the database as the backup saw it, its indexes used; a backup holds no subject’s value in the clear; a restore after FORGET leaves the subject out, the audit chain intact, a later backup’s new rows of the subject restored; incremental backups — after the database is opened again too — restored to each point, a subject’s row’s delete sealed, FORGET dropping the kept branch; an encrypted backup needing its key, refusing another, an altered manifest and an unencrypted backup, a new key starting a new chain; KEEP removing the older chains, the metrics counting backups and failures; a restore test catching a part’s byte flipped, a part cut short behind a manifest made to match and a manifest’s count of entries altered, holding again once mended, each in the audit log), storage tests/branch.rs (the ranges two branches differ in hold every difference, a base written since too), kv tests/contract.rs (changed_since holds every change: deletes of runs, a transaction running across the branch point, spilled ones), the CLI’s backups_restored_to_a_point and scheduled_encrypted_backups (a server backing up each second, a full one every second backup, one chain kept, nothing of the rows in the clear, the metrics, nucleus restore with and without the key) and scheduled_restore_tests_catch_a_corrupted_backup (a server’s restore tests failing once a part’s byte is flipped, the metrics, nucleus restore --test); modules/s3 (the signature examples; a stand-in store checking every signature, listing in pages, a full and an incremental backup restored from it) and scripts/s3-test.sh, CI’s backups in object storage (S3), against rclone’s real S3 server.