Mirexa

Wiki Internals

Chunks and compression

The chunk file format, the per-column codecs and their measured ratios, checksums and verification, the block index, patch chunks, and how a chunk is installed and garbage-collected.

A chunk is an immutable, compressed, columnar file holding a contiguous run of one stream's candles. Bars leave the hot cache as chunks, history back-fills arrive as chunks, and every flushed read comes from them. A chunk is never edited: a restatement of its bars is written as a separate patch chunk, and a chunk is removed only when the stream index stops naming it.

File structure

A candle chunk file (chunks/chk_NNN.bin) has four sections, all little-endian:

text
┌──────────────────────────────┐
│ header             80 bytes  │ magic "MIRX", version 1, flags, row count, column count,
│                              │ first and last timestamp, interval, first value of each
│                              │ OHLCV column
├──────────────────────────────┤
│ column pointers  6 × 16 bytes│ per column: offset, size, codec
├──────────────────────────────┤
│ data                         │ [block index, if flagged] then the six columns
│                              │ back to back: timestamp, open, high, low, close, volume
├──────────────────────────────┤
│ footer             32 bytes  │ data end offset, 0, reserved,
│                              │ data checksum, footer checksum
└──────────────────────────────┘

Both checksums are CRC-32C (stored in 64-bit fields for format stability). The data checksum covers everything from byte 0 to the end of the data section — header, column pointers and columns. The footer checksum covers the footer's own fields. On read the footer checksum is verified first and the data checksum second, before any column is decoded.[1]

Two further rules are enforced on every read:

  • Every coded column must declare exactly the chunk's row count. The checksums cannot catch a writer bug or a crafted file that carries valid ones, so Chunk.Validate compares each column's own count with the header.[2]
  • Chunks carry no gap index. The footer field for one is kept so older files parse, but a chunk that claims a gap index is refused. Gaps live only in the stream's gap.idx, which can hold their classification and describe a gap spanning two chunks.[3]

Codecs

Each column records the codec it was written with, so a stream may hold chunks written with different codecs and every chunk is read as written. The codec for new chunks is the compression.algorithm setting, read when the node starts (in a cluster, the cluster's agreed value). Changing it never rewrites existing chunks.[4]

Setting Timestamp column Value columns Lossless?
fixed_point_dod (default) delta-of-delta value × 10⁴ rounded to int64, then delta-of-delta No — values are kept to 4 decimal places
gorilla delta-of-delta Gorilla XOR float compression Yes
none raw 8-byte raw 8-byte float64 (48 bytes a candle) Yes

Delta-of-delta, raw or bit-packed

A regular timestamp series has a constant step, so the difference between consecutive differences is almost always zero. The encoder stores the first value and first delta, then one delta-of-delta per row, choosing the smaller of two bodies:[5]

  • Raw: one little-endian int64 per delta-of-delta.
  • Packed: each delta-of-delta zig-zag encoded and written with a unary bucket prefix: 0 for zero (one bit, no payload), 10 + 8 bits, 110 + 16 bits, 1110 + 32 bits, 1111 + 64 bits.

Because the smaller body wins, the worst case is the raw size plus a one-byte tag: the codec never expands a column meaningfully. The decoder reads 64 bits at a time, taking a run of zero buckets in one step; it is checked against a bit-at-a-time reference decoder on every input, errors included.[6]

Fixed point

fixed_point_dod scales prices and volumes by 10,000 into integers so they compress like timestamps. Two consequences matter:

  • Precision. A value is rounded to the nearest 0.0001 on write. Data needing more decimal places (some crypto prices and sizes) loses digits under the default codec. The setting is node-wide (cluster-wide in a cluster), so choose gorilla or none for a deployment that holds such data.
  • Range. A value must be finite and its magnitude below about 9.22 × 10¹⁴ (types.MaxStorableMagnitude, MaxInt64 / 10⁴). NaN, ±Inf and larger values are refused at ingest, under every codec, because converting them is implementation-defined in Go and would store a different wrong number on each CPU architecture.[7]

On read the integer is converted back by dividing by 10,000 rather than multiplying by 0.0001: 0.0001 has no exact binary form, and the reciprocal product disagrees with the correctly rounded quotient for roughly 30% of inputs.[8] Volume is scaled like price, though it seldom needs decimals, which is part of why realistic data compresses only about 3×.

Measured ratios

From TestCompressionRatio_Regression, run on 2026-10-30 at af3a8ef: four synthetic corpora of 1,440 one-minute candles each, default codec, ratio of 48 raw bytes per candle to the encoded chunk (block index excluded).

Corpus Raw bytes Encoded bytes Ratio Test floor
flat 69,120 1,414 48.9× 8×
trending 69,120 2,665 25.9× 3×
realistic OHLCV 69,120 22,872 3.0× 3×
volatile 69,120 37,902 1.8× 1×

These are synthetic series; your ratio depends on your data's price grid and volatility.

The block index

A chunk of more than 256 rows (and not Gorilla-encoded) begins its data section with a block index, flagged in the header, so a read can decode the rows near a timestamp without decoding from row 0 or reading the rest of the file. Per block of 256 rows it records the first timestamp, and per column a checkpoint — the bit offset of the block's first value and the decoder state before it — plus a CRC-32C of the block's bytes; a CRC of the header, pointers and index closes it. The column bytes are unchanged, so a reader that ignores the flag reads the chunk correctly. It costs under 0.7 bytes a candle. A partial read checks every byte it decodes; rot in a block a read does not fetch is caught by the read that fetches it, and the whole-file checksums still guard every whole read, the replication seed and the scrub.[9] How reads use it is on The read path.

Tick chunks

Tick chunks (ticks/tick_chunk_NNNNNN.bin, magic MIRT) have the same shape with three columns — timestamp, price, volume — a 48-byte header and a 16-byte footer of two CRC-32C checksums. Price and volume take the same three codecs as candle values, so gorilla and none store ticks losslessly. A tick chunk with gorilla columns is format version 2; every other tick chunk is version 1. A build that predates gorilla tick columns refuses a version-2 chunk rather than misreading it.[10] See Ticks.

Patch chunks

A chunk is immutable, so a restated bar in a flushed chunk is written as a patch: a second chunk (chk_NNN_patch.bin) holding replacement bars for the base chunk's time range. Its stream.idx entry is flagged as a patch, names its base by the base's stable sequence number (BaseSeqNo), repeats the base's time range, and is placed directly after the base so the index stays in time order.[11]

A read applies exactly one patch — the newest — so every patch is cumulative. ChunkPersister.PersistCorrection reads the base's current patch, lays the new bars over it (the new value wins a timestamp both hold), and installs the result as the next patch. Older patches stay on disk, superseded and unread, and go with their base when it is dropped. Folding on write rather than overlaying every patch on read keeps a read at one base plus one patch however often a chunk is restated, and lets a replica serve exactly what its primary serves without knowing anything about folding. The cost is a read-modify-write per correction, serialized per stream.[12]

A patch is written with the node's current compression.algorithm, like any new chunk, so a restated bar keeps every digit on a gorilla or none node.[13] A patch records its own codec and need not share its base's. Being a new chunk, it also takes a codec switched to since its base was written: after a change to fixed_point_dod, the bars a patch carries forward are rounded to 4 decimal places.

Installing a chunk

Every chunk a node writes — live flush, history back-fill, or patch — goes through one implementation, ChunkPersister.install, which is safe against a concurrent garbage collector, a concurrent reader, and a crash at any point:[14]

  1. Take the next sequence number from the stream index and write the chunk durably under chk_NNN.bin.pending, then record the file's size for the index entry. GC ignores pending files.
  2. Under the index's install guard (StreamIndex.LockInstall): rename the pending file to its final name and fsync the directory, then insert the entry into stream.idx. If another install published a higher sequence number meanwhile, this one takes the next number and the final name changes accordingly.

The order inside step 2 protects readers: an index entry never names a file that does not exist yet. Renaming first means a final-named file briefly has no entry — exactly what GC deletes — so GC takes the same guard for its whole pass. A crash between the steps leaves a pending file that ReconcileChunks removes when the stream is next opened (its bars are still in the WAL); a crash inside step 2 leaves an unreferenced final file the next GC removes.

After the install the flusher records the chunk's classified gaps in gap.idx. A gap record that fails to insert is logged as a warning and not retried.

Verifying a chunk against its entry

storage.VerifyChunk checks that a byte slice is the chunk its index entry names: the size the entry recorded, the chunk's own checksums and header, the record count, and the time range (exactly for a base, within the base's range for a patch). A sound chunk that is not the one the entry describes is invisible to the chunk's own checksums, which is why replication runs this check on both ends of a transfer and the scrubber runs it on chunks at rest. See Reconciliation, scrubbing and repair.[15]

Garbage collection

ChunkGCScheduler runs RunChunkGC hourly per stream: under the install guard, it deletes every chk_*.bin in the stream's chunks/ directory that no stream.idx entry names. Unreferenced files appear when an index entry is dropped by compaction, retention mirroring or a failed publish. GC never touches .pending files.

References

Source

Tests

  • TestCompressionRatio_Regression (internal/compression/ratio_regression_test.go).
  • TestUnmarshal_RefusesEverySingleBitFlip — every single-bit flip in a chunk is caught.
  • TestChunk_AColumnDeclaringAnotherRowCountIsRefusedByEveryRead, TestChunk_RejectsAnInChunkGapIndex.
  • TestDoDReader_AgreesWithTheBitReader, FuzzDoDReader.
  • TestFixedPointRoundTripLargeValues, TestFixedPointDecodeIsCorrectlyRounded, TestDecodersAgree, TestTickChunkDecode_UsesExactFixedPointConversion, TestServer_IngestRejectsNonFiniteCandle.
  • TestIngest_ChangingTheCompressionSettingAffectsOnlyNewChunks, TestCompressionNone_PacksAsSmallAsTheDefaultOnGridPrices, TestTickChunk_NoneStoresRawAndReadsBack.
  • TestBlockIndex_IsInvisibleToAWholeRead, TestBlockIndex_CostsUnderSevenTenthsOfAByteACandle, TestBlockIndex_CheckpointsAgreeWithADecoderWalk, TestBlockIndex_DecodeRangeAgreesWithDecompress, TestBlockIndex_ARottenByteIsRefusedOnAPartialRead, FuzzParseChunkLayout, FuzzDecodeRange, FuzzChunkColumnCounts.
  • TestCorrection_SecondCorrectionToOneChunkIsServed, TestCorrection_ConcurrentCorrectionsToOneChunkAreAllServed, TestCorrection_APatchEntryRecordsItsSizeAndRecordCount, TestStreamIndex_SearchesSeeEveryBaseWhenPatchesExist.
  • TestPersist_IndexEntryNeverNamesAMissingChunk, TestPersist_GCConcurrentWithInstallKeepsTheChunk, TestPersist_AnInstallOvertakenByAnotherStillLands, TestPersistPatch_GCDuringInstallKeepsThePatch.
  • TestVerifyChunk_RefusesBytesThatAreNotTheChunkTheirEntryNames.
  • TestDurability_ChunkWritesAreNotPlainWriteFile.

Further reading

External

  • T. Pelkonen et al., "Gorilla: A Fast, Scalable, In-Memory Time Series Database", VLDB 2015: https://www.vldb.org/pvldb/vol8/p1816-teller.pdf
  • D. Lemire, L. Boytsov, "Decoding billions of integers per second through vectorization" (zig-zag and bit-packing background), 2012: https://arxiv.org/abs/1209.2137
  • IEEE 754-2019, Standard for Floating-Point Arithmetic (correctly rounded division): https://doi.org/10.1109/IEEESTD.2019.8766229

  1. Chunk.Marshal and Unmarshal in /internal/compression/chunk.go; TestUnmarshal_RefusesEverySingleBitFlip. ↩︎

  2. TestChunk_AColumnDeclaringAnotherRowCountIsRefusedByEveryRead. ↩︎

  3. TestChunk_RejectsAnInChunkGapIndex. ↩︎

  4. TestIngest_ChangingTheCompressionSettingAffectsOnlyNewChunks. ↩︎

  5. Marshal format comment in /internal/compression/delta.go. ↩︎

  6. TestDoDReader_AgreesWithTheBitReader. ↩︎

  7. validateFixedPointValue; TestServer_IngestRejectsNonFiniteCandle. ↩︎

  8. fixedPointToFloat; TestFixedPointDecodeIsCorrectlyRounded. ↩︎

  9. TestBlockIndex_IsInvisibleToAWholeRead, TestBlockIndex_ARottenByteIsRefusedOnAPartialRead. ↩︎

  10. TestTickChunk_GorillaKeepsEveryDigitAndIsVersionTwo, TestIngest_TicksAtGorillaKeepEveryDigit. ↩︎

  11. TestStreamIndex_SearchesSeeEveryBaseWhenPatchesExist. ↩︎

  12. TestCorrection_SecondCorrectionToOneChunkIsServed, TestCorrection_ConcurrentCorrectionsToOneChunkAreAllServed. ↩︎

  13. TestIngest_ARestatementKeepsTheDigitsItsCodecKeeps, TestIngest_ARestatementBelowFixedPointIsAChangeOnALosslessNode. ↩︎

  14. TestPersist_IndexEntryNeverNamesAMissingChunk, TestPersist_GCConcurrentWithInstallKeepsTheChunk. ↩︎

  15. TestVerifyChunk_RefusesBytesThatAreNotTheChunkTheirEntryNames. ↩︎