Mirexa

Wiki Internals

Materialization

How derived streams are computed — the pure derivation rules for ticks to candles and candles to longer candles, bucketing, the live deriver and its cursor, INCOMPLETE marks, re-derivation after source changes, serving-node-only derivation, and query-time rollups.

A derived stream is a candle stream Mirexa computes and stores itself: one-minute bars made from a symbol's trades, five-minute bars from its one-minute bars, daily bars from either. Derived bars are ordinary stored candles — served, replicated and subscribed to like any other — but the node writes them, keeps them in step with their source, and marks a bar made from less than its full window. This page is how that works inside. The user-facing view is Derived streams and lineage and Deriving bars from ticks and candles.

The design splits in two: what a bar is, decided by pure functions in internal/materialize with no I/O, and when and where it is written, decided by the deriver in internal/ingestion.

The lineage

A stream becomes derived when its lineage is declared (types.Lineage, part of the stream's metadata in streams.meta):[1]

Field Meaning Default
Source the stream it is derived from —
Kind the source's ticks, or its candles —
CloseGrace how long past a bar's close late source data is waited for 1 s
NoTradeLimit (tick source only) the longest silence between trades that is not missing data 10 s
Since when derivation begins; set at declaration now
Rederive the source's history from Since is still being derived false

Lineage.Validate is the one set of rules: the source must be the same instrument (exchange and symbol), so it lives in the same partition and derivation never crosses the network; a candle source's timeframe must divide the target's and be at most half of it. That last rule makes a cycle unrepresentable — every candle link at least doubles the interval and a tick source is a leaf — so there is no cycle check. Only SetStreamLineage writes a lineage; a metadata update or re-registration keeps the existing one. Clearing a lineage stops derivation and deletes nothing.

Buckets

materialize.Buckets decides which bar a moment belongs to:[2]

  • Below a day, bars are aligned to the Unix epoch.
  • Daily bars hold one trading date in the stream calendar's timezone (UTC without one), stamped 00:00 UTC of that date. The stamp keeps a constant stride — the hot cache stores fixed-width slots — while the window follows the local calendar, so a daylight-saving day's window is 23 or 25 hours.
  • Weekly bars hold a Monday-start week, stamped Monday 00:00 UTC. A weekly stream's slot grid counts from Monday 1970-01-05, not the epoch's Thursday, so a client-written weekly bar stamped on another day is refused as unaligned.
  • Above a day only 1d and 1w exist. A source bar of a day or longer is bucketed by its date label, not its stamp read as an instant.

Ticks to candles

materialize.DeriveTicks is a pure function of the trades in a range, the trade before it, the clock, and the derived stream's calendar. Its key notion is a silence: trading time with no trade, cut by trades and by closures (it restarts at a session open). A silence is long when it lasts more than the no-trade limit, and a long silence is a gap over its whole span.[3] Every slot is one of:

Kind When Written as
bar the slot has trades their OHLCV, by timestamp, ties by arrival
flat no trade, inside a short silence open = high = low = close = previous close, volume 0
flat + INCOMPLETE no trade, partly inside a long silence a flat bar carrying an INCOMPLETE mark
gap no trade, wholly inside long silence nothing; filed as missing data by the calendar
closed no trading time nothing; filed OFF_TIME
pending no trade, inside a silence that could still go either way nothing yet; decided later
none before the source's first trade ever nothing

Any written slot that overlaps a long silence is INCOMPLETE, and that mark can arrive after the bar was written. A slot is pending rather than flat because a flat bar written early could never become the gap that a silence turning long makes it.

Candles to longer candles

materialize.DeriveCandles decides a bucket from the source slots it expects — those the calendar gives trading time, not before Since. A bucket is final once every expected slot is present, once a source bar of a later bucket exists, or once the clock passes its end plus the grace plus one source interval; until then it, and every bucket after it, is pending. A final bucket is the OHLCV of what it holds, INCOMPLETE when an expected slot is missing or a source bar is itself incomplete, a gap when it holds nothing it expected, and closed when it expected nothing.[4]

The live deriver

tickDeriver (despite the name it handles both source kinds) runs those rules for every derived stream the node serves.[5]

Activation. A derived stream is activated only by a live write of its source: every live tick batch, live candle batch and correction reaches the deriver after it is logged. A node taking no live writes of the source — a replica holding the lineage and the source's data, or a node just restarted — derives nothing until one arrives. (A stream with a pending Rederive is the exception: it is activated at once.)

Passes. A loop runs every 100 ms. For each active stream it reads the source back from the stream's cursor, asks the rules about every slot whose grace has passed, and reconciles with what the derived stream holds: a missing bar is written, a different bar is corrected, and a mark is set or cleared through GapIndex.SetIncomplete.

No stored cursor. The cursor is the first pending slot. After a restart it is recovered from the derived stream's newest bar (or, with none, the bar of the source's first trade since Since). Every read is clamped at Since, so data before the declaration is neither a bar nor a previous close.

Late source data. A trade for a slot the cursor has passed marks that slot dirty; the next pass re-derives from the bar of the trade before it, since a late trade reshapes the silence on both sides — its bar is corrected, gaps it fills become bars, marks it makes stale are cleared. Each bar corrected below the cursor is counted in mirexa_materialize_late_corrections_total{stream_id}; a steady rate means the grace is too short. A trade inside its bar's grace simply joins it.[6]

Write routes. Derived bars go through the dispatcher, never the network handler, each by the route that reaches it (writeDerivedBars): live when the hot cache admits it; a correction (a patch) when a stored chunk's range holds its slot; a history install, in runs of adjacent slots, otherwise. Derived candles are ordinary writes, so they reach subscribers, replicas and further derived streams.[7]

Client overwrites. A client may write a derived stream only with the overwrite flag. The last write wins: a pass rewrites a stored bar that differs only where the source may have changed under it — from the cursor on, and over a late tick's reach — so an overwrite stands, data and mark, until the source changes beneath it.[8]

Chains and cascades

The deriver indexes derived streams by source and kind. Its own writes reach it like any other write, which is what carries a chain (ticks → 1m → 5m → 1h → 1d), and a mark it changes on one link is handed on, so INCOMPLETE propagates down a chain after the fact. A correction or a gap fill of a source — by hand or by auto-fill — re-derives the buckets it touches and onward down the chain. A history back-fill of a source reaches the deriver once its chunk is installed. [9]

A pass reads at most 2,048 target intervals (deriveWindow) from where it starts, so a change far behind the cursor costs a bounded number of passes, not one unbounded read. A capped read also takes the first datum after the window, so the window's last bucket is judged as an uncapped pass would judge it. A change landing while a pass writes is not cleared by that pass. [10]

Re-deriving history

Declaring a lineage with REDERIVE and no explicit Since sets Since to the source's first trade or bar and flags the lineage as pending. The stream is activated at once and walks the source's history a window per pass, then continues deriving live. No cursor is stored: after a restart a pending flag puts the walk back at Since, and the walk re-reads from there, rewriting only bars that differ. The flag is cleared when a pass ends uncapped with nothing dirty, and only if the lineage is still the one the walk ran under. A chain is declared with REDERIVE link by link, each once the link before it has finished; a link whose source is still empty starts at now.[11]

The code cites a test for "a restart mid-walk resumes it", but no such test exists in the repository at this commit, so the restart behaviour above is read from the code and is unverified by test.

Only the serving node derives

In a cluster, cmd/server installs the data path's own answer as the dispatcher's serving check (Dispatcher.SetServing): the node derives a stream only if it would accept a write for it — primary of the partition, under a current lease, its replica log replayed. A stream a pass finds not served is deactivated and forgets its cursor; served again, it waits for a live write and recovers from what is stored. A single node serves everything. A copy promoted by failover replays its replica log first (which may hold the old primary's unflushed derived bars) and then derives on from its own newest bar.[12]

Not guaranteed: a pass that checked just before a partition's cutover may still write one round of bars on the old primary afterwards; the new primary re-derives them from its own copy of the source, since a derived bar is a function of its source.

Retention

Every 5 s the deriver retires a served candle-derived stream's chunks that end before its source's oldest base chunk begins, so a derived history never outlives the data it was derived from. A tick source has no such cap. See index compaction.[13]

Ad hoc rollups

A query with the rollup flag and a bar length (QueryRequest.Rollup) asks for bars made at query time from a stream's candles or trades and stored nowhere (Dispatcher.QueryRollupLimited). It runs the same DeriveCandles/DeriveTicks, with the stream's own calendar and the lineage defaults for grace and no-trade limit, on the deriver's clock, so it answers what a stored derivation of the same source would write. It reads what the live deriver reads: the window's source, the trade before it, the first datum after it, and, for a candle source, one source interval early. Only closed buckets whose stamps fall in the range are returned; a gap is an OPEN marker and a closure an OFF_TIME marker. The range is first clamped to what can answer — from the bucket of the stream's first datum to two buckets past the later of its last datum and now — so an unbounded range is answered at once rather than walked bucket by bucket. Candle rollups read column runs and fold them a bucket at a time (materialize.CandleDeriver). A rollup cannot be combined with a stale read.[14]

Measured costs

All figures are from the repository's own measurement notes; they were not re-run for this page, and the machine is not recorded beyond what is stated.

What Result Date, source
Tick ingest, no lineage / hook only / deriver running 183 / 197 / 495 ns a trade, at ~5M trades/s on one stream 2026-10-22, BenchmarkIngestTicks_LineageOverhead, min of 3, GOMAXPROCS 4
DeriveTicks, 1M trades → 100,000 one-second bars, one call 37–42 ms; 27 ms with a New York weekday calendar 2026-10-22, BenchmarkDeriveTicks_AMillionTradesIntoAHundredThousandBars
REDERIVE walk of the same data 0.30 s of work; 7.1 s on the production 100 ms loop 2026-10-22, BenchmarkRederive_AMillionTradesIntoAHundredThousandBars
Rollup: 1M trades → 1m bars 45 ms 2026-10-22, BenchmarkRollup_QueryTime, min of 3
Rollup: a year of 1m → 1h bars 67 ms 2026-10-22, BenchmarkRollup_QueryTime, min of 3

The ingest overhead with the deriver running is the deriver's CPU, not the ingest path: each pass re-reads every trade of a bar still in its grace, so at that rate each trade is read about ten times. The REDERIVE wall time is cadence, not work — about 49 windows of 2,048 bars at one pass per 100 ms, plus passes refused while the derived stream's hot cache was full.

References

Source

Tests

  • TestLineage_RefusedDeclarations, TestLineage_DefaultsFillOnlyWhatIsUnset, TestSetStreamLineage_OnlyItWritesTheLineage.
  • TestBuckets_ADaylightSavingDayHasA23HourWindowAndTheSameStride, TestTickDeriver_ADailyBarIsTheLocalTradingDate, TestGrid_AWeekStartsOnMondayEveryOtherIntervalAtTheEpoch.
  • TestTickDeriver_NothingIsDerivedWithoutLiveTicksOfTheSource, TestTickDeriver_ARestartPicksUpFromTheNewestDerivedBar, TestTickDeriver_TicksBeforeACrashAreDerivedAfterIt, TestTickDeriver_ATradeBeforeTheDeclarationIsNeverABar.
  • TestTickDeriver_ALateTickAfterTheGraceCorrectsItsBarAndIsCounted, TestTickDeriver_ALateTickThatShortensASilenceFillsItsGapsAndClearsTheMark.
  • TestTickDeriver_ABarBelowTheHotCacheIsWrittenByTheRouteThatReachesIt, TestGapIndex_HoldsBarCutsAMissingDataRecordAroundTheSlot, TestTickDeriver_AnOverwriteStandsUntilTheSourceChangesUnderIt, TestServer_AWriteToADerivedStreamIsRefusedWithoutOverwrite.
  • TestCandleDeriver_FiveMinutesMakeABarAndAMissingOneMarksIt, TestCandleDeriver_AChainFromTicksCarriesItsMarks, TestCandleDeriver_ACorrectedSourceBarCorrectsItsDerivedBar, TestCandleDeriver_AHistoryBackfillOfTheSourceIsDerivedFrom, TestCandleDeriver_AgreesWithTheSliceDerivation.
  • TestDeriveCascade_AnAutoFillOfTheSourceMakesTheChainWhole, TestDeriveCascade_AFillFarBehindTheCursorIsDerivedAWindowAtATime, TestRederive_ASourceChangeDuringAPassOutlivesIt.
  • TestRederive_TheSourcesHistoryIsDerivedAWindowAtATime, TestRederive_CompletionLeavesALaterDeclarationAlone.
  • TestTickDeriver_ANodeThatStopsServingTheStreamStopsDeriving, TestServedHere_FollowsTheResolver, TestFailover_ADerivedStreamIsDerivedOnByTheCopyMadePrimary, TestFailover_ABarPendingWhenItsPrimaryDiesIsWrittenOnceByTheCopy.
  • TestDerivedRetention_ADerivedBarNeverOutlivesItsSource.
  • TestMaterialize_AChainFromTicksToDaysMatchesAReferenceAndHealsWhenItsSourceIsFilled, TestMaterialize_LateTicksOnTheWallClock.
  • TestRollup_AnswersWhatAStoredDerivationWould, TestRollup_DailyBarsWestOfUTCMakeWholeWeeks, TestRollup_ColumnsAnswerWhatPointsDo, TestServer_ARollupOverAnUnboundedRangeIsAnsweredAtOnce.
  • TestQueryCandles_AnIncompleteBarComesBackMarkedWithItsData.

Further reading

External

  • A. Gupta, I. S. Mumick, "Maintenance of Materialized Views: Problems, Techniques, and Applications", IEEE Data Engineering Bulletin, 1995: http://sites.computer.org/debull/95JUN-CD.pdf

  1. /internal/types/lineage.go; TestLineage_RefusedDeclarations, TestSetStreamLineage_OnlyItWritesTheLineage. ↩︎

  2. TestBuckets_ADaylightSavingDayHasA23HourWindowAndTheSameStride, TestGrid_AWeekStartsOnMondayEveryOtherIntervalAtTheEpoch. ↩︎

  3. DeriveTicks in /internal/materialize/ticks.go; one test per rule in internal/materialize/ticks_test.go. ↩︎

  4. TestCandleDeriver_FiveMinutesMakeABarAndAMissingOneMarksIt. ↩︎

  5. TestTickDeriver_NothingIsDerivedWithoutLiveTicksOfTheSource, TestTickDeriver_ARestartPicksUpFromTheNewestDerivedBar. ↩︎

  6. TestTickDeriver_ALateTickAfterTheGraceCorrectsItsBarAndIsCounted. ↩︎

  7. TestTickDeriver_ABarBelowTheHotCacheIsWrittenByTheRouteThatReachesIt. ↩︎

  8. TestTickDeriver_AnOverwriteStandsUntilTheSourceChangesUnderIt. ↩︎

  9. TestCandleDeriver_AChainFromTicksCarriesItsMarks, TestDeriveCascade_AnAutoFillOfTheSourceMakesTheChainWhole. ↩︎

  10. TestDeriveCascade_AFillFarBehindTheCursorIsDerivedAWindowAtATime, TestRederive_ASourceChangeDuringAPassOutlivesIt. ↩︎

  11. TestRederive_TheSourcesHistoryIsDerivedAWindowAtATime, TestRederive_CompletionLeavesALaterDeclarationAlone. ↩︎

  12. TestTickDeriver_ANodeThatStopsServingTheStreamStopsDeriving, TestFailover_ADerivedStreamIsDerivedOnByTheCopyMadePrimary. ↩︎

  13. TestDerivedRetention_ADerivedBarNeverOutlivesItsSource. ↩︎

  14. TestRollup_AnswersWhatAStoredDerivationWould, TestServer_ARollupOverAnUnboundedRangeIsAnsweredAtOnce. ↩︎