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
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
Front ends and authentication are registered (principle 12): a
front end is a FrontEnd (name, default_addr, handle(stream, kv, config, id)) — the built-in Ncp in FrontEnds::builtin(), Pg from
the pg-compat module, Mongo from the mongo-compat module and Ndjson
from the ndjson module (§8.46), which the nucleus edition adds;
serve_front_end(front, listener, kv, config) runs any. The server
starts ncp and each --front-end <name> (--pg-compat is --front-end pg, --mongo-compat --front-end mongo). Config { auth, registry, log_queries, tls } (tls: a
transport::Tls, Config::with_tls; the front end negotiates it and
reads and writes through the stream it returns; TlsInfo says what was
agreed, and client_name who a verified client certificate names): auth is an Authenticator
(describe, wants_password, accepts(kv, user, password)) —
Password (the catalog’s roles, or while unclaimed one user;
Config::password, the default nucleus / nucleus) or Trust
(Config::trust, --no-auth); after it accepts, a front end logs the
session in (Session::login). For SCRAM it gives a user’s verifier
(verifier(kv, user): the catalog role’s, with LOGIN and VALID UNTIL
checked, or while unclaimed one derived from the configured password),
and fake_salt / scram_nonce for the exchange; ncp version 4 uses it
(§10). Further methods (tokens, certificates, OIDC, LDAP) are §M14.25’s
later steps. Config::registry is what sessions have (the
built-ins by default; a custom build adds its modules —
Config::with_registry); pg-compat’s front end adds its module on top.
The nucleus protocol over WebSocket (modules/web, §M16.6b W1):
--web (--front-end web, default 127.0.0.1:20039) answers GET /ncp with Upgrade: websocket (RFC 6455; the subprotocol ncp named
when offered) and carries ncp’s bytes in binary messages both ways,
into the server TCP clients reach (handle_native_carried, with the
client’s address and the TLS it came over): the same Hello, SCRAM login
(without channel binding — a page cannot see the certificate), tokens,
roles, budgets and live queries. For browsers and the serverless and
edge runtimes without TCP; the JavaScript driver connects to
ws://user:pw@host:20039/ncp and wss:// (§11). No origin is checked:
the login is inside the protocol, never a cookie. /ncp without the
upgrade is 426, other paths 404. The HTTP request reader and the
WebSocket frames are nucleus-http-serve’s (modules/http-serve),
shared with the console. Measured beside TCP on one machine: a point
query 29 µs either way, 100,000 rows 18.6 ms against 18.2 ms.
The nucleus protocol over HTTP, a request at a time (modules/web,
§M16.6b W2), for where even a WebSocket cannot stay open (a serverless
function, an edge worker): POST /ncp?version=<v>&database=<db>, its
body (Content-Type: application/vnd.nucleus.ncp) the messages a client
sends after logging in, the reply (200, the same type, Nucleus-Protocol: <v> the version spoken) the server’s answers — no Welcome first. The
request runs in a session of its own that ends with it
(Exchange::logged_in, sans-IO as the WebAssembly edition’s): COPY data
goes with its COPY, results come whole, a transaction left open is rolled
back. Authorization names the caller in each request: Basic (a
password — taken only over TLS or from this machine, since it crosses the
wire; a directory’s only over TLS, as PLAIN), Bearer (a token, when
the server has an issuer; ?user= names whom the throttle counts) or
none (a server that trusts, or a client certificate’s login). A refused
login is 401 with WWW-Authenticate and <SQLSTATE>: <message> as
text — throttled and audited as over TCP; a connection’s requests with
the same proof are one login in the audit log (admitted, it is recorded
once per connection; refused, every time), as a TCP connection’s.
OPTIONS /ncp answers a page’s preflight: any origin may call
(Access-Control-Allow-Origin: *, never with credentials — the caller
is named in the request, not by a cookie), and since a POST must say
ncp’s media type, a form of another site cannot post to it with a
password the browser remembers (415). Connections are kept alive
between requests (idle for 30 s at most). Measured on one machine: a
request’s cost in the server 44 µs from a raw client (a TCP query’s
about 30 µs) — 183 µs before a connection’s repeated logins stopped being
recorded each time, 78% of it the audit record’s commit; 65 µs with a
password checked (5.3 ms before a password’s check was known again); from Node’s
fetch a point query 113 µs against 38 µs over TCP or a WebSocket,
100,000 rows 60 ms against 37 ms, a connection 1–6 ms (no SCRAM round
trips) against 10–25 ms.
Services beside /ncp (nucleus_web::Service): a module answers
requests at a path of its own (and below it) on the same listener —
Web::new().with(Arc::new(…)) — each in a session logged in as its
caller (Call::session, nucleus_server::session_for): the same
Authorization as POST /ncp, the throttle, the access rules, the
audit (a connection’s same proof recorded once), and the service’s name
as nucleus.front_end. A request done with its session gives it back
(Call::done, Logins::done; gh #28): the connection’s next request of
the same login (user, database, front end, Authorization) logs in on
it again (nucleus_server::session_for_reusing), every check made again
— a password changed or a login revoked meanwhile is refused — and
keeps what it parsed and read of the catalog. Only a session as a login
leaves it is taken again (Session::reuse: no open transaction, no
setting, no SET ROLE, no subscription, no subject key presented; its
currvals and statement rate cleared); any other is replaced by a fresh
one. GraphQL, REST’s reads and writes, gRPC’s calls (a deadline’s
statement_timeout reset first) and MCP (RESET ALL first) give theirs
back; streams keep their own. The preflight is answered with its methods; a
path no one serves is 404, naming the services. A service may take a
WebSocket at its path too (§M16.6b G3: Service::subprotocol,
Service::socket): an upgrade there must offer its subprotocol (400
otherwise), and the service gets a Socket — its messages read by one
thread and sent by any, a reader waiting holding nothing (it waits for
bytes, then reads what came without blocking, the WebSocket’s reads
resumable where one stopped) — and Logins, the sessions of a caller
who names itself in a message rather than in the upgrade, each a login
with session_for’s checks, the first recorded in the audit log.
GraphQL (modules/graphql, §M16.6b G1–G3, D19): /graphql on the
web front end (nucleus server --web). GraphQL over HTTP: POST
with application/json (query, variables, operationName) or
application/graphql, GET with ?query=; the answer 200 and
{"data": …} or {"errors": [{"message", "locations", "extensions": {"code"}}], "data": null} — code a SQLSTATE for the database’s
refusals (42501, 57014), GRAPHQL_PARSE_FAILED or
GRAPHQL_VALIDATION_FAILED for the request’s. Another media type is
415 before any login (a form of another site cannot post); a refused
login is 401 as at /ncp.
- The schema is the catalog as the caller sees it (
nc_catalog.tables,columns,foreign_keys; a partition is not a type of its own): a type per table named as it (a name GraphQL cannot take is left out), its columns —Int(smallint,integer),Float(real,double precision),String(text,varchar,char),Boolean, a list for an array, and a scalar named after any other type (bigint,numeric,uuid,timestamp_with_time_zone, …, as SQL’s JSON renders it) —NOT NULLas non-null, comments as descriptions, and each foreign key a relation both ways: one row (authorforauthor_id, else the table’s name) and many (the referencing table’s name;<table>_by_<columns>when that is taken). Introspection (__schema,__type,__typename) is answered from it in Rust. - Queries take Hasura’s forms:
posts(where:, order_by:, limit:, offset:),posts_by_pk(id:);where:aposts_bool_exp— per column_eq,_neq,_gt,_gte,_lt,_lte,_in,_nin,_is_null, and_like,_ilikefor text;_and,_or,_not; a relation’s own expression (EXISTS);order_by:per columnasc,desc,asc_nulls_first, …, and through a one-row relation. Variables (with defaults), fragments, inline fragments, aliases,@skipand@include. - Mutations (§M16.6b G2) take Hasura’s forms:
insert_<t>(objects:, on_conflict:)andinsert_<t>_one(object:, on_conflict:)— a column left out takes its default;on_conflict: {constraint, update_columns, where}updates those columns from the row inserted (wherewhereholds) or, with none, leaves the row out;update_<t>(where:, _set:, _inc:)andupdate_<t>_by_pk(pk_columns:, …);delete_<t>(where:)anddelete_<t>_by_pk(<key>). The many-row forms answer a<t>_mutation_response(affected_rows,returning), the one-row forms the row ornull. Each root field is one statement —WITH m AS (INSERT … | UPDATE … | DELETE … RETURNING *) SELECT <its JSON>— and a request’s run in order in one transaction: each sees the ones before it, and an error rolls all back (data: null). Whatreturningreaches through a relation is read as its statement began (a data-modifyingWITH’s rule). Privileges and row-level security are the database’s:INSERT,UPDATE,DELETEgranted, a policy picking the rows changed and checking the new ones. A mutation byGETis405(a link or an image of another site must not write). - Subscriptions (§M16.6b G3) go over a WebSocket at
/graphqlwith the subprotocolgraphql-transport-ws(the graphql-ws library’s protocol, which Apollo’s and Hasura’s clients speak). The client sendsconnection_initwithin 10 s (Graphql::connection_init; else the close4408), its login in the payload —{"headers": {"Authorization": "Basic …"}}as Hasura and Apollo send it, or{"Authorization": …}— or in the upgrade’s own header; it is checked then (refused:4403, with the SQLSTATE and message) and answered withconnection_ack. Eachsubscriberuns in a thread and a session of its own, logged in again with the same proof (at most 64 at once; one more is anerror). A subscription selects one root field of theSubscriptiontype — the query’s fields — and is a live query (§8.47): its statementSUBSCRIBEd, its result sent whole asnextat once and again after each commit that changes it (a commit that leaves it as it was sends nothing), with the caller’s privileges and row-level security on every run. A query or a mutation sent the same way is answered once,nextthencomplete. A document that does not validate iserror; a refusal of the database’s — a privilege revoked, a table dropped, the role’s login stopped — is anextwith its errors, thencomplete.completefrom the client stops one (nothing more is sent for its id, checked as each message is sent);pingis answered withpong. What breaks the protocol closes the connection with graphql-ws’s codes:4400a message not understood,4401asubscribebeforeconnection_ack,4409an id already running,4429a secondconnection_init. A subscription sent over HTTP is an error. Measured (10,000 rows, a commit changing one of the 100 a subscription selects, to its last subscriber): 1.8 ms for 1 subscriber, 2.1 ms for 10, 4.5 ms for 100 — what its statement costs overncptoo (its JSON is one row, run whole after each commit, where the plain query is applied by key: 0.9, 1.0, 3.0 ms). - One statement per request: each root field a column of one row; a
list
string_aggover its rows in order, a relation a subquery correlated to its row — no N+1. The JSON is written as text in the statement, so an object’s keys keep the order asked (the database’sjsonsorts them). Values are parameters (CAST($n AS type)) and names quoted: nothing of the request reaches the SQL as text. The statement runs in a session logged in as the caller, with the database’s privileges, row-level security and statement budget;Limitsbounds a request’s depth (12) and fields (2,000). - Measured on one machine (a raw keep-alive client, a password checked):
a point query 165 µs against 65 µs for its SQL over
POST /ncp(the schema’s three catalog reads are about 60 µs of it — a catalog version to cache it by is issue #27), 1,000 rows as JSON 1.12 ms against 0.34 ms for the rows over/ncp(the JSON built in SQL, about 0.7 µs a row: the same statement over/ncptakes 1.0 ms), ten authors with ten posts each 1.1 ms;insert_posts_one339 µs against 190 µs for itsINSERTover/ncp,update_posts_by_pk335 µs against 188 µs.
REST (modules/rest, §M16.6b R1, D19): /rest on the web front
end, the tables as resources in PostgREST’s forms.
- Reads —
GET /rest/<table>:select(columns,*,alias:column; embeddings by foreign keys both ways, named by the relation, as GraphQL names it, or by the table it leads to when one relation does; nested); filterscol=<op>.<value>witheq,neq,gt,gte,lt,lte,likeandilike(*for%),in.(a,"b,c"),is.null|not_null|true|false,not.before any;or=(…)andand=(…), nested (or=(a.eq.1,and(b.gt.2,c.is.null))), andnot.or;order=col.desc.nullslast,…, also by a to-one embedding’s column (author(name).asc);limit,offset, orRange: first-last. Each of these butselectalso applies to a to-many embedding by its name (posts.order=id.desc,posts.limit=3,posts.title=like.a*); a filter on a to-one embedding is refused. The answer is a JSON array,Content-Range: first-last/*(*/*for none);Accept: application/vnd.pgrst.object+jsonasks for one object,406(PGRST116) when not exactly one row. - Writes —
POSTan object or a list (a column left out takes its default);Prefer: resolution=merge-duplicatessets every column given on a conflict (the key too),ignore-duplicatesleaves the row out, on the primary key or the unique constrainton_conflict=<cols>names (42P10when none matches).PATCH(an object of the columns set) andDELETEact on the rows the filters pick; order and limits are refused there.Prefer: return=representationanswers the rows asselectasks (201forPOST,200); else nothing (201,204). A body isapplication/json(415). - One statement per request: the request is read into
nucleus-graphql’s tree (aDocumentof one root field:posts,insert_posts,update_posts,delete_posts) and compiled by its compiler — embeddings subqueries correlated to their row, the JSON built in the statement, valuesCAST($n AS type)parameters (so PostgREST’s text values are read by the column’s type:id=eq.xis22P02), names checked against the schema first (42703,PGRST200for an embedding no foreign key makes). The session is logged in as at/ncp, its namerestasnucleus.front_end: the database’s privileges, row-level security and statement budget. - Errors are PostgREST’s —
{"code", "details", "hint", "message"}, the SQLSTATE ascode— with its statuses:42501403,23505and23503409,42P01404,53…503,54…413, the class errors500, the rest400;PGRST100for a query string not understood,PGRST205for a table not there. GET /rest/: an OpenAPI 3.0 document of the tables the caller sees — a path per table withget,post,patch,deleteand their parameters (select,order,limit,offset,or,and, a filter per column,Prefer,Range), a schema per table (types and formats from the columns’ SQL types,nullable,requiredforNOT NULL, comments as descriptions,x-sql-type).- The front end’s preflight lets a page send
Accept,PreferandRange, and readContent-Range. - Changes (§M16.6b R2) —
GETwithAccept: text/event-streamanswers server-sent events:event: snapshot(data:the rows, as theGETanswers them), then anevent: changeper commit that changes them (data: {"deleted": […], "inserted": […]}, an update one of each;id:the commit’s timestamp), a: keep-alivecomment everyRest::heartbeat(15 s) while nothing changes. The query is theGET’s, compiled to a row of JSON text per row (compile_rows) and subscribed to as a live query (§M16.6) in the caller’s session: a query of one table’s rows, flat — no derived table — is kept by its keys (S4); one with embeddings, or a policy reading another table, runs whole after each commit. A refusal before the stream (a bad query, a privilege) is an ordinary error answer; one later (a privilege revoked, the table dropped) isevent: errorwith PostgREST’s body, and the end. NooffsetorRange(400); no length — the connection closes at the end, and a client not reading for 30 s is dropped. - Not taken: casts and JSON paths in
select, embedding hints (!inner,!fk), many-to-many embedding through a join table,Prefer: count=exact, CSV, RPC. - Measured on one machine (a raw keep-alive client, a password
checked): a row by key 181 µs (GraphQL 166 µs, its SQL over
POST /ncp66 µs; the schema’s catalog reads are most of the difference, issue #27); ten authors with ten posts each 4.7 ms (GraphQL 4.7 ms); 1,000 rows 1.14 ms (GraphQL 1.10 ms, the rows over/ncp0.34 ms). A commit to its stream’s last reader (a table of 10,000 rows, one of the 100 rows selected updated; 1, 10, 100 readers): 0.88–1.08, 1.16–1.28, 1.94–2.01 ms; the same statement subscribed overncp1.21, 1.33, 2.79 ms; GraphQL’s subscription, run whole, 2.06–2.67, 2.09–2.28, 4.33–4.54 ms.
gRPC (modules/grpc, §M16.6b P1, D20): the front end grpc
(--grpc, 127.0.0.1:20040) serves the service nucleus.v1.Nucleus,
defined in modules/grpc/proto/nucleus/v1/nucleus.proto.
Query— one statement and its parameters (Value: null,bool,int64,double,string,bytes): a server stream ofQueryReplys — the columns (name, SQL type) in the first, rows in batches of about 64 KiB as the executor produces them, the command tag in the last. Types protobuf lacks (dates, decimals, vectors, JSON) are their text.Subscribe— a live query (§M16.6) or a changefeed’s query: aChangewith the rows as they are (snapshot), then one per commit that changes them (deleted,inserted,tsthe commit), until the client cancels; a batch past 64 KiB comes in parts (more). It runsSUBSCRIBEand waits onCHANGES … WAITin slices of 250 ms, so a cancel or a deadline is seen within one.- The caller: the metadata
authorization(Basicover TLS or from this machine,Bearer),nucleus-database,nucleus-user— logged in, throttled and audited as at/ncp(nucleus-web’sLogins), each call in a session of its own.grpc-timeoutbecomes the statement’sstatement_timeout. - Errors: a gRPC status by SQLSTATE (
42501PERMISSION_DENIED,42P01/3D000NOT_FOUND,23505ALREADY_EXISTS,40001ABORTED,57014DEADLINE_EXCEEDED,0A000UNIMPLEMENTED,28…UNAUTHENTICATED,22…/42…INVALID_ARGUMENT, …), the SQLSTATE in the trailernucleus-sqlstate,grpc-messagepercent-encoded; before the first message, a trailers-only answer. Compression other thanidentityisUNIMPLEMENTED; a body that does not decodeINVALID_ARGUMENT; notPOST405, notapplication/grpc415. - HTTP/2 is nucleus’s own (
nucleus-http-serve’sh2andhpack, RFC 9113 and 7541), synchronous: a connection’s reader thread, its requests run on its threads (an idle one takes the next; eight wait at most, ten seconds each), 100 streams at once (REFUSED_STREAMpast them), bodies up to 16 MiB, header lists up to 64 KiB. Flow control both ways: our windows (1 MiB a stream, 16 MiB the connection) given back a megabyte at a time to the connection, half a window to a stream; an answer waits for the peer’s windows, 30 s at most. An answer’s frames are held and written together (Response::hold) — a call by a key is one write — and aSubscribe’s change goes at once. Cleartext with prior knowledge, or TLS offeringh2by ALPN (Tls::accept_offering). A protocol error ends the connection withGOAWAY. - A service per table (§M16.6b P2):
nucleus.tables.v1.<Table>Servicefor each table the caller’s database shows it (not partitions), asnucleus codegen protowrites them (§8.37). Its row is the message<Table>(a name made of the table’s words:order lines→OrderLines), a field per column numbered as the column (nc_catalog.columns.number), eachoptional: absent isNULLread, the column’s default inserted, the column left as it is updated. Types:smallint/integerint32,bigintint64,realfloat,double precisiondouble,booleanbool,byteabytes, the reststring(their text, cast to the column’s type on the way in). Methods —Get(<T>Key),List(<T>List)(a stream in the key’s order:limit,aftera key),Insert(<T>),Update(<T>Update)(row’s key picks it;fieldsnames those set, absent ones toNULL— empty: the fields present),Delete(<T>Key)(each answering the row, as stored or as it was;NOT_FOUNDwithout one),Watch(<T>List)(its live query:<T>Changes asSubscribe’s). A table without a primary key hasList,Insert,Watch. Each call is one statement in the caller’s session: its privileges, row-level security, constraints and their statuses asQuery’s. The tables are read fromnc_catalogat each call. - Server reflection (
grpc.reflection.v1.ServerReflection, andv1alpha’s): one bidirectional stream, each request answered as it comes —list_services,file_containing_symbol,file_by_filename(nucleus/v1/nucleus.proto,nucleus/tables/v1/tables.proto), asFileDescriptorProtos byte for byte asprotocwrites them; no extensions. The caller logs in as for any call and is described the tables of its database, sogrpcurl -H 'authorization: …' 127.0.0.1:20040 listanddescribework without a.proto. - HTTP/2’s requests reach their handler at their headers, the body read as it comes (a bidirectional stream), the stream’s window given back as it is read.
- Not taken: compression, client streaming (but reflection’s), gRPC-Web.
- Measured on one machine (Rust clients that decode every row,
tonicandnucleus-client): a row by key 91.6 µs (ncp27.2 µs); 1,000 rows 498 µs (315); 100,000 rows 22.3 ms (18.1). Of a call by a key, 51 µs is thetonicclient’s round trip (to any server); the connection’s session kept between calls took it from 106.5 µs (gh #28). A table’sGet105.7 µs (Query89.2 µs; 177 µs while each call’s schema read ran in a fresh session), itsListof 1,000 rows 722 µs (606).
The web console (modules/console, §M14.17 E3): --console
(--front-end console, default 127.0.0.1:20036) serves a page to
browse the tables, run SQL, see EXPLAIN / EXPLAIN ANALYZE drawn as a
tree — each node’s own time as a bar, an estimate ten times off what
happened marked — and ANALYZE QUERY’s findings with their fixes. The
page is the module’s (src/web/: HTML, CSS and a script with no
dependencies, compiled in); HTTP/1.1 over the standard library, TLS with
the server’s certificate when it has one. It logs in with a user and
password checked as the other front ends check them (the
authenticator, a directory’s users only over TLS or from loopback, the
throttle, refusals audited, CONNECT, --max-connections); the session
is a database session kept under a random 256-bit token in an
HttpOnly, SameSite=Strict cookie (Secure over TLS), dropped after
30 minutes unused, at most 64. POST /api/query runs a script’s
statements in order through Session::run_into, each reply’s rows
(as text) up to limit (≤ 10,000; the statement stops there,
truncated); the first error ends it, with its code and hint. A
POST needs X-Nucleus-Console: 1 (no form can send it, no other
origin may without CORS, which it never allows) and, when the browser
names one, the page’s own Origin; replies carry a CSP of 'self',
nosniff, no referrer. Beyond loopback without TLS the server refuses
to start (the page sends the password) unless --insecure. When
listening the server names its URL (connect: … or http://…/ (the console)). modules/console/test/browser.mjs goes through the page in
headless Chrome against a server — login refused and accepted, tables,
rows, NULLs, two statements, a plan, the linter, an error and its hint,
a transaction’s state, a new table listed, the logout — in CI on Linux.
Read replicas (replication.rs, PLAN.md §M17.5 R2, D25).
- Serving replicas.
nucleus server <dir> --replicationopens the database for replication:wal_minimalis off, and spilling transactions hold the log. The server answersL(§10) from a superuser’s login. - Slots. Each replica names a slot (
--replica-slot, defaultreplica). A slot holds the primary’s log from where its replica reads again, moved by the replica’s answers to heartbeats. The slots are kept in<dir>/replication-slots: a line each, with the name, the restart LSN and the last commit applied, rewritten (a new file renamed over the old) when one is made and at most once a second as answers come. A restarted primary holds its log for each slot again, and stops holding it as a whole. A database with slots is served as with--replicationeven without the flag. One replica at a time uses a slot (55006otherwise). - Gone positions. A replica whose position the log no longer holds
(its slot was dropped,
Primary::drop_slot, and the log moved on) is told so (55000, “seed the replica again”). - The slots’ cap (§M17.5 R6).
--max-slot-log <MiB>(PostgreSQL’smax_slot_wal_keep_size; no cap by default, as there) bounds the log a slot may hold: looked at every second, a slot holding more is dropped, its hold let go and the server’s log told. A replica connected is cut off at its stream’s next round; one away is told when it comes back (55000, “slot … was dropped: it held … bytes of the log, past the cap”). Either must be seeded again (a new directory); seeded under the same name, the slot is made anew.nc_drop_slot(name)drops a slot by hand (a superuser’s; not while its replica is connected; PostgreSQL’spg_drop_replication_slot). - Being a replica.
nucleus server <dir> --replica-of <host:port> [--replica-slot <name>] [--replica-user <name>] [--replica-password <pw>](orNUCLEUS_REPLICA_PASSWORD; the user and password default tonucleus) makes the server a replica. A new, empty directory is seeded first, before the server listens: the primary’s snapshot, written as one commit at the snapshot’s timestamp. Then it follows the primary on a thread of its own, reconnecting after a failure (waiting longer each time, up to 5 s). - A silent peer (§M17.5 R6c). A stream silent for
--replication-timeout <s>(default 60, PostgreSQL’swal_sender_timeoutandwal_receiver_timeout) is cut on either side: the replica’s reads wait that long at most (heartbeats come each second), and the primary’s reads of its answers and writes to it too, so a peer cut off without a reset (a cable pulled, packets dropped) is let go; the replica reconnects and resumes. A cluster member’s request to another waits a lease at most, so one that falls silent holds up no later request (nucleus_client::Config::read_timeout). - Members over TLS (§M17.5 R6c).
--peer-tls-ca <file>: a replica reaches its primary, and a member the others, over TLS, checking their certificates against that CA (each server’s own--tls-cert, which must name the host the others reach it by); a server with--tls-certand--tls-keyshows its certificate as the client’s, so servers started with--tls-client-calog their members in by certificate — a certificate whose common name is the replica’s user needs no password. - Applying. Each commit is applied at the primary’s timestamp and
time (§5.4), with the replica’s position in the primary’s log in the
same commit (
00 25 00: the restart LSN, the commit, the slot). A replica that stops or crashes starts again exactly after its last durable commit; one started on a directory that is not a replica, or follows another slot, is refused. A commit applied is visible at once and made durable with the rest of its batch, by one sync, before the heartbeat ending the batch is answered (§M17.5 R7;Transaction::commit_replicated_lazy,Engine::sync_log): what a replica says it applied is durable, and a commit lost by its crash before that is one its primary sends again (only the primary’s durable log is streamed). A replica’s history begins at its seed (the engine’s00 06record,Transaction::begin_history):AS OFa commit or time before it is72000, snapshot too old — it read an empty database before (§M17.5 R7). Waiting for a sync each, a replica applying one commit at a time fell behind a primary whose concurrent commits share theirs (bench/replication.py: a synchronous commit 2.28 → 0.32 ms, the lag under eight writers 26,000 commits → 6). - Its engines (§M17.5 R7). A table of the LSM engine (§M14.28) is
one on a replica too: the primary’s routes — ranges given an engine,
made out of the log — come in the stream (
r, protocol 13) before the seed’s keys and before the first commit after one is made, and the replica makes those it lacks. A range that holds keys there already (a replica that followed before protocol 13) stays in its B+tree, said so in its log. - Its branches (§M17.5). A replica follows every branch of its
primary, each on a stream of its own — logged in to that branch,
under the same slot name — its commits at the primary’s timestamps.
Each branch’s stream names that branch’s own branches (
n, protocol 15: name, id, the clock it was made at), each told of before the first commit after it was made, so the replica’s copy of the parent is then where the primary’s was when the branch was made of it: the replica makes the branch of its copy the same way (constant time, no data sent) and follows it from the start of the branch’s log, which a slot of its name, made by the primary as it tells of the branch, holds. A branch told of later — made before the replica was seeded, or before the primary restarted — is made empty, its clock its own, and seeded. A seed, or a branch’s first commit, records the primary’s branch id (00 25 03): a branch dropped on the primary is dropped here (its own branches first), and one dropped and made again under its name meanwhile — another id — is dropped and made anew; one made of its parent here and never written yet, the replica restarted, is made anew too (it carries its parent’s place in the log).CREATE,DROPandRESET BRANCHfail there with25006. Promoted, each branch’s history forks after its own last commit, its position gone, and its replica stops; the role is the server’s, so every branch takes writes at once. Each branch’s link is a row ofnc_catalog.replication(itsbranchcolumn); the metrics andnucleus cluster statusare the main branch’s. - What a replica does not do. Its transactions only read, and a
write fails with
25006as on a PostgreSQL standby. It does not run what writes on its own: expiry, storage policies, stream trimming, resumed DDL and the embedding jobs. Its primary’s commits bring their results. Its own audit records (logins, refused statements) go to the server’s log,nucleus: audit (replica): …, since only its primary writes the chain. Its secrets read only with the primary’s key files (--secrets-key, the keyring) copied to it. nc_catalog.replication. A row per slot on a primary (roleprimary) and one for a replica itself (rolereplica). Its columns are the slot, the peer, whether it is connected, the commit applied, the last commit, the lag in commits and in seconds, the restart LSN, when it was last heard from, the error that stopped it (a slot dropped for the cap, too), the epoch, and the bytes of the log a slot holds (retained_bytes), and the branch (branch:main, or another’s).- The lag in seconds (§M17.5 R7). On a primary, per slot: since
the oldest commit its replica lacks was here — the primary notes its
last commit at each heartbeat it sends, and when (PostgreSQL’s
LagTracker). On a replica: since its primary had the oldest commit it lacks, by the primary’s clock in the heartbeats (as PostgreSQL’snow() - pg_last_xact_replay_timestamp(), the clocks’ difference in it). Zero when it lacks nothing;NULLbefore a heartbeat told. - Metrics (§M17.5 R6), with the server’s others (§M14.18:
--metrics,nc_catalog.metrics):- every server that replicates:
nucleus_replication_role{role}(1 for its role:primary,replica,stepped down, and in a clustercandidateorwitness),nucleus_replication_writable(1 while it takes writes),nucleus_replication_epoch; - a primary, per slot:
nucleus_replication_slot_connected,…_slot_lag_commits,…_slot_lag_seconds,…_slot_retained_bytes; andnucleus_replication_slot_cap_bytes(0: no cap),nucleus_replication_slots_lost_total(dropped for the cap),nucleus_replication_sync_replicas,…_sync_waiting_commitsand…_sync_wait_seconds(how long the oldest commit waiting for replicas has waited: a commit with too few replicas waits without a time limit, as on PostgreSQL, and this is where that shows); - a replica:
nucleus_replica_connected,…_lag_commits,…_lag_seconds,…_heard_seconds(since its primary was last heard); - a cluster member: see “Managing a cluster”.
- every server that replicates:
- Synchronous replication (§M17.5 R3).
--sync-replicas <k>(it implies--replication) makes a commit wait untilkreplicas — anykof the slots, PostgreSQL’sANY k— have applied it durably. Until then its client gets no answer and no other session sees it: the commit is durable here but not yet visible (the engine’s visible snapshot waits,Engine::require_replicas/set_replicated; MySQL’s semi-synchronousAFTER_SYNC). So nothing any client read can be missing from a replica promoted later. With fewer thankreplicas, commits wait, as on PostgreSQL. A replica seeded meanwhile gets the waiting commits in its snapshot (it reads past the visible one,Engine::begin_seed). The primary reads a replica’s answers at once when its log goes quiet, so a commit waits about one round trip and the replica’s sync. The server’s own records — a login’s audit record — do not wait (Engine::begin_local, assynchronous_commit = local; a replica’s login writes one): they are visible once replicated, and a failover before that can lose them. Such a transaction reads from the last commit, visible or not, so the next audit record does not conflict with the one before it that still waits; what it reads is visible before it is. A transaction that lost a conflict to a waiting commit waits for it at most 100 ms before it tries again (Engine::settle). - Failover (§M17.5 R4).
nucleus promote [connection options](SELECT nc_promote()as a superuser, on the replica) makes a replica the primary of a new epoch. It stops following, takes writes, and writes in one commit the database’s epochs (00 25 01: each epoch after the first, 0, with the last commit before it — where its history forks from the one before) and the deletion of its position. The epochs are in the database, so its replicas have them. A replica names its epoch when it asks to follow (L):- A primary of an older epoch was replaced. It steps down — its
transactions only read from then on, as a replica’s — and serves
that replica nothing.
nc_catalog.replicationshows its slots asstepped down. - A replica whose last commit is past the fork of the epoch after its own has commits the new primary never had (its old primary’s, after the promotion): it is told to be seeded again.
- The other replicas of the old primary follow the promoted one from where they are, without a seed (§M17.5 R4b, PostgreSQL’s failover slots). Each heartbeat names the primary’s other slots and what each applied. A replica keeps them in its own slots file, each with where its own log was before the commit that replica applied (it applies one commit after another, so every later commit’s records come after), and holds its log from there. Promoted, it resumes such a replica from that point of its own log rather than the old primary’s position the replica sends. A replica in no such slot — unknown here, or new to the old primary after the last heartbeat — is told to be seeded again: its position is in another server’s log.
- The old primary itself comes back as a replica by a seed: emptied,
started with
--replica-ofthe new primary. - A replica of another database is refused: a primary gives its
database an identity when it first serves replicas (
00 25 02, 8 random bytes; PostgreSQL’s system identifier), a seed copies it, andLnames it. - A replica serves no replicas:
--replica-ofopens its database with the whole log and its replication side ready, and it serves them once promoted. The old primary must not take writes after a promotion: stop it first. In asynchronous replication what it committed that the promoted replica did not have is lost, as on PostgreSQL and MySQL; in synchronous replication it could not have answered such a commit.
- A primary of an older epoch was replaced. It steps down — its
transactions only read from then on, as a replica’s — and serves
that replica nothing.
- Automatic failover (§M17.5 R4c;
cluster.rs).--cluster <name>@<host:port>,…names a server’s fellow members,--memberits own name (a replica’s default: its slot),--lease <ms>the lease (default 5000).nucleus witness <dir> --cluster … --member <name>is a member without data, which only votes and grants leases (a third member for a primary and one replica). Members ask each other overncpas a superuser (--replica-user,--replica-password; over TLS with--peer-tls-ca, see “Members over TLS”):- The lease. The primary asks every member for its lease each
quarter-lease (
U). It takes writes only while a majority — itself one — said yes within the last lease. Without, its transactions read only. It starts without one: a restarted primary writes nothing until a majority grants it. A member says no to an epoch older than the newest it voted for or granted, and learns a newer one from a lease it grants. So once a newer epoch is elected — or promoted by hand and leased — the old primary never gets its lease again. - The election. A replica that has not heard from its primary for
two leases and a random part of one first asks whether a majority
would vote for it (
Vwithpre, Raft’s pre-vote: nothing is kept, so a replica cut off alone does not raise the epoch). Then it asks for the votes of the epoch after every epoch it knows. A member votes once per epoch (kept in<dir>/cluster-vote), never within a lease of hearing from a primary (a lease it granted, a vote it gave, its own standing, or a replica’s stream), never while it is a leased primary, and only for a candidate at least as far as itself: whose last commit is of a later epoch than its own last commit, or of the same epoch and not before it (Raft’s last log term, then index — the epochs are written in the commit that starts one, so a database’s newest epoch is its last commit’s). A timestamp alone says nothing across epochs: a former primary’s commits after the fork may stand past a newer epoch’s, and it refused that epoch’s replicas its vote; a replica that went on following it past the fork would have had the vote of a member holding the newer epoch’s commits. With a majority — itself one — it promotes itself to that epoch and asks for its lease at once. A vote is a promise not to vote for another candidate within a lease (Raft’s leader lease), so no other is elected meanwhile. Promoted, it takes writes only after its database shows the new epoch: a replica of the old primary asking to follow in between would be served as one of the same epoch. A primary cut off therefore stops writing within a lease, and a replica is elected only after the members it needs stopped hearing from it for a lease: the two never take writes at once (on clocks that run at the same rate, as every lease assumes). - The lease’s end is the engine’s (§M17.5 R7). Granted, the
lease’s end is given to the database (
Engine::set_writes_until): past it the database is a replica — transactions begin read only, a commit is refused with25006and writes nothing — though the thread that keeps the lease has not run since. A process paused (a stopped VM, a thread not scheduled) whose sessions run first when it goes on so writes nothing after a replica may have been elected; a chaos test found two members taking writes at once before. The engine reads the clock for it only under a lease. - Lossless when every majority includes a synchronous replica
(
--sync-replicas k, withkat least the members a majority can lack); otherwise what the old primary committed that the elected replica lacked is lost, as in asynchronous replication. - Following whichever member serves (R4d). A replica in a cluster
follows its
--replica-ofand, when that one fails or refuses it (a replica, a primary that stepped down or holds no lease), the other members in turn, waiting longer only after a whole round of them. After a failover it so reaches the new primary, which serves it from the slot it kept (R4b). In a cluster a new replica is seeded only once following, from the member that serves: the primary takes writes, and serves seeds, only under a majority’s lease, which may need this member’s answer — so a member whose database has no identity yet answers any primary, and never stands. - A primary that takes no writes now (its lease lost, or stepped
down) sends what it has, then ends its replicas’ streams: they look
for the member that does — following it, a replica would go on
hearing a primary and never vote. Its commits waiting for
synchronous replicas are let go: each fails with
40003(“whether it survives is unknown”: the next primary may lack it) and stays unseen there (Engine::set_replicalets them go) — they had waited for good. Read back on the primary what such a commit wrote. --sync-replicasholds on a replica only once it is promoted: until then its commits are its primary’s, and wait for nobody.- A failover under load (
crates/server/tests/cluster.rs): four writers on a synchronous primary with two replicas, the primary cut off; one replica elected within about two and a half leases, every commit a writer was answered there, the other replica following it. - A replaced primary rejoins (§M17.5 R7,
--rejoin). A primary that a newer epoch replaced (it knows the epoch from a lease or a vote it granted, and hears from it) takes no writes again, and what it committed after the fork is in no other member’s history: it can come back only as a replica seeded anew. Without--rejoinit says so in the log. With it, it marks its directory (cluster-rejoin) and exits with 75 (EX_TEMPFAIL: a supervisor’sRestart=on-failurestarts it again); started, it renames the directory<dir>.forked-<epoch>— kept whole, to read what only it had (nucleus sql <dir>.forked-<epoch>, with--root-keynaming<dir>.root-keyif the database was encrypted) — makes<dir>anew with only its vote (cluster-vote: a member votes once per epoch whatever its database), and follows the cluster’s primary as a replica in the slot of its member’s name (--memberis needed), seeded from it. It stays a replica across restarts until it is promoted (Patroni’spg_rewindor reinitialization; nucleus has no rewind yet, so even a primary with nothing after the fork is seeded anew). - Chaos tests (§M17.5 R7,
crates/server/tests/cluster.rs,chaos_*): a primary and two replicas, or a primary, a replica and a witness, three writers on whichever takes writes, each commit waiting for one replica; meanwhile, chosen by a seed (more withNUCLEUS_SIM_CASES, one withNUCLEUS_SEED), members cut off, ways cut one way only, made late, connections reset, a member’s rounds held back (a process paused). Then healed: one member takes writes, every commit answered is on it, the replicas following it have its rows, never did two take writes at once, and every snapshot a replica showed during the run (read thereAS OF COMMIT, at the commit it had applied) is the last primary’s at that commit when the commit is in its history. The threads are the OS’s, so a seed’s run is not exactly repeated; the simulator’s network is §M19’s. - A primary without its lease waits before asking again (§M17.5 R7): two leases and a random part of one after a round without a majority. A member that grants a lease hears a primary and votes for nobody within a lease; asking on, a primary cut off from all but a few members (four members or more) kept those few from voting, and nobody was elected until the partition healed (Raft’s CheckQuorum steps such a leader down). So a lease lost to a short break comes back after the wait, or a replica is elected meanwhile. Waiting, it may vote — and, as every member, only for a candidate whose last commit is at least its own: a chaos seed elected a replica lacking commits the other replica had answered for, by the vote of a primary that compared nothing.
- The lease. The primary asks every member for its lease each
quarter-lease (
- Reading one’s writes on a replica.
nc_last_commit()is the session’s newest commit (abigint, 0 before any). A commit has the same timestamp on the primary and its replicas, so that is a token:SELECT nc_wait_commit(token, ms)on a replica waits until its snapshot has that commit, at mostmsmilliseconds (an hour at most), and says whether it does. A transaction begun after it reads at least what the token’s session wrote (CockroachDB’s causality tokens, PostgreSQL 19’sWAIT FOR LSN, MySQL’sWAIT_FOR_EXECUTED_GTID_SET). On the primary it returns at once. - Managing a cluster (§M17.5 R6;
nucleus cluster status,modules/prometheus,docs/alerts/replication.yml).nc_catalog.cluster: the members as the server asked knows them — its own row (self, with itsrole,epochand, a primary’s,leased) and one per other member (host,port, the epoch it last answered with and when,answered_at). Empty outside a cluster.nucleus cluster status [connection options]reads it from the server it connects to, then asks every member over a connection of its own (the same options, the member’s address): its role, epoch, lease, its lag (a replica: in commits and seconds, and whom it follows) or its replicas (a primary: each slot’s lag, or why it is away). A member that does not answer is shownunreachable, with why. The last line names the member taking writes (“taking writes: a”), or says none or more than one does. A server not in a cluster is shown alone with its replicas. As Patroni’spatronictl list.- Health checks for load balancers, on the metrics listener
(
--metrics):/health/primaryanswers 200 on a ready server taking writes — a primary, leased in a cluster, or a server that does not replicate — and 503 with its role otherwise;/health/replicaanswers 200 on a ready replica connected to its primary,?lag=<commits>and&lag_seconds=<s>bounding how far behind (Patroni’s/primary,/replica?lag=). They are read from the metrics below. - Metrics of a member:
nucleus_cluster_epoch,nucleus_cluster_leased, and per other membernucleus_cluster_member_answered_seconds{member}(+Inf before its first answer). A witness serves its role and these. - Alert rules:
docs/alerts/replication.yml(Prometheus): no primary, more than one, a replica not following or lagging, a slot away, near its cap, holding much log or dropped, commits waiting for replicas, a member silent. A test checks that every metric they name is served.
- Clients of a cluster (§M17.5 R5). A connection names several
servers — in the Rust client
Config::hosts, in the shellnucleus sql -h a:1,b:2,c:3, in the drivers’ URLsnucleus://u:p@a:1,b:2/db(libpq’s form) — and atarget:primary(the default),any,replica,prefer-replica(libpq’starget_session_attrs).load_balanceshuffles them first (load_balance_hosts=random). The Welcome says each server’s role (protocol version 12), so one that is not wanted is left without a query. With several servers, outside a transaction block, a statement refused because the server takes no writes (25006: a former primary) or whose connection failed before it was sent runs again on the server found anew, for up tofailover_timeout(30 s); one whose connection failed while it ran gives that error — its outcome is unknown, as nucleus does not deduplicate a retried write (MongoDB’s retryable writes do) — and the next statement connects anew. Inside a transaction block, a failed connection took the transaction with it: the next statement connects anew but is refused with08007(“the connection was lost inside a transaction block: its work is gone”) — run alone on the new primary, it would autocommit what was meant as part of the block — but aROLLBACK, which has nothing left to undo, passes; the statement after runs. A connection lost is08006in every driver, one that cannot be made08001. What the session set (prepared statements,SET, temporary tables) does not come along; the commit token does: each Ready brings it (Client::last_commit), andClient::wait_commit(token, ms)on a replica’s connection reads one’s writes there. A witness’s sessions read only (it holds no data). The drivers do the same: C (nc_config.hosts,target,load_balance,failover_timeout_ms;nc_role,nc_last_commit,nc_wait_commit,nc_reconnect) and C++ and Swift over it; Java (Config.hosts(...),target,loadBalance,failoverTimeoutMillis; Android with it); Python (hosts=,target=, the URL’s servers and?target=,load_balance,failover_timeout); JavaScript over TCP (hosts,target,loadBalance,failoverTimeoutMs; the WebSocket and HTTP transports reach one server).scripts/cluster-tests.shruns each against a primary and two replicas: the target settled on whatever the order, one’s writes read on a replica by the token, the primary killed (SIGKILL) and the new one found, a transaction block cut off refused as above; then the last replica killed, the new primary loses its lease and refuses writes, and the statement it refused, run again on the primary looked for anew, ends with there being none (not with the refusal). The C driver sends withMSG_NOSIGNAL(SO_NOSIGPIPEon Apple’s systems,SIGPIPEblocked around a TLS write elsewhere, as libpq does): a write to a server that died ends no program.
crates/server/tests/replication.rs runs a primary server and a
replica under SQL work: a large transaction whose commit crosses in
parts, one rolled back, DDL. At every commit the replica applied, its
snapshot and commit time are the primary’s. The test then stops the
replica, lets the primary go on, and starts the replica again from
where it was. The primary lets go of its log behind the replica. A slot
dropped while its replica was away, with the log moved on, gets the
replica told to be seeded again. Each mechanism was mutation-checked:
the position in the replica’s commits, the commit parts, the primary’s
time, and the hold moved by the answers.
A second test checks synchronous replication. With no replica, a commit
waits and no session sees it. A replica seeded meanwhile lets it go,
and from then on each commit returns with the replica already having
it. With two replicas required and one there, a commit waits while its
replica has it; that replica, restarted ahead of what its primary shows,
picks up. Asynchronous again, each token is waited for on the replica
before reading the row. crates/txn/tests/replication.rs checks the
engine’s gate, the seed past it, the commits that do not wait (one
after another on the same key) and wait_visible.
A third test checks failover. A replica promoted is the primary of epoch
1, forked at its last commit, its position gone, and it takes writes;
before that it served no replica. A new replica seeded from it has epoch
1 and the promoted history, without what the old primary wrote after the
fork. Another replica of the old primary is told to be seeded again,
first as new to the promoted primary, then — having taken the old
primary’s write after the fork — as past the fork. A replica of epoch 1
sent to the old primary makes it step down: its writes then fail with
25006. A fourth checks failover slots: a replica stopped while its
sibling’s log moves on past it (checkpoints) follows the sibling, once
promoted, from where it was, its every snapshot the promoted one’s; a
primary of another database refuses it.
crates/server/tests/cluster.rs runs a primary, a replica and a
witness, each one’s way to each other through a proxy the test cuts
and heals (lease 400 ms). Cut off from both, the primary stops writing
(within two leases), and only then is the replica elected; a watcher
sampling both every 0.2 ms never sees two writing; healed, the old
primary gets no lease again. The replica cut off alone starts no
election, does not raise the epoch, and follows again once healed.
Unit tests check the vote’s rules and a witness’s memory of its votes.
MongoDB compatibility (optional, §M16 Q5): --mongo-compat also
listens for MongoDB’s wire protocol (nucleus_mongo_compat::Mongo, default
127.0.0.1:27017), with the same credentials (SCRAM-SHA-256), so
mongosh and MongoDB’s drivers run CRUD and queries on collections
(§8.42).
PostgreSQL compatibility (optional, D14): --pg-compat also listens
for the PostgreSQL protocol (nucleus_pg_compat::Pg, default
127.0.0.1:5432), with the same credentials, so psql and PostgreSQL
drivers and tools can connect. Its sessions have the pg-compat module
(§8.11); ncp sessions do not. It is frozen: kept working, not extended
for the catalog queries particular tools send (some, like Valentina
Studio, ask for PostgreSQL internals nucleus does not have). PostgreSQL
protocol 3.0:
SSL requests accepted (S, then TLS) when the server has TLS, else
declined (N), as are GSS requests; the request is read unbuffered, so
nothing sent before the handshake counts as sent inside it; trust or
SCRAM-SHA-256 authentication — over TLS SCRAM-SHA-256-PLUS too, offered
first, which libpq takes by default: the proof is bound to the TLS
session (tls-server-end-point, RFC 5929: the server certificate hashed
by its signature’s hash; certificates whose signature names no hash, as
Ed25519, get no binding), so a man in the middle cannot relay it, and a
client claiming it cannot bind (y,,) is refused where the server can
(channel_binding=require works)
(SASL, without channel binding; never a cleartext password; 28P01 on
failure), parameter status (server_version
16.0 (nucleus), UTF8, ISO dates), backend key data, ReadyForQuery with
the transaction status. Simple query protocol (statements one by one, the
first error stops the rest) and extended protocol: Parse (parameter types
inferred, or given; the description kept by the statement’s text in the
session’s cache, §8.2), Bind (text or binary parameters; the statement
described again against the catalog as it is — from the cache while the
catalog holds — and refused with 0A000 “cached plan must not change
result type” when its result columns changed since Parse, as PostgreSQL
refuses it), Describe (statement
and portal), Execute (streamed as produced; with a row limit the result
is kept and sent a part at a time, PortalSuspended), Sync, Close,
Flush; after an error, messages are skipped until Sync. Types on the wire:
bool 16, int8 20 (int2/int4 accepted), float8 701 (float4
accepted), text 25 (varchar, bpchar, name accepted), numeric
1700, date 1082, timestamp 1114, timestamptz 1184, interval 1186,
and their arrays, uuid 2950 (binary: its 16 bytes), jsonb 3802 —
nucleus’s json (text: its text; binary: jsonb’s, a version byte 1 and
the text; a parameter typed json, 114, read as json too) —, vector 13201
(pg_type lists it — pgvector’s oid is per database, its clients look it
up with to_regtype('vector') — text [1,2,3], binary pgvector’s: the
dimension count and an unused int16, then big-endian float4s; psycopg
with pgvector’s register_vector works both ways), sparsevec 13203
(listed likewise; text {1:0.5}/10 as pgvector’s, binary pgvector’s:
the dimensions, the non-zero count and an unused int32, then the
0-based positions and the float4 values, big-endian — positions out of
order are put in order); other registered types as text; record
2249 (text (1,"a b",) as record_out, binary record_send’s: the
field count, then each field’s type oid, length and binary form); text
and binary formats for all of them (binary numeric and dates checked
against PostgreSQL’s *_send). COPY … FROM STDIN takes CopyData
after CopyInResponse; COPY … TO STDOUT sends CopyOutResponse,
CopyData per line, CopyDone (§8.7).
Not supported: cancellation. psql’s \d family works through
the compatibility catalog (§8.11).
Tests: crates/client/tests/client.rs runs every slt script over the
nucleus protocol and checks typed values both ways, parameters, errors,
transactions and passwords; modules/pg-compat/tests/wire.rs runs every
slt script (the kit’s and the module’s) over the PostgreSQL protocol with
a minimal client, checks password authentication and the SSL refusal,
and drives the extended protocol with the postgres crate (prepared
statements, typed and NULL parameters, binary results, SQLSTATE codes,
transactions, portals, RETURNING). scripts/psql-smoke.sh (run by CI on
Linux) uses the real psql, including \d, \d+, \dt, \di, \dn,
\l and a foreign key’s Referenced by.