Referencia · §9

Server

nucleus-server

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

nucleus server <dir> [--listen <addr:port>] [--socket <path>] [--pg-compat [<addr:port>]]
                     [--mongo-compat [<addr:port>]] [--console [<addr:port>]] [--web [<addr:port>]]
                     [--front-end <name> [<addr:port>]]
                     [--metrics [<addr:port>]] [--otlp <endpoint>]
                     [--user <name>] [--password <pw>] [--no-auth] [--log-queries]
                     [--sync ordered|full] [--wal minimal|full] [--cache <size>]
                     [--index-cache <size>] [--secrets-key <file>]
                     [--subject-keys <file>] [--history <duration>]
                     [--root-key <file> | --root-key-env <var> |
                      --root-passphrase-env <var>] [--old-key-files remove|keep|manual]
                     [--encrypt-backups yes|no]
                     [--backup-key <file>] [--backup-to <repository>
                      --backup-every <duration> [--backup-full-every <n>]
                      [--backup-keep <n>] [--restore-test-every <duration>
                      [--restore-test-dir <dir>]]]

--subject-keys names the file of subjects’ keys (§8.30; default <dir>.subject-keys). --backup-key the file of the key backups are encrypted with (or NUCLEUS_BACKUP_KEY_FILE); --backup-to and --backup-every back up on a schedule, every --backup-full-every-th backup (default 7) a full one, the last --backup-keep full ones kept; --restore-test-every restores the last backup and checks it, in --restore-test-dir (default <dir>.restore-test) (§8.30).

--metrics serves Prometheus’s GET /metrics and the health checks /health/live, /health/ready (default 127.0.0.1:20037), --otlp pushes the metrics to an OpenTelemetry collector (§8.38).

Stopping (issue #17; modules/signals). SIGTERM — what docker stop, systemd, launchd and Kubernetes send —, SIGINT (Ctrl-C) and SIGHUP stop the server as PostgreSQL’s fast shutdown does: not ready any more (/health/ready 503); every statement refused and the running ones stopped where they look at their deadline (57P01, nucleus_sql::budget::stop_all), so a transaction left open never commits; the commits under way waited for (2 s at most); a checkpoint; exit code 0 (nucleus: stopped: checkpoint taken in … ms). The next start replays nothing. A second request ends the process at once (exit code 130). Without a checkpoint — kill -9, a crash, a failed one — nothing committed is lost either (every acknowledged commit is in the WAL); the next start replays it and says so (nucleus: recovered: N batch(es) of the WAL replayed in … s, Database::replayed). In the container image nucleus is PID 1, which the kernel sends no signal without a handler: before, docker stop waited its 10 s and killed it. Measured: six sessions committing, one in a long join and one with an open transaction — stopped in 0.15 s (the checkpoint 0.14 s), the restart replaying nothing; after kill -9 the same load replayed 39,726 batches.

--history keeps every snapshot of that long ago readable — 7d, 12h, 90min, '30 minutes' (the units of statement_timeout) — for AS OF TIMESTAMP (§8.7): each commit records its time, and the vacuum keeps old versions that long (nucleus_kv::Options::history_time). None by default; nc_catalog.history shows how far back it reaches (times since the server ran with it).

--cache sizes the page cache (default 128MB; units as work_mem‘s: kB, MB, GB) — PostgreSQL’s shared_buffers. --index-cache sizes the decoded index objects kept across transactions (object_cache: HNSW graphs’ parts, text segments) — an index past it is decoded again each time it is read. By default it is a quarter of the memory the process may use (real::physical_memory; 1 GB where the OS does not say) — PostgreSQL’s advice for shared_buffers, DuckDB’s memory_limit sized by the machine too; a bound, not memory taken. The server’s first line names it (index cache 8192 MB). --sync sets how far commits and checkpoints sync (§3.2, D17): ordered (the default) or full, which also flushes the drive’s cache (on macOS). --wal (D16): minimal (the default) writes a new index’s entries without the WAL and checkpoints at its commit; full logs every write. Both front ends read and write through 64 KiB buffers.

The server speaks the nucleus protocol (§10, nucleus_server::serve) on --listen (default 127.0.0.1:20035), and with --socket <path> on a Unix socket too (nucleus_server::serve_local, PLAN.md §M14.33 R2): a client on the same machine skips loopback TCP — a round trip 4.4 µs against 16.0 on macOS. No TLS there and no client address; the login as on TCP. A socket file a stopped server left is replaced; one a server answers on is refused. A client reaches it by its path as the host — nucleus sql -h /tmp/nucleus.sock, nucleus_client::Config { host: "/tmp/nucleus.sock".into(), .. } — as libpq takes a directory. Who logs in is the database’s roles (roles.rs, §M14.25): CREATE ROLE / CREATE USER (a role with LOGIN) [WITH] SUPERUSER | LOGIN | INHERIT | CREATEROLE | CONNECTION LIMIT n | PASSWORD 'p' | VALID UNTIL 't' | IN ROLE r, … (and their NO… forms), ALTER ROLE … options | RENAME TO, DROP ROLE [IF EXISTS] (refused while it owns a table, 2BP01, or is the session’s, 55006), GRANT role TO role [WITH ADMIN OPTION] (a cycle is 0LP01), REVOKE [ADMIN OPTION FOR] role FROM role, SET ROLE r / RESET ROLE. Passwords are kept as SCRAM-SHA-256 verifiers (nucleus-crypto: SHA-256, HMAC, PBKDF2, 4096 iterations), never in clear. A password sent in clear (HTTP’s Basic, PLAIN, PostgreSQL’s cleartext method) that matched a verifier is known again without the key derivation — ScramVerifier::matches keeps the verifier’s StoredKey and HMAC(ServerKey, password), never the password, for the last 256 matches; a changed password is another verifier, and the role’s LOGIN and VALID UNTIL are asked each time. Over HTTP, where each request logs in, the derivation was nearly all of a request’s cost (5.3 ms of it). An administrator (SUPERUSER) may do everything; CREATEROLE manages roles other than administrators, and a role it makes is administered by its maker; a role may change its own password; anyone else gets 42501. current_user is the role a statement runs as, session_user the one that logged in (access::with_who, as now()’s time); a table’s owner is its maker (nc_catalog.tables.owner, table record version 7).

Privileges (privileges.rs): GRANT privilege [(columns)], … | ALL ON [TABLE] t, … | ALL TABLES IN SCHEMA public | SCHEMA s | FUNCTION f [(args)] | TYPE t | DATABASE nucleus TO role | PUBLIC, … [WITH GRANT OPTION], REVOKE [GRANT OPTION FOR] … FROM … (on a table also from its columns), ALTER DEFAULT PRIVILEGES [FOR ROLE r] [IN SCHEMA public] GRANT | REVOKE … ON TABLES …. Each object has an ACL — written out on its first GRANT or REVOKE, until then its kind’s default: the owner has everything; PUBLIC may EXECUTE functions, use types and schema public, and CONNECT to the database; nothing else (so making a table or a type needs CREATE on schema public, as in PostgreSQL 15). Administrators and owners are never refused; privileges come through inherited roles and PUBLIC. A user’s statement is bound with checks (Binder::checked): reading a table needs SELECT on it or on some column, and every column read — in the select list, *, WHERE, joins, RETURNING, an UPDATE’s expressions — SELECT on it; INSERT on the columns written, UPDATE on those set, DELETE on the table; EXECUTE on each function and aggregate called (internal binding — constraints, defaults, mappings — checks nothing). DDL is checked before it runs (authorize_ddl): changing, dropping or indexing a table, or altering or dropping a type, is its owner’s; a foreign key needs REFERENCES on the columns it references; a column’s registered or enum type needs USAGE. A login needs CONNECT. Granting needs the owner’s rights or the grant option (else 42501 — where PostgreSQL warns that nothing was granted). A refusal is 42501 naming the privilege and the object (permission denied: SELECT on column salary of table pay), never a value; EXPLAIN is checked as the statement is. Dropping a role is refused while it holds privileges. crates/testkit/slt/31_privileges.slt was checked against PostgreSQL 18 in one session (as another role too).

Row-level security (policies.rs): ALTER TABLE t ENABLE | DISABLE ROW LEVEL SECURITY, … [NO] FORCE ROW LEVEL SECURITY, CREATE POLICY p ON t [AS PERMISSIVE | RESTRICTIVE] [FOR ALL | SELECT | INSERT | UPDATE | DELETE] [TO roles | PUBLIC] [USING (cond)] [WITH CHECK (cond)], DROP POLICY [IF EXISTS] p ON t (the table owner’s). On a table with it, for a role that is neither an administrator nor — unless forced — the owner, a command touches only rows passing (its permissive USING conditions, OR-ed) AND (its restrictive ones) — no permissive policy, no row — and new rows (INSERT, UPDATE’s result) must pass the WITH CHECK ones (or USING where none is given), else 42501 “new row violates row-level security policy”. Conditions see the row and the session: current_user, current_setting('nucleus.tenant') (SET name = value, dotted names allowed, RESET name | ALL; current_setting(name, missing_ok) is the core’s). The binder applies the policies wherever a user’s statement reads a table, as a barrier, Plan::Secure (“Row Security” in EXPLAIN): the optimizer may narrow the scan by key ranges from the policy and from the statement’s bounds on a column by a value free of the row (evaluated once, on no row), but no other predicate of the statement is evaluated on a row before the policies have passed it — UPDATE and DELETE likewise filter by the policy first — so an error, a count, a join, a subquery or a side effect reveals nothing of a hidden row (crates/testkit/slt/32_row_security.slt, the leak cases among them, agrees with PostgreSQL 18 run in one session).

Retrieval under it (§M14.24 R3, tests/permissioned_retrieval.rs): nearest vectors through HNSW, BM25 ranked by the text index, @@ counted, rrf and convex — on a table and on one partitioned by tenant — give a role, for random queries, exactly the rows and order an administrator gets with the policy written out as a filter; recall() returns a subject’s memories alone, and REMEMBER never merges into another subject’s or a hidden one. BM25’s statistics are a statistical side channel: counted over rows a policy hides, a term’s document frequency and the average length move visible rows’ scores. On a table partitioned by the tenant they are the readable partitions’ alone: the binder (Binder::readable_parts) gives the text index’s score() a text[] of the partitions, each behind its partition::guard under the policies’ condition (evaluated when the statement runs, so current_setting('app.tenant') picks one), and text_stats sums those — a tenant’s scores are those of its rows in a table of their own, whatever the other tenants hold. On a table not partitioned by it, the statistics still count hidden rows: partition by the tenant where scores must not depend on other tenants’ rows.

Tokens (tokens.rs): API keys for programs and AI agents. CREATE TOKEN name [FOR role] [READ ONLY] [ON [TABLE] t, …] [VALID UNTIL 't'] returns one row — name, login (nct_ and 16 hex digits) and secret (64 hex digits), shown this once; only the secret’s SCRAM-SHA-256 verifier is stored. A client logs in with login as its user and secret as its password, so every driver, psql and any PostgreSQL client take a token as they are (and prove it by SCRAM like any password). The session acts as the token’s role (current_user, session_user) under the token’s ceiling (access::Ceiling), which narrows the role’s privileges and holds through SET ROLE: READ ONLY runs every transaction read only (a write is 25006); ON TABLE … admits no other table and no new one (42501). Tokens may be made for a role that cannot log in. A role makes and drops its own tokens; a member with the admin option, those of its role; an administrator, any — an administrator’s tokens only an administrator. A token session cannot make tokens or set passwords (42501), so no credential outlives a revoked token. DROP TOKEN [IF EXISTS] name revokes one; dropping its role drops it, renaming follows; a dropped table leaves the tokens scoped to it; after VALID UNTIL it does not log in (28P01, as any refusal). Role names starting nct_ are reserved. Row, time and cost budgets come with §M14.25’s protection step (T6); schema and branch scopes when there are schemas and branches.

Secrets (secrets.rs, §M14.22 E2a; catalog 00 14 <name>): credentials the database uses on its own behalf (an embedding provider’s API key). CREATE SECRET [IF NOT EXISTS] name VALUE '…' seals the value with ChaCha20-Poly1305 (nucleus_crypto::aead, RFC 8439; ChaCha20 four blocks side by side, Poly1305 in 64-bit limbs) under the keyring’s key — a random nonce, the secret’s name authenticated beside it, the key’s id (8 bytes of a hash of it) kept so another key is refused by name, not by garbage; … FROM ENV 'VAR' names an environment variable of the server’s process, read when the secret is used — only an administrator makes one. ALTER SECRET name VALUE '…' | FROM ENV '…' replaces it; DROP SECRET [IF EXISTS] name drops it with its grants. Making one needs CREATE on the database; its maker owns it (changes and drops it; a role that owns one is not dropped, a renamed one keeps it); GRANT USAGE ON SECRET name TO role lets a role use it — name it in a model (E2b) — and see it in nc_catalog.secrets (name, owner, source value or env, env, created, changed; never a value). The keyring (secrets::Keyring, set for the process by secrets::set_keyring) is the key hierarchy’s data key secrets (below), so a copy of the directory or a backup holds no secret in the clear. Without a keyring a secret with a value is refused (55000); a damaged record does not open (22000). Values are secrets::Revealed, which prints as ***; a statement that names a secret or a password is kept in the audit log and the server’s query log with its strings as '***' (statements::redacted), and a mistyped CREATE SECRET k 'v' is a syntax error that does not echo the string.

The key hierarchy (§M14.30 K1; nucleus_crypto::keys, nucleus_sql::keys, nucleus_server::keyring). One root key wraps the data keys — secrets, the backups’ backup (§8.30, Under the key hierarchy), and subjects, which seals the subject keys’ table (§8.30) — which are kept only wrapped, in the keyring <dir>.keyring beside the data directory (text: nucleus keyring 1, root <id> <custody>, a passphrase root’s salt <hex> <iterations>, dek <purpose> <id> <wrapped> <made>, and prev … for a data key being replaced; mode 0600, each change a new file synced and renamed over the old one). A wrapped key is deterministic authenticated encryption (RFC 3394’s key wrap and SIV’s synthetic IV): the nonce an HMAC of the purpose and the key under a key derived from the root, ChaCha20-Poly1305 under another, the purpose as associated data — 61 bytes, opened only by its root and for its purpose. The root’s custody is the owner’s (nucleus server, nucleus sql <dir>, nucleus keys): database-managed by default, <dir>.root-key made at first use (mode 0600: it guards a copied directory or a stolen backup, not a compromised host); user-managed with --root-key FILE (64 hex digits; or NUCLEUS_ROOT_KEY_FILE), --root-key-env VAR, or --root-passphrase-env VAR (PBKDF2-HMAC-SHA-256, 600,000 rounds, its salt in the keyring); or a KMS’s key that never leaves it, --root-kms <scheme>:<key> — a module’s KeyProvider registered for its scheme (keyring::register_kms, K3). AWS KMS is modules/aws-kms (aws-kms:<key id, ARN or alias/…>, configured by the AWS SDKs’ variables): at opening DescribeKey turns the name into the key’s ARN — the root’s id, so an alias and its ARN are one root and an alias moved to another key is refused — and refuses a key not Enabled, not ENCRYPT_DECRYPT or not symmetric; each data key is wrapped by Encrypt and unwrapped by Decrypt once at opening, under the encryption context {"nucleus-purpose": <purpose>}, so KMS itself refuses a wrapped key offered for another purpose. A key disabled or deleted in KMS leaves the database unopenable. Vault’s (or OpenBao’s) Transit engine is modules/vault-transit (vault-transit:[<mount>/]<key>, VAULT_ADDR, VAULT_TOKEN or ~/.vault-token, VAULT_NAMESPACE, VAULT_CACERT): opening reads the key and refuses one that is not an AEAD key or cannot both encrypt and decrypt; a data key is encrypted with its purpose as associated data; the root’s id is vault-transit:<mount>/<key>. A token whose policy loses the key leaves the database unopenable. (nucleus-http trusts a private authority beside Mozilla’s roots through trust_pem.) Google Cloud KMS is modules/gcp-kms (gcp-kms:projects/<p>/locations/<l>/keyRings/<r>/cryptoKeys/<k>): opening reads the key and refuses one not for ENCRYPT_DECRYPT or whose primary version is not enabled; a data key is encrypted with its purpose as additional authenticated data; tokens come as Google’s client libraries find them (GOOGLE_OAUTH_ACCESS_TOKEN, a service account’s key — a JWT it signs RS256 with ring —, gcloud’s refresh token, the metadata server, which nucleus-http reaches over plain HTTP as a link-local address). Azure Key Vault is modules/azure-kv (azure-kv:<vault>/<key> or the key’s URL): an RSA key’s encrypt and decrypt (RSA-OAEP-256); having no associated data, the purpose is encrypted with the data key and checked when it comes back (OAEP is non-malleable), and the key’s version is kept beside the ciphertext so a rotated key still opens the keyring; tokens from a service principal’s secret, workload identity’s federated token, a managed identity’s endpoint, or the instance metadata service. A hardware security module, or any PKCS#11 token, is modules/pkcs11 (an RFC 7512 URI: pkcs11:token=<label>;object=<label>?module-path=<library>&pin-source=<file>, or NUCLEUS_PKCS11_MODULE and NUCLEUS_PKCS11_PIN): opening finds the one secret key so named and refuses one not AES-256 or not able to both encrypt and decrypt; a data key is encrypted in the token with AES-GCM, an IV from the token’s generator and the purpose as additional authenticated data; the root’s id is pkcs11:token=<label>;object=<label>[;id=<id>], read from the token; the library is loaded once a process (through cryptoki, so the module has no unsafe of its own) and one session is kept, opened again once when it goes stale. A root that did not wrap the keyring is refused, naming both ids. An old key file (<dir>.secrets-key, or --secrets-key’s) is taken in at start — its bytes become the data key, so what it sealed still opens — and, by --old-key-files, removed once the keyring holding it is on disk and read back (the default), kept with a warning at every start (keep), or used as before until nucleus keys <dir> import (manual). --encrypt-backups yes|no encrypts backups unasked (default: yes with a root given or a backup key in the keyring, no with the database-managed root alone, which a lost disk takes with it). nc_catalog.keys (an administrator’s: name, role root, data or previous, id, custody, location, created) and `nucleus keys

list` show the hierarchy — never a key. A root the keyring names and that is not there is an error, never replaced by a new one.

Rotation (K1e; the server stopped — nucleus keys takes the database’s lock). nucleus keys <dir> rotate-root with the new root (--to-root-key FILE, --to-root-key-env VAR, --to-root-passphrase-env VAR — a new salt —, or --to-managed-root, a new <dir>.root-key) and the present one’s options wraps every data key again under it: seconds whatever the data, nothing sealed is touched. A new database-managed root is written to <dir>.root-key.next and renamed over the old file once the keyring names it; a crash between is finished at the next start (a next file the keyring does not name, from a crash before, is dropped). The old database-managed root’s file is removed — or, when the keyring holds a backup key (the backups made before carry it wrapped by the old root), kept as <dir>.root-key.retired-<old id>; a user’s old root is the user’s, needed as long as those backups. nucleus keys <dir> rotate secrets | subjects makes a new data key, keeps the old one as prev — what it sealed opens with either meanwhile —, seals everything again (the secrets’ records in one transaction, secrets::reseal; the subject keys’ table rewritten) and then drops the old key; a rotation cut short is finished at the next start (or by the command again). rotate backup makes a new backup key: the next backup is a full one, the backups before carrying their own key wrapped by the root.

The pages’ AEAD (K2a; nucleus_crypto::siv, for encryption at rest). A page is written again under the same id and birth before its commit (the buffer pool evicts it twice), and after a crash a commit’s number comes round again, so a nonce from (id, birth) would repeat — and with ChaCha20-Poly1305 a repeated nonce gives away the XOR of two pages. So pages are sealed with a deterministic, misuse-resistant AEAD: RFC 8452’s (AES-GCM-SIV’s) structure with ChaCha20 — keys for the nonce from ChaCha20’s block function, Poly1305’s polynomial under a secret point over the associated data and the plaintext, that hash through a ChaCha20 block as the 16-byte synthetic IV, which is both the tag and the key stream’s nonce. The same inputs give the same bytes; different ones never share a key stream but by a 128-bit collision. Checked by an implementation written apart (crates/crypto/tests/siv_reference.py) and every bit of tag, data and associated data flipped; 11.9 µs an 8 KiB page (docs/benchmarks.md, Sealing a page). Key overwrites its bytes with zeros when dropped (a best effort without unsafe) and never prints.

The CPU’s AES (§M14.30, the speed after K2; nucleus_kernels::aes). Where the CPU has AES instructions — ARMv8’s AES and PMULL, x86-64’s AES-NI and PCLMULQDQ, detected at run time — pages, log records and scratch blocks are sealed by AES-256-GCM-SIV proper (RFC 8452): 1.7 µs an 8 KiB page against ChaCha20-SIV’s 12. The instructions’ copy keeps blocks in vector registers, hashes POLYVAL eight blocks at a time (the products with H^8 … H^1 summed unreduced and reduced once — the reduction is linear — the powers computed three products deep) and encrypts the counter blocks eight at a time, round by round; a portable, constant-time copy (the S-box as the inverse in GF(2^8) by multiplies, a masked carry-less multiply) is the reference it is tested against and opens such a file on a CPU without the instructions — correctly, at about 1 MB/s. Checked against OpenSSL’s AES-GCM-SIV (crates/kernels/tests/aes_gcm_siv_reference.py), FIPS-197 and RFC 8452’s vectors, both copies against each other at every length to a page and past, the counter’s wrap, and every bit flipped; the x86-64 copy runs under Rosetta on an Apple CPU, which emulates AES-NI and PCLMULQDQ. The kernels crate’s one unsafe per architecture is the call into the detected instructions, as for CRC-32C. The cipher is the file’s: a new data file takes the one this CPU runs fast (code 2, AES-256-GCM-SIV, or 1, ChaCha20-SIV, in its header), and a file opened keeps its own — the pager adopts the header’s cipher (PageCipher:: for_code) and the store seals its logs with it. AES seals under a key derived from the database key by HKDF-Expand (RFC 5869; the key is already uniform, so it is the pseudorandom key), so no key serves two algorithms: the key check value and the header tags stay ChaCha20- SIV’s under the database key, whichever cipher seals the pages.

Encrypted data files (K2b; nucleus_storage::cipher). A store opened with a page key (StoreOptions::page_key, nucleus_kv::Options:: encryption_key) is created encrypted, and an existing one opens only under the key it was made with. Every data page, free-list pages included, is sealed on its way to the file and opened on its way back — never while cached, so nothing above the pager changes. On disk: the 16-byte SIV tag, then parity << 63 | birth << 8 | page type (8 bytes, in the clear, authenticated), then the 8,168-byte payload encrypted; the page id is the nonce’s first 8 bytes and associated data, not stored — a page read anywhere else does not open, as a plain page’s stored id catches a misdirected write. The tag replaces the CRC. The two header pages stay readable without the key and say what is needed: format version 3 (older builds refuse the file), the cipher at payload offset 176, the key’s check value (the tag of a fixed empty message: the wrong key is refused as such, Error::Key, not as damage) and a tag over the header’s bytes, so a header changed with its CRC made right again is passed over like a torn copy. A file in the clear opened with a key is refused (encrypting one comes with nucleus keys <dir> encrypt, K2e). The WAL’s records (K2c), the main branch’s and every other’s, are sealed the same way under the same key: a 28-byte header — the length, the SIV tag in place of the CRC, the LSN — and the payload encrypted, the LSN as nonce and, with the length, associated data; a torn tail written again at the same LSNs is what the SIV allows. A log in the clear opened as encrypted is refused (Error::Key), not cut off as a torn tail. Everything else of a database — column segments, text, sparse and HNSW indexes, the embedding queue, a transaction’s spilled writes — lives in its key-value store, so in those pages and records. A table of the LSM engine lives in its runs, files of their own: the engines’ files go through a file system that seals them (nucleus_storage::sealed, §M14.28 L4e) — a 32-byte header (magic, the key’s generation, the cipher, a random file nonce, the chunk size), then 1 KiB chunks each sealed under the database key by the pages’ cipher, its tag first: one nonce for the file’s chunks (its random nonce and 0xFFFF_FFFF, the message keys derived from it once a file — aes::Derived, siv::Derived), the header, the chunk’s index and whether it is the last chunk the associated data (the STREAM construction), so a file cut short at a chunk’s end, a chunk moved or a header changed does not open. A first-version file (ncseal\0\x01, 4 KiB chunks, the file’s nonce and the chunk’s index each chunk’s nonce) is read as it was written. A file is written once, in order (its last chunk sealed again as it grows), and read anywhere — a read opens the chunks it spans, read at once. Not caught: a whole file put in place of another of the same database. nucleus keys <dir> encrypt seals the engines’ files beside themselves (.sealing) before the data file, and puts them in place after it; an open finishes either way. What is not is scratch space (K2d): a sort’s runs and a hash join’s partitions past work_mem, in <dir>/scratch. An encrypted database seals its scratch files too (nucleus_kv’s SealedScratch), each under a key of its own made at random with the file (the OS’s generator) and never written anywhere — after a crash such a file is unreadable, and opening removes it. Its bytes are kept in 4 KiB blocks, each sealed by the cipher this CPU runs fast (nucleus_storage::cipher::Aead) — the tag, then the block encrypted, its number as nonce and associated data — so a block moved or changed does not open. The last block, while not full, stays in memory in the clear and goes to the file sealed once it is: appending, what sorts and partitions do, seals each block once and never reads one back; a write over blocks in the file opens, changes and seals them again; a read opens the blocks it covers, read in one read of the file, into the caller’s buffer. Larger blocks were measured and not taken: a run is read in 64 KiB pieces from record boundaries, so a larger block opens more bytes than it serves (16 and 64 KiB: the spilled sort no faster within the noise).

The edition (K2e). A database is encrypted under the keyring’s data key data: every command that opens a local directory (server, sql, kv, branch, init, restore, keys) goes through keys::open_database, which reads the key from the keyring before the database opens (Keyring::before_open: new keys’ bytes and the time from the platform, not the database) and opens with it when the keyring has one. A new database is made encrypted — a new data key data first — when --encrypt-data yes, or by default when the root is given explicitly (--root-key …, as backups); with the database-managed root the default is in the clear (a key beside the data guards against a copied directory without its key file, not a stolen disk). nucleus keys <dir> encrypt, the server stopped, encrypts a database in the clear in place: the data key made and in the keyring first, then Store::encrypt — the store opened in the clear and recovered, scrubbed (every tree checkpointed, the logs moved on and what they dropped zeroed, free pages zeroed), each branch’s log checked to hold nothing past its checkpoint, then under its lock every page sealed into data.encrypting, renamed over data, and the logs’ segments and spares removed (each starts again, sealed, at its checkpoint). A crash leaves it in the clear or encrypted; a keyring with data and a file in the clear is an encryption cut short, finished at the next open. The file in the clear is replaced, not overwritten: its old blocks are the file system’s — encrypt a database when it is made for none to exist. The search for erased bytes (§8.30, scan::find_with) opens what it reads in an encrypted database: every data page that opens, free ones too, decoded as in the clear, and every WAL record from each segment’s and spare’s first on; scratch files, under keys gone with their queries, are left out. Measured: docs/benchmarks.md, Sealing a page.

A new data key (K3f). ROTATE KEY data (the server running) or nucleus keys <dir> rotate data (stopped) replaces the key the files are sealed under. The keyring makes the new key and keeps the old as prev data; the store takes the new one at once (Store::rekey): the file’s key gets the next generation (header offset 180, 0 for a file never given a new key), every page and log record written from then on is sealed under it, and a page says which of the two keys sealed it by the top bit of its clear packed field — the generation’s parity, authenticated with the rest — so a read needs no trial. The header names the previous key’s check value and the range still to look at (offsets 216–247, inside the header’s tag past generation 0; a file never rotated is tagged exactly as before). Then the pages the old key sealed are sealed again in place (Pager::reseal_step) — the one exception to the pager’s rule that a durable page is never written, safe because the contents stay the same: no state changes, only the key. What a torn write could do is undone by a journal, InnoDB’s doublewrite buffer for this one use: each batch’s old bytes go to data.reseal (its entry synced when made) and are synced before the pages are overwritten; opening puts back from it every page that opens under neither key. A batch takes only pages durable and in use (not free, not freed since the last commit, not a commit in flight’s), and a commit making pages free waits for a batch, so no page is reused under it; a read meeting a page mid-write (opening under neither key) waits for the batch and reads again. Batches start once the new key’s first commit is durable — every page written under the old key until then is in it — and cover the pages the file had when the key was made; the header keeps how far they got from one commit to the next. Done, the engines’ files the old key sealed are sealed again (a copy renamed over each; no compaction or checkpoint meanwhile, a run open keeping the key it opened with), every branch’s log moves to a new segment (its directory entry synced) and a checkpoint writes a header naming no previous key, so the log starts where no record is under the old key; the pager lets the old key go, and only then does the keyring drop prev data (nucleus_server::reseal, after a rotation it saw running — never between a ROTATE KEY’s keyring and its store). Midway the database opens only with both keys (Options::previous_encryption_key, the edition’s open_database from the keyring); a file still under the old key opened with both is given the new one as it opens (a crash between the keyring and the store); one done before the keyring dropped the old key has it dropped then. The maintenance thread seals again at full speed while the database is idle, else paced as a forced vacuum. Pages shared by branches are sealed once — the file’s, not each tree’s — which is why it is done in place rather than by copying every tree. The erased-bytes search reads pages under either key. Tests: a crash at every I/O point of it, dropped or torn (crates/storage/tests/rekey.rs), the server’s step with writes between batches (crates/server/tests/rotate_data_key.rs), the CLI’s the_data_key_rotated. Measured: docs/benchmarks.md, Sealing a page.

Access rules (rules.rs): CREATE ACCESS RULE name [FOR role, … | FOR ALL] [FROM 'cidr', …] [VIA ncp | pg, …] [AUTH password | token | certificate | oidc | ldap | trust, …] [WITH TLS | WITHOUT TLS] {ALLOW [READ ONLY] [AS ROLE r] | REJECT} [BEFORE rule | AFTER rule], DROP ACCESS RULE [IF EXISTS] name (an administrator’s). After a client authenticates, the rules are tried in order and the first whose conditions all hold decides — its role (the user or a role it is a member of), the client’s address, the front end, the method it authenticated by, TLS: REJECT, or no rule matching, refuses the login (28000, naming the rule or saying none admits it); ALLOW admits it under the rule’s ceiling, READ ONLY (every transaction read only, 25006) and AS ROLE r (every privilege must be r‘s too — a ceiling, never more). With no rules every login is admitted; a local session (ncsql <dir>, an embedded database) is under none, the way back in after a lockout. Dropping a role takes it out of the rules (a rule left for no role, or whose ceiling role went, is dropped). Conditional memberships: GRANT role TO member [WITH ADMIN OPTION] WHEN (condition) — a boolean over the connection, source (inet, the client’s address), auth, front_end, tls (source <<= '10.2.0.0/16' AND auth = 'certificate'), checked when made (42703, 42804) — holds only in a session whose connection meets it, decided at login: inherited privileges, SET ROLE and access rules’ FOR see it only then; granted again without WHEN, it holds always. The connection is the session’s, read only (55P02 on SET): current_setting('nucleus.client_addr'), nucleus.front_end (ncp, graphql, …), nucleus.auth_method, nucleus.tls (on / off), nucleus.access_rule — so a row-level security policy can use it too — and nc_catalog.sessions lists the sessions; ncsql’s \conninfo shows them. Behind a load balancer, --trusted-proxy <cidr> (repeatable, Config::trusted_proxies) takes the client’s address from the PROXY protocol header (HAProxy’s, version 1 or 2) of a proxy in it — which must send one; nobody else’s is read (transport::client_address). An address alone is weak identity (shared networks, NAT, a spoofing neighbour): for more than read access a rule should require TLS or a certificate too.

Protection. The database’s settings: ALTER DATABASE nucleus SET name = value | RESET name (an administrator’s; dbsettings.rs, catalog 00 11, nc_catalog.database_settings) — password_min_length (default 1), password_lifetime (an interval, default infinity), statement_timeout (default 0, none), login_lock_failures (10), login_lock_time (15 minutes), work_mem (64MB, §8.5), batch_size (1024, 0 – 65536, §8.5), parallel_workers (0, automatic; up to 256, §8.5), model_urls (empty; URL prefixes a model not an administrator’s may call, §8.23); a duration is milliseconds, 5s, 100ms, 2min, 1h, 1d or an interval; a memory size kB, or with B, kB, MB, GB, TB (at least 64 kB). Passwords: at least password_min_length characters and not the role’s name (22023; a verifier given as such, from a dump, is not checked); one set without VALID UNTIL expires after password_lifetime. Failed logins (nucleus_server::throttle): from the third in a row, by user name or by client address, an answer waits a quarter second, doubling up to four; after login_lock_failures the role is locked for login_lock_time — even its password is refused (28000); a success clears the count; unknown names count alike; the counts are the server’s memory. Connection limits: a role’s CONNECTION LIMIT (administrators aside) and the server’s --max-connections (Config::max_connections) — past either, 53300. Statement budgets (budget.rs): SET statement_timeout = … (or the database’s) ends a statement that runs longer (57014), checked as rows are read or made — scans, table functions, recursive rounds, an index build’s rows (on its workers too; a cancelled CREATE INDEX leaves no index), a JSON path’s items (every 4,096 — a path’s items can grow exponentially with its length) — and as work is done that reads no rows (budget::charge_work, every 4,096 steps): a nested loop’s pairs (counted per left row, or per right row of a block), a sliding window’s frames (a 3,000 × 200,000 nested loop over a column table ran 100 s under a 100 ms timeout before, its left side read in three batches; now any statement tried stops within 0.1–0.2 s); a token’s ROWS n (the most rows a statement returns), SCAN n (the most it reads) — 54000 — TIMEOUT '…' and RATE n PER MINUTE (statements, 53400): CREATE TOKEN … ROWS 1000 SCAN 100000 TIMEOUT '5s' RATE 60 PER MINUTE. An insecure start: nucleus server refuses to listen beyond loopback without authentication, or with the default password while the database is unclaimed, unless --insecure.

The audit log (audit.rs; catalog 00 12 <seq>, its head 00 13): every login — admitted, with the rule, or refused, with why (a wrong password, a token not accepted, a rule, a limit; over HTTP a connection’s requests with the same proof are one login, §9) — and every statement that changes the catalog (ddl: tables, types, indexes, roles, grants, policies, tokens, rules, settings), always; statements as the database’s settings ask (audit_statements = all, audit_roles = 'a,b' — those roles’ and their members’, audit_tables = 't,u' — those that touch these tables, by the privilege checks’ lookups). A record holds when, who (session and current user), the connection (address, front end, method, TLS, rule), what (the statement’s text) and whether it went through (the SQLSTATE if not); a statement naming a secret or a password with its strings as '***'. It is written in the transaction of what it records — a statement rolled back leaves none, a committed one always has one — and a refusal, a read or a login in one of its own. Each record’s hash is SHA-256 over its fields and the previous record’s hash; a record of version 2 (eight ff bytes, then its fields’ length) hashes its detail’s SHA-256 in the detail’s place and keeps the detail apart, so an erasure can blank it (§8.29: the detail NULL, erasure its number — or −1, blanked by a restore whose subject’s key was destroyed, §8.30) and the chain still holds; version 1 records (the fields, then the hash) read as written. nc_catalog.audit_chain walks the chain: a changed record, a gap, or records cut off the end (the head names more) show, with where — and a version 2 detail that is neither its digest’s nor blanked. A local session’s DDL is recorded too. Records are not pruned yet; a stream of them comes with §M16.5.

Bootstrap. A database whose catalog has no administrator that can log in with a password is unclaimed: the server’s --user / --password (default nucleus / nucleus) log in as an administrator, so a fresh server and client work together unconfigured; NUCLEUS_PASSWORD in the server’s environment is --password’s default (a container’s settings). When listening, the server says how to connect (connect: nucleus sql -h … or psql -h … -p … -U …). `nucleus init

[--user ]` claims it — creates the first administrator, the password from `NUCLEUS_PASSWORD` or standard input (none given: 20 letters and digits from the system's randomness, shown once), then says how to start the server and connect — or one is made with `CREATE USER … SUPERUSER PASSWORD …`; from then on only the catalog's roles log in (a wrong user or password, a role without `LOGIN` or an expired password: `28P01`, not told apart). `--no-auth` accepts any user that is a role (any name while unclaimed). Passwords are proved by SCRAM-SHA-256 and never sent (`ncp` version 4, and the PostgreSQL front end; older `ncp` clients still send theirs in clear). **TLS** (the `tls` module, `modules/tls`, over rustls): `--tls-cert --tls-key ` offers it on every front end to clients that ask — `ncp` clients by starting a TLS handshake (§10), PostgreSQL clients by `SSLRequest` (`sslmode=require`, `verify-full`); clients that do not ask still connect in plain text until access rules can require it (§M14.25 T5). TLS 1.2 and 1.3. **Client certificates** (mutual TLS): `--tls-client-ca ` asks clients for a certificate of that CA — not required, but one that is sent must verify, or the handshake fails; a verified certificate whose subject common name is the user logging in stands in for the password, for a role with `LOGIN` (while unclaimed, the configured user) and never for a token (`Authenticator::accepts_certificate`, `certificate_login`); a certificate naming someone else changes nothing — the password is asked as before. **OpenID Connect** (the `oidc` module, `modules/oidc`): `--oidc-issuer --oidc-audience [--oidc-jwks ] [--oidc-user-claim ] [--oidc-role-claim ]` takes identity tokens (JWTs) of that issuer through OAUTHBEARER (§10) as well as passwords: the signature is checked against the issuer's keys (the file's, or found by OpenID Connect Discovery over HTTPS and fetched again for an unknown key, at most once a minute) — RS256/384/512, PS256/384/512, ES256, ES384, EdDSA, never `none` — with `iss`, `aud`, `exp` and `nbf` (a minute of leeway). The user claim (`sub` by default) must name a role that exists and may log in, whether the database is claimed or not (`28000` otherwise, as for any refused token); the role claim's roles are granted for the session (`access::Who::session_roles`: those that exist and are not administrators, while the session acts as itself, and `SET ROLE` to them); every claim is `current_setting('nucleus.claims.')` (names in lower case; an array's items joined by commas), which `SET` cannot change (`55P02`) — so a policy can use a tenant claim (`Session::login_as`, `access::Identity`, `nucleus_server::Bearer`). **LDAP** (the `ldap` module, `modules/ldap`): `--ldap-url (--ldap-bind-dn