Wiki Internals
The read path
How a candle query is planned and answered — the hot cache read before the index, in-flight batches and pending gaps, chunk reads, the decoded-chunk and query caches, patches, the gap overlay, limits, QUERY_MULTI and rollups.
A candle for a given timestamp can be in one of four places at the moment a query runs: the
hot cache, a batch the cache has just evicted but not yet installed (the in-flight batch),
a chunk, or a chunk plus its patch. The read path's job is to read each source exactly once,
in time order, with no bar duplicated or missing, while flushes, compactions and corrections
run concurrently — and to report where data is missing, not just where it is. This page
follows a QUERY_STREAM for candles; ticks, QUERY_MULTI and rollups are covered at the end.
1. The request
Server.handleQuery parses the request and refuses an invalid range in the shape the client
asked for (end ≤ start, or a negative start for a candle query). It then routes: a rollup
to the rollup path, a tick query to the tick path. For candles it checks READ_CANDLES,
lets an in-sync replica answer a read that allows a stale answer, and otherwise redirects a
request for a partition this node does not serve.
The result has to fit one response frame, so the server computes a limit: the smaller of
what network.max_frame_payload_bytes (16 MiB) can carry and the client's MaxResults. An
ascending read without gap markers is answered straight from column runs (below); everything
else goes through Dispatcher.QueryCandlesLimited.
2. Reading only the end of the range that answers
A "latest 100" query over a long range should not decode the whole range. queryLimited
first asks for a window of limit + 1 intervals at the end the result comes from — the
end of the range for a descending read, the start for an ascending one — and doubles the
window until it holds more than limit records or covers the range. Only the last window's
answer is returned, so the result is one consistent query's, not a splice of several.
Descending reads keep the tail of the range before reversing, so "the 3 most recent"
returns the newest three, not the oldest three reversed.[1]
3. Planning
Dispatcher.planCandles builds the plan in a deliberate order:
- Read the query-cache generation first, before anything the answer is built from (see the query cache).
- Find the stream's live writer, if any. With no writer, an explicit
statofstream.idxdistinguishes a cold stream on disk from one that does not exist (opening a missing index yields an empty one). - Build a planner over the dispatcher's shared index pair when it is open, or open
gap.idxfrom disk for a cold stream.
Planner.Plan then:
- Reads the hot cache first.
StreamCache.ScanWithSpanbuffers the cache's points for the range and resolves the span of data it holds, in one consistent view that includes any in-flight batches. - Then reads the index: a
StreamIndex.Snapshot()of the live pair (an O(1) copy-on-write view), or the file itself for a cold stream. - Finds the base chunks overlapping the range and clips each chunk segment against the cache's data span. The cache is authoritative for its own span, because in-place corrections live in its version chain while a chunk covering the same range holds the values as of its flush.
- Attaches the overlapping gap records, plus any pending gaps the cache has published
(holes not yet filed in
gap.idx), less whatgap.idxalready covers.
Why the cache is read before the index. A flush hands a batch over in a fixed order: install the chunk and its index entry, then release the in-flight batch from the cache. Reading the cache first means that any release the cache read already observed was preceded by an index write the later index read will see; and where the cache still held the batch, clipping drops the overlapping chunk. Reading them the other way round lets a flush completing between the two reads hide its whole batch from the query, with no error.[2]
The plan keeps its own buffer of the cache's points and its own index snapshot, and
Execute resolves chunk segments by SeqNo against that snapshot. Nothing the live
cache or the index does after Plan returns can change the answer: not a release, not a
compaction shifting entry positions.[3]
4. Executing: sources read in sequence
The segments are chronological and disjoint by construction, so there is nothing to merge:
concatIterator reads each source to its end in order, feeding the cache's points in as runs
between chunk segments. A source is not opened until it is reached, so a query that stops
early never decodes the chunks after it. The disjointness is checked, not assumed: a
point not strictly after the previous one ends the read with an error.[4]
Results are CandlePoints, ascending, with gap markers inline.
The gap overlay
Chunks know nothing of gaps, so gapOverlayIterator wraps the sequence and joins it with
gap.idx: it stamps the stored classification (status and reason) onto gap markers the cache
emitted, and synthesizes markers for flushed ranges that no source can produce. Real data
wins a tie. An INCOMPLETE record (a derived bar made from less than its window) is the
exception: it synthesizes nothing and stamps its mark on the bars it covers.[5]
Gap markers are dropped unless the request asked for them.
Reading a chunk
Read, not mapped. A chunk is read into memory the reader owns with os.ReadFile, so a
file deleted or replaced mid-query does not affect it. Chunks used to be mmaped; mmap and
munmap both take the process's address-space lock for writing, so concurrent queries
serialized on it. Measured on 2026-10-16 (BenchmarkQueryCandles_FlushedChunks, 60 candles
across three flushed chunks, no query cache, 12 cores at load average ~5, minimum of 10 runs):
[6]
| Read path | Parallel ns/op | ≈ queries/s |
|---|---|---|
index reopened per query + mmap per chunk |
55,797 | 17,900 |
| shared index pair only | 66,227 | 15,100 |
ReadFile only |
15,258 | 65,500 |
shared index + ReadFile + lazily sized cache buffer (current) |
11,345 | 88,100 |
Partial reads. A chunk with a block index need not be read whole. On a cache miss for a small range, the reader fetches the file's prefix (header, pointers, index — 40 KB, enough for the largest index in one read), then only the column bytes of the 256-row blocks the range needs, announcing them all to the kernel before reading the first so the disk reads overlap. A point read of one bar in a 50,000-row chunk measured 1,199 → 95 µs with no cache on 2026-10-26.[7] When the plan already knows a chunk is needed whole, the file is opened and read once.
Read-ahead. A scan or a long read announces the next two chunk files to the kernel
(POSIX_FADV_WILLNEED, in 128 KiB steps, a no-op off Linux) while the current one decodes, so
decoding and disk I/O overlap. A read stopped after its first point announces nothing.
Patches. A base chunk with a patch is read through its newest patch: the patch's bars replace the base's at the same timestamps.
The decoded-chunk cache
Decoding is most of a query's CPU, and a chunk never changes once installed, so the node
keeps decoded chunks in an LRU bounded by storage.decoded_chunk_cache_bytes (256 MiB by
default; 0 disables it).[8]
- Keyed by the file's identity — path, device, inode, size, modification time. Every path that replaces a chunk's bytes does so by atomic rename, which changes the inode, so a stale entry is never served and nothing has to remember to invalidate. A patched chunk is cached as its merged rows under the base's and the patch's identities, so a newer patch is a new key.
- Held packed. A candle chunk is kept as a
PackedChunk: each column bit-packed against a line per 128 rows, so any row can be decoded on its own. About 12 bytes a realistic candle, against roughly 13.6 for its chunk file and 56 decoded — the default holds on the order of 20 million candles. - Admission. A chunk is packed whole only when a read needs half of its blocks or more. A smaller read caches nothing on its first miss; on a second miss of the same block it caches just that block. A read whose chunks would take more than half the cache caches nothing at all, so one large scan does not evict everyone else's warm data.
- Tick chunks share the cache as decoded ticks. Hits, misses and bytes held are exported as
mirexa_decoded_chunk_cache_*.
Column runs
A plain ascending read without gap markers, and any column query, is answered from column
runs (Planner.ScanColumns): the stamps and only the requested value columns, decoded
straight into slices without building a point per row, and written into the response. It
yields exactly what Execute would, minus gap markers; a plan touching an open INCOMPLETE
record falls back to points, because the mark rides on points.[9]
The query cache
An optional cache of whole answers, keyed by stream and range, is off by default
(query_cache.enabled: false; TTL 30 s, 1,000 entries when on). Its correctness rests on
invalidation, not the TTL:
- Every write that changes what a range answers — a live write, a chunk install, a
restatement, and, on a replica, what the seed installs — calls
InvalidateStream, which drops the stream's entries and bumps a per-stream generation. - A query reads the generation before it reads anything, and
Putrefuses to store an answer if the generation moved meanwhile. Without the generation, a write landing while a query was computing would have nothing cached to drop, and the stale answer would be stored after it.[10]
Backpressure on responses
A response is written with one Connection.Write on the connection's serving goroutine, under
a write deadline (network.write_timeout). A client that stops reading closes its TCP window,
the write blocks, and because the connection serves requests strictly one after another the
client cannot issue another query; when the deadline passes, the connection is closed. There
is no queue and nothing to shed: block, then reap.[11]
There is no node-wide memory budget for responses.
MaxResultsand the frame size bound what is sent, not what is built, and a response is held until its write finishes or times out. Many concurrent maximal reads against slow clients can use a lot of memory.
QUERY_MULTI
A QUERY_MULTI frame carries up to network.max_subqueries_per_request (128) independent
sub-queries. Nothing is merged: each sub-query runs through the same dispatcher calls as a
single query, and the batch changes only how one response frame's budget is spent. Every
sub-query gets an answer slot, reserved before any records are filled, so a batch too big for
one frame comes back with every position present — the served ones with records, the rest
with a resume point. The frame is filled in two passes, an equal share to every sub-query and
then the remainder in request order, so the first unfinished sub-query always makes progress
and a client paging the batch always terminates. Sub-query reads run concurrently on a
node-wide pool sized to three-quarters of the cores, leaving the rest for ingest.[12]
In a cluster, a sub-query for a stream this node does not serve is answered in place with a redirect, and the routing client re-asks the right node. See Partitions and routing.
Rollups
A query with the rollup flag and a bar length asks for bars made at query time from a stream's candles or trades, stored nowhere. It runs the same derivation rules a stored derived stream uses, so it answers what a stored derivation would; see Materialization.
Ticks
Tick queries read the stream's tick storage: its in-memory buffers and its tick chunks, found
by binary search over tick_index.bin. A limited read walks chunks from the end the result
comes from and stops at limit + 1, so "the latest 1,000 trades" opens only the newest
chunks. See Ticks.
References
Source
Server.handleQuery,queryLimit,answerFromColumns, QUERY_MULTIDispatcher.QueryCandles,planCandles,queryLimited,invalidateStreamPlanner,NewLivePlanner,Plan,Execute,withPendingGaps,admitsconcatIterator,gapOverlayIteratorDecodedChunkCache,readRangeOrWhole,ReadChunkFilePlanner.ScanColumns, read-aheadQueryCache,StreamCache.ScanWithSpan,PendingGaps
Tests
TestQueryCandlesLimited_AgreesWithTheFullQuery,TestServer_LatestNStopsAtTheNewestData,TestServer_DescendingWithMaxResultsReturnsTheNewest.TestQueryCandles_AFlushDuringPlanningCannotHideItsBatch,TestPlanner_Execute_ReleaseBetweenPlanAndExecute,TestPlanner_Execute_CompactionBetweenPlanAndExecute.TestDecomposeRange_ChunkAndCacheDoNotOverlap,TestConcatIterator_DoesNotLoadASourceBeforeItIsReached.TestExecute_FlushedGapCarriesItsClassification,TestQueryCandles_GapClassificationSurvivesToTheResult,TestGapOverlay_AnIncompleteBarCarriesItsMarkWithItsData,TestWithPendingGaps_AddsOnlyWhatNoGapRecordCovers,TestQuery_APauseStillGoingOnIsReportedWhole.TestReadChunkFile_SurvivesTheFileBeingDeleted,BenchmarkQueryCandles_FlushedChunks.TestChunkRange_APointReadOfAnIndexedChunkReadsOnlyItsBlock,TestChunkRange_AColdPartialReadIsTwoRoundTrips,TestPlanner_AReadOfAWholeChunkOpensItOnce,TestExecute_ReadsTheNextChunksAheadOfDecodingThisOne.TestDecodedChunkCache_AReplacedChunkIsNeverServedStale,TestQueryCandles_ReadsAPatchedChunkThroughTheDecodedChunkCache,TestDecodedChunkCache_HoldsAChunkInLittleMoreThanItsCompressedSize,TestPlanner_AReadLargerThanTheCacheShareLeavesTheCacheAlone,TestQueryCandles_TheChunkCacheChangesNoAnswer.TestScanColumns_YieldsExactlyWhatExecuteDoes,TestCanScanColumns_RefusesOnlyAPlanWithAnOpenIncompleteRecord,TestPackedChunk_ColumnsAgreeWithRows.TestQueryCache_InvalidationBetweenMissAndPutIsNotLost,TestQueryCache_WriteLandingMidQueryIsNotServedStale.TestServer_SlowQueryClientBlocksThenIsReaped,TestServer_SlowQueryClientCannotIssueAnotherQuery.TestServer_QueryMultiHeadAlwaysProgresses.
Further reading
- Reading data, Wire protocol
- The hot cache, Chunks and compression, Indexes and the on-disk layout
- Reads from copies
External
- Linux
posix_fadvise(2): https://man7.org/linux/man-pages/man2/posix_fadvise.2.html - Linux
mmap(2)(mapping and unmapping take the process's memory-map lock): https://man7.org/linux/man-pages/man2/mmap.2.html
Dispatcher.queryLimited;TestQueryCandlesLimited_AgreesWithTheFullQuery,TestServer_DescendingWithMaxResultsReturnsTheNewest. ↩︎TestQueryCandles_AFlushDuringPlanningCannotHideItsBatch. ↩︎TestPlanner_Execute_ReleaseBetweenPlanAndExecute,TestPlanner_Execute_CompactionBetweenPlanAndExecute. ↩︎TestDecomposeRange_ChunkAndCacheDoNotOverlap,TestConcatIterator_DoesNotLoadASourceBeforeItIsReached. ↩︎TestExecute_FlushedGapCarriesItsClassification,TestGapOverlay_AnIncompleteBarCarriesItsMarkWithItsData. ↩︎ReadChunkFilein /internal/storage/chunk_file.go;BenchmarkQueryCandles_FlushedChunks; figures from the repository'sdocs/dev-overview.md, not re-run for this page. ↩︎TestChunkRange_APointReadOfAnIndexedChunkReadsOnlyItsBlock; figure fromdocs/dev-overview.md, not re-run. ↩︎TestDecodedChunkCache_AReplacedChunkIsNeverServedStale,TestDecodedChunkCache_HoldsAChunkInLittleMoreThanItsCompressedSize. ↩︎TestScanColumns_YieldsExactlyWhatExecuteDoes. ↩︎TestQueryCache_WriteLandingMidQueryIsNotServedStale. ↩︎TestServer_SlowQueryClientBlocksThenIsReaped,TestServer_SlowQueryClientCannotIssueAnotherQuery. ↩︎header comment of /internal/network/multiquery.go;
TestServer_QueryMultiHeadAlwaysProgresses. ↩︎