Mirexa

Wiki Reference

On-disk formats

Every directory and file a Mirexa node keeps under its data directory, with byte layouts, magic numbers, versions, checksums and what happens when a file is old or damaged.

A Mirexa node keeps everything it stores under one directory, storage.data_dir: a write-ahead log, a catalog of streams, and per stream a chunk index, a gap index, compressed chunk files and tick storage. A clustered node adds its consensus state, the logs it keeps as a copy of other nodes' partitions, and a quarantine area for data it has set aside. This page is for anyone who has to inspect, back up or write tooling against that directory: it lists every path, then gives each binary format byte by byte, with what the node does when it meets an older version or a damaged file.

Mirexa ships no offline tool that reads these files; the layouts below are what such a tool would implement. They are checked against the encoders and parsers named in each section, not against a specification, because there is none besides the code.

Conventions that hold everywhere

Property Rule
Byte order Little-endian for every multi-byte integer and float in every format, with one exception: the 8-byte WAL segment header is big-endian.
Floats IEEE-754 binary64 bit patterns, stored as uint64.
Timestamps int64 Unix nanoseconds.
Checksums CRC-32C (Castagnoli polynomial) everywhere Mirexa computes one. Chunk files store theirs in 64-bit fields (the upper 32 bits are zero).
Versioning Each binary file starts with a 4-byte ASCII magic and a version number. A version the reader does not know is refused, never guessed at. Only the tick index reads older versions of itself.
Durability Every whole-file write goes temp file → fsync → rename → fsync of the parent directory. See Atomic writes.

The directory tree

text
<storage.data_dir>/
├── streams.meta                     node-wide stream catalog (magic SMET)
├── wal/                             the node write-ahead log
│   ├── wal.lock                     exclusive advisory flock; one process per directory
│   ├── 000000001.log                segments (magic MRXW), nine-digit index
│   ├── 000000002.log
│   ├── shard_<n>/                   tick WAL shards, same layout and its own wal.lock
│   └── quarantine.floors            JSON; present only after a partition was set aside
├── raft/                            only when cluster.enabled
│   ├── raft-log.bolt                replicated log + stable store (BoltDB)
│   └── snapshots/<id>/              meta.json + state.bin (control-plane snapshot)
├── quarantine/                      only after something was set aside; never pruned
│   ├── partition_<id>-epoch_<e>/
│   ├── partition_<id>-epoch_<e>-released[-<n>]/
│   ├── partition_<id>-epoch_<e>-diverged[-<n>]/
│   └── partition_<id>-epoch_<e>-corrupt[-<n>]/
└── partition_<id>/                  decimal id, no padding
    ├── replica.wal/                 only while this node holds the partition as a copy
    ├── replica.ticks/
    │   └── n<origin>-<log>/         a copy's tick records, per primary node and log
    └── <exchange>@<symbol>_<timeframe>/  one per stream
        ├── stream.idx               chunk index (magic SIDX, v5)
        ├── gap.idx                  gap index (magic GIDX, v1)
        ├── chunks/
        │   ├── chk_001.bin          candle chunk (magic MIRX)
        │   ├── chk_002_patch.bin    correction of a base chunk
        │   └── chk_003.bin.pending  transient, during an install
        └── ticks/
            ├── tick_index.bin       tick chunk index (magic TIDX, v3)
            └── tick_chunk_000001.bin  tick chunk (magic MIRT)

Where a stream lives

A stream is identified by exchange, symbol and timeframe. Its partition is FNV-64a(symbol ‖ 0x00 ‖ exchange) mod partition.count (types.AssignPartition; the count defaults to 4,096 and, in a cluster, is fixed once agreed). The timeframe is not part of the key, so every timeframe of one symbol on one exchange lives in the same partition directory. The stream directory name is <exchange>@<symbol>_<timeframe> (types.StreamID.StreamDir): the exchange ends at the first @ and the timeframe begins after the last _ (storage.ParseStreamDirName). @ is outside the identity alphabet every entry path enforces, and a timeframe that parses holds no _, so the name is unique per stream.[1]

Until 2026-10-30 the name was <symbol>_<timeframe>, and two streams with the same symbol and timeframe on different exchanges in one partition shared a directory. At startup the node renames each directory in the old form to the new one, using the registry (Layout.MigrateStreamDirs). A directory two registered streams claim, one no registered stream claims, or one whose new name is taken stops the node with ErrStreamDirMigration, renaming nothing; the operator moves or renames the directory it names.

Directories are created on demand: a partition directory and the stream's chunks/ when the stream is first registered or written, ticks/ when its tick store is first opened, and stream.idx/gap.idx only when the first chunk or gap is recorded. A stream directory without those files is simply a stream with nothing flushed yet.

Files that are not where you might expect

  • There is one catalog per node, <data_dir>/streams.meta. Layout.StreamMetaPath names a per-partition partition_<id>/streams.meta, but nothing in the server reads or writes it.
  • There is one WAL per node, not per stream. Layout.WALPath (a per-stream wal/) is deprecated and unused.
  • Ticks shard by stream: tick records go to wal/shard_<Hash() mod shard_count>/ (wal.shard_count, default 16; 0 or 1 sends ticks to the shared wal/). At startup every shard_<n> directory on disk is recovered, whatever shard_count now says.

The write-ahead log

Every acknowledged write is in the WAL before it is acknowledged; chunks are written later by the flusher, and a checkpoint deletes segments whose records are all in chunks. See The write-ahead log for the mechanism and Crash recovery for replay.

Segment files

A WAL directory holds wal.lock and segment files named with a nine-digit zero-padded index and .log (000000001.log). The reader accepts any digit count. A segment is rotated when the next append would push it past wal.max_segment_bytes (default 512 MiB); the limit is soft, since a single append is never split.

Every segment begins with an 8-byte header, big-endian:[2]

Offset Size Field Value
0 4 magic 0x4D525857 ("MRXW")
4 2 version 1
6 2 reserved 0

Records follow back to back with no padding between them.

Record layout

Each record is a 28-byte header and a payload, little-endian:[3]

Offset Size Field Notes
0 4 CRC CRC-32C over bytes 4 through the end of the payload
4 4 length payload byte count, at most 65,536
8 8 sequence monotonic within this log (the shared WAL or one shard)
16 8 timestamp wall-clock Unix nanoseconds at append time; not market time
24 2 payload type see below
26 2 reserved 0, so the payload starts 4-byte aligned
28 n payload

A reader takes the length first, bounds it, and only then checks the CRC over exactly [4, 28+length), so a corrupt length is caught by the checksum rather than steering a read past the buffer.

Sequence numbers are per log. The shared WAL and each tick shard number independently, and a restart continues each log's sequence rather than starting again.[4]

Payload types

Type Name Written by the node? Payload
1 Tick yes tick batch
2 Candle yes candle batch
3 Materialized no defined, never written
4 Gap no defined and parsed; nothing in the server writes one

Candle batch (type 2):

Field Size
stream id length 4 (uint32)
stream id n bytes, the stream's string form
candle count 4 (uint32)
candles 48 bytes each: timestamp int64, open, high, low, close, volume (float64)

Tick batch (type 1):

Field Size
stream hash 8 — FNV-64a of symbol ‖ 0 ‖ timeframe ‖ 0 ‖ exchange
tick count 4
reserved 4
ticks 32 bytes each: stream hash (repeated), timestamp, price, volume

A tick record names its stream only by hash; streams.meta is what turns the hash back into a stream. The parser refuses a tick whose repeated hash differs from the batch's.

Gap (type 4): stream id length (4), stream id, then one 18-byte gap range in the gap.idx entry layout.

Corruption and versions

Recovery treats damage differently depending on where it is:[5]

What recovery finds Outcome
A torn record (short or CRC-failed) at the end of the last segment, with no CRC-valid record after it truncated away; normal after a crash mid-write
Damage in the last segment with a CRC-valid record after it refused, ErrCorruptMidLog; nothing is truncated — unless a whole 512-byte-aligned sector of zeros lies before that record, which is a tear and is truncated (since 2026-10-30)
A last segment with no complete header treated as an empty tail
A bad record in any earlier segment refused, ErrCorruptMidLog; nothing is truncated
A header with the wrong magic or version, in any segment refused, ErrCorruptSegment
A missing header on a non-final segment refused, ErrCorruptSegment

A refused WAL stops the node from starting. That is deliberate: truncating committed records to get past a hole would lose acknowledged writes silently.

wal.lock is held with an exclusive, non-blocking flock; a second process opening the same directory fails at once. Creating a segment also fsyncs the directory, so a crash cannot remove a segment whose records were already acknowledged.

Replica logs (cluster only)

A node holding a partition as a copy keeps the primary's log records for that partition in partition_<id>/replica.wal/, an ordinary WAL directory with the same segment and record formats and its own wal.lock. Records are stored verbatim, so sequence numbers inside it are not monotonic: it interleaves the primary's candle log and its tick shards. It is trimmed from the front as seeded chunks come to cover it, and deleted when a promotion has replayed it. Its presence on a node that is the partition's primary means a promotion has not yet run or was refused; it is kept on failure because it holds acknowledged writes.

Tick records a copy receives go to partition_<id>/replica.ticks/n<origin>-<log>/, one WAL directory per primary node id (<origin>) and primary log (wal or shard_<n>), because a tick record's sequence is only meaningful within its own log on its own node.[6] See Replication.

Candle chunk files

A chunk holds one contiguous run of a stream's candles, column by column. Names are chk_<seq>.bin for a base chunk and chk_<seq>_patch.bin for a correction, where <seq> is the entry's SeqNo printed with at least three digits (chk_001.bin, chk_1234.bin).[7]

Layout

text
[ header 80 B ][ 6 column pointers × 16 B ][ data section ][ footer 32 B ]
                                           └ optional block index, then the six columns

Header (80 bytes):

Offset Size Field Notes
0 4 magic 0x4D495258 ("MIRX" as a little-endian uint32; the bytes on disk read XRIM)
4 2 version 1; a higher version is refused
6 2 flags bit 0 HasGaps (refused if set); bit 1 BlockIndex
8 4 record count candles in the chunk; must be non-zero
12 2 column count always 6
14 2 reserved holds the rows per block when the block-index flag is set, else 0
16 8 base timestamp first candle
24 8 end timestamp last candle
32 8 interval stream interval in nanoseconds
40 40 base open, high, low, close, volume first candle's values, float64 each

Column pointers (6 × 16 bytes), in the order timestamp, open, high, low, close, volume:

Offset Size Field
0 8 offset of the column, relative to the start of the data section
8 4 compressed size in bytes (must be > 0)
12 1 codec (below)
13 3 reserved

Footer (32 bytes):

Offset Size Field Notes
0 8 data end absolute file offset where the data section ends (= footer start)
8 4 in-chunk gap count always 0; a non-zero value is refused
12 4 reserved
16 8 data checksum CRC-32C over header + column pointers + data section
24 8 footer checksum CRC-32C over footer bytes 0–23

Gaps are never stored inside a chunk; they live in gap.idx, which is the only place that carries their classification and can describe a range spanning two chunks. A chunk claiming an in-chunk gap index, by flag or count, is refused on read.[8]

Both checksums are verified on every read. CRC-32C detects every single-bit error, and a test flips each bit of a chunk in turn to prove the parser refuses all of them.[9]

Column codecs

The codec is chosen by compression.algorithm when a chunk is written (in a cluster, by the agreed cluster setting) and recorded per column, so chunks written under different settings coexist; nothing rewrites old chunks.

Code Name Used for Encoding Exact?
0 none every column under none 8 bytes per value: raw int64 timestamps, raw float64 bits lossless
1 delta-of-delta timestamps (default and gorilla) DoD stream, below lossless
2 Gorilla OHLCV under gorilla uint32 count, then a Gorilla XOR bit stream lossless
3 fixed-point DoD OHLCV (default fixed_point_dod) each value × 10,000, rounded to int64, then a DoD stream rounded to 0.0001

The default codec stores prices and volumes at a resolution of 1/10,000. A value whose scaled magnitude would overflow int64, and NaN or ±Inf, is refused at ingest rather than stored; decoding divides by 10,000 (it never multiplies by the reciprocal, which would round twice).[10]

Delta-of-delta stream (codes 1 and 3), 21-byte header then a body:

Offset Size Field
0 1 format: 0 raw, 1 packed
1 4 count of values
5 8 first value
13 8 first delta (value₁ − value₀)
21 … the count − 2 delta-of-deltas

In the raw body each delta-of-delta is an int64. In the packed body each is zig-zag encoded and written most-significant-bit first behind a unary prefix: 0 for a zero delta-of-delta (no payload), 10 + 8 bits, 110 + 16 bits, 1110 + 32 bits, 1111 + 64 bits. The writer picks whichever body is smaller, so a column never grows by more than the one-byte tag.[11]

Block index

A chunk of more than 256 rows written with the default or none codec carries a block index at the start of its data section (flag bit 1, rows per block in the header's reserved field). It lets a reader decode the rows near one timestamp without decoding the chunk from its first row. Its layout is: a head of one format byte per column plus 2 reserved bytes; per block, the block's first timestamp (8) and, per column, the bit offset of the block's first delta-of-delta, the value before it, the delta before it (8 each) and a CRC-32C of the bytes that block's rows decode from (4); then a CRC-32C of the file from offset 0 through the index. The column pointers point past it, so a reader that ignores the flag still reads the chunk correctly. The footer checksums cover the index too.[12]

Patch chunks

A correction to candles already in a chunk is written as a patch chunk: an ordinary chunk file (always the default codec) holding only the restated candles, named chk_<seq>_patch.bin and recorded in stream.idx with the patch flag and the SeqNo of the base it corrects. A read merges base and patch, the patch winning per timestamp. Patches are cumulative: only the newest patch of a base is read, so each new patch folds in the one before it. A patch of a patch is refused.[13] See Corrections, restatements and history.

Install protocol and leftover files

A chunk is installed in three steps under the stream's install lock:[14]

  1. write chk_<seq>.bin.pending durably (temp, fsync, rename, directory fsync);
  2. rename it to chk_<seq>.bin and fsync the directory;
  3. publish the stream.idx entry naming it.

Garbage collection deletes every chk_*.bin no stream.idx entry names, and ignores .pending files. When a stream is opened, .pending files are reconciled: one whose final name is in the index is rolled forward, any other is deleted (its candles are still in the WAL). So after a crash a chunks directory may hold an unreferenced chk_*.bin (crash between steps 2 and 3, removed by the next GC) or a .pending file (removed when the stream next opens). Neither is ever read as data.

stream.idx

The chunk index: one entry per chunk file, in time order, each patch placed directly after its base. Every write rewrites the whole file.

Header (12 bytes):

Offset Size Field Notes
0 4 magic ASCII SIDX
4 2 version 5
6 2 entry count at most 65,535
8 4 issued-through highest SeqNo the stream has ever issued; compaction never lowers it

Entry (38 bytes):

Offset Size Field Notes
0 8 start timestamp first candle
8 8 end timestamp last candle
16 2 flags 0x0000 base chunk, 0x0002 patch; no other bit is written
18 4 SeqNo the chunk's stable identity; names its file
22 4 BaseSeqNo for a patch, the base it corrects; 0 on a base
26 4 record count copied from the chunk header
30 8 byte size the chunk file's compressed size on disk

Footer: 4-byte CRC-32C over header and entries.

SeqNo is the key, not position: a history back-fill inserts below existing entries and compaction drops entries, so positions shift while SeqNos never change. The issued-through mark exists so a SeqNo is never issued twice, even after compaction has dropped the highest one and the node has restarted.[15] To count a stream's records, sum record count over base entries only — a patch restates records its base already counts. A patch entry repeats its base's time range.

On open the reader checks, in order: size at least 16 bytes, magic, version (exactly 5), that the file size equals 12 + 38 × count + 4, the CRC, and then each entry: start ≤ end, SeqNo ≤ issued-through, and that base entries do not overlap (a base may begin exactly where the previous one ended; patches are exempt).

Older versions are refused. Versions 1–4 and anything above 5 fail with an error naming the version; there is no upgrade path.[16]

gap.idx

The gap index: one record per gap range, sorted by start, non-overlapping. Every write rewrites the whole file. See Gaps and trading calendars for what the records mean.

Part Layout
header (8) magic GIDX (4), version 1 (2), entry count (2, at most 65,535)
entries 18 bytes each, below
footer (4) CRC-32C over header and entries

Entry (18 bytes) — the same encoding the WAL's gap payload and the wire protocol's gap lists use:

Offset Size Field
0 8 start (inclusive), Unix ns
8 8 end (exclusive), Unix ns
16 1 status
17 1 reason
Status Name Reason Name
0 OPEN 0 UNKNOWN
1 FILLING 1 CORRUPTION
2 CLOSED 2 NETWORK
3 PERMANENT 3 CRASH
4 ACCEPTED 4 MAINTENANCE
5 RATE_LIMIT
6 EXCHANGE
7 MANUAL
8 OFF_TIME
9 INCOMPLETE

Mirexa's own classifier files UNKNOWN (a hole in trading time), OFF_TIME (a market closure) and INCOMPLETE (a derived bar built from less than its window — the one record that sits over slots holding data). Reasons 1–7 are valid and accepted on read. A record is refused if start ≥ end, a code is out of range, ACCEPTED is used with any reason but INCOMPLETE, or an INCOMPLETE record is PERMANENT.[17] A filled gap is marked CLOSED, not deleted.

Tick storage

tick_index.bin

The index of a stream's tick chunks, in ticks/tick_index.bin. Version 3 is written; versions 1 and 2 are still read.

Part Layout
header (8) magic TIDX (4), version (2), entry count (2, at most 65,535)
entries v3: each 24-byte entry followed by its own coverage record; v2: 24-byte entries, then one stream-wide coverage trailer; v1: entries only
footer (4) CRC-32C over everything before it

Entry (24 bytes): SeqNo (int32), start timestamp (int64), end timestamp (int64), tick count (int32). Entries are in time order and must not overlap. SeqNos may have holes where a chunk was rewritten to take a late tick and the old chunk retired.

Coverage record (v3, after each entry) — which WAL records that chunk's ticks came from, so replay can tell a tick already in a chunk from one that is not (a timestamp cannot: two trades in one nanosecond are ordinary):

Field Size
unattributed flag 1 (0 or 1; 1 means some ticks have no known WAL position)
log count 1
per log, in name order: name length 1
name n bytes: wal, shard_<n>, or n<node>/<log> for chunks seeded from a primary
highest sequence 8

The stream's coverage is derived from the entries: for each log, the newest chunk by SeqNo that names it wins.[18]

A damaged tick_index.bin is not fatal. If it fails to parse, it is treated as absent and rebuilt by scanning tick_chunk_*.bin files; of two chunks whose ranges overlap, the one with the higher SeqNo is kept, and the rebuilt index marks everything unattributed.[19]

Tick chunk files

tick_chunk_<seq>.bin, <seq> zero-padded to six digits. Same shape as a candle chunk with three columns (timestamp, price, volume) and a smaller header and footer:

Part Layout
header (48) magic 0x4D495254 ("MIRT" as a little-endian uint32; the bytes read TRIM), version 1, or 2 for a chunk with Gorilla columns, flags (2), tick count (4), column count 3 (2), reserved (2), base timestamp, end timestamp, base price, base volume (8 each)
column pointers 3 × 16 bytes, as for candles
data timestamps delta-of-delta (or raw under none); price and volume fixed-point DoD, Gorilla XOR (version 2) or raw
footer (16) data checksum: CRC-32C over header + pointers + data (8); footer checksum: CRC-32C over the 8 data-checksum bytes (8)

Default chunk size is 1,024 ticks.

streams.meta

The node's stream catalog: every stream the node knows, with its metadata — gap thresholds, trading calendar (weekly hours and declared closures), lineage for a derived stream, and a hot-cache size override. It is also how a tick record's stream hash is turned back into a stream.

File:

Part Layout
header (12) magic SMET (4), version 1 (uint32), entry count (uint32)
entries per stream, sorted by exchange, symbol, timeframe: key length (4), key, metadata length (4), metadata
footer (12) total file size (uint64), CRC-32C over everything before the CRC (uint32)

Key (the stream id): three uint32 lengths (exchange, symbol, timeframe), then the three strings in that order.

Metadata. A single byte 0x00 means "no metadata". Otherwise the record is a series of sections; the later ones are optional and their absence is meaningful:

Section Layout When present
gap thresholds low, high (int64 ns each) always
working hours flag (1); if 1: timezone length (4) + IANA name, day count (4), then per day: weekday (1), window count (4), per window open hour, open minute, close hour, close minute (1 byte each) flag always
custom fields count (4), then key length (4) + key + value length (4) + value always
closures count (4), then start (8), end (8), note length (4) + note written always; a record ending before it reads as "no closures"
lineage marker 1 (or 2 while a re-derivation is pending); source exchange, symbol, timeframe (each 4-byte length + bytes); source kind (1: 1 ticks, 2 candles); close grace, no-trade limit, since (int64 each) only for a derived stream
cache capacity marker 0x10, slots (uint32, never 0) only with an override

See Streams, symbols and timeframes and Derived streams and lineage for what the fields mean.

An update that would store the same bytes writes nothing, so reading a stream does not rewrite the file.[20]

On open the reader checks the magic, version 1, that the footer's file size matches, the CRC, and that the entry count is plausible for the file's length. Any failure stops the node from starting with open stream registry: ….

Custom fields are written in Go map order, which is not stable. A stream with two or more custom fields can therefore be encoded to different bytes on different writes. This does not affect correctness of what is read back; whether any server path sets more than one custom field is unverified.

wal/quarantine.floors

JSON, written only when a partition has been retired from this node (see Quarantine). It maps a partition id (decimal string) to how far each WAL log had reached when the partition was retired, and the names of its streams:

json
{
  "17": {
    "logs": { "wal": 48211, "shard_3": 902 },
    "streams": ["BTCUSDT:1m:binance"]
  }
}

Recovery skips that partition's records at or below each log's floor, so the abandoned history is never replayed into the node; a floor drops out once its log no longer reaches it. It lives inside wal/ deliberately: a WAL directory wiped and started again takes its floors with it. A file that does not parse stops the node from starting, because ignoring it would replay the history it exists to keep out.[21]

Quarantine

<data_dir>/quarantine/ holds whole partition directories the node has moved aside — chunks, indexes, ticks, replica logs, with any unflushed data drained into them first. Nothing in Mirexa deletes anything here; it is evidence, kept until an operator removes it. The move is one rename with both parent directories fsynced, and a target name that already exists is refused rather than merged.[22]

Directory Why it was moved
partition_<id>-epoch_<e>/ this node held a copy the cluster declared divergent after a failover
partition_<id>-epoch_<e>-released[-<n>]/ this node no longer holds any role in the partition (a migration's source, a moved or dropped copy)
partition_<id>-epoch_<e>-diverged[-<n>]/ as a copy, it was found holding a history different from its primary's
partition_<id>-epoch_<e>-corrupt[-<n>]/ at startup, one of its streams' stream.idx or gap.idx did not parse

<e> is the partition's epoch in the cluster directory; -2, -3… are added because a node can set a partition aside more than once at one epoch. In every case the node then records WAL floors for the partition and, in a cluster, gets a fresh copy from the partition's primary. See Reconciliation, scrubbing and repair.

A corrupt index at startup

A stream.idx or gap.idx that fails any check above is reported as storage.ErrCorruptIndex (an I/O error such as a permission failure is not, and stays fatal). What happens next depends on the node:[23]

Node Outcome
single node (no cluster) startup fails; the node holds the only copy
clustered, a copy of the partition the partition is moved to …-corrupt, the node starts without it and is re-seeded from the primary
clustered, primary, with another in-sync copy the node waits for the cluster to fail the partition over, then sets it aside; if that does not happen within the wait, startup fails
clustered, no other holder startup fails

A partition set aside this way is counted by mirexa_reconcile_startup_quarantines_total. A damaged index met after startup fails the request that touched it, not the node.

raft/ (cluster only)

Present only when cluster.enabled is on, and always under the data directory so the consensus log cannot outlive the data it describes.[24]

Path Owner Contents
raft/raft-log.bolt hashicorp/raft-boltdb the replicated control-plane log and the stable store (current term, vote)
raft/snapshots/<id>/meta.json hashicorp/raft snapshot metadata (term, index, membership)
raft/snapshots/<id>/state.bin Mirexa the encoded control-plane state

cluster.snapshot_retention snapshots are kept. A directory ending in .tmp is a snapshot being written.

state.bin holds the control-plane state — node registry, partition directory, in-flight migrations, revoked issuer keys and cluster settings — in Mirexa's own encoding. Only candle and tick data's placement is here; no market data ever enters the Raft log. In summary:[25]

Offset Size Field
0 4 magic MXCP
4 1 version 12
5 4 node count
9 4 partition count
13 4 migration count
17 4 revoked-key count
21 8 position: log index of the last command applied
29 … node records, partition records, migrations, revoked keys, then the settings trailer (settings version, partition count, liveness timeout, replication factor, codec name)

Records must be in ascending id order and every length is bounded by the remaining bytes. Any version other than 12 is refused (ErrBadVersion): an older snapshot would read missing fields as zero, which here means a cluster that has forgotten its settings, its migrations or its revocations. A cluster's raft/ directory therefore does not survive an upgrade that changes the snapshot version. See The control plane.

Atomic writes

Every index and catalog is replaced as a whole file, never edited in place:[26]

  1. write the full image to <name>.tmp;
  2. fsync it;
  3. rename it over <name>;
  4. fsync the parent directory, because a rename is a directory change and an fsync of the file does not make its new name durable.

streams.meta, tick_index.bin, tick chunks, seeded chunks and quarantine.floors go through one helper (storage.writeFileAtomic); stream.idx and gap.idx run the same four steps in their own writer, which adds a hook tests use to simulate a crash between steps. A crash therefore leaves either the old file or the new one, never a torn one, and possibly a stale .tmp that nothing reads and the next write overwrites. A build-time test fails if any rename in the storage package is not followed by a directory fsync, and another fails if a chunk is written with a plain os.WriteFile.

Backing up and inspecting

  • Stop the node for a consistent copy. The files are written at different moments (WAL, then chunks, then indexes) and nothing gives a point-in-time view across them while the node runs. A clean stop drains every stream's hot cache to chunks (TestShutdownDrain_PersistsEverythingToChunks, /tests/shutdown_drain_test.go). Copying a running node's directory is not tested; whether the copy recovers cleanly is unverified.
  • Keep the WAL with the chunks. Acknowledged writes not yet flushed exist only in wal/ (and, on a copy, replica.wal/). A backup without them loses those writes.
  • wal.lock and .pending/.tmp files are transient and need not be backed up.
  • Do not hand-edit an index. Every index is checksummed; an edited file is refused as corrupt, and in a cluster that sets the whole partition aside.
  • A file written by a newer build with a higher version is refused by an older one; no format here is forward-compatible.

References

Source

Tests

Further reading

External


  1. Layout.StreamPath, StreamID.PartitionKey, StreamDir, AssignPartition. ↩︎

  2. segmentMagic, segmentFormatVersion, writeSegmentHeader in /internal/wal/manager.go; TestManager_SegmentHasHeader. ↩︎

  3. /internal/wal/record.go, Record.MarshalBinary / UnmarshalBinary; FuzzRecordUnmarshalBinary. ↩︎

  4. TestRecovery_AShardedTickWALContinuesItsSequenceAcrossARestart. ↩︎

  5. applySegmentResult and classifyLastSegmentDamage in /internal/wal/recovery.go; TestRecover_TornTailLastSegmentTruncated, TestRecover_CorruptionFollowedByValidRecordsInTheLastSegmentIsRefused, TestRecover_MidLogCorruptionRefused, TestRecover_ForeignSegmentRefused. ↩︎

  6. replicaTicksDir, tickLogKey in /cmd/server/replica_ticks.go; TestReplicaLog_ATickRecordLandsInTheLogOfItsOriginAndLog. ↩︎

  7. StreamIndexEntry.ChunkFilename in /internal/storage/stream_index.go. ↩︎

  8. Unmarshal in /internal/compression/chunk.go; TestChunk_RejectsAnInChunkGapIndex. ↩︎

  9. TestUnmarshal_RefusesEverySingleBitFlip. ↩︎

  10. scaleFixedPoint, fixedPointToFloat in /internal/compression/fixed_point.go; types.FixedPointScale in /internal/types/value.go; TestTickChunkDecode_UsesExactFixedPointConversion. ↩︎

  11. MarshalEncodedTimestamps, packDoDs in /internal/compression/delta.go; TestCompressionRatio_Regression. ↩︎

  12. /internal/compression/block_index.go, DefaultBlockRows = 256; TestBlockIndex_CheckpointsAgreeWithADecoderWalk. ↩︎

  13. ChunkPersister.PersistPatch, CreatePatchChunk, ApplyPatch; TestCorrection_SecondCorrectionToOneChunkIsServed, TestCorrection_IndexReopensAfterPatch. ↩︎

  14. ChunkPersister.install in /internal/storage/chunk_persister.go; RunChunkGC, ReconcileChunks in /internal/storage/chunk_file.go; TestPersist_GCConcurrentWithInstallKeepsTheChunk, TestReconcileChunks_RemovesOrphanPending. ↩︎

  15. TestStreamIndex_ASeqNoIsNeverIssuedTwiceAcrossCompactionAndRestart. ↩︎

  16. entrySizeFor, validateStreamIndexData; TestStreamIndex_RefusesAnOlderFormat. ↩︎

  17. GapRange.Validate in /internal/types/gap.go, validateGapIndexData in /internal/storage/gap_index.go; TestGapRange_AcceptedIsOnlyAResolutionOfAnIncompleteMark, TestGapIndexCorruptionDetection. ↩︎

  18. tickIndex.derive, appendEntryCoverage, parseEntryCoverage in /internal/storage/tick_index.go; TestTickIndex_EachChunkKeepsItsOwnCoverage. ↩︎

  19. openTickIndex, buildTickIndexFromScan, keepLatestOfOverlapping; OpenTickStorage; TestTickIndexOpenCorrupt, TestTickStorage_AScanSkipsAChunkTheIndexHadReplaced. ↩︎

  20. encodeRegistry, readRegistry in /internal/storage/registry.go; StreamMetadata.MarshalBinary in /internal/types/metadata.go; TestStreamRegistry_NilMetadataRoundTrips, TestStreamRegistry_AnUnchangedUpdateWritesNothing, TestStreamMetadata_APendingRederiveRoundTrips. ↩︎

  21. loadQuarantineFloors in /internal/ingestion/quarantine.go; TestQuarantineFloors_ACorruptFileIsRefused. ↩︎

  22. Layout.QuarantinePartition; setAsidePartition in /cmd/server/replica.go; TestLayout_QuarantinePartitionMovesEverythingAndDeletesNothing, TestReleasePartition_ANameAlreadyTakenIsNeverReused. ↩︎

  23. ErrCorruptIndex in /internal/storage/stream_index.go; /internal/ingestion/startup_quarantine.go; /cmd/server/startup_quarantine.go; TestStartup_ACorruptIndexSetsItsPartitionAsideAndTheNodeStarts, TestStartupPolicy. ↩︎

  24. Config.RaftDir, LogStorePath in /internal/raft/config.go; TestRaftNode_LogStorageIsCreatedUnderTheDataDir. ↩︎

  25. snapshotMagic, snapshotVersion, State.MarshalBinary/UnmarshalBinary in /internal/cluster/codec.go; TestState_AVersionOneSnapshotIsRefused, FuzzParseControlPlaneSnapshot. ↩︎

  26. writeFileAtomic in /internal/storage/chunk_file.go; StreamIndex.saveEntriesHook, GapIndex.saveEntriesHook; TestDurability_EveryRenameIsFollowedByADirectorySync, TestDurability_ChunkWritesAreNotPlainWriteFile. ↩︎