Wiki Internals
Indexes and the on-disk layout
The data directory tree, how streams map to partition directories, the stream and gap indexes, how index files are written, count-based index compaction, and why a stream index has exactly one open handle.
Everything a node stores lives under one directory, storage.data_dir. Inside it, data is
grouped by partition and then by stream, and each stream keeps two small index files
beside its chunks: stream.idx, the catalog of its chunk files and the source of truth for
which chunks exist, and gap.idx, its classified record of where data is missing. This page
describes that tree and the rules that keep the indexes correct.
The data directory
<data_dir>/
├── streams.meta the node's stream registry (magic SMET): every stream it
│ knows, with its metadata — trading calendar, lineage,
│ cache-size override
├── wal/ the write-ahead log and tick WAL shards (see The write-ahead log)
├── raft/ consensus state, only when cluster.enabled
├── quarantine/ partition directories set aside, never deleted automatically
└── partition_<id>/
├── replica.wal/ (a cluster copy only) the primary's tail records, verbatim
├── replica.ticks/ (a cluster copy only) the primary's tick records
└── <exchange>@<symbol>_<timeframe>/ one directory per stream
├── stream.idx chunk catalog (magic SIDX, version 5)
├── gap.idx gap records (magic GIDX, version 1)
├── chunks/
│ ├── chk_001.bin
│ ├── chk_002_patch.bin a cumulative patch of an earlier chunk
│ └── chk_003.bin.pending transient: an install in progress
└── ticks/
├── tick_index.bin tick chunk catalog (magic TIDX, version 3)
└── tick_chunk_000001.bin
Partition. A stream's partition is FNV-64a(symbol, exchange) mod partition.count
(4,096 by default, a power of two). The timeframe is not part of the key, so every timeframe
of one instrument lives in one partition — which is what lets derived streams be computed
locally. In a cluster the partition is also the unit of placement and replication; the
partition count is fixed once a cluster agrees on it, because changing it would remap every
stream. See Partitions and routing.
Stream directory. <exchange>@<symbol>_<timeframe> (types.StreamID.StreamDir, inverted
by storage.ParseStreamDirName). It names all three parts of a stream's identity, so two
streams that differ only in exchange get two directories even in one partition. Until
2026-10-30 it was <symbol>_<timeframe>, and such streams shared one stream.idx, gap.idx
and chunks/ — after a restart one exchange read the other's bars. A node renames old-form
directories from the registry at startup, before anything opens a stream's files
(Layout.MigrateStreamDirs); one it cannot attribute to exactly one registered stream stops
the node with ErrStreamDirMigration, renaming nothing
(TestRestart_OneSymbolOnTwoExchangesKeepsTwoHistories,
TestRestart_AStreamInTheOldDirectoryLayoutIsReadAfterTheUpgrade,
TestMigrateStreamDirs_RefusesWhatItCannotRenameAndRenamesNothing).
The per-partition streams.meta path that Layout.StreamMetaPath names is not written or
read by the node; the node-level streams.meta at the root is the only registry.
stream.idx: the chunk catalog
stream.idx lists every chunk the stream holds. It is a small binary file:
| Part | Size | Content |
|---|---|---|
| Header | 12 bytes | magic SIDX, version 5, entry count (uint16), issued-through mark (uint32) |
| Entries | 38 bytes each | start timestamp, end timestamp, flags, SeqNo, BaseSeqNo, record count, byte size |
| Footer | 4 bytes | CRC-32C of header and entries |
Older versions are refused rather than upgraded. A file that does not parse — too short, a bad
magic, size or checksum — is ErrCorruptIndex, which startup handles specially (see
Crash recovery).[1]
Entry fields worth understanding:
SeqNois the entry's stable identity and names its file (chk_<SeqNo>.bin). Entries are ordered by time, not arrival, so a history back-fill inserted below existing chunks sits first while holding the newestSeqNo. Slice positions shift whenever an entry is inserted or compacted away; everything downstream — the query planner, patches, replication — addresses an entry bySeqNo, never by position.[2]BaseSeqNois set on a patch entry and names the base chunk it corrects. A patch repeats its base's time range and sits directly after it, which keeps the entries sorted by time so the binary searches stay correct. A patch of a patch is refused.[3]RecordCountandByteSizeare copied at install time so that per-stream statistics are a sum over the index instead of a read of every chunk file. A sum must skip patch entries, whose records restate their base's.- The issued-through mark in the header is the highest
SeqNothe stream has ever issued. Compaction can drop the entry holding the highestSeqNo; without the mark, a restart would rebuild the counter from what remains and issue thatSeqNoagain to a different chunk. Compaction never lowers it.[4]
Insert places a base entry at its chronological position and refuses an overlap with the
neighbour on either side. BaseCoverage reports which time ranges base chunks cover, and
is the one rule both crash recovery and replica promotion use to decide what is already
stored.[5]
The header's entry count is a uint16, so one stream.idx holds at most 65,535 entries.
That bound is why index compaction exists (below).
gap.idx: where data is missing
gap.idx is a sorted list of gap records:
| Part | Size | Content |
|---|---|---|
| Header | 8 bytes | magic GIDX, version 1, entry count (uint16) |
| Entries | 18 bytes each | start, end, status (1 byte), reason (1 byte) |
| Footer | 4 bytes | CRC-32C |
Statuses are OPEN, FILLING, CLOSED, PERMANENT and ACCEPTED; reasons include UNKNOWN, OFF_TIME (a market closure) and INCOMPLETE (a derived bar made from less than its window). Records are written when a chunk is installed — the flusher files the gaps it classified — and when a calendar change re-files them; a fill that covers a gap entirely marks it CLOSED rather than deleting it, so the record that a range was back-filled is kept. Only gaps over flushed ranges are here; a hole still in the hot cache is reported by the cache itself. The meaning of each status and reason is on Gaps and trading calendars.
How index files are written
Every index write is a full rewrite of the file, never an in-place edit:
- Write the new image to
<file>.tmp. - fsync the temporary file.
- Rename it over the old file.
- fsync the parent directory, so the rename itself survives a crash.
Step 4 is easy to forget — it looks unnecessary on ext4 with its default ordering and loses the file's name on XFS or btrfs — so a test parses the storage package's source and fails the build if any rename there is not followed by a directory sync.[6] A torn write leaves the old file intact.
In memory, a StreamIndex is copy-on-write: each write publishes a fresh entry slice and
never edits the published one. That makes Snapshot() free — it shares the slice — and a
snapshot refuses every write, so a query can hold a consistent view without being a second
writer.[7]
The one-handle rule
An index write rewrites the whole file from that instance's in-memory entries, and each
instance allocates SeqNos from its own counter. Two StreamIndex instances over one
stream.idx therefore silently erase each other's entries and can hand out the same SeqNo,
overwriting each other's chunk files. So, node-wide, each stream has exactly one open
stream.idx/gap.idx pair, owned by the dispatcher (getOrCreateStreamIndexes) and shared
by the live writer, the history back-fill path, the replication seed installer and the query
path. Anything else that needs to read an index takes a snapshot or opens the file read-only
and never writes through it.[8]
Two related rules:
- Indexes are opened, never created over existing files. Creating writes an empty index over whatever is at the path; doing that on a restart would erase the chunk catalog and every gap classification.[9]
- Opening a stream reconciles its chunks directory (
ReconcileChunks): a pending file whose final name the index names is rolled forward, and any other pending file is removed — its bars are still in the WAL.
Index compaction is count-based retention
Each live stream runs an IndexCompactionScheduler every storage.compaction_interval
(1 hour). When the index holds more than storage.compaction_entry_threshold entries (50,000
by default), it keeps the newest threshold / 2 entries — 25,000 — and drops the rest,
deleting their chunk files (StreamIndex.CompactByCount). A patch is dropped with its base
wherever it sits, so slightly fewer entries may remain. The issued-through SeqNo mark is
kept, so no dropped SeqNo is ever issued again. A threshold of 0 or less disables it; it is
on by default.[10]
This is the only retention mechanism on a primary, and it is by chunk count, not time. When it fires it permanently deletes the oldest data of that stream. There is no time-based retention setting.
gap.idxis not trimmed with it.
How much time 50,000 chunks covers depends on how often the stream's chunks are cut, which is
mostly the 15-minute checkpoint for a busy stream: roughly 520 days of continuously written
data at one chunk per 15 minutes (arithmetic, not measured). A replica in a cluster mirrors its
primary's retention by retiring the same entries (StreamIndex.Retire, which shares
compaction's drop path); a derived stream's history is capped at its source's.
References
Source
Layout,StreamID.PartitionKey,StreamDir,AssignPartitionStreamIndex,StreamIndexEntry,Insert,AppendPatch,BaseCoverage,Snapshot,Compact,CompactByCount,Retire,encodeStreamIndexGapIndex,GapStatus,GapReasonIndexCompactionSchedulerwriteFileAtomic,ReconcileChunksStreamRegistryDispatcher.getOrCreateStreamIndexes
Tests
TestStreamIndexAppendCrashIsRecoverable,FuzzReadStreamIndex,FuzzReadGapIndex.TestStreamIndex_EntryBySeqNoFindsAnOutOfOrderInsert,TestPlanner_Execute_CompactionBetweenPlanAndExecute.TestHistoryBackfill_LandsBelowAnAlreadyFlushedChunk,TestStreamIndex_InsertRefusesAnOverlapOnEitherSide.TestStreamIndex_SearchesSeeEveryBaseWhenPatchesExist,TestStreamIndex_AnIndexWithPatchesAtTheEndOpensInTimeOrder.TestStreamIndex_ASeqNoIsNeverIssuedTwiceAcrossCompactionAndRestart.TestStreamIndex_BaseCoverage.TestDurability_EveryRenameIsFollowedByADirectorySync.TestStreamIndexSnapshot_IsUnmovedByEveryWrite,TestStreamIndexSnapshot_RefusesEveryWrite.TestHistoryBackfill_BelowTheCacheAnchorSurvivesRestart— the one-handle rule.TestBuildLiveWriter_DoesNotTruncateExistingIndexes.TestStreamIndexCompactByCount_DropsEveryPatchOfABaseItDrops,TestIndexCompactionScheduler_ZeroThresholdDisablesCompaction,TestDispatcher_IndexCompactionKnobsReachTheLiveWriter.TestGapIndex_ReplaceRefusesAListItCouldNotReadBack,TestGapIndexStatistics_ClosingAGapDropsItsMissingTime.
Further reading
- Chunks and compression, The read path, Crash recovery
- On-disk formats — byte-level reference
- Streams, symbols and timeframes
External
- T. S. Pillai et al., "All File Systems Are Not Created Equal: On the Complexity of Crafting Crash-Consistent Applications", OSDI 2014: https://www.usenix.org/conference/osdi14/technical-sessions/presentation/pillai
- Linux
rename(2)andfsync(2)manual pages: https://man7.org/linux/man-pages/man2/rename.2.html
encodeStreamIndex,readStreamIndexin /internal/storage/stream_index.go;FuzzReadStreamIndex. ↩︎TestStreamIndex_EntryBySeqNoFindsAnOutOfOrderInsert,TestPlanner_Execute_CompactionBetweenPlanAndExecute. ↩︎TestStreamIndex_SearchesSeeEveryBaseWhenPatchesExist. ↩︎TestStreamIndex_ASeqNoIsNeverIssuedTwiceAcrossCompactionAndRestart. ↩︎TestStreamIndex_BaseCoverage,TestStreamIndex_InsertRefusesAnOverlapOnEitherSide. ↩︎TestDurability_EveryRenameIsFollowedByADirectorySync. ↩︎TestStreamIndexSnapshot_IsUnmovedByEveryWrite,TestStreamIndexSnapshot_RefusesEveryWrite. ↩︎TestHistoryBackfill_BelowTheCacheAnchorSurvivesRestart. ↩︎TestBuildLiveWriter_DoesNotTruncateExistingIndexes. ↩︎IndexCompactionScheduler.RunOnce;TestStreamIndexCompactByCount_DropsEveryPatchOfABaseItDrops,TestIndexCompactionScheduler_ZeroThresholdDisablesCompaction. ↩︎