The nucleus protocol
ncp
Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.
nucleus’s own client protocol (D14): what nucleus server speaks by
default and what nucleus’s drivers (§11) implement. This section is the
whole specification; nucleus-wire (crates/wire) is its one Rust
definition — versions, message kinds, value tags, frames, a value’s
encoding and decoding, the columnar layout — which the server and the
Rust driver each map their own values onto. The protocol’s encoding is
its own: the server no longer writes values in the storage’s row
encoding (whose tags 0–10 it once shared), so either can change
without the other.
Transport. TCP, default port 20035 (NC in ASCII). Every integer
is little-endian. A string is a u32 byte length and that many
bytes of UTF-8. From version 4 the password never travels: the client
proves it with SCRAM-SHA-256 (RFC 5802 / 7677); before 4 it is sent in
Hello in clear text. A client refuses a server’s first message asking
for more than 1 000 000 PBKDF2 iterations (SCRAM_MAX_ITERATIONS, about
a second’s work; the server’s verifiers use 4 096) — else a server
could hold it in the key derivation for minutes. TLS: a client that wants it starts a TLS
handshake as soon as it is connected, before Hello; the server sees the
handshake’s first byte (0x16, never a frame kind) and, if it has TLS,
answers it — every frame then travels inside TLS; a server without TLS
closes the connection. No round trip is spent on asking, and the version
of the protocol does not change.
Frames. Each message is a u8 kind, a u32 body length (the 5
header bytes not included; at most 1 GiB), then the body.
| Kind | Direction | Body |
|---|---|---|
H Hello |
client → server, first | u16 version (10; 1–9 still accepted), string user, string database (a branch’s name, §8.32; nucleus the main one), string password (version 4: empty — it is proved, not sent; before 4: the password, empty for none), string client name |
A Authentication |
server → client | string: the mechanisms, space-separated (SCRAM-SHA-256; over TLS with a channel binding SCRAM-SHA-256-PLUS SCRAM-SHA-256), then SCRAM’s server-first and server-final messages |
a Authentication response |
client → server | string: SCRAM’s client-first, then client-final message — or OAUTHBEARER’s initial response, or PLAIN’s |
W Welcome |
server → client | u16 version (the lower of the client’s and the server’s), string server (nucleus 0.1.0), u32 session id; from version 12 u8 role: 0 a primary taking writes, 1 a replica, 2 a primary taking none (no lease, stepped down; a witness) |
Q Query |
client → server | string SQL, u8 result format (0 typed, 1 text, 2 columnar — version 7), version 6: u32 fetch size (rows per batch; 0: the whole result at once), u16 parameter count, the parameters as values |
C Columns |
server → client | u16 count, then per column: string name, type |
D Row |
server → client | one value per column |
B Batch |
server → client | version 7, result format 2: rows as a buffer per column (below); client → server during COPY: typed rows in the same layout |
I Copy in |
server → client | version 7: a COPY … FROM STDIN takes data — u16 count, then per column: string name, type (as in C) |
d Copy data |
client → server | bytes of the COPY’s text or CSV, any split |
e Copy end |
client → server | empty: the data is complete |
f Copy fail |
client → server | string: why the client gives up (the statement fails, 57014) |
K Done |
server → client | string command (SELECT, INSERT, CREATE TABLE, BEGIN, …), u64 rows returned or affected (0 when it does not apply) |
E Error |
server → client | string SQLSTATE (5 characters), string message; version 5: string hint (what to do about it; empty: none) |
R Ready |
server → client | u8 transaction status: 0 idle, 1 in a transaction block, 2 in a failed block; from version 12 u64 the session’s last commit (its commit token, nc_last_commit()) |
S Suspended |
server → client | empty (version 6): a batch is sent; the server waits for F or c |
F Fetch |
client → server | u32 the next batch’s size (0: the rest at once), after S |
c Close |
client → server | empty, after S: no more rows — the statement ends there |
X Bye |
client → server | empty; the server closes |
k Subject key |
client → server | version 8: u8 action (0 present, 1 give into the user’s keeping), string subject, bytes (u32 32, then the user’s 32-byte secret) — a message of its own so no log or audit record holds the secret (§8.40); answered E on failure, then R |
O Document request |
client → server | version 9: u8 operation (1 find, 2 count, 3 insert, 4 update, 5 replace, 6 delete), u8 flags (1 every match, 2 upsert), strings collection, filter, body (insert: a document or an array of them; update: the update document; replace: the replacement; find: the projection), sort (a sort document, read in its text’s order) — JSON texts, empty where not given —, u64 skip, u64 limit (0: none). Compiled to one statement (nucleus_sql::documents, below) and answered as a typed Q with it, fetched whole: find C D* K of one json column doc; count one row (n, bigint); insert a row per document (_id); update and replace one row (matched, modified — the documents the update changed —, upserted: the inserted document’s _id or NULL); delete K (DELETE n) |
w Stream wait |
client → server | version 10: string stream, i64 the seq waited past, u32 the longest wait in milliseconds. The server reads the stream’s newest seq as a statement would (SELECT on it), then waits on the engine outside any transaction, woken by the commit that makes an entry visible (§8.43); answered as a typed Q: C D K of one bigint column seq — the newest, past the one given unless the time ran out — then R |
Session. The client sends Hello. If the server wants a password and
the client speaks version 4, they run SCRAM-SHA-256: the server sends A
with the mechanisms — SCRAM-SHA-256, and over TLS, when the server’s
certificate defines a tls-server-end-point value (RFC 5929: the
certificate hashed by its signature’s hash, SHA-256 for MD5 and SHA-1),
SCRAM-SHA-256-PLUS SCRAM-SHA-256 — or, for a role whose password a
directory checks (LDAP), over TLS only, PLAIN instead of SCRAM — and with
an OpenID Connect issuer OAUTHBEARER after them. PLAIN (RFC 4616): one
a with <NUL><user><NUL><password>; a client sends it only over TLS. A client with an identity token takes
OAUTHBEARER: one a with RFC 7628’s initial response
(n,,\x01auth=Bearer <token>\x01\x01); the token names the user (Hello’s is
not used), and the server answers Welcome or Error (28000, with why).
Otherwise the client a client-first
(<gs2>n=,r=<nonce>, the user being Hello’s), whose GS2 header picks:
p=tls-server-end-point,, binds the proof to this TLS session (so a man in
the middle, who has a session of its own with each side, cannot relay
it), y,, says the client could bind but was not offered it (refused by
a server that can — the offer was stripped on the way), n,, no binding;
the server A server-first (r=<nonce>,s=<salt>,i=<iterations>); the
client a client-final (c=<base64 of the GS2 header, and the binding data after it when bound>,r=<nonce>,p=<proof>); the server A server-final
(v=<signature>), which the client checks — a server that cannot sign
does not know the password’s verifier, and the client hangs up. An
unknown user gets a salt of its own (derived from a server secret), so
the exchange does not tell which users exist. The server then answers
Welcome and Ready, or Error and closes (28P01 wrong user or password —
an unclaimed database takes the server’s credentials, by default user
nucleus, password nucleus; 08P01 unsupported version or a malformed
message, an a out of turn included). Then any number of Query messages, each answered
by, per statement, [C D*] K (Columns and Rows only for statements that
return rows), and finally Ready. A failing statement sends Error instead
of Done, the remaining statements of that Query are skipped, and Ready
follows. A Query with parameters must hold one statement; $1, $2, …
refer to them.
Documents (version 9, PLAN.md §M16 Q4). O is MongoDB’s requests
on a collection — find (filter, projection, sort, skip, limit), count,
insert, update and replace (one or every match; upsert), delete (one or
every match) — so that every driver sends the same request and the
server compiles it once: nucleus_sql::documents::statement makes the
one statement each is, over §8.41’s functions (doc @? json_filter(…),
json_project, json_sort_key, json_update, json_upsert_document),
the JSON texts as literals (a constant filter compiled where it is
bound, and served by a path index) and the collection’s name quoted as
an identifier. An update or a replacement is WITH m AS (the matches, or the first), u AS (UPDATE … the matches the update changes RETURNING _id) [, i AS (INSERT … json_upsert_document(…) WHERE NOT EXISTS m)] SELECT counts; …_one’s match, a delete’s one, is the first the plan
finds. Each part is checked before any document, as MongoDB refuses a
bad request whether or not anything matches: the filter compiled, the
sort document read, an update applied to an empty document, a
projection too (22023, 0A000). An update document needs operators
and a replacement has none (22023). It runs in the session’s
transaction, beside its SQL.
Streams (version 10, PLAN.md §M16.5 S4). w waits for a stream’s
next entry without the transaction SELECT stream_wait(…) holds for as
long as it waits (a snapshot kept open an hour holds back what MVCC
may clean up): the session runs stream_wait(s, after, 0) — its
privileges, the stream’s newest seq now — and, when nothing is past
after, waits on Kv::wait_appended holding nothing (Session:: wait_stream); a connection’s thread waits, the others go on. Appending
and consuming are statements (INSERT, CONSUME), so they need no
message of their own.
Replication (version 11, PLAN.md §M17.5 R2, D25;
nucleus_wire::replication). After a login as a superuser, L turns
the connection into a replica’s stream. Its body is the slot’s name,
then 0 (seed me) or 1 with the restart LSN, the last commit the
replica has, the newest epoch it knows and its database’s identity
(u64 each, §M17.5 R4). From
then on only these messages cross it:
- The seed:
Ythe snapshot’s commit (u64timestamp, its time, the restart LSN the commits after it are read from, the primary’s epoch),ythe snapshot’s keys and values in key order (u32count, then each key and value as bytes, about 1 MiB a message), thenZ. - A commit:
Gwith its timestamp, its time, where it ends in the primary’s log, where to read again from after it (u64each), and its writes (u32count, then each key,u81 and the value or 0 for a delete). A large commit’s writes come first ingparts of about 4 MiB (the count and writes alone), so no frame holds it whole. - Routes (version 13, §M17.5 R7):
rthe primary’s ranges of store keys given an engine of their own (§M14.28;u32count, then each start and end as bytes and the engine’su8: 1 map, 2 LSM), afterYand at the stream’s start, then before the first commit after they changed. The replica makes those it lacks. - Branches (version 15, §M17.5):
n, on every branch’s stream, that branch’s own branches (u32count, then each name, its id there,u32, never reused, and — when its log is whole from where it was made and a slot of the stream’s name holds it — its clock then:u81 and au64, elseu80): at the stream’s start, then before the first commit after one was made, and when one was dropped. The replica follows each on a stream of its own, logged in to it. Version 14’sb(the database’s branches, on the main branch’s stream only) is still sent to a version-14 replica. - Heartbeats:
hcomes after each batch of commits, and once a second when there are none. It carries the primary’s last commit, its clock (µs since the Unix epoch), its epoch, and its other slots (u32count, then each name and the last commit it applied), which the replica keeps for a failover. The replica answers each withp: the restart LSN and timestamp of its last commit applied and durable. The primary holds its log from that LSN, and reads the answers once more than 4 are outstanding: a replica that applies slowly slows its stream. One thread serves the stream, since the connection may be TLS.
A time is a u8 (1: there is one) and a u64 (µs since the Unix
epoch). An E ends the stream; so does closing the connection.
A cluster’s members (version 11, PLAN.md §M17.5 R4c;
nucleus_wire::cluster). After a superuser’s login a member asks
another, on a connection it keeps: V a vote (the database’s identity,
the epoch, the candidate’s name, its last commit, u8 1 for a pre-vote,
then the epoch of its last commit — absent from a member before
2026-12-04, whose last commit alone is then weighed; such a member
refuses the longer V, so a cluster is upgraded between elections)
or U a lease (the identity, the primary’s epoch, its name). The answer
is v: u8 yes or no, and the newest epoch the member knows. A server
that is no cluster’s member answers 55000.
Pipelining. A client may send Queries without waiting for the
replies to those before: the server reads and answers them in order,
each as if sent alone (one that fails does not skip the next; inside a
transaction block the next ones fail as the block has). The server
writes its replies when it has read every whole message the client sent
— Ready is flushed only when no next message is waiting in its read
buffer — so a pipeline’s replies go out together. A client keeps what
it has sent and not had answered below what the sockets’ buffers hold
(the Rust driver: 32 KiB, PIPELINE_WINDOW), reading the replies before
sending more: else both sides can wait on writes the other is not
reading. A pipelined statement is not a COPY FROM STDIN (the next
Query would be read as its data, 08P01) nor fetched in batches.
Streaming (version 6). A query’s rows are sent as the executor
produces them, so a result never has to fit in the server’s memory, and
an error can come after some rows (Error then ends the statement, as
above). With a fetch size n > 0 (one statement only, else 42601), the
server sends n rows, then S, and waits: F asks for the next batch
(of its size; 0 for the rest), c ends the statement there — Done counts
the rows sent — and X closes the connection; anything else is 08P01
and the connection closes. A result of exactly n rows ends without
S. The statement holds its snapshot while it waits, and the time spent
waiting does not count toward its statement_timeout. While the client
handles a batch the server makes the next: the rows after an S are
produced and held — up to a batch of the size last asked for — and sent
when F comes, or dropped on c (Done counts the rows sent, never those
dropped). So an error in a row read ahead ends the statement with its
Error even when the client then sends c, as a sort’s would have before
any row was sent. Rows of other
statements (RETURNING, SHOW, EXPLAIN) are sent once the statement has
committed, so one retried after a conflict sends them once.
Columnar results (version 7, result format 2). Instead of a D per
row, B batches of rows, a buffer per column, so a driver can hand a
column over without building a value per cell (as a numpy or Arrow
array). A batch holds the fetch size’s rows (the server’s choice, 16384,
for 0), and with a fetch size S follows each batch as above; a result
without rows has none. Its body: u32 rows n, then per column a u8
(1: a validity bitmap follows; 0: no NULLs), the bitmap (n bits, least
significant first, set for a value), and the data; every bitmap, data
and offsets buffer starts at a multiple of 8 bytes from the start of the
body (zero padding before it). The data by column type:
| Types | Data |
|---|---|
| boolean | a u8 (0, 1) each |
| smallint · integer, date · real | i16 · i32 · f32 each (date: days since 2000-01-01) |
| bigint · timestamp, timestamptz, time · double | i64 · i64 (µs) · f64 each |
| interval | 16 bytes each: i32 months, i32 days, i64 µs |
| uuid | its 16 bytes each |
| vector | variable width: its components, little-endian f32s (4-byte aligned, read in place as floats) |
| numeric | 17 bytes each: i128 mantissa, u8 scale |
| anything else | variable width: n + 1 u32 offsets, then the bytes value i takes from offset i to i + 1 — UTF-8 for text, char(n), enums and unknown types; the bytes of a bytea and a registered type’s binary form; family, mask length and address for inet and cidr; an array as a value (tag 10, as in rows) |
A NULL’s slot is zeros, or empty.
A query the vectorized executor runs (a scan with filters and
projections, §8.5) hands its batches to the result as columns — the
Sink::takes_batches / Sink::batch hook, nucleus_sql::vector::batches
— and the server copies their typed vectors into the buffers without a
value per cell (columnar::Builder; the same bytes as from rows, which
other queries still give). A million rows of three numeric columns
reach numpy in 92 ms from a row table and 51 ms from a column table (262
and 241 ms through rows). The test kit’s scripts run once with their
results taken this way.
COPY FROM STDIN (version 7). The statement answers I with the
columns it takes; the client sends d (text or CSV bytes, split
anyhow) or B (batches of rows in the columnar layout above, of the
columns I named: each value of its column’s type) messages, then e —
or f to give up — and the statement ends as any (K COPY n, or E).
If it fails before e, the server reads and drops the client’s data up
to e or f before Error. A query without data to send (a plain
Query) answers I with f. Transactions are SQL (BEGIN, COMMIT, ROLLBACK), as in
§8.7; outside a block every statement commits on its own.
Versions. 2 adds registered types (uuid, a module’s type): tag 11
below. 3 adds tags 12–20, §M14.26’s types. 4 proves the password by
SCRAM-SHA-256 instead of sending it (§M14.25). 5 adds the hint to E
(§8.14). 6 streams results and fetches them in batches (Q’s fetch
size, S, F, c; §M14.11). 7 adds the columnar result format (B)
and COPY FROM STDIN (I, d, e, f). 8 subject keys (k), 9
requests on documents (O), 10 waits on streams (w), 11 replication
(L). An older client gets what
its version knows — registered types as text before 2; before 3,
smallint and integer as bigint (tag 2), real as a double (tag 3),
bytea, time, char(n), inet, cidr and enums as text — so older
drivers keep working. A record (a row value, ROW(…)) is text in
every version, as PostgreSQL writes it: (1,"a b",).
Types (in Columns): a u8 tag — 0 unknown (sent as text), 1 boolean,
2 bigint, 3 double precision, 4 text, 5 numeric, 6 date, 7 timestamp, 8
timestamptz, 9 interval, 10 array followed by the element’s tag, 11 a
registered type followed by its name (a string: uuid); version 3: 12
smallint, 13 integer, 14 real, 15 bytea, 16 time, 17 char(n), 18 inet,
19 cidr, 20 an enum followed by its name.
Values (in Rows and parameters): a u8 tag, then:
| Tag | Value | Payload |
|---|---|---|
| 0 | NULL | — |
| 1 | boolean | u8 0 or 1 |
| 2 | bigint | i64 |
| 3 | double precision (and, for now, real) | f64 (IEEE 754 bits) |
| 4 | text | string |
| 5 | numeric | i128 mantissa (16 bytes, two’s complement), u8 scale: value = mantissa × 10^-scale |
| 6 | date | i32 days since 2000-01-01 |
| 7 | timestamp | i64 µs since 2000-01-01 00:00 |
| 8 | timestamptz | i64 µs since 2000-01-01 00:00 UTC |
| 9 | interval | i32 months, i32 days, i64 µs |
| 10 | array | u32 count, then each element as a value |
| 11 | a registered type (version 2) | string type name, u32 length, the value’s binary (canonical) form — or the form the type sends instead (Type::wire_output): json’s text, which every language parses — for uuid its 16 bytes, for vector its components as little-endian f32s, for sparsevec its dimensions and non-zero count, positions and values (§8.1) |
| 12 | smallint (version 3) | i16 |
| 13 | integer (version 3) | i32 |
| 14 | real (version 3) | f32 (IEEE 754 bits) |
| 15 | bytea (version 3) | u32 length, the bytes |
| 16 | time (version 3) | i64 µs since midnight (0 – 86 400 000 000) |
| 18, 19 | inet, cidr (version 3) | u8 family (4 or 6), u8 mask length, the address (4 or 16 bytes, network order) |
A char(n) value and an enum’s are text (tag 4): their column types say
what they are. An integer goes as the column’s width (a bigint, or an
expression’s integer of no column, as tag 2); a parameter may use any
integer tag.
Tags 0–10 are the tags of the storage’s row encoding version 1 (§8.1), but
the protocol’s encoding is its own (native::wire_value, parameter):
the storage may store a value differently without the protocol
changing. A cidr parameter with host bits set is refused (22P02). A registered type’s carries its name instead
of its id, so drivers need no table of ids. A tag-11 parameter of a type
the server does not know is refused (42704); one the type’s check refuses is refused with
the check’s SQLSTATE (22000 for a sparse vector’s position past its dimensions), and one
the check accepts is kept as it reads back — a sparse vector’s positions in order, its zeros
dropped — so equal values have equal bytes. With result format 1 (text) every non-NULL value is
sent as text (tag 4), rendered as ncsql prints it. Parameters are
converted to the type their place needs (a text parameter is parsed, as an
untyped literal would be).