KV contract and the CLI
Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.
6.1 The contract
What every layer above the core uses (principle 1), and what the distributed implementation will provide (§F3).
trait Kv:begin(&self, TxnOptions) -> Result<Box<dyn KvTxn>>;wall_clock()— the time as the implementation keeps it (the local one’s platform clock), the only clock layers above read (principle 4);elapsed()— monotonic time, for measuring how long something took (EXPLAIN ANALYZE, statement statistics; simulated in a simulation);back_off(attempt)— the wait before a retry: first until the commits already past their conflict check are visible (Engine::settle, joining their log sync — the visible snapshot lags a commit until it is durable, so a retry begun at once would start before the commit it lost to and lose again for as long as the sync takes), then exponential with jitter, through the platform, so a simulation does not wait;random_bytes(buf)— unpredictable bytes from the platform;parallelism()— the threads a statement may split its work across (default 1; the local implementation’s platform’s);instance()— which open database this is, unique in the process (KvTxn::instance()is its transaction’s): what a layer above keys state it keeps in memory for one database by (an HNSW index’s upkeep, §8.18); 0 by default (not told apart), one perDatabase::openand branch;branch_name(),branches()(Branch { name, parent }, the main one —MAIN_BRANCH,main— first),branch(name),create_branch(name)(of this handle’s branch, as it is now),create_branch_at(name, at)(as this one was at snapshotat),drop_branch(name),reset_branch(name)— a database’s branches (§M14.13;branch,create_branchandreset_branchgive anArc<dyn Kv>that is a database of its own: its own instance, the same for every handle to the branch; by default only the main one);scratch()— scratch space for work too large for memory (aScratch:write_at,read_at), private, gone when dropped; by default in memory (MemoryScratch), for the local implementation files in<dir>/scratch/(left-overs removed on opening).Kv::vacuum()/Kv::vacuum_wanted(): the store’s maintenance and whether it has work (committed intents to make versions); by default none.Kv::snapshot_at(time)→ theTimestampto begin at for a time,Kv::commit_time(ts),Kv::reach()→ the oldest snapshot a time reaches and its time (§5.2’s time travel; by default none known), withOptions::history_time(aDuration; zero by default).Kv::vacuum_range(start, end): the versions no snapshot sees removed from those keys alone (keys with an intent left whole) — for a range used as a queue, keys put then deleted and never written again, whose tombstones a scan would otherwise step over until the whole vacuum runs (RocksDB’s queue pattern; an HNSW index’s delta, §8.18);Engine::vacuum_range, a chunk of the vacuum’s sweep (sweep_chunk) bounded by the range. A whole vacuum (Engine::vacuum) sweeps the keyspace in parts cut at user keys’ first versions where the B+tree’s internal nodes cut its leaves evenly (Tables::split_keys; one part where another engine holds keys), a window of them at once on up to 8 threads (the platform’s parallelism), each up to a chunk of writes, their writes one batch in key order; the background vacuum one chunk at a time (issue #4).Kv::scrub(ranges, wait)→Option<Scrub { complete, versions, pages, wal_bytes }>(erasure, §8.29): the full vacuum if intents are pending, then — once no snapshot older than the call runs (polled every 2 ms up towait; elsecomplete: false) — every version of those ranges no snapshot sees removed past any history kept (Engine::purge_range: the watermark is the oldest snapshot,Engine::oldest_snapshot), then the store’s scrub (§4.6).Kv::find_bytes(needles)→ the places in the files holding one (nucleus_storage::scan::find, re-exported asnucleus_kv::scan). BothNoneby default (an implementation with no files of its own).Kv::files()→ the file system its files are on (BACKUP TOwrites beside them, §8.30);Noneby default.Kv::vacuum_background(go_on): the same in small batches (2 048 entries),go_onasked between them —falsestops the sweep there, and the next call goes on from it (with the transactions it began with: their statuses go when a sweep has passed every key).Kv::activity(): transactions begun so far;Kv::running(): running now.Kv::rekey(key)makeskeythe one the files are sealed under (§9, A new data key),Kv::rekey_state()says where sealing again under it stands,Kv::reseal_background(go_on)does it 256 pages a batch;Options::previous_encryption_keyopens a database midway. The server’s maintenance thread (nucleus_server::maintain) vacuums when no transaction began in the last 10 s and none is running (a longCOPYis), stopping at the first one that begins; after 10 minutes without such a pause, paced instead (each batch followed by a pause four times as long). Reads resolve intents by their status meanwhile, at about the cost of versions; vacuuming during a load’s next statements (an index build,ANALYZE) or queries slowed them more.trait KvTxn:read_ts,get(&self),scan(&self, start, end) -> KvIter(ascending),get_validated/scan_validated(reads checked at commit at any isolation level, §5.2),validate_range(a range checked so, unread — by default it is read),scan_chunks/scan_chunks_validated(the same entries aChunkat a time — up toCHUNK_ENTRIESkeys and values packed into one buffer the caller reuses, so a large read allocates nothing per entry — the first chunk, and the first after a seek,FIRST_CHUNK(64) entries, each next twice the last, so a query that wants a few rows reads a few; provided overscan, the local implementation fills chunks straight from the engine; a chunk scan may alsoseekforward to a key —falsewhere it cannot — and fill a chunk with only the keys awantpredicate takes, passing the others by their keys, their values not read, up tomostof them:next_chunk_where),shared()(the transaction’s reads as aKvRead— the same read methods,Sync— for worker threads to share while it is borrowed,firstamong them without the empty ranges remembered, which the workers would contend for; defaultNone),split_points(start, end, parts)(up toparts - 1keys cutting a range into parts of about equal size, from the B+tree’s internal nodes — each node’s children in the range found by binary search —, none smaller than 64 leaves; default none),first(start, end)(the range’s first entry, without a scan’s read-ahead; the engine’s transaction, outsideSERIALIZABLE, remembers up to 8 ranges it found the store empty in — where none of its own writes lay — until its intents next enter the store, and answers a look inside one from its write set: a load’s look past the stored rows reads the store once, not once a row),put(&mut self),delete(&mut self),put_new(key, value) -> bool(sets a key that has no value, elsefalse; by defaultgetthenput, locally one look at the key’s versions decides both the value seen and the write’s conflict),fresh(start, end)(declares a range no version and no other transaction’s write can be in until this one ends, and no one else reads before it commits — a new index’s keys: locally, their writes skip the conflict checks, and their values the WAL, §5.2; by default ignored),watched_as_at(at)(whether it reads the keysKv::watch(start, end)watches as a snapshot atatdid — no commit between the two, nor this transaction, wrote one; §5.2; by defaultfalse, andKv::watchdoes nothing),commit(self: Box<Self>) -> Timestamp,rollback. Reads take&selfso a scan can stay open while the same transaction reads keys. A scan reads ahead 8 entries at first, twice as many at each refill up to 128, so one that wants a single entry reads few.TxnOptions { isolation, read_only, at }(read_only(),serializable()).Error:Conflict { key }(the only retryable one —is_retryable()),SnapshotTooOld,ReadOnly,KeyTooLarge,Storage(boxed).- Helpers:
transact(kv, opts, f)runsfand commits, retrying on conflicts (100 attempts,back_offbetween them);prefix_end(prefix)gives the exclusive upper bound of a prefix scan. - Not yet in the contract: reverse scans, scan limits pushed down. They will be added as provided methods, so implementations keep compiling.
Database is the local implementation: Database::open(dir, Options) on
the real file system, open_on(platform, dir, Options) on any platform;
checkpoint, vacuum, latest, pages (the data file’s pages and the free ones among them), scratch_files_made, close. Options: cache_bytes (128 MiB — 16 MiB on 32-bit targets —, a frame allocated when first used — made with the page read into it, so a cold scan after a start allocates no empty page only to replace it (issue #2: TPC-H Q6 cold 226.6 → 187.3 ms); LSM tables’ block cache shares it — it takes what the page cache’s frames leave, at least a quarter —, filled only as they are read),
checkpoint_wal_bytes (1 GiB — 64 MiB on 32-bit targets), wal_segment_bytes (16 MiB), history
(0), txn_memory_bytes (64 MiB: a transaction’s writes held in memory
before they spill, §5.2). tests/contract.rs holds the contract as a suite any implementation
must pass (run on the simulation and on real files, plus 8 threads through
Arc<dyn Kv>).
6.2 The nucleus CLI
nucleus --version
nucleus kv <dir> get <key> | put <key> <value> | delete <key> | scan [<prefix>]
nucleus kv <dir> checkpoint | vacuum
nucleus kv <dir> # shell: the same commands, plus begin/commit/rollback
nucleus sql [<dir> | :memory:] [-h <host[:port]>] [-p <port>] [-U <user>] [-d <db>] [--password <pw>] [-c <sql>]
ncsql … # the same shell under its own name
nucleus server <dir> [--listen <addr:port>] [--password <pw>] [--log-queries] # §9
nucleus restore <repository> <dir> [--at <commit|backup|time>] [--subject-keys <file>] [--backup-key <file>] # §8.30
nucleus restore <repository> --test [--subject-keys <file>] [--backup-key <file>] # a restore test, §8.30
nucleus branch <dir> create <name> [--from <branch>] [--at <time> --history <duration>] | list | drop <name> | reset <name> # §8.32
nucleus dump --schema [<dir> | :memory:] [connection options of nucleus sql] # §8.33
nucleus migrate new <name> | status | up [--to <v>] [--dry-run] | down [--to <v> | --all] [--dry-run] | diff [--new <name>] [<dir>] [connection options] [--dir <migrations>] # §8.34, §8.36
nucleus codegen <ts|rust|python|java|proto> [<dir> | :memory:] [connection options] [--out <file>] [--tables <a,b> | --queries <file|dir> …] [--import <module>] [--package <name>] [--class <name>] # §8.37
nucleus status [<dir>] [connection options] # a server's health for people, §8.38
nucleus keys <dir> list | import | encrypt | rotate-root --to-… | rotate <data|secrets|subjects|backup> [root key options] # the key hierarchy, §9
nucleus sql <dir> -d <branch> opens a local database’s branch.
:memory: in place of a directory (nucleus sql, nucleus kv) is a
database in the process, gone when it ends — the embedded editions’
name (Database::open_in_memory, Options::in_memory: the memory
platform’s files, smaller WAL segments, sooner checkpoints; no key
files for secrets beside it).
Keys and values are text; any byte can be written as \xNN (\\ for a
backslash), and output escapes non-printable bytes the same way. Outside
begin each command is its own transaction; an open transaction at the end
of input is rolled back. crates/cli/tests/cli.rs drives the binaries.
ncsql (§M14.6) is nucleus’s SQL shell: with a directory it opens
that database itself; otherwise it connects to a nucleus server over the
nucleus protocol (default 127.0.0.1:20035, user, password and database
nucleus; the password also from NCPASSWORD). An error prints its hint
on a HINT: line. Statements end with ; (a script on stdin,
or one -c command); the prompt shows * in a transaction block and !
in a failed one. A line beginning db. is a request on a collection’s
documents as MongoDB’s shell writes it (§M16 Q4) — db.<collection>.
find(filter, projection) with .sort(…), .skip(n), .limit(n) on the
same line, findOne, countDocuments, insertOne, insertMany,
updateOne, updateMany, replaceOne ({upsert: true} as the third
argument), deleteOne, deleteMany — its arguments JSON or the shell’s
relaxed form (unquoted keys, single quotes, trailing commas; their order
kept), over lines until its brackets close; it is compiled to the
statement a driver’s O is (§10 Documents) and its result printed as
a statement’s. Its backslash commands read nc_catalog (§8.11), so they
work the same locally and remotely:
| Command | Shows |
|---|---|
\d, \dt, \tables |
tables, with index, foreign key and statistics counts |
\d <table> |
columns, then indexes (with index ids), foreign keys, referencing tables, checks; the title has the table id, key prefix and whether it is analyzed |
\indexes [<table>], \di |
indexes |
\fks [<table>] |
foreign keys from or to a table |
\stats <table> |
ANALYZE statistics |
\lint <statement> |
the linter’s findings (ANALYZE QUERY, §8.13), or “No findings.” |
\statements |
the 20 statements that took the most time (nc_catalog.statements) |
\copy <table> [(<columns>)] FROM '<file>' [WITH (…)] |
loads the file (text, or CSV with FORMAT csv) through COPY … FROM STDIN (§8.7), locally or over the network |
\schemas, \dn · \types, \dT |
schemas, types |
\wait <stream> [<after> [<ms>]] |
waits for a stream’s entry after seq <after> (by default its newest now: the next one), at most <ms> (30 s by default): its newest seq — no transaction held (the w message over the network, Session::wait_stream locally; §8.43) |
\live [<batches> [<ms>]] <query> |
subscribes to the query (SUBSCRIBE, §8.47) and prints its result, then each commit’s change as it comes — (nc_ts, nc_diff, columns…) rows — until <batches> came (10 by default) or <ms> passed without one (30 s by default); then UNSUBSCRIBE |
| `\timing [on | off]·\echo TEXT·\conninfo·?·\q` |
The network side is nucleus-client (crates/client), the Rust driver
(§11).
6.3 Packaging
scripts/package.sh <rust-target> [<out>] builds a release and writes, per
PLAN.md “Packaging and install”: nucleus-<v>-linux-<arch>.tar.gz (gnu),
…-linux-<arch>-musl.tar.gz, …-macos-<arch>.tar.gz,
…-windows-<arch>.zip, and for musl targets nucleus-<v>-d-os-<arch>.tar.gz
(<arch> x86_64, aarch64, i386). Every archive has one top directory
nucleus-<v>/ with bin/ (nucleus and ncsql), LICENSE, README.md;
the d-os one adds the .dos-app manifest from integrations/d-os/ (linking
/bin/nucleus, /bin/ncsql, /bin/nucleus-settings). CI packages every
tested target, unpacks it and runs nucleus --version and ncsql --help. .github/workflows/ release.yml does the same for every target on a v<version> tag (the tag
must match Cargo.toml) and attaches the archives to a GitHub release. No
release has been tagged yet.
Installing (§M14.17 E1). Where dpkg-deb / rpmbuild are
installed, the musl targets also give nucleus_<v>_<amd64|arm64|i386>.deb
and nucleus-<v>-1.<arch>.rpm: the static binaries in /usr/bin, any
distribution’s (sudo apt install ./….deb, sudo dnf install ./….rpm —
unsigned yet: rpm 6 refuses rpm -i without --nosignature, dnf takes
a local file with a warning). The release adds SHA256SUMS, the
Homebrew formula nucleus.rb and the winget manifests
(scripts/manifests.sh <dist>: macOS’s archives and Linux’s static ones
for brew; the zip’s two programs as portable commands for winget —
published to a tap and to winget-pkgs by the maintainer), and pushes
the container image ghcr.io/<owner>/nucleus:<v> / :latest, amd64
and arm64 (packaging/Dockerfile on scripts/image-context.sh’s
context: the static nucleus on distroless’s static base — a /tmp,
CA certificates, the user 65532 owning /data, 33 MB; ENTRYPOINT nucleus, CMD server /data --listen 0.0.0.0:20035, so it refuses to
start without NUCLEUS_PASSWORD or a claimed database, and docker run --rm -it <image> sql :memory: is a shell). scripts/install.sh
(Linux, macOS; sh, curl or wget, sha256sum or shasum) and
scripts/install.ps1 (Windows) take the release’s SHA256SUMS, pick
the platform’s archive — Linux’s static one, macOS’s native one under
Rosetta too —, check its SHA-256 and put the binaries in
~/.nucleus/bin (%LOCALAPPDATA%\nucleus\bin, added to the user’s
PATH; install.sh tells the PATH, edits nothing): NUCLEUS_VERSION,
NUCLEUS_INSTALL and NUCLEUS_DOWNLOAD_URL (a mirror or a directory)
change where from and to. CI runs them on every push against the
packages it just built (Linux musl, macOS, Windows), installs the
.deb and, in a Fedora container, the .rpm, and builds and runs the
image: a query in memory, then the server reached from the host.
d-os: the archives are built and checked in CI (layout, manifest), but installing and running them on d-os needs the d-os harness and has not been done yet.
6.4 Benchmark baseline
cargo run --release -p nucleus-kv --example bench (real files). First
numbers, 2026-10-17, Apple Silicon laptop, APFS (F_FULLFSYNC), 100-byte
values:
| Workload | Rate |
|---|---|
| single-row commits (one fsync each) | 242 /s |
| rows in 500-row commits | 23 184 /s |
| single-row commits, 8 threads (group commit) | 698 /s |
| point reads (one read-only snapshot) | 98 881 /s |
| full scan | 3.6 M rows/s |
Commits are fsync-bound, as they should be on a durable store. Point reads are bounded by decoding whole nodes per level (§4.4).
6.5 nucleus mcp (modules/mcp)
nucleus mcp [<dir>] [nucleus sql's connection options] [--allow-writes] [--memory] [--allow-erasure] [--max-rows <n>] [--timeout <ms>] serves the Model Context Protocol on
standard input and output (JSON-RPC 2.0, one message per line; protocol
versions 2025-06-18, 2025-03-26, 2024-11-05), for a local database
directory or a server. An MCP client — an AI assistant, an IDE — starts
it as a command ({"command": "nucleus", "args": ["mcp", "/path/to/db"]})
and gets the tools: list_tables (name, comment, analyzed rows),
describe_table (columns with type, nullability, default and comment;
primary key, indexes, foreign keys, referencing tables), sample_rows,
summarize_table (SUMMARIZE), query ($1… from params, bound as literals), explain (and
analyze), lint (ANALYZE QUERY), and with --allow-writes
execute. With --memory (§8.28), independent of --allow-writes:
remember (store, subject, content; kind, confidence, expires_in an
interval, source, replaces — a REMEMBER, its id and action back),
recall (store, subject, query, k up to --max-rows; read-only, as
the other reads), forget (store, id: a DELETE, how many back) and
cite (store, ids, as_of: the memories AS OF COMMIT as_of — id, kind,
content, confidence, valid_from, valid_to, source; read-only) — an
agent keeps memories without being given every write. With
--allow-erasure (Options::erasure), on its own: forget_subject
(subject: FORGET SUBJECT, §8.29, its row back). A tool not
offered is unknown (-32602). The initialize answer’s instructions
tell the model where to start.
Reads cannot write: the edition parses a read tool’s SQL with nucleus’s
parser and refuses it (25006, with a hint pointing at execute) unless
every statement is a read (a query, EXPLAIN, SHOW, ANALYZE QUERY),
and the module runs it in BEGIN READ ONLY … ROLLBACK, after SET statement_timeout (default 5000 ms). At most --max-rows rows (default
100) are returned, row_count and truncated saying how many there were.
Results are JSON (structuredContent and the same as text): booleans and
integers as JSON’s, real and double precision as numbers, a json
column’s value as the JSON itself (its text instead where a number in it
has more than 15 significant digits and is not a 64-bit integer — what
a JSON reader’s f64 would change), the rest — numeric too — as
strings, NULL as null. A failure is the tool’s
(isError), its text ERROR: … (SQLSTATE) and HINT: …; an unknown tool
or method is a JSON-RPC error. The module is the protocol over a
Database trait (SQL text in, answers with column types out); the
edition implements it for nucleus sql’s backends.
Over HTTP (the module’s http feature, nucleus_mcp::http::Mcp;
§M16.6b, D19): nucleus server --web serves the same tools at /mcp,
MCP’s Streamable HTTP transport, for a client that cannot start
nucleus mcp on the database’s machine ({"url": "https://db.example:20039/mcp", "headers": {"Authorization": "Basic …"}}). A POST of JSON-RPC (one message or a batch) is answered as
JSON; one of notifications and responses only is 202. Each request
logs in as the web front end’s services do (Basic or Bearer,
?database=, the roles, access rules and budgets) and runs the tools in
that session, reads read-only as above. No MCP session is kept (no
Mcp-Session-Id) and no stream opened: GET and DELETE are 405.
Refused: an Origin that is not the loopback’s (http://localhost:…,
127.0.0.1, [::1]) nor named by --mcp-origin (403, against DNS
rebinding; a request without one is not a browser’s and is taken); an
MCP-Protocol-Version not spoken (400); a body not
application/json (415) or not JSON (400, -32700); an Accept
without JSON (406). The tools offered: --mcp-allow-writes,
--mcp-memory, --mcp-allow-erasure (as nucleus mcp’s flags);
--max-rows and --timeout keep their defaults. OAuth’s discovery
(resource metadata) is not served. Checked with the official
TypeScript SDK’s Streamable HTTP client.
6.6 Ranges (nucleus-range, §M18)
The keyspace cut into ranges — the unit §F3 replicates and places (PLAN.md D26). On one node they are logical: a range is a span of keys and its descriptor, its keys stay in the one store, and a split or a merge is a transaction over descriptors that moves nothing.
Descriptors are keys (principle 8, DOCS §8.2): 00 26 02 01 <end>
holds the range ending at <end> (00 26 02 02 the last one) — keyed
by end key, as CockroachDB’s meta2 records and Bigtable’s METADATA rows,
so the first record after 01 <key> names the range holding key. A
descriptor holds its id, start and end, a generation raised by every
split and merge (TiKV’s region epoch), and two flags: its start set by
hand (sticky) or a boundary no merge takes away (forced). A new database has one range, [ , ), id 1. Being
keys, the descriptors are copied with a branch (it begins with its
parent’s ranges and splits on its own) and by a backup, and replicated.
RangeStore — one per open branch in a process — holds the ranges
as they are, loaded from their records, and makes the changes: split (at, sticky) (the left keeps its id, the right takes the next one, both
a generation on; at a range’s start it does nothing but set sticky) and
merge(key, force) (the range holding key consumes the next, keeping
its id, a generation past both; a sticky start stays unless forced) —
each one transaction over the records, made in memory once it
committed. serve(id, generation, key) is a range server’s check: a
request cut for that range at that generation runs; any other is
refused with the range holding its key now.
Ranged is a Kv over the local one (principle 12): its
transactions route every read and write through the router — a
location cache in front of the servers, filled by lookups, corrected by
each refusal (the refused part cut again; CockroachDB’s DistSender,
TiKV’s region cache). A scan, chunked or not, a first, a range’s
validation are cut at each range’s end and go on in the next, looked up
as it is reached; each part runs within its range’s keys alone, as its
server would hold them once ranges live apart (a router that did not go
on loses rows: what the tests see). The parts run on the store’s one
transaction, so commits stay atomic across ranges as the store’s are
(§M21 replaces this when ranges live apart). Parallel scans’ workers
read the store’s snapshot directly (cutting their work by range is
§M22’s).
The router’s cost (§M18 S5). A router’s location cache is a
view of the ranges, kept by each thread for each store (by the store’s
id, at most eight): every change of the ranges publishes a new view and
then raises the store’s epoch. A request whose thread’s view is of the
epoch now is routed in it — the range servers’ check of each range’s
generation, short-cut on one node: no range changed since the view was
taken — at the cost of one load of a word only splits and merges write.
In the view: the range the transaction routed to last, tried first by
the view’s own ends; else a search over the ends kept in one buffer, the
eight bytes past their common prefix as big-endian words searched
branch-free, ends compared whole only between equal words. A request
whose view is older asks the range’s server ([RangeStore::serve]), is
refused and cut again if the range changed, and the thread takes the view
afresh. Nothing shared is written per request but the range’s counter: a
stripe of it a thread (eight, on a cache line each, the stripe also
holding whether the range is sampled), and a transaction counts its
reference on one of eight handles on the router, not on the router
itself. The first router took a lock and a reference count on shared
lines and allocated per request: 8 threads reading one range ran 60 %
slower than the local store. Measured (crates/range/tests/cost.rs,
1M keys of 100 B, in memory, rounds interleaved, medians; percent against
the local Kv):
| one range | 1,000 ranges | |
|---|---|---|
| point reads, 100 a transaction, 1 thread | +1.6 % | +8.6 % |
| the same, 8 threads | +1.1 % | +12.0 % |
| point reads, one a transaction, 1 thread | −2.7 % | +2.5 % |
| the same, 8 threads | +0.3 % | +2.5 % |
| single-key commits | −1.0 % | +0.4 % |
| full scans | +1.4 % | +8.2 % |
The round-to-round spread is ±3 %. A thousand ranges of a thousand keys
(116 kB each) is a stress, not a layout: at the default sizes (256 MiB)
that many ranges hold 64 GB or more. There each read pays a search over
a thousand ends and a counter line of its own (about 18 ns in all,
measured apart), and a scan opens a piece at each range’s end. TPC-H at
scale 1 through nucleus server --ranges against the same
build without (bench/phases.py reads --nucleus-args=--ranges, five
runs): every query within the noise, the geometric mean 1.004. Splits
and merges while 8 threads read across 100 ranges: 79 a second cost the
reads 8 %, 733 a second 20 % (each change makes every thread’s view
stale once); the background check takes 34 ms a pass over 1,000 ranges,
every 10 s by default.
Tests. The ranged KV against the store under random reads, writes,
scans (bounds of every kind, chunked, seeks across ranges) and
get_many, ranges split and merged at random between operations —
inside transactions, so their caches go stale; a stale cache refused
and corrected; ranges across a reopen and in a branch. Every
sqllogictest script also runs through it with changing ranges
(Ranged::with_chaos): after about a third of the commits a split at a
key the commit wrote, after a tenth a merge — 462 splits, 201 merges and
585 parts refused and cut again over the scripts, every answer the
same.
Where a range may end (§M18 S2). The layer above lays out its keys,
so it says: a KeyLayout (KV contract; the SQL layer’s is
nucleus_sql::ranges::layout(), given with Ranged::with_layout) has
unit_start(txn, key) — the start of the unit holding a key, keys
never cut apart — and boundaries(txn, start, end) — where ranges
should end, each forced or not. SQL’s units are a row’s long values’
chunks (01 <table> FFFFFFFF <pk> …: the primary key read with the
table’s key columns from the catalog) and a column segment’s columns
(… FFFFFFFE <segment> …); a row and an index entry are one key each.
Its boundaries are each table’s start and where the tables begin, a
partition’s start and end forced. A split rounds down to a unit’s
start; a merge leaves a forced boundary — a descriptor’s (a route’s: the
ranged store makes a table’s route ends forced as add_engine makes the
route, one engine a range) or the layout’s — even when forced over a
sticky one. check() also finds a range starting inside a unit.
SQL. ALTER TABLE t SPLIT AT VALUES (v, …), … makes ranges start at
those primary key values — a prefix of the key may be given, so a split
falls between rows — kept from merges (sticky; CockroachDB’s statement);
UNSPLIT AT VALUES … gives them back to the merges, UNSPLIT ALL every
sticky start inside the table. Done as the statement runs, not with its
transaction (as a branch is made); a partitioned table’s partitions are
split each on its own (42809); a database not cut into ranges refuses
(0A000). nc_catalog.ranges (range_id, start_key, end_key
— bytea, the last one’s end null —, generation, sticky, forced,
table_name — the table its start lies in, bytes — about how many it
holds, load — the requests a second its server counted at the last
check): empty when the database is not cut into ranges. The KV contract carries it: Kv::ranges(),
split_range(at), unsplit_range(at) (the local store: none, refused).
Sizes (§M18 S3). A range’s size is estimated, not counted on a
commit (TiKV’s approximate sizes, FoundationDB’s sampled ones): the KV
contract’s approx_bytes(start, end) — every version kept, keys and
values as stored — asked of each engine over its part. The B+tree
counts the leaves over the range from its internal nodes (a level of
more than 1024 nodes thinned evenly, the count scaled back) and reads up
to 64 of them, evenly spread, for their bytes in the range, an
overflowing value’s chain counted by the length its cell holds:
“pages × fill”, about a hundred pages read, exact over a range of a few
dozen leaves; noisier (within ±25 % in the tests) where a few large
values hold most of the bytes. An LSM tree adds its runs’ blocks over
the range from their indexes in memory and its memtables’ entries (the
first 4096 summed, past them its sampled keys standing for the rest).
RangeStore::balance(sizes) is one pass of the periodic check: each
range past split bytes split once — tables first, at the table
start (the layout’s boundary) that balances it best, so a large table
comes apart from the small ones beside it; within one table about its
middle by bytes (the store’s split points), rounded to a unit — then,
from the first range on, a range below merge merged with the next
while the two hold under merged, across a table’s start too (small
tables share a range) but never across a forced or sticky one. The
defaults: split past 256 MiB, merge below 64 MiB into under 128 MiB —
the gap between them keeps a merged range from splitting again. A
replica’s pass does nothing (its primary’s records rule).
Load (§M18 S4). A range’s server counts the requests it serves —
each key read or written, each piece of a scan — in counters striped
over cache lines (threads serving one hot range do not share one), kept
beside the descriptor and counted afresh from each split or merge. Each
check takes every range’s rate (requests a second since the check
before). A range past LoadRules::per_second is hot: from then on one
request in four is offered to a reservoir of 128 (Vitter’s algorithm R)
— a key, or a scan’s span. Hot at two checks in a row, it is split
where the sample says: the distinct sampled keys weighted by their
requests, a cut allowed only where at most a quarter of the requests
cross it (CockroachDB’s test of few requests crossing the new boundary),
cut into up to parts parts — ⌈rate / threshold⌉ of them, not halved
round after round — whose heaviest is as light as can be: exact
chains-on-chains partitioning (Pınar and Aykanat, JPDC 2004: a binary
search over the bottleneck, each tried by a greedy probe cutting each part
as late as allowed). Refused, with the reason in the check’s result:
one direction (more than 80 % of the offers a new highest or lowest key —
a sequential insert, which a split moves along), requests crossing every
cut (scans of the whole range: each part’s load counts every request
that touches it), one key holding nine tenths of the load (a key at less
than that ends in a part of its own, as Spanner isolates a hot row). A
load split’s parts count as hot from the split on, so a part still hot
is split again at the next check, and are kept from merges for
hold; ranges merge only when together they serve under half the
threshold. Defaults (LoadRules::DEFAULT): 2,500 requests a second
(CockroachDB’s load_qps_threshold), 8 parts, held 5 minutes
(its by_load_merge_delay); the hold is in memory (a restart lets them
merge). Measured (crates/range/tests/load.rs, 80 % of the reads on a
tenth of 10,000 keys, a test clock, five seeds): at 8× the threshold k
parts settle in 5.4 checks against halving’s 8.0, at 32× in 11.0 against
13.8, as many ranges in the end.
The server: nucleus server --ranges cuts its database into ranges
(its branches too) with the SQL layer’s layout, and runs the size check
in the background (Ranged::balance_every, a thread, a pass over every
branch of the database open in the process): --range-split <size>
(default 256MB; merges below a quarter of it into under half), by load
past --range-load <requests/s> (default 2500, 0 none) every
--range-check <duration> (default 10s). Without --ranges the store
is the local one, unchanged. A replica keeps its ranges in memory, as
loaded. On TPC-H SF1’s column tables (1.2 GB estimated) a first pass
found four ranges — the catalog and small tables (74 MiB), orders,
lineitem in two of 484 and 562 MiB — and the next two cut lineitem
into six of 129 to 243 MiB within seconds, orders and the small tables
left whole.
Crashes. A crash at every I/O operation of a workload of writes, splits, merges and unsplits (dropped unsynced writes, torn writes): reopened, the ranges cover the keys and are those some step left, with that step’s data — a split or a merge is one transaction (a mutant writing a split’s two records in two is caught).
Size tests. The B+tree’s estimate against the bytes summed entry by
entry (random ranges of trees past 1024 leaves, one value in fifty in
overflow pages), the LSM tree’s in its map, its tail, its runs written
by a save and by spills; ranges loaded past the split size split until
each fits, settle (another pass changes nothing), emptied and vacuumed
merge again, every key read through them; a small range left beside one
the two would make too large; the background check under three writers
reading what they wrote; in SQL, a large table cut apart from five small
ones and a middle-sized one, the small ones sharing a range; the server
splitting in the background. Mutants, all killed: splits blind to
tables, merges past merged, overflow chains not counted, the thinned
level not scaled back, the memtable’s sampled rest not counted, a run’s
blocks counted from its first.
Load tests. Chains-on-chains against brute force (3,000 random
weight sequences with forbidden cuts); a hot range split where its load
is, until no range is hot, k parts against halving; a sequential
insert, scans of the whole range and one hot key left whole, each with
its reason; a load split’s parts held from merges, then merged once cool
and the hold over; a part still hot split again at the next check; the
rates requests a second; in SQL, reads on 500 of a table’s rows cutting
it among them. Mutants killed: spans counted as points, no direction
test, no hold, the greedy probe cutting early, rates not per second, no
counting, a split’s parts not taken as hot.
6.7 Raft (nucleus-raft, §M19)
Ranges are to be replicated by Raft, a group a range (D27). The crate holds the protocol, its storage, membership changes, reads, a key-value store with client sessions, a linearizability checker and the simulator it is all tested in; R5 adds the groups of a node’s ranges.
The protocol (nucleus_raft::Raft) is a pure state machine, as
etcd’s raft library is (its documentation; written fresh): fed messages
(step), ticks of the caller’s clock (tick) and commands (propose),
it does no I/O and keeps no clock. What it needs done it hands out as a
Ready: the entries and the hard state (term, vote, commit) to
persist, the entries first — entries[0] and after replace what is
persisted from its index — the
messages to send once they are, the committed entries to apply; then
advance. So nothing is promised before it is durable: a vote, a
follower’s acknowledgment, and a leader’s count of its own entry all
wait for the write they rest on.
Raft as the paper has it (Ongaro and Ousterhout, 2014) — terms,
randomized election timeouts (election_ticks to twice it), the log
replicated by appends checked at their previous entry, commit once a
majority holds an entry of the leader’s term (§5.4.2; a new leader
appends a no-op so its predecessors’ entries commit) — with the thesis’s
additions (Ongaro, 2014):
- Pre-vote: a member asks whether it could win at the next term before raising its own; one cut off and back does not depose a working leader by its raised term.
- CheckQuorum: a leader that heard no majority for an election timeout steps down; a member that heard its leader within one ignores votes (the leader still holds its lease).
- Appends sent ahead while a follower keeps up (
nextoptimistic), one probe at a time after a refusal; a refusal names where the logs may agree (the last index at most the refused term’s — etcd’sfindConflictByTerm), a whole term skipped a round trip; a follower whose appends are out but untaken for three heartbeats is probed again (lost, or slow). A follower commits only what it is known to share: an append’s last entry, a heartbeat’s commit at most what the leader knows it holds. An append repeated, late or out of order changes nothing; one that differs replaces the tail from where it differs, never a committed entry.
Storage (nucleus_raft::LogStore): a node keeps all its groups in
one append-only file of records — [length u32][crc32c u32][group u64][tag u8][body], a hard state, a run of entries or a snapshot — on
the platform’s FileSystem. Each group’s Ready is saved, and all are
written with one write and one sync a round (TiKV’s batch system: the
cost of a sync shared by every group with something to persist).
Recovery reads the records in order and stops at the first that is
short or whose checksum fails (a torn write’s zeros make an empty
record, refused by its length), truncating the file there: what follows
was never synced, so never acknowledged. A round’s records are written
entries before hard state, as etcd’s WAL saves them: a torn write keeps
a prefix, and a hard state’s commit kept over a log that lost what it
commits would apply the entries it was replacing (the simulator found
this in §M20 C3 — seed 1793, after the order had held for every run
before). Once a segment is past its
limit — or twice the live state last rewritten, if that is more — the
live state of every group is written to a new segment between a
begin and an end record, synced, and the older segments removed;
recovery starts at the newest segment that is whole, so a rewrite cut
short, or older segments half removed, leave the state as it was. A
directory the store makes is synced into its parent.
Snapshots: the caller persists its state machine’s snapshot at an
applied index and hands it to Raft::compact, which drops the log up
to it. A leader whose member needs entries it no longer holds sends
the snapshot instead (one at a time, as a probe). The member ignores
it if it committed as far, takes it as a commit if its log holds the
snapshot’s last entry (the log matching property: then everything
before matches), and otherwise installs it in place of its log —
handed out as Ready::snapshot, persisted and installed in the state
machine before anything after it.
Membership (Raft::change_membership): a group’s members are
voters and learners (which take the log and never vote or stand). The
membership is an entry of the log, in effect as soon as a member holds
it, committed or not (the thesis, §4.1) — so a member whose log is cut
back returns to the membership before it, and a snapshot carries the
membership as of its index. A change of voters passes through a
joint membership (the paper, §6): old and new voters both vote, and an
election or a commit needs a majority of each; once the joint entry
commits, the leader appends the new membership by itself. One change at
a time: the leader refuses another while the last is not committed (or
is joint). A node added later starts knowing no membership — it learns
it from its leader’s appends or snapshot — and does not stand until it
is a voter. A leader not among the new voters keeps leading until the
new membership commits, then steps down (§4.2.2); a member removed
stands only while its removal is not yet committed in its log — it may
be the one needed to commit it (a leader that lost its lease before the
new membership committed, the only member holding it). Replacing a
member: add the new node as a learner, wait until it is caught up
(Raft::caught_up), then change the voters. Caught up is measured in
rounds (the thesis, §4.2.1): a round runs from the leader’s last index
when it began until the member holds that index; a member whose last
round took less than an election timeout, and whose round under way is
not yet older, keeps up — under steady writes a member is always a few
entries short of the commit, so holding the commit alone is rarely seen.
Reads without a write to the log (the thesis, §6.4). ReadIndex
(Raft::read_index(ctx)): the leader notes its commit — or, if it has
not yet committed an entry of its term (it may not know the latest
commit), the commit once it has — and confirms it still leads by a
round of heartbeats sent after the read was asked: heartbeats carry a
round number, answers echo it, and once a majority (of each set, if
joint) answered that round or a later one the read is handed out as a
ReadState in Ready::reads, to be served when the state machine has
applied its index. Reads asked between two readys share one round.
A leader that steps down drops the reads not yet confirmed; their
callers ask again elsewhere. Lease reads (Raft::lease_read): with
CheckQuorum, a member that heard a leader ignores votes for an election
timeout of its own ticks — counted from when it last heard one, not
reset by a term raised meanwhile, and from its start, since it may have
answered a leader just before a crash. So once a majority answered a
round, no other leader can be elected for that long; the leader serves
reads at its commit without a round trip while fewer than
Config::lease_ticks of its ticks passed since it sent the round — the
election timeout less one tick (the first may come at once), cut by the
ticks’ possible drift (clock_drift_percent, 10 % by default). The
ticks must count the time that passed: after a pause, every tick
missed.
Many groups on a node (nucleus_raft::multi::MultiNode, multi-raft):
a node holds a member of each of its ranges’ groups, and shares what is
costly per group. A round persists the ready of every group touched
since the last with one write and one sync (the LogStore), advances
each, and packs the messages one packet a destination node — a tick’s
heartbeats of a thousand groups between two nodes are one packet
(CockroachDB’s coalesced heartbeats, generalized to every message of a
round); every node sends every peer node a packet each tick, empty if
need be, so its peers hear it is alive. Quiescence (CockroachDB’s;
TiKV’s hibernate regions): a leader whose group is idle
(Raft::is_idle — every member holds its whole log, all committed,
applied and persisted, nothing waiting, no membership change under way)
stops ticking it and sends its followers a notice, on which a follower
whose log ends at the leader’s commit with an entry of the leader’s term
stops too (Raft::quiesce: its log is then the leader’s, so it may take
that commit). Any message for the group, a proposal or a read wakes it;
the quiesced followers of a node silent for an election timeout wake and
elect another leader. A quiesced group’s timers stand (a follower keeps
its promise, a leader its CheckQuorum window) but its lease clock is
caught up when it wakes (Raft::quiet_ticks), before it serves
anything. A round looks only at the groups touched since the last, a
tick only at those awake: an idle group costs nothing. Measured
(multi_raft_costs, 3 nodes, 100 commands a second, a simulated second):
| groups | packets | messages | wall time, awake | wall time, quiesced |
|---|---|---|---|---|
| 1 | 1,410–1,560 | 880–1,160 | 3.6 ms | 2.5 ms |
| 10 | 1,410–1,940 | 890–4,640 | 3.1 ms | 1.4 ms |
| 100 | 1,410–1,940 | 880–39,600 | 23.2 ms | 1.8 ms |
| 1,000 | 1,410–1,940 | 880–390,000 | 317 ms | 1.4 ms |
Packets stay at one a destination a round whatever the groups (without packing, they would be the messages); quiesced, 1,000 groups cost what one does.
A key-value store (nucleus_raft::kv): puts, compare-and-swaps
(from a value or from nothing, to a value or to nothing — each
returning what the key held), deletes (returning what was removed) and
reads through the log, on byte keys and values, each a client’s
numbered command. Client sessions (the thesis, §6.3): the
state machine keeps each client’s last command number and its result;
a command committed again — its answer lost, the client retrying
elsewhere — is answered with the first’s result and not applied again,
and an older one is ignored, so each takes effect at most once, between
its call and its answer.
Ranges as groups (nucleus_raft::range): each range of keys is one
group’s state machine — a §M18 Descriptor (its keys [start, end),
its id the group’s, a generation raised by every split and merge) —
and it splits and merges by commands of its own log. A client’s command for a key the
range no longer holds (it split or merged since the client looked) is
refused (moved), not applied, and the client asks again where the
routing now says; a range frozen for a merge refuses everything. So a
key’s history runs unbroken across splits and merges.
On the storage engine (§M19 R6): a node’s ranges share its one store
(a nucleus_kv::Database, the simulator’s on each node’s simulated
disk beside its Raft log), as §M18’s ranges do: a range’s keys are the
store’s keys in its span, and beside them, by range id, what its log
made of it (CockroachDB’s range-ID-local keys, 00 27 <id>): the last
entry applied, the descriptor and whether frozen, each client’s session,
the members it started with, and — once removed here — a tombstone. An
entry applies in one transaction with what it writes, the store’s
commit durable, so a crash leaves a range at an entry’s edge and a node
restarted goes on from there. The Raft log and the store are two
files; wherever they change together the store goes first — a split
writes the new range there before its group starts, a member removed
goes from the store before its log’s tombstone — and a node starting
reconciles them: a range the store removed is removed from the log, a
snapshot the log persisted and the store has not is installed, a range
the store holds and the log does not is started, and entries committed
past what the store applied are applied. A snapshot is the range read
from the store in one transaction (its keys, sessions and applied
index together); installed, it replaces in one transaction what the
member held and the keys of its span.
- Split (
Admin::Split): the range keeps[start, at); the new range’s descriptor, members and a copy of the sessions are written in the same transaction, its keys left where they are. A split applied late on a node that removed the right-hand range already (merged away) deletes the right-hand keys: they are no range’s here (the merge to come brings them back) — as CockroachDB’s split trigger clears the right-hand data of a replica destroyed before it. Every member applies the split at the same index, so each starts the new group from the same state, as a snapshot at a fixed first index (10, term 5) with the same members — CockroachDB’s split trigger and initial log index. Every range starts so, the first ones too, so a member added later always starts from a snapshot of the range as it is, never by replaying the range’s past. - Merge, with the keys in place (CockroachDB’s, §M19 R6b): the two
ranges’ members on the same nodes, the right-hand range is frozen by a
command of its own log (
Admin::Freeze; it answers nothing more); once every member of it applied the freeze (CockroachDB’s wait for application), the left one proposesAdmin::Merge, naming the frozen descriptor and carrying no data: on each node the right-hand member’s keys stay where they are, the left’s now, its sessions join the left’s (each client’s later command kept), and it is removed for good — a tombstone in the store and in the node’s log store, so a late message never brings it back. A node’s right-hand member is so kept until its left one applied the merge: the routing’s garbage collection spares it while a member of the range it merged into is behind the merge here (CockroachDB’s replica GC does so), and a snapshot replaces a member of a range merged away only where the two share keys. A left-hand member that found its right-hand one not frozen as the merge names it would be a bug — the store refuses, the simulator panics; 5,000 seeds never did. - Each admin command names the generation it expects: a copy committed twice, or late, takes no effect.
A node’s ranges never share a key, as no store shared by them may —
checked after every event; and the store itself is checked after every
restart and at the end of every run: each range it holds is a member’s
of the node as that member has it, no key lies outside its ranges, and
the members of a range that applied as far hold the same keys and
sessions. The danger is a snapshot: a range’s
snapshot may meet, on a node, another range’s member over keys it holds
or will hold once its log catches up — taking keys in by a merge, or
splitting off a range that will. range::overlap decides from the
routing’s history of splits and merges — on both sides, for the
snapshot too may be older than a merge its range’s log will apply: a
member of a range merged away goes (CockroachDB’s replica GC queue; the
merge carried its state); a member of a live range makes the snapshot
refused until the two agree. Neither containment nor generations alone
tell the cases apart (a range that took a neighbour in and split again
holds part of its keys only): the simulator found each simpler rule
wrong in turn. A leader whose
member needs a snapshot first takes a fresh one (Raft::needs_snapshot)
and sends only that (Config::fresh_snapshots, Raft::send_snapshots)
— CockroachDB sends snapshots made at the moment; an old one may name
keys that moved since and be refused for ever, or predate a merge its
member could not then apply (its right-hand member long gone). The
members a snapshot replaces go when it is installed, in the same
transaction of the store — not when it arrives: a member whose log
holds what the snapshot carries already ignores it. A node restarted applies
again at once what its persisted commit covers, as a durable store
would hold it, so its ranges never go back before a split or merge.
A new range has a leader at once: the node leading the range it split
from stands for it on applying the split (Raft::campaign_now,
CockroachDB’s way), and a member that never answered a leader of the
range promised no lease, so it votes at once (Raft::promised_none);
a member removed by a merge tells the clients waiting on it that the
range is not here, and they ask again where the routing says. Measured
(range_change_costs, 3 nodes, a calm network, five clients on 8 keys
at 200 operations a second, 20 simulated seconds):
| changes a second | split | merge | commands moved | p50 | p99 | max |
|---|---|---|---|---|---|---|
| 0 | — | — | 0 | 2.0 ms | 3.5 ms | 18.3 ms |
| 1 | 6 ms | 34 ms | 8 | 2.0 ms | 3.7 ms | 41.4 ms |
| 4 | 8 ms | 34 ms | 71 | 2.1 ms | 27.3 ms | 67.4 ms |
A split is a commit and an election; a merge two commits (the freeze, then the merge) and the wait for every member to apply the freeze, during which the right-hand range’s keys wait — the tail (a merge carrying the frozen state took 27 ms, the slowest operation 38 ms). First, without the eager election, the promise forgone and the removed member’s answer, a split took 28 ms, a merge 132 ms, and the slowest operation 785 ms.
A node (nucleus_raft::node::Node, §M20 C1) is all of this for
one node — its groups (a MultiNode), their ranges and the store they
share — driven from outside by whoever owns the clock and the network:
tick; admit then step for a packet (a member made for a group it
does not hold, a snapshot let in only where it fits the node’s other
ranges, as the routing’s history says); persist and take for a
round (one sync; the packets are the caller’s to send, the snapshots
installed, the committed entries queued); apply (at once, or later:
a state machine may lag its log); send_snapshots; and a client’s
read by ask_read with ReadIndex or lease_read. What it has to tell
comes out as events — a client answered or sent elsewhere, a member
removed — and an error is a fault of its disk: it stops, and open
reconciles its log and store when it starts again. It knows nothing of
the simulator, the network or the time: the simulator drives it, and
the server is to run the same code. Moved out of the simulator without
changing a run: 1,000 seeds gave the same counts to the last command,
election and crash before and after (which found one slip — a lease
read through the member as it is, not woken: a quiesced group’s lease
clock is behind until it wakes, so a lease run out looks held; 1,000
seeds of the history checker did not see it. Raft::lease_read now
takes the member mutably, so a MultiNode’s is reached only through
raft_mut, which wakes it).
The system range and the driver (nucleus_raft::driver, §M20 C2,
D28). Group 1 holds the span 00 28–01 — clients’ keys start at
01 — and in it the cluster’s records: the cluster (its id, the next
range id), each node (address, locality, state: active,
decommissioning, gone), the history of splits and merges, each range’s
descriptor, and the change under way. They are written through its log
like any range’s keys. The driver is a state machine on that
range’s leader: it starts once an entry of the leader’s term has
committed and the node applied everything — before that, a new
leader’s commit index may be behind the cluster’s — and stops when the
node no longer leads. It writes one Op::Batch at a time, each
applied before the next, each holding the state it changes whole.
Every node sends it a heartbeat: that it is alive, the ranges it leads (term, descriptor, membership, whether frozen), which of its members are frozen, and how much of the split-and-merge history it holds. The answer carries the history it lacks. A node’s routing — what it asks before a snapshot may replace a member — is that cached history, a prefix of the driver’s: a stale one only refuses more. A node unknown is registered on its first heartbeat under the random 64-bit id it chose (as FoundationDB’s processes do: no allocation round); one of another cluster, or whose id another address holds, is refused. A node unheard turns suspect, then dead.
Splits and merges are the driver’s: it writes the intent first (a split’s new range id taken with it), sends the admin command to the range’s leader and again after a while, sees it applied in the leader’s report (the generation past), then writes the history, the descriptors and the intent’s removal at once. A merge first freezes the right-hand range and waits until every voter reports its member frozen. A driver elected mid-change finds the intent and carries it on. Data never waits for the driver: ranges elect, serve and lease without it.
Placement (§M20 C3). A rule covers a span of keys: how many
voters its ranges have, and the locality tiers their nodes must stand
in (region=eu); a new cluster starts with one rule for every key, and
a rule set over part of another cuts it back. From each range’s latest
report the driver decides, one step at a time, what the range needs —
TiKV’s PD has the same split, decisions in the driver, operators carried
out by the ranges’ leaders:
- a voter on a node dead, leaving or outside the rule, or too few voters: a learner added on the best node — fitting the rule, live, the most diverse from the voters kept (the fewest locality tiers shared, outermost first), then the one holding fewest replicas, as CockroachDB’s allocator ranks them;
- the learner caught up: swapped in for that voter (a joint membership), or added;
- too many voters: the most crowded, then the most loaded, removed;
- placed by count, but crowded — a node outside the range would share fewer locality tiers with the others than the most crowded voter does: a learner added there, then swapped in for that voter (CockroachDB’s allocator rebalances for diversity so). Each swap lowers what the voters share, so swaps end.
Each step is sent to the range’s leader as a membership change from
the members it was decided on: stale, it is ignored. A step is not
recorded — the range’s own membership is the state, so a new driver
picks up from the reports. A node unheard is suspect, never a place for
a replica, and dead only after dead_after (5 minutes in a server,
--node-dead-after).
Silence is measured by every node too — ticks since it last had a packet
from each node it hears from — and sent in its heartbeats: a driver just
elected takes the least silence the nodes it hears measured (a node any
of them heard lately is not dead), so drivers following each other
quickly still find a dead node dead. A learner no longer needed is kept while a voter
may yet be found dead. Decommissioning a node moves every replica
off it; once no range reports it, it is recorded gone, and its
heartbeats are refused — answered gone: the node then lets every
member it still holds go (one removed while it lagged, say) and takes no
more messages — to the cluster, the same as a node stopped for good, as
no range holds it and none will. A node that knows no driver asks the
nodes it joined by, then those its directory names, in turn (the first
node joined by none, and the driver may have moved off it). Splits need a range’s members steady; merges,
the two ranges on the same voters — the keys merge in place. A merge
whose member’s node dies, or leaves, before every member froze is
given up: an Unfreeze thaws the right range and moves its
generation on, so a freeze still on its way finds nothing to freeze
(CockroachDB aborts a merge so).
Collecting removed members. A member removed while its node was away, or lagging, never learns it: it stays — and, still a voter as it knows, stands for election over and over (without pre-vote it deposes the range’s leaders). A node tells the driver of its orphans — members that heard no leader for two election timeouts — each with the log index it knows its members as of. The driver has one dropped when the range’s leader reported lately, as of that index or later, that the node is no member, nothing changing (TiKV’s PD has a store’s stale peers removed so; CockroachDB has a replica GC queue). The node drops it only if it still hears no leader and learned no newer members meanwhile: a follower that hears a leader is that leader’s, which keeps what it acknowledged — a follower losing it would never be sent it again. Dropped is forgotten, not refused: the log store records the group forgotten — first, durably; then its keys go (a crash between finishes it) — keeping its term and vote, so a member made again later starts from them; and until a snapshot gives it the range again it votes for no one (its log is gone: members lagging in an old membership still count it a voter, and it would vote as if it never held what it helped commit). A node the cluster started with never makes a forgotten range again from its initial ones.
On the wire (nucleus_raft::wire, §M20 C4). What nodes send each
other is a Frame: a round’s packet of Raft messages, or a control
message — [tag u8][from u64][to u64][body], fixed-width and
little-endian as the log store writes, refused unless it decodes whole.
The simulator sends every frame through its bytes. The driver’s answers
carry a directory when the node’s is out of date: every node’s
address, locality and state, every range’s descriptor, voters and leader, with a
version (the driver’s term, then a count of changes) — what a server
routes by. A node that is not the driver answers a heartbeat with the
leader it knows of the system range, and its address.
A node in a server (nucleus_raft::host, nucleus_server::kvnode,
§M20 C4b). A Host drives a Node on a thread of its own as the
simulator does: ticks of a real clock (10 ms), frames in, a round after
each, its heartbeat to the driver (every 50 ticks), the driver’s turn.
Frames go to other nodes over ncp (version 16): a superuser’s login,
as §M17.5’s members have, then T messages, one frame each, never
answered — a thread and a connection a peer, a second for frames of
256 KiB or more (snapshots) so they do not hold back heartbeats; frames
for a peer that is down are dropped (Raft sends again). The node’s
files are under <dir>/cluster-node: its id, its Raft log, its ranges’
store, and peers — the other nodes’ addresses as its directory last
named them, asked besides --join’s when it knows no driver (after a
restart its directory is gone, and the nodes it joined by may be too;
CockroachDB keeps its gossip’s addresses so). nucleus cluster init <dir> --address host:port makes a new
cluster’s first node (the system range and one range of every key from
01, 3 voters wanted); nucleus server <dir> --join host:port --locality region=…,zone=… makes a node that joins — it asks the
address it was given, which answers with where the driver is.
--advertise is the address others reach it at (default --listen);
--node-dead-after <s> how long a node is unheard before its replicas
are replaced (default 300; give every node the same — any may run the
driver).
The replicated key-value store. M (version 16): get, put,
delete, compare-and-set on a key from 01 (below are the cluster’s
own); a superuser for now. Any server takes a call: it runs it if it
leads the key’s range, else forwards it to the leader it knows or a
voter from the directory (at most 3 hops), asking again while no leader
is known; the answer is the value, unknown (no answer in time, or the
member removed under it: it may have taken effect — never run twice by
the server), or unavailable (not taken effect). A host runs calls on
16 client ids of its own, one command out on each — a range keeps one
result a client to answer a command sent again — so a range keeps hosts
× 16 sessions. nucleus cluster kv get|put|delete|cas … calls it.
Seeing and managing the nodes (§M20 C4c), as the server asked knows them — its node’s directory, not asked of the driver:
nc_catalog.nodes:node_id,address,locality,state(active,decommissioning,gone),self,driver(runs the driver, as last heard),voters(the ranges it is a voter of),leaders(those it leads),silent_ms(since this node last had a packet from it; null: never — nodes that share no range need not talk).nc_catalog.cluster_ranges:range_id,start_key,end_key(null: the last),voters(ids, comma-separated),leader(the node that last reported it),role(this node’s member:leader,follower, …; null: none). (nc_catalog.rangesis a database’s own ranges, §6.6.)nc_decommission(node)(a superuser): asked of the server whose node runs the driver — elsewhere refused, naming it; a node not in the cluster, or gone, refused.nucleus cluster nodesprints the first;nucleus cluster decommission <node> [--wait]finds the driver’s server through the one it connects to and asks it there (again, if the driver moved), and with--waitfollows the node’s voters down to gone. The leaving node may be the driver’s own: the system range moves off it, and the driver with it.
Not yet: rebalancing ranges over nodes that joined (§M23); timestamps from the leader (§M21).
Linearizability (nucleus_raft::linearizable): whether a history of
operations — each with its call, its answer if one came, and what it
returned — could have taken effect one at a time in an order that
respects real time and a sequential model. Wing and Gong’s search
(1993) with Lowe’s pruning of states already seen (2017), checked key
by key (Horn and Kroening’s P-compositionality, 2015: a store of
registers is linearizable if each register’s history is), written
fresh from the papers. An operation never answered may have taken
effect at any time after its call, or never. It lives in the raft
crate, not nucleus-testkit, which depends on the SQL engine.
The simulator (nucleus_raft::sim) runs nodes as state machines
driven by one loop, every event at a simulated time — FoundationDB’s
and TigerBeetle’s way (their documentation) — not threads the OS
schedules: each node’s clock ticks a little fast or slow (within 5 %),
messages arrive after a random delay (so out of order), are lost,
duplicated, cut on one link or both ways, nodes are cut off,
partitioned, paused, and crashed. Each node persists through a
LogStore on its own simulated file system (§M2’s SimFs): a crash
loses what was not synced — all of it, or torn by sectors, as the seed
says — and may strike at any of a disk’s next operations, inside a
sync, a segment’s rewrite or a recovery; writes and syncs fail now and
then (the node stops then, as at a crash: a failed sync forgets its
writes). A node starts again from what its disk holds — its snapshot,
hard state and log. Snapshots are taken every 5, 20 or 100 applied
entries or never, segments rewritten past 2 KB, 20 KB or never, by the
seed. Voters are replaced under the same faults: a new node joins as
a learner, is caught up, is swapped in by a joint membership, and the
node it replaces is stopped once the change commits. All of it from one seed: a failure is replayed by its seed
(NUCLEUS_SEED). After every event its checker asserts one leader a
term (election safety), a new leader holding every committed entry
(leader completeness), every node’s committed and applied entries one
sequence (state-machine safety), and every two logs the same up to
their last common entry (log matching). settle heals every fault and
requires the group to elect a leader, commit a new command and bring
every node to it (liveness). Clients of the key-value store run
through it all: one to five, each a command at a time on one to three
keys — puts, swaps from the value it last saw, reads by ReadIndex, by
lease or through the log, as the seed says — sent where the client
thinks the leader is, to the leader a node names, and again after
300 ms without an answer. Clients reach nodes directly, so a leader cut
off from its group still hears them — what ReadIndex and leases must
withstand. Every call and answer is recorded at its simulated time,
and the history is checked for linearizability at the end of each run.
Tests (crates/raft/tests/sim.rs, core::tests): a calm group;
a leader cut off stepping down and another elected; a node back from a
partition not deposing the leader with pre-vote (and raising its term
without); and 1,000 seeds of faults (NUCLEUS_SIM_CASES) — a group of
1, 3 or 5, a network losing up to 20 % and duplicating up to 5 %,
delays up to 30 ms, appends of 1, 3 or 64 entries, pre-vote and
CheckQuorum on or off — in 5 to 7 s. 2,000 seeds: 970,000 commands
committed through 6,600 elections, 84,000 faults and 10,000 crashes.
Mutants killed: a vote without the log’s check, two votes in a term, an
append without its previous entry’s check, a heartbeat’s commit not
bounded by the follower’s match, a leader without its no-op, an older
term’s entry committed by counting (Figure 8: by the simulator once
appends of one entry let a leader’s match stop at an older term’s entry,
and by a direct test), a follower committing past what it shares (a
direct test), a repeated append truncating. An equivalent mutant: a
late refusal taken (slower, not wrong). Storage and snapshots (R2):
1,000 seeds in 4 s (release); 10,000 commit 3.8 M commands through
132,000 crashes, 589,000 snapshots, 84,000 installed and 365,000
segments rewritten, in 43 s. Mutants killed: a ready’s sync skipped, a
rewrite’s segment not synced, a new directory not synced into its parent
(by store::tests), checksums ignored at recovery, a snapshot taken as a
commit without its term’s check, an older snapshot installed over a
committed log, an install keeping a conflicting log, and a torn tail not
cut off at recovery (survived the simulator — its leftovers come back
only when the next write ends exactly at a sound record among them — and
killed by a direct test). Membership (R3): 10,000 seeds replace 12,654 voters
among 3.8 M commands in 58 s; mutants killed: a quorum, a commit or a
refusal blind to the outgoing voters, the joint membership left before
it commits, changes not serialized, voters changed without a joint
membership, a membership kept after its entry was cut back, learners
standing, a removed leader never standing or leading on, a snapshot’s
membership wrong or ignored. Reads and the store (R4): besides the
history, the simulator checks the promises reads rest on after every
event — no leader holds its lease while a leader of a later term exists,
no leader confirms a read if a leader of a later term was elected before
it was asked — and is harsher: now and then a message a second late,
and state machines up to 4 entries a tick behind (by seed). 1,000
seeds in 8 s; 10,000 check 2.18 M client operations (1.01 M by
ReadIndex, 151,000 by lease) linearizable, in 89 s. Mutants killed, 13
of 13: ReadIndex without its round or before the leader’s own commit, an
earlier round’s answer taken for the latest, reads kept across a step
down, a lease too long, without its margin or without a majority’s
answer, a restarted member voting at once, the promise forgotten at a
raised term, a same-term vote within it, a retried command applied
again, an older one applied late (kv’s test; equivalent under the
simulator), a read served before its index is applied. The first round
killed 4: the history alone is a weak witness of a stale read (it needs
a write completed elsewhere, on the same key, in a narrow window) — the
promises are checked directly since.