Wiki Internals
Crash recovery
What a node replays at startup and why it happens inside the dispatcher's constructor — WAL scanning, base coverage, anchors and floors for rebuilt caches, tick shard recovery, quarantine floors and corrupt indexes.
Every live write is in the write-ahead log before it is anywhere else, and chunks are
installed with a crash-safe protocol. Recovery's job at startup is therefore narrow: put back
into memory exactly what the WAL holds that no chunk does, without duplicating anything
already in a chunk, and without refusing to start over damage it can safely work around. It
runs inside ingestion.NewDispatcher, before the node serves anything. The same rules apply
after a clean shutdown, which drains every stream to chunks but does not delete the WAL.
The startup sequence
NewDispatcher performs, in order:[1]
- Scan the shared WAL (
scanWAL). One pass over every segment, keeping only each segment's highest sequence and the log's first and last sequence — not the records. A torn tail in the last segment is truncated here, but damage with a CRC-valid record after it refuses the start (see the corruption policy). - Load the quarantine floors (
wal/quarantine.floors). An unparseable file refuses to start: replaying without it could resurrect a partition the node deliberately set aside. - Open the stream registry (
streams.meta), needed to map tick records' stream hashes back to streams and to create writers during replay, and rename stream directories still in the old<symbol>_<timeframe>form to<exchange>@<symbol>_<timeframe>(Layout.MigrateStreamDirs); a directory it cannot attribute to exactly one registered stream refuses the start, renaming nothing. - Open the WAL manager, adopt the segment high-water marks from step 1, and create the WAL writer seeded with the last sequence on disk, so sequences continue rather than restart and a later replay can never have an old record overwrite a newer one.
- Recover every tick shard the same three ways — scan, open and adopt, seed the writer —
for every
shard_<n>directory on disk, configured or not. - Replay (
replayRecovered): read the logs again, one record at a time, and apply what no chunk holds (next section). - Start the stream writers replay built, together, only now.
- Start the materialization deriver's loop.
Why all of this is inside the constructor: the writer must be seeded after the scan and before anything appends; the registry must be open before replay; replay must finish before anything is served; and the writers it builds must not start until it has finished. Splitting it out would make "constructed but not yet safe to query" a representable state.[2]
Startup memory does not grow with the WAL: the scan keeps marks, not records, and replay streams records through a visitor with read buffers allocated once per log.[3]
Replaying candles
Replay calls the writers' replay methods directly, not the ingest path, so replayed data is
neither logged again nor sent to subscribers. For candles it is planned in full before
anything is applied (candleReplay):
Only what no chunk covers. For each record, every candle whose timestamp a base chunk's
range covers (StreamIndex.BaseCoverage, both ends inclusive) is dropped. It must be
coverage, not "at or below the newest chunk": a history back-fill can install a chunk above
live candles that were still in the hot cache at the crash, and those must be replayed.
Replaying covered candles would build a cache whose next flush overlaps the chunk already
holding them, which the index refuses.[4] A promoted replica's log is replayed by the
same rule.
Anchored at the earliest candle restored. Records reach the log in the order batches took
the append lock, not in time order, so each stream's cache is anchored at the earliest candle
it will restore, before any record is applied. Records are then applied in log order through
SetAt, which turns a second record for a timestamp into a correction exactly as the live path
did.[5]
A floor where nothing is restored. A stream whose WAL records are all covered gets no anchor. Instead its writer sets a floor at its newest chunk's end, so the first live write after the restart cannot land in flushed data; and any anchor later placed above the slot after the floor keeps the span between as a hole, so a pause across a restart is filed as a gap.[6]
Nothing compacts while replay runs. A writer's flusher would compact the cache on a timer and move its base above slots a later record still targets. The writers replay builds stay stopped until it returns.[7]
Replayed records hold their segments. Replaying a record advances the stream's
cachedSeq to its sequence, so a stream that still cannot flush after the restart keeps its
segments from being reclaimed by the next checkpoint.[8]
Skipped, not fatal. A record naming a timeframe with no interval, or a tick whose stream hash the registry cannot resolve, is skipped with a warning: this build cannot use it, and refusing to start over it would make the node unbootable.
Replaying ticks
Tick records from every tick log (and any in the shared log) are replayed merged by the time each was written, never reordered within one log. Each record is skipped or replayed whole by its WAL position against the coverage each tick chunk records — never by timestamp, which would lose a second trade sharing a nanosecond. See Ticks.[9]
Quarantine floors
In a cluster, a node can set a partition aside — a diverged copy, a copy it no longer holds a
role in, a partition whose index is corrupt — by moving its directory under
<data_dir>/quarantine/. Its records are still in the node's shared WAL, and replaying them
would recreate the abandoned data in a fresh directory. So retiring a partition first records,
in wal/quarantine.floors, how far each log had reached and which streams the partition held
(a tick record names its stream only by hash). Replay skips that partition's records at or
below the floor and replays records above it normally; an entry drops itself once no log
reaches back to it, which matters because a log begun again numbers from one.[10]
A corrupt stream index at startup
Replay opens each recovered stream's index pair. An index that does not parse
(storage.ErrCorruptIndex: too short, bad magic, size or checksum — never an I/O error, which
stays fatal) used to stop the node on every start.[11]
- Single node (no policy installed): fail-stop. The node refuses to start and names the stream, because it may hold the only copy.
- Clustered node:
cmd/serverinstalls aCorruptionPolicy. Replay skips that stream's records, and before anything is applied the whole partition is retired (writers stopped, WAL floored) and moved toquarantine/partition_<id>-epoch_<e>-corrupt— never deleted. The policy allows this only while the cluster names another in-sync holder of the partition; a node still named primary waits for the cluster to fail the partition over first, and a node holding the only copy still fails stop. The node then rejoins as a copy and re-seeds. The count is exported asmirexa_reconcile_startup_quarantines_total.
A stream whose corrupt index is first touched after startup (it had no WAL records to replay) still fails per request rather than being set aside.
Chunks interrupted mid-install
Opening a stream's writer runs ReconcileChunks before anything else touches the chunks
directory: a .pending file whose final name the index already names is rolled forward, and
any other .pending file is deleted — its bars are in the WAL and will be replayed. A
final-named file no entry names is left for the hourly chunk GC. See
Installing a chunk.
Limits
- Recovery time grows with the WAL since the last checkpoint (15 minutes by default), because the log is read twice — scan, then replay — and every replayed batch goes through the hot cache.
- A replay larger than one arena fails. Replay runs without compaction, so if more
uncovered candles must be restored for one stream than its arena holds — possible only when
chunk installs were failing or in progress at the crash — the node refuses to start with
ErrOutOfRange. - Damage inside the last WAL segment truncates everything after it in that segment; see the warning on The write-ahead log.
References
Source
NewDispatcher,scanWAL,replayRecovered,candleReplay,planCandleRecord,replayTickRecord,openTickWALShards,startReplayedWritersquarantineFloors,RetirePartition,CorruptionPolicy,startupCorruptionPolicyRecoverStream,AdoptRecoveredHighsStreamIndex.BaseCoverage,TickStorage.Unheld,ReconcileChunksStreamCache.Anchor,SetFloor
Tests
TestCrash_KillDashNine,TestCheckpoint_SurvivesCrashAfterCheckpoint,TestShutdownDrain_PersistsEverythingToChunks.TestRecovery_StartupMemoryDoesNotGrowWithTheWAL,TestRecoverStream_AllocatesItsReadBuffersOncePerLogNotPerSegment.TestRecovery_ReplaysWhatNoChunkHoldsAndOnlyThat,TestRecovery_ReplaysALiveTailABackfillLandedAbove,TestStreamIndex_BaseCoverage.TestRecovery_ReplaysBatchesThatReachedTheLogOutOfTimeOrder,TestIngest_CorrectionDoesNotWedgeRecovery,TestPromotion_ReplaysALogWhoseRecordsAreOutOfTimeOrder.TestRecovery_ACorrectionAfterACleanRestartHidesNoFlushedCandle,TestRecovery_AfterACleanRestartALiveWriteIntoFlushedDataStaysOutOfTheCache,TestIngest_AResumedStreamFilesTheAbsenceBeforeIt.TestRecovery_AFlushBetweenTwoReplayedRecordsCannotStopTheNodeStarting.TestRecovery_ReplayedCandlesHoldTheirSegmentsUntilTheyAreInAChunk,TestRecovery_ACleanRestartKeepsFlushingAndReclaimingTheWAL.TestRecovery_TicksInShardedWALsSurviveACrash,TestRecovery_AShardedTickWALContinuesItsSequenceAcrossARestart,TestRecovery_ACleanRestartReplaysNoTickTwice,TestRecovery_TicksSharingATimestampAcrossARecordBoundarySurvive.TestRetirePartition_NothingOfItIsReplayedAfterACrash,TestRetirePartition_ItsStreamWrittenAgainIsReplayed,TestRetirePartition_PartitionsRetiredAtOnceAllKeepTheirFloors.TestStartup_ACorruptIndexStopsTheDispatcherWithoutAPolicy,TestStartup_ACorruptIndexSetsItsPartitionAsideAndTheNodeStarts,TestStartup_APolicyThatRefusesKeepsTheFailStop,TestStartupPolicy,TestServerBinary_ANodeWithACorruptStreamIndexStartsAndItsPartitionIsReplicated.TestRecover_MidLogCorruptionRefused.
Further reading
- Startup, shutdown and recovery — the operator's view
- The write-ahead log, The hot cache, Ticks
- Reconciliation, scrubbing and repair
External
- C. Mohan et al., "ARIES: A Transaction Recovery Method Supporting Fine-Granularity Locking and Partial Rollbacks Using Write-Ahead Logging", ACM TODS, 1992: https://doi.org/10.1145/128765.128770
NewDispatcherin /internal/ingestion/dispatcher.go. ↩︎TestRecovery_AFlushBetweenTwoReplayedRecordsCannotStopTheNodeStarting,TestRecovery_AShardedTickWALContinuesItsSequenceAcrossARestart. ↩︎TestRecovery_StartupMemoryDoesNotGrowWithTheWAL. ↩︎TestRecovery_ReplaysWhatNoChunkHoldsAndOnlyThat,TestRecovery_ReplaysALiveTailABackfillLandedAbove. ↩︎TestRecovery_ReplaysBatchesThatReachedTheLogOutOfTimeOrder. ↩︎TestRecovery_ACorrectionAfterACleanRestartHidesNoFlushedCandle,TestIngest_AResumedStreamFilesTheAbsenceBeforeIt. ↩︎TestRecovery_AFlushBetweenTwoReplayedRecordsCannotStopTheNodeStarting. ↩︎TestRecovery_ReplayedCandlesHoldTheirSegmentsUntilTheyAreInAChunk. ↩︎TestRecovery_TicksSharingATimestampAcrossARecordBoundarySurvive. ↩︎TestRetirePartition_NothingOfItIsReplayedAfterACrash,TestRetirePartition_ItsStreamWrittenAgainIsReplayed. ↩︎TestStartup_ACorruptIndexSetsItsPartitionAsideAndTheNodeStarts,TestServerBinary_ANodeWithACorruptStreamIndexStartsAndItsPartitionIsReplicated. ↩︎