Mirexa

Wiki Reference

Wire protocol

Byte-level specification of Mirexa's binary client protocol, version 2 — framing, handshake, every frame type, checksums and limits.

Mirexa's data plane speaks one binary protocol over a single TCP connection (optionally TLS): a client authenticates once with an INIT frame, then sends requests and receives responses and subscription pushes as length-prefixed frames. This page specifies that protocol, version 2, byte for byte, as it is implemented in /internal/wire and served by /internal/network. It is written for someone implementing a client in another language; the Go and Python SDKs are two such implementations.

The operator-facing gRPC control plane is a different protocol and is described in Control-plane gRPC API. Error codes and permission bits have their own pages: Error codes and Permissions.

Conventions

  • Byte order. Every multi-byte integer and float is big-endian, in the header and in every payload.[1] (The on-disk formats are a separate, mostly little-endian set of codecs and are never reused on the wire; see On-disk formats.)
  • Timestamps are signed 64-bit integers, Unix nanoseconds.
  • Prices and volumes are IEEE 754 binary64 (float64), sent as their raw bit pattern.
  • Strictness. Every parser refuses reserved bits that are set, trailing bytes, counts that disagree with the bytes present, and values no encoder writes. One message has exactly one encoding. A client should be equally strict about what it accepts from the server.
  • Checksums are CRC-32C (the Castagnoli polynomial, 0x1EDC6F41), the same polynomial the write-ahead log uses.[2] Which payloads carry one is listed under Checksums.
  • In the byte tables below, u8/u16/u32/u64 are unsigned, i64 is signed, f64 is a binary64 float, and offsets are from the start of the payload unless stated.

The conformance suite

/conformance/wire-v2.json is the protocol's frozen, language-independent test vector file. It was generated once from the Go codecs on 2026-10-22 and is checked against them on every test run, never the other way round: TestConformance_TheCodecsAgreeWithTheFrozenFixtures encodes each case and requires the frozen bytes, and parses the frozen bytes and requires the frozen meaning.[3] Regenerating the file is, by definition, a protocol change.

The file has three arrays:

Key Count Each entry
frames 37 name, type (frame name), flags (header flags byte), correlation (header correlation id), frame (the whole frame in hex: 14-byte header plus payload), decoded (what the payload means, as JSON). A QUERY_RESPONSE case may carry shape (candles or ticks), because that payload's form depends on the request it answers.
tokens 1 An Ed25519 key seed, the public_key, the exact signing_input bytes, the resulting base64 token, and its decoded claims.
rejects 22 A malformed frame (hex) and the class of refusal a conforming parser must produce: magic, version, reserved, checksum, format, redirect, epoch, init_ack or truncated.

A conforming client:

  1. decodes every frames[].frame to exactly decoded, with the header's flags and correlation as listed;
  2. encodes every decoded back to exactly frame;
  3. derives signing_input from the token's claims, verifies the token's signature against public_key, and (given the seed) reproduces token byte for byte;
  4. refuses every rejects[].frame with an error of the named class.

The suite covers the handshake and renewal, every ingest variant (acked, fire-and-forget, history, correction, fenced), INGEST_ACK, candle and tick queries and responses (with gap markers, stale answers and not-found), the subscription frames, LIST_STREAMS, LIST_GAPS, LIST_NODES, REDIRECT_COMMAND and ERROR. It does not yet cover QUERY_MULTI, STREAM_ACK, OFFLOAD_SUBSCRIPTION, NODE_STATS, FILL_GAP, ACCEPT_GAP, the stream-metadata frames, column queries or rollups; for those, this page and the Go codecs are the reference. The Python SDK vendors a copy of the file and passes it.

Frame header

Every frame, in both directions, starts with a fixed 14-byte header.[4]

Offset Size Field Value
0 u16 magic 0xCA44. Anything else ends the connection.
2 u8 version 2. Any other value ends the connection (ErrUnsupportedVersion).
3 u8 type The frame type; see Frame types.
4 u8 flags Bits 0–4 defined (below); bits 5–7 must be zero.
5 u8 reserved Must be zero.
6 u32 correlation id Chosen by the client; echoed by the server on every frame that answers the request. 0 is connection-level (the handshake).
10 u32 length Payload length in bytes, excluding this header.

The payload follows immediately. A header with any reserved bit or the reserved byte set is refused (ErrReservedFieldSet): undefined bits are never ignored, so a newer sender can never have its meaning silently dropped by an older receiver.[5]

The field at offsets 6–9 is called StreamID in the Go code. It is not a stream identity; it is a request correlation id. Stream identities travel in payloads (see Stream identity).

Header flags

Bit Mask Name Meaning Used on
0 0x01 ACK The sender wants a reply on success (INGEST_ACK). Without it a successful ingest is not answered at all. Ingest frames
1 0x02 HISTORY The batch is bulk history: it takes the history route, which stages, compresses and installs chunks directly rather than going through the WAL and hot cache. INGEST_CANDLE_BATCH
2 0x04 CORRECTION The batch restates bars the stream already holds; refused for any bar past the newest one stored. Mutually exclusive with HISTORY (both set is a Protocol error). INGEST_CANDLE_BATCH
3 0x08 EPOCH The payload is prefixed by a 12-byte fencing epoch; see Epoch prefix. Every write frame
4 0x10 OVERWRITE The write is meant for a derived stream; without it a write to a derived stream is refused DerivedStream. INGEST_CANDLE_BATCH, FILL_GAP
5–7 reserved Must be zero.

The header parser accepts any defined bit on any frame type; each handler reads only the bits it defines. Adding a flag bit is safe in one direction only: an older server refuses the whole frame, rather than serving it without the bit's meaning.[6]

Frame size limit

The server refuses any frame whose length exceeds network.max_frame_payload_bytes (default 16 MiB; configurable between 4 KiB and 64 MiB).[7] Because the payload of an oversized frame is never read, the stream cannot be resynchronised: the server sends one ERROR (PayloadTooLarge, naming the limit) and closes the connection. Response frames are sized by the server to fit the same limit, which is why large reads are paged.

Checksums

Payloads whose values are trusted end in a 4-byte CRC-32C computed over every preceding byte of the payload (not the header). The receiver checks the CRC before decoding any record.

Frame Checksummed
INGEST_CANDLE_BATCH, INGEST_TICK_BATCH Yes, trailing CRC over the batch. The epoch prefix, if present, has its own CRC.
QUERY_RESPONSE (all three forms) Yes
QUERY_MULTI_RESPONSE Yes, one CRC over the whole batch of results
STREAM_DATA Yes
REDIRECT_COMMAND, OFFLOAD_SUBSCRIPTION Yes
Epoch prefix Yes, its own CRC over the 8 epoch bytes
INIT, INIT_ACK, REAUTH, REAUTH_ACK No (the token is signed instead)
INGEST_ACK, ERROR, every request frame, the list frames, NODE_STATS_RESPONSE, FILL_GAP*, ACCEPT_GAP*, the metadata frames No

The redirect is checksummed because of its epoch: a client's route cache refuses any epoch older than one it holds, so a single corrupted high bit would wedge that partition's routing until the client restarted.[8]

Common encodings

Stream identity

A stream is named by three length-prefixed strings, in this order:

Field Encoding
exchange u8 length, then that many bytes
symbol u8 length, then that many bytes
timeframe u8 length, then that many bytes

Each component must be 1–64 bytes of [0-9A-Za-z._-] and must not be . or ..; these strings become path segments in the node's data directory, so the parser is the security boundary. The timeframe must also parse as <positive integer><unit> with unit s, m, h, d or w (for example 1m, 4h, 1w); banana or 0m is refused.[9] Where a stream id appears as a string (a LIST_STREAMS cursor or match), its form is symbol:timeframe:exchange.

Candle record (49 bytes)

Offset Size Field
0 u8 record flags
1 i64 timestamp (Unix ns, the bar's slot)
9 f64 open
17 f64 high
25 f64 low
33 f64 close
41 f64 volume

On ingest (INGEST_CANDLE_BATCH) and in STREAM_DATA, the record flags byte must be zero. Every ingested candle is validated at the byte boundary: timestamp ≥ 0, every value finite and within the storable magnitude (about 9.22 × 10¹⁴, from the fixed-point scale), volume ≥ 0, low ≤ open, close ≤ high. One bad record refuses the whole batch with Protocol; nothing is stored.[10]

In a QUERY_RESPONSE or QUERY_MULTI_RESPONSE, the flags byte carries a point's classification:

Bits Mask Meaning
0 0x01 Gap marker: this slot holds no candle; OHLCV are zero.
1–2 0x06 Low two bits of the gap status.
3–6 0x78 Gap reason (0–9).
7 0x80 High bit of the gap status (status 4, ACCEPTED).

Status values: 0 OPEN, 1 FILLING, 2 CLOSED, 3 PERMANENT, 4 ACCEPTED. Reason values: 0 UNKNOWN, 1 CORRUPTION, 2 NETWORK, 3 CRASH, 4 MAINTENANCE, 5 RATE_LIMIT, 6 EXCHANGE, 7 MANUAL, 8 OFF_TIME (market closure), 9 INCOMPLETE.[11]

Only two shapes are legal, and the parser refuses every other combination:

  • A gap marker (bit 0 set) with any status except ACCEPTED and any reason except INCOMPLETE.
  • A real candle (bit 0 clear) with flags zero, or carrying an INCOMPLETE mark: reason INCOMPLETE with status OPEN, FILLING or ACCEPTED. This marks a derived bar whose source had a hole under its window; see Derived streams and lineage. [12]

Tick record (24 bytes)

Offset Size Field
0 i64 timestamp (Unix ns)
8 f64 price
16 f64 volume

Ticks carry no flags byte. An ingested tick needs timestamp ≥ 0, finite storable values and volume ≥ 0. Price may be zero or negative.[10:1]

Epoch prefix

When the header's EPOCH flag is set, the payload begins with a 12-byte prefix, and what follows it is byte-identical to the unfenced payload:[13]

Offset Size Field
0 u64 partition fencing epoch the sender believes is current
8 u32 CRC-32C over bytes 0–7

A client sends it only once it has learned an epoch from a redirect; a first write carries no flag and no prefix and is accepted unfenced. The server compares it with its directory: equal is served; older is answered with a REDIRECT_COMMAND naming the current placement; newer, or a node with no placement for the partition, is answered StalePlacement with a 250 ms retry hint.[14] The prefix is accepted on every write frame: both ingest frames, FILL_GAP, ACCEPT_GAP, and the four stream-metadata writes. See Partitions and routing.

Connection lifecycle

sequenceDiagram
    participant C as Client
    participant S as Node
    C->>S: INIT (token)
    alt token accepted
        S->>C: INIT_ACK (session id, granted permissions)
        loop requests
            C->>S: request (correlation id N)
            S->>C: response or ERROR (correlation id N)
        end
        S-->>C: STREAM_DATA pushes (subscription tag)
        C->>S: REAUTH (new token), before expiry
        S->>C: REAUTH_ACK (new grant)
    else refused
        S->>C: ERROR (reason)
        S--xC: close
    end

Handshake: INIT and INIT_ACK

The first frame on a connection must be INIT (type 0x01, correlation id 0). The whole exchange must finish within network.connection_timeout (default 30 s).[15]

INIT payload (84 bytes) — a session token's bytes, verbatim:

Offset Size Field
0 u16 tenant id
2 u16 reserved, must be zero (covered by the signature)
4 i64 expiration, Unix ns
12 u64 requested permission bitmap
20 64 bytes Ed25519 signature

A token is an INIT payload. The token string an operator mints with mirexa-cli token is standard base64 (with padding) of exactly these 84 bytes: 112 characters, no line breaks, canonical encoding only.[16] A client decodes it and sends the bytes unchanged; it never re-encodes claims, because that would invalidate the signature.

What is signed. The signature is Ed25519 over the 34-byte signing input: the ASCII domain string mirexa-cst-v1 followed by one zero byte (14 bytes), then payload bytes 0–19 (tenant, reserved, expiration, permissions) exactly as above.[17] The conformance file's tokens[0].signing_input is a worked example.

What the server checks, in order:[18]

  1. The frame is INIT and its payload is exactly 84 bytes with zero reserved bytes.
  2. The token has not expired, and does not expire more than one hour from now (a token claiming a longer life cannot have been legitimately issued).
  3. The signature verifies against one of security.auth.trusted_keys (on a single node with none configured, the issuer the node generated for itself). With security.auth.enabled: false any signature is accepted, and the requested bitmap is self-asserted.
  4. The signing key has not been revoked through the control plane.
  5. The bitmap sets no undefined permission bit (bits 7–63 must be zero).
  6. The grant is the requested bitmap ANDed with security.max_permissions, when that is set.

INIT_ACK payload (16 bytes), correlation id 0:

Offset Size Field
0 u32 session id (process-unique, from 1)
4 u32 cluster epoch — always 0 in this build
8 u64 granted permission bitmap

The granted bitmap is what the server enforces for the session and may be narrower than the request. A client should read it rather than assume. See Permissions.

On refusal the server sends one ERROR frame (correlation id 0) and closes the connection. The code is Unauthorized for an expired token, a token beyond the validity window, a bad signature, a revoked key or an undefined permission bit, and Protocol for a malformed INIT; the message says which.[19] A handshake that times out is closed with no frame.

A client without a token. The Go SDK, given no token, sends tenant 0, an expiry 30 minutes ahead, a zero signature, and a request for READ_CANDLES | WRITE_CANDLES | READ_TICKS | WRITE_TICKS | ADMIN_STREAM | LIST_STREAMS. Only a node with authentication disabled accepts it; authentication is on by default.[20]

Requests, responses and ordering

After INIT_ACK, the client sends request frames with correlation ids of its choosing; every answer to a request carries that request's correlation id. The server reads and handles one frame at a time per connection, so responses to requests come back in request order, but subscription pushes (STREAM_DATA, and the ERROR or REDIRECT_COMMAND that ends a subscription) are written by other goroutines and interleave freely.[21] A client should dispatch incoming frames by correlation id rather than by arrival order.

A per-request failure is answered in band (an ERROR frame, or a status byte inside a response) and the connection stays open. The connection is closed on: an invalid magic or version, an oversized frame, a truncated frame, a client-sent ERROR frame (logged as a report), an expired or revoked session's next frame (answered Unauthorized first), or an I/O timeout. Reads time out after network.read_timeout (30 s) of silence, and a connection with no activity at all is closed after network.idle_timeout (120 s).[22]

An unknown frame type, or a known type the server only sends (such as REDIRECT_COMMAND), is answered ERROR Unsupported and the connection continues, since its payload was fully read. This is how new frame types stay compatible: an older node answers Unsupported.[23]

Session expiry

A token's expiry binds the session. A frame arriving after it is refused Unauthorized before its handler runs (so a write is provably not applied), and the connection is closed. A subscriber, which sends nothing, is cut by a timer at expiry, optionally delayed by security.auth.subscriber_grace (default 0).[24]

Renewal: REAUTH and REAUTH_ACK

REAUTH (0x03) renews the session's token without reconnecting. Its payload is an INIT payload (a new token) and it is checked by exactly the handshake's rules. The new token must name the same tenant. On success the server answers REAUTH_ACK (0x04, an INIT_ACK payload with the same session id and the new grant) under the request's correlation id; the session's grant and expiry are replaced, and subscriptions are kept. A refused renewal is an ERROR and changes nothing. A renewal whose grant drops READ_CANDLES or READ_TICKS that the session had ends its subscriptions and closes the connection. An older node answers Unsupported.[25]

Frame types

Code Name Direction Permission Answered with
0x01 INIT C→S — INIT_ACK or ERROR + close
0x02 INIT_ACK S→C
0x03 REAUTH C→S — REAUTH_ACK or ERROR
0x04 REAUTH_ACK S→C
0x10 INGEST_TICK_BATCH C→S WRITE_TICKS INGEST_ACK if ACK; ERROR on failure
0x11 INGEST_ACK S→C
0x12 INGEST_CANDLE_BATCH C→S WRITE_CANDLES INGEST_ACK if ACK; ERROR on failure
0x20 REDIRECT_COMMAND S→C
0x21 OFFLOAD_SUBSCRIPTION S→C
0x30 SUBSCRIBE_STREAM C→S READ_CANDLES or READ_TICKS STREAM_DATA (Established), then pushes
0x31 UNSUBSCRIBE_STREAM C→S — nothing
0x32 STREAM_DATA S→C
0x33 STREAM_ACK C→S — nothing
0x40 QUERY_STREAM C→S READ_CANDLES or READ_TICKS QUERY_RESPONSE
0x41 QUERY_RESPONSE S→C
0x42 QUERY_MULTI C→S per sub-query QUERY_MULTI_RESPONSE
0x43 QUERY_MULTI_RESPONSE S→C
0x44 LIST_STREAMS C→S LIST_STREAMS LIST_STREAMS_RESPONSE
0x45 LIST_STREAMS_RESPONSE S→C
0x46 LIST_GAPS C→S READ_CANDLES LIST_GAPS_RESPONSE
0x47 LIST_GAPS_RESPONSE S→C
0x48 LIST_NODES C→S LIST_STREAMS, READ_CANDLES or READ_TICKS LIST_NODES_RESPONSE
0x49 LIST_NODES_RESPONSE S→C
0x4A NODE_STATS C→S LIST_STREAMS NODE_STATS_RESPONSE
0x4B NODE_STATS_RESPONSE S→C
0x4C FILL_GAP C→S WRITE_CANDLES FILL_GAP_RESPONSE
0x4D FILL_GAP_RESPONSE S→C
0x4E ACCEPT_GAP C→S WRITE_CANDLES ACCEPT_GAP_RESPONSE
0x4F ACCEPT_GAP_RESPONSE S→C
0x50 GET_STREAM_METADATA C→S READ_CANDLES STREAM_METADATA
0x51 STREAM_METADATA S→C
0x52 SET_STREAM_METADATA C→S ADMIN_STREAM STREAM_METADATA
0x53 ADD_STREAM_CLOSURE C→S ADMIN_STREAM STREAM_METADATA
0x54 REMOVE_STREAM_CLOSURE C→S ADMIN_STREAM STREAM_METADATA
0x55 SET_STREAM_LINEAGE C→S ADMIN_STREAM STREAM_METADATA
0xF0 ERROR both

Any request may instead be answered ERROR (for example Unauthorized, Protocol, Overloaded), and any request naming a stream may be answered REDIRECT_COMMAND or PartitionUnavailable in a cluster. Codes 0x05–0x0F, 0x13–0x1F, 0x22–0x2F, 0x34–0x3F, 0x56–0xEF and 0xF1–0xFF are unassigned.[26]

Where checks happen. For every request that names a stream, the node parses the payload, checks the permission, then checks placement (redirect, unavailable, epoch, cutover drain) before anything is dispatched. A request refused at any of these steps provably did nothing, so re-sending it later is a first attempt, not a retry of an unknown outcome.[27]

Writing data

INGEST_CANDLE_BATCH (0x12) and INGEST_TICK_BATCH (0x10)

Both batch payloads have the same shape (after the optional epoch prefix):

Field Encoding
stream identity see Stream identity
count u32, must be ≥ 1
records count × 49-byte candle records, or count × 24-byte tick records
crc u32 CRC-32C over everything above

The record count must match the bytes exactly; trailing bytes are refused.[28] The header flags select the route:

Flags Route What an INGEST_ACK means
none / ACK Live: WAL, then hot cache. A bar the stream already stores is restated rather than refused. The batch's WAL record is flushed and synced per the WAL sync policy — a durability receipt.[29]
HISTORY (+ACK) Bulk history: staged, compressed and installed as chunks, with no WAL. Staged, compressed and installed.
CORRECTION (+ACK) Restatement of stored bars only; refused for any bar past the newest stored. The restatement is applied.
OVERWRITE Combinable with any of the above; required to write a derived stream.

How the node routes each bar, and what a restatement does, is described in Writing data and Corrections, restatements and history. Ticks take only the live route; HISTORY and CORRECTION have no effect on INGEST_TICK_BATCH (the tick handler does not read them — verified by reading handleIngestTicks).

INGEST_ACK (0x11)

Offset Size Field
0 u32 number of records accepted (the batch's count)

Sent only when the request set ACK. A batch sent without ACK that fails is still answered with an ERROR under its correlation id; a client in fire-and-forget mode typically discards it.

Ingest refusals: Protocol (malformed or inadmissible batch, with the reason), HistoryRequired (bars no chunk or hot cache can hold; re-send with HISTORY), DerivedStream, Overloaded (nothing stored, retry after the hint), Unauthorized, Internal. See Error codes.

Reading data

QUERY_STREAM (0x40)

Offset Size Field
0 i64 start (inclusive, Unix ns)
8 i64 end (exclusive, Unix ns)
16 u32 max results; 0 means as many as fit one frame
20 u8 query flags (below)
21 … stream identity
… u64 rollup bar length in ns — only if flag 0x10; must be > 0 and ≤ 2⁶³−1
… u8 column set — only if flag 0x20; must be non-zero

Query flags:[30]

Mask Name Meaning
0x01 ticks Read raw ticks; the answer is the tick form. Needs READ_TICKS.
0x02 include gaps Include gap-marker records for empty slots. Ignored for ticks.
0x04 descending Newest first. With max results, returns the last N of the range.
0x08 allow stale An in-sync copy may answer (cluster only). Not with ticks or rollup.
0x10 rollup Bars of the given length, made at query time from the stream's candles, or from its trades with 0x01; nothing is stored. Answered in candle form. Not with allow stale.
0x20 columns Return only the value columns in the column set. Not with ticks, include gaps, allow stale or rollup.
0x40, 0x80 reserved Refused.

Column set bits: 0x01 open, 0x02 high, 0x04 low, 0x08 close, 0x10 volume; bits 5–7 must be zero.[31]

QUERY_RESPONSE (0x41)

The response comes in one of three forms. Which one the client parses is determined by its request: a tick query (without rollup) gets the tick form, a column query the column form, anything else the candle form. The conformance file marks this with shape.

Candle form:

Field Encoding
status u8 (below)
flags u8: 0x01 has more, 0x02 stale; other bits refused
count u32
records count × 49-byte candle records (gap markers and marks as above)
level at i64 — only if stale: when the answering copy was last level with its primary, Unix ns
crc u32

Column form (flags has 0x04; never stale):

Field Encoding
status u8
flags u8: 0x04 columns, plus 0x01 if more
count u32
column set u8
rows count × (u8 mark + i64 timestamp + one f64 per column in the set, in the order open, high, low, close, volume)
crc u32

A row's mark byte is zero, or an INCOMPLETE mark; a gap marker never appears in the column form.

Tick form:

Field Encoding
status u8
has more u8, exactly 0 or 1
count u32
records count × 24-byte tick records
crc u32

Status values:[32]

Value Name Meaning
0x00 OK Records follow.
0x02 STREAM_NOT_FOUND The node has never ingested this stream. Count is 0.
0x03 INVALID_RANGE end ≤ start, or a candle (or rollup) query starting before 0.
0x04 ELSEWHERE Only inside QUERY_MULTI_RESPONSE; see below.

Paging. A response is capped by the frame limit and by max results. When has-more is set, the client continues from the last record: ascending, start = last + 1; descending, end = last (the Go client's rule, in pageAfter).[33]

A rollup returns only closed bars whose stamp lies in [start, end); a bar still open is not returned. A stale answer is sent only to a request that set allow stale; a copy answers only while within cluster.copy_read_max_staleness (default 5 s) of its primary, and otherwise redirects.[34] See Reads from copies.

QUERY_MULTI (0x42) and QUERY_MULTI_RESPONSE (0x43)

A batch of independent sub-queries answered in one frame. Nothing is merged; result i answers sub-query i, and two windows of one stream in one batch are legal.[35]

Request:

Field Encoding
count u16, 1 to 4,096
sub-queries count × a QUERY_STREAM payload, back to back

The node also enforces network.max_subqueries_per_request (default 128): a larger batch is refused whole with PayloadTooLarge, never truncated. Permissions are checked for every sub-query before anything runs; one sub-query lacking its read permission refuses the batch with Unauthorized.

Response:

Field Encoding
count u16
results count × result (below)
crc u32 over everything above

Each result:

Field Encoding
status u8 (as QUERY_RESPONSE)
flags u8: 0x01 has more, 0x02 ticks, 0x04 stale, 0x08 columns; others refused
resume from i64: where to restart this sub-query, meaningful when has more is set
count u32
then, by kind candles: count × 49 bytes, then i64 level-at if stale · ticks: count × 24 bytes · columns: u8 column set, then count column rows · ELSEWHERE: see below

A result whose status is ELSEWHERE (0x04) was not run on this node: its flags hold at most the ticks bit, resume-from and count are zero, and it is followed by a u16 length and a REDIRECT_COMMAND payload naming the node that serves that stream. The client regroups such sub-queries by node and asks again. Every result has a slot even when the frame filled before the node reached it: such a result has has-more set and its original start as the resume point, which is why the resume point travels explicitly.[36]

Subscriptions

SUBSCRIBE_STREAM (0x30)

Field Encoding
flags u8 (below)
stream identity
start time i64 — only if backfill (0x02): oldest timestamp to replay; 0 means from the earliest stored
ack window u16 — only if ack (0x08): must be non-zero

Subscribe flags:[37]

Mask Name Meaning
0x01 ticks Subscribe to ticks (needs READ_TICKS) rather than candles (READ_CANDLES). Part of the subscription's identity.
0x02 backfill Replay stored history from start time before live data.
0x04 partials In-progress candles. Not implemented: answered Unsupported, because the ingest path produces closed candles only.
0x08 ack Bounded-ack delivery: at most window live batches beyond the last STREAM_ACK, never dropped; a subscriber that falls too far behind is evicted instead.
0x10 offloadable The client can follow an OFFLOAD_SUBSCRIPTION. Candles only.
0x20 offloaded This SUBSCRIBE follows an offload; only then does a copy serve it. Candles only.
0x40, 0x80 reserved Refused.

A subscription is identified by (connection, stream, ticks bit); there is no server-assigned id. The SUBSCRIBE's header correlation id becomes the subscription's tag: every frame the node sends for that subscription — the confirmation, each batch, the eviction ERROR, the REDIRECT_COMMAND sent when its partition moves away — carries it. A duplicate SUBSCRIBE is idempotent and keeps the existing sequence numbering (and gets no second backfill). Each connection may hold network.subscription.max_per_connection subscriptions (default 256); one more is answered Unsupported.

STREAM_DATA (0x32)

Field Encoding
flags u8 (below)
sequence u64
stream identity
count u32
records count × 49-byte candles (flags byte zero) or count × 24-byte ticks
level at i64 — only if stale
crc u32

Stream-data flags: 0x01 ticks, 0x02 backfill, 0x04 live (first live batch after a backfill), 0x08 established, 0x10 stale (sent by a copy; trails the primary by about one replication poll). Others are refused.[38]

Sequence rules:

  • The node confirms a subscription with an Established frame: sequence 0, no records.
  • Live batches are numbered from 1, one per frame. A batch the node drops for a slow consumer still consumes its number, so a gap in the sequence is how a client detects a drop.
  • Backfill batches carry sequence 0 and sit outside the live numbering.
  • The backfill window and the live queue overlap, so a record can arrive twice across the seam; ingest is idempotent by (stream, timestamp), and consumers should dedupe.

A fire-and-forget subscriber whose queue stays full is evicted after network.subscription.drop_limit consecutive drops (default 10,000) with ERROR SlowConsumer under its tag; the connection and its other subscriptions continue.

UNSUBSCRIBE_STREAM (0x31)

Payload: flags u8 (only 0x01 ticks allowed) and the stream identity. No answer. Unsubscribing from a subscription that does not exist is not an error.

STREAM_ACK (0x33)

For a bounded-ack subscription: the client has processed every live batch up to and including sequence. Cumulative. No answer.

Field Encoding
flags u8 (only 0x01 ticks)
stream identity
sequence u64, non-zero

OFFLOAD_SUBSCRIPTION (0x21)

Server to client only, under the SUBSCRIBE's tag, with a REDIRECT_COMMAND payload naming an in-sync copy. A primary holding network.subscription.offload_above or more live subscriptions (0, the default, disables this) sends it to a new candle subscriber that set offloadable. The client re-sends its SUBSCRIBE to that copy with offloaded set.[39]

Discovery

LIST_STREAMS (0x44) and LIST_STREAMS_RESPONSE (0x45)

Enumerates the streams a node holds, one page at a time, by key-set pagination over the registry's sorted order.[40]

Request:

Offset Size Field
0 u16 limit: 0 means 200; above 1,000 is refused
2 u16 request flags (below)
4 u16 cursor length (≤ 258)
6 … cursor bytes
… u16 match length (≤ 258), then match bytes
… u8 + bytes exchange filter (empty = any; exact)
… u8 + bytes symbol filter (empty = any; case-insensitive prefix)
… u8 + bytes timeframe filter (empty = any; exact)

Request flags: 0x0001 include stats; bits 1–3 (0x000E) sort key (0 id, 1 last update, 2 record count, 3 storage size); 0x0010 descending; 0x0020 served here (only streams whose partition this node serves, for a cluster-wide listing). Other bits are refused.

The cursor is empty for the first page. For the default sort it is the last stream id of the previous page in symbol:timeframe:exchange form; for any other sort it is <sort value>|<stream id>. match, when non-empty, returns only that exact stream id. Sorting by anything but id makes the node compute statistics for every stream before it can answer.

Response:

Offset Size Field
0 u16 count (≤ 1,000)
2 u8 has more, exactly 0 or 1
3 u8 flags: 0x01 entries carry stats; others refused
4 … count × (stream identity, then a 60-byte stats block if flagged)

Stats block (60 bytes): record count u64, byte size u64, first timestamp i64, last timestamp i64, missing duration i64 (ns of genuinely absent time, closures excluded), chunk count u32, patch count u32, gap count u32, open gap count u32, off-time count u32. Record count and byte size are persisted totals from the stream index; the first and last timestamps include data still in memory.

LIST_GAPS (0x46) and LIST_GAPS_RESPONSE (0x47)

A stream's gaps as stored ranges.[41]

Request:

Field Encoding
stream identity
start i64
end i64 (start ≤ end)
cursor i64: a gap start; next page is everything strictly after it
limit u16: 0 means 200; above 1,000 refused
flags u16: 0x0001 cursor present, 0x0002 open gaps only, 0x0004 exclude market closures; others refused

Response:

Field Encoding
count u16 (≤ 1,000)
has more u8, 0 or 1
reserved u8, must be 0
summary 32 bytes: missing duration i64, off-time duration i64, gap count u32, open count u32, off-time count u32, fillable count u32
gaps count × 18 bytes: start i64, end i64, status u8, reason u8

A gap overlapping the window is returned whole. Whether a gap may be filled is not on the wire; clients compute it with the same rule the node uses (a market closure is never fillable). See Finding and filling gaps.

LIST_NODES (0x48) and LIST_NODES_RESPONSE (0x49)

The request payload is empty. The response lists the cluster's nodes from the answering node's applied control-plane state, ascending by node id:[42]

Field Encoding
count u16
each node node id u64 (non-zero) · flags u8 (0x01 serving, 0x02 draining; others refused) · primaries u32 · copies u32 · address length u16 (1–320) · data address bytes

An empty list means the node is not in a cluster.

NODE_STATS (0x4A) and NODE_STATS_RESPONSE (0x4B)

The request payload is empty. The response is one node's own measurements, fixed layout:[43]

Field Encoding
node id u64 (0 for a node with no cluster)
known u32 bitmask: 0x1 CPU and start time, 0x2 memory, 0x4 disk, 0x8 last ingest. A value whose bit is clear was not measured and must not be read as zero.
sampled at, started at, last ingest 3 × i64 Unix ns
CPU seconds f64 (cumulative user + system)
resident bytes, disk total, disk free 3 × u64
held streams u32, records u64, bytes u64, partitions u32
primary streams u32, records u64, bytes u64, partitions u32
candles ingested, ticks ingested, queries 3 × u64 (cumulative)
subscriptions u32
ingest latency histogram, query latency histogram each: bucket count u16 (≤ 256), that many upper bounds f64 (strictly ascending, seconds), that many cumulative counts u64, sum f64, total u64

Rates are for the consumer to compute from two samples of one node, on that node's clock.

Gap and metadata operations

FILL_GAP (0x4C) and FILL_GAP_RESPONSE (0x4D)

Asks the node to fill one gap with candles it synthesises from the real candles either side. A write: needs WRITE_CANDLES, accepts the epoch prefix and OVERWRITE.[44]

Request: stream identity, then gap start i64 (must equal a gap's start exactly), method u8 (1 linear, 2 forward, 3 backward; 0 refused), reserved u8 (0), max candles u32 (0 = the node's own cap).

Response (24 bytes): filled u32, has more u8 (0 or 1), reserved u8 (0), then the gap as the node found it (18 bytes: start, end, status, reason). Re-sending is safe; it fills only what is still missing. A market closure is refused.

ACCEPT_GAP (0x4E) and ACCEPT_GAP_RESPONSE (0x4F)

Marks a derived bar's INCOMPLETE mark ACCEPTED, or puts it back to OPEN. A write: WRITE_CANDLES, epoch prefix allowed.

Request: stream identity, mark start i64 (exact), accept u8 (1 accept, 0 revert), reserved u8 (0). Response (18 bytes): the mark as it now stands (start, end, status, reason).

Stream-metadata frames (0x50–0x55)

These read and set a stream's calendar, gap thresholds, closures and lineage over the data protocol. GET_STREAM_METADATA is a read (READ_CANDLES); the four setters need ADMIN_STREAM, accept the epoch prefix, and take a write's placement checks. Every request is answered with one STREAM_METADATA frame.[45]

Frame Payload after the stream identity
GET_STREAM_METADATA nothing
SET_STREAM_METADATA flags u8 (0x01 create the stream if unknown), then a metadata record without a lineage
ADD_STREAM_CLOSURE start i64, end i64, note (u16 length + bytes)
REMOVE_STREAM_CLOSURE start i64, end i64 (removes that range, cutting any closure it overlaps)
SET_STREAM_LINEAGE history u8 (0 clear — nothing follows; 1 from now; 2 re-derive the source's history), then source stream identity, kind u8 (1 ticks, 2 candles), close grace i64 ns, no-trade limit i64 ns

A lineage is set only through SET_STREAM_LINEAGE; a SET_STREAM_METADATA carrying one is refused.

STREAM_METADATA:

Field Encoding
status u8: 0x00 OK or 0x02 stream not found
flags u8: 0x01 the request created the stream
reserved u16, zero
refiled i64: nanoseconds of filed gap time the change re-classified
record the metadata record, only when status is OK

Metadata record:

Field Encoding
flags u8: 0x01 working hours present, 0x02 lineage present
gap threshold low, high 2 × i64 ns
working hours (if flagged) timezone (u16 + bytes), day count u8, each day: weekday u8 (0 = Sunday … 6 = Saturday), window count u8, each window: open hour, open minute, close hour, close minute (u8 each; hour 0–24, minute 0–59)
closures count u32, each: start i64, end i64, note (u16 + bytes)
custom fields count u16, each: key (u16 + bytes), value (u16 + bytes); keys strictly ascending
lineage (if flagged) source stream identity, kind u8, close grace i64, no-trade limit i64, since i64, re-derive u8 (0 or 1)

An invalid metadata change is refused Protocol with the reason. See Gaps and trading calendars and Derived streams and lineage.

Routing frames

REDIRECT_COMMAND (0x20)

Sent by a node that does not serve the stream a request named (or whose fenced write carried an older epoch). It is emitted after the permission check and before anything is dispatched, so following it is a first attempt. A client that sends one is answered Unsupported.[46]

Offset Size Field
0 u32 partition id
4 u64 partition epoch
12 u64 node id, non-zero
20 u16 address length, 1–320
22 … the node's data address, host:port
… u32 CRC-32C over everything above

The payload is exact: trailing bytes are refused. A client following redirects should require each hop's epoch to be newer than the last it saw for that request: an equal epoch from a different node means two directories disagree. The Go client waits out an older epoch briefly, because a node that has not yet applied a move answers from behind. See Partitions and routing.

ERROR (0xF0)

Offset Size Field
0 u16 error code
2 u16 retry after, milliseconds; 0 = no hint
4 u16 message length
6 … message (UTF-8, at most 512 bytes as sent by the node)

The parser requires the message to be present in full; extra bytes after it are tolerated. The retry field was a reserved zero field in earlier builds, so a frame from an older node reads as "no hint".[47] The codes, their meaning and what a client should do are in Error codes.

Limits

Limit Value Where
Header 14 bytes protocol
Frame payload network.max_frame_payload_bytes, default 16 MiB, range 4 KiB–64 MiB config
Stream identity component 1–64 bytes protocol
Sub-queries per QUERY_MULTI 4,096 (protocol); network.max_subqueries_per_request, default 128 protocol / config
LIST_STREAMS / LIST_GAPS page 1,000 (default 200) protocol
Cursor / match 258 bytes protocol
Redirect or node address 320 bytes protocol
Histogram buckets 256 protocol
Token lifetime at most 1 hour ahead of the node's clock protocol
Handshake network.connection_timeout, default 30 s config
Read deadline / idle close network.read_timeout 30 s / network.idle_timeout 120 s config
Subscriptions per connection network.subscription.max_per_connection, default 256 config
ERROR message 512 bytes (truncated by the node) server

Evolving the protocol

  • A new frame type needs no version change: an older node answers Unsupported.
  • A new header flag bit, query flag bit, or request flag bit is refused by an older peer, which is the safe failure: the request fails loudly instead of being served without its meaning.
  • The ERROR retry field is the one place a meaning was added to bytes older peers ignore.
  • An incompatible change bumps the version byte. Version 2 replaced version 1 when INIT_ACK grew from 8 to 16 bytes to carry the granted permissions; there is no version 1 compatibility.[48]

References

Source

Tests

Further reading

External

  • Castagnoli, Bräuer, Herrmann, "Optimization of Cyclic Redundancy-Check Codes with 24 and 32 Parity Bits", IEEE Transactions on Communications, 1993 — the CRC-32C polynomial.
  • RFC 3720, "Internet Small Computer Systems Interface (iSCSI)", Appendix B.4 — CRC-32C test vectors: https://www.rfc-editor.org/rfc/rfc3720#appendix-B.4
  • RFC 8032, "Edwards-Curve Digital Signature Algorithm (EdDSA)" — Ed25519: https://www.rfc-editor.org/rfc/rfc8032
  • RFC 4648, "The Base16, Base32, and Base64 Data Encodings" — the token's standard base64: https://www.rfc-editor.org/rfc/rfc4648
  • IEEE 754-2019, "IEEE Standard for Floating-Point Arithmetic" — binary64.

  1. /internal/wire/payload.go header comment; every codec uses binary.BigEndian. ↩︎

  2. castagnoli in /internal/wire/payload.go; wire.CRC32C in /internal/wire/sizes.go. ↩︎

  3. /internal/wire/conformance_test.go; the reject classes map to Go sentinels in rejectClasses (magic → ErrInvalidMagic, truncated → ErrShortHeader, and so on). ↩︎

  4. HeaderSize, FrameMagic, ProtocolVersion and ParseHeader in /internal/wire/protocol.go. ↩︎

  5. TestParseHeader_ReservedFieldsRejected; conformance rejects header_undefined_flag, header_reserved_byte. ↩︎

  6. FlagAckMode … FlagOverwrite and definedFlags in /internal/wire/protocol.go; the correction-plus-history refusal is in Server.handleIngest. ↩︎

  7. Defaults in /internal/config/config.go; bounds minFramePayloadBytes, maxFramePayloadBytesCeiling in /internal/config/validate.go; Server.reportReadFailure in /internal/network/server.go. ↩︎

  8. Header comment of /internal/wire/redirect.go. ↩︎

  9. validStreamComponent, validateStreamID in /internal/wire/payload.go; types.ParseTimeframe and StreamID.String in /internal/types/stream.go. ↩︎

  10. Candle.Validate in /internal/types/candle.go, Tick.Validate in /internal/types/tick.go, MaxStorableMagnitude in /internal/types/value.go; ParseCandleBatchPayload refuses the batch on the first bad record. ↩︎ ↩︎

  11. GapStatus and GapReason constants in /internal/types/gap.go. ↩︎

  12. decodePointFlags in /internal/wire/payload.go; TestQueryResponsePayload_RefusesAMarkNoRecordCanCarry. ↩︎

  13. /internal/wire/epoch.go; conformance cases ingest_candles_fenced, fenced_ingest_bad_epoch_crc. ↩︎

  14. Server.fenced and stalePlacementRetryMillis (250) in /internal/network/fencing.go; ingestPayload is called by every write handler in /internal/network. ↩︎

  15. Handshaker.Perform in /internal/network/handshaker.go; the timeout is cfg.ConnectionTimeout passed to newHandshaker in NewServer. ↩︎

  16. EncodeToken, ParseToken, EncodedTokenLen in /internal/wire/handshake.go; FuzzParseToken. ↩︎

  17. signingDomain and SigningInput in /internal/wire/handshake.go. ↩︎

  18. Handshaker.admit in /internal/network/handshaker.go; TestHandshake_ExpiredTokenRejected, TestHandshake_ValidityWindowExceeded. ↩︎

  19. tokenRefusal and tellClientWhyTheHandshakeFailed in /internal/network/server.go. ↩︎

  20. Client.initFrame, unauthenticatedRequest in /internal/wireclient/client.go. ↩︎

  21. Server.serveFrames handles frames sequentially; subscription pushes are written by the subscription registry's push loops (Server.writeStreamData). ↩︎

  22. Connection.Read sets a read deadline of network.read_timeout before every read; the idle monitor uses network.idle_timeout (/internal/network/connection.go). ↩︎

  23. The default branch of serveFrames; TestServer_UnsupportedFrameAnswered. ↩︎

  24. Server.sessionRefusal, sessionExpiry in /internal/network/server.go; TestServer_ExpiredSessionRefusesNewWork, TestServer_ExpiredSubscriberIsDisconnected. ↩︎

  25. Server.handleReauth in /internal/network/reauth.go; TestReauth_* in /tests/auth_renewal_test.go. ↩︎

  26. frameTypeNames in /internal/wire/protocol.go; Server.handlers in /internal/network/server.go. ↩︎

  27. placementChecked in /internal/network/fencing.go and redirected in /internal/network/redirect.go. ↩︎

  28. ParseCandleBatchPayload, ParseTickBatchPayload; TestCandleBatchPayload_PartialBatchRejected. ↩︎

  29. Server.handleIngest uses IngestCandlesDurable when ACK is set; TestServer_AckedCandleIngestIsInWALBeforeAck. ↩︎

  30. queryFlag*, queryFlags, parseQueryBody, checkColumnQuery in /internal/wire/payload.go. ↩︎

  31. ColumnSet in /internal/wire/columns.go. ↩︎

  32. QueryStatus constants and QueryRequest.InvalidRange in /internal/wire/payload.go. ↩︎

  33. QueryResponse.HasMore and pageAfter in /internal/wireclient/rows.go. ↩︎

  34. QueryRequest.AllowStale and QueryRequest.Rollup doc comments in /internal/wire/payload.go; TestStaleRead_ACopyBeyondItsStalenessBoundRedirects. ↩︎

  35. /internal/wire/multiquery_payload.go; MaxSubQueries; handleQueryMulti in /internal/network/multiquery.go. ↩︎

  36. appendElsewhereResult, parseElsewhereResult; TestServer_QueryMultiHeadAlwaysProgresses. ↩︎

  37. subFlag*, ParseSubscribePayload in /internal/wire/subscription_payload.go; Server.handleSubscribe in /internal/network/server.go. ↩︎

  38. streamFlag*, ParseStreamDataPayload; TestStreamDataPayload_EstablishedFrame, TestServer_BackfillStreamsHistoryBeforeLive. ↩︎

  39. Server.offloaded in /internal/network/server.go; TestServer_ASaturatedPrimaryOffloadsANewSubscriberToACopy. ↩︎

  40. /internal/wire/list_streams.go; Server.handleListStreams. ↩︎

  41. /internal/wire/list_gaps.go; Server.handleListGaps. ↩︎

  42. /internal/wire/list_nodes.go; Server.handleListNodes. ↩︎

  43. /internal/wire/node_stats.go. ↩︎

  44. /internal/wire/fill_gap.go, /internal/network/fill_gap.go; FillMethod in /internal/types/gap_autofill.go. ↩︎

  45. /internal/wire/stream_metadata.go, /internal/network/stream_metadata.go. ↩︎

  46. /internal/wire/redirect.go, Server.writeRedirect; TestRedirect_AClientSendingOneIsStillRefused. ↩︎

  47. WriteErrorFrameRetryAfter, ParseErrorFrame in /internal/wire/protocol.go; the 512-byte cap is maxErrMsg in Server.writeErrorRetryAfter. ↩︎

  48. ProtocolVersion doc comment in /internal/wire/protocol.go. ↩︎