Mirexa

Wiki Internals

The write-ahead log

Segment files, the record format and its CRC-32C, sequence allocation, group commit, backpressure, poisoning, tick shards, and how checkpoints reclaim the log.

The write-ahead log (WAL) is Mirexa's durability boundary for live writes. Every live candle and tick batch is written to it before it becomes visible in memory, and an acknowledged write is acknowledged only once its WAL record has been fsynced. After a crash, replaying the log rebuilds whatever had not yet reached a chunk. The package deals in sequence numbers, checksums and segment files; it knows nothing about candles beyond two payload encodings.

Layout on disk

One node has one shared candle WAL and, by default, sixteen tick WAL shards:

text
<data_dir>/wal/
├── wal.lock              exclusive flock: two processes never share a log directory
├── 000000001.log         segments, nine-digit zero-padded index
├── 000000002.log
├── shard_0/ … shard_15/  tick WAL shards, each its own segment set and wal.lock
└── quarantine.floors     JSON: how far each log reached for a set-aside partition

A segment starts with an 8-byte header — the magic MRXW, a uint16 format version (currently 1) and two reserved bytes, written big-endian. Everything after the header, and every other format in Mirexa, is little-endian. A segment is rotated before a write would push it past wal.max_segment_bytes (512 MiB by default); a segment holding only its header is treated as empty, so a single oversized record is never split and rotation never loops.

The directory is guarded by an advisory flock on wal.lock, taken non-blocking: a second Manager on the same directory fails at once rather than waiting.

Record format

Records follow the segment header back to back:

Offset Size Field Notes
0 4 CRC-32C Castagnoli, over bytes 4 to the end of the payload
4 4 Length payload byte count, at most 65,536
8 8 Sequence number monotonic within this log
16 8 Timestamp wall-clock nanoseconds when the record was buffered
24 2 Payload type 1 tick, 2 candle (3 and 4 are defined but not written by ingest)
26 2 Reserved zero; keeps the payload 4-byte aligned
28 n Payload

The reader takes the length before the CRC that covers it, bounds-checks it against the 64 KiB maximum, and only then verifies the checksum over exactly header[4:] + payload, so a corrupt length field cannot make it read past the record and a single bit flip anywhere is caught before a field is used.[1]

Payloads:

  • Candle (CandlePayload): a 4-byte stream-id length, the stream id string, a 4-byte count, then 48 bytes per candle — timestamp and five float64 OHLCV values.
  • Tick (TickPayload): a 16-byte batch header (stream hash, count, reserved), then 32 bytes per tick — the stream's FNV-64a hash repeated, timestamp, price, volume. The hash is repeated so a record stays self-describing during recovery; the stream registry inverts it back into a stream id.

Sequence numbers are allocated under the append lock

Each wal.Writer owns a sequence generator seeded from the highest sequence recovery found on disk, so sequences continue across restarts. A record's sequence is allocated and its bytes appended to the writer's buffer under the same mutex, so records land in the segment in sequence order however many goroutines append at once. That ordering is load-bearing: replay runs front to back, and a record physically behind one with a higher sequence would overwrite the newer data.[2]

The sequence is an input to the record CRC, so computing the CRC also moved inside the critical section. The writer's own benchmark (BenchmarkWriter_AppendCriticalSection) measured the critical section at about 390 ns before and 860 ns after, at 1 KiB payloads and 12 goroutines; the end-to-end cost is invisible behind the fsync (BenchmarkWriter_ConcurrentAppend). The date and machine of that measurement are not recorded in the source.

Group commit and the durability barrier

Writer.Append and Writer.AppendBatch return as soon as the record is in the in-memory buffer; they promise nothing about the disk. A background flusher drains the buffer either every wal.flush_interval (500 µs by default) or as soon as the buffer passes wal.batch_size (64 KiB), whichever comes first:

  1. Under the buffer lock, swap the filled buffer out and record the highest sequence it contains.
  2. Write it to the active segment in one AppendRecords call.
  3. Apply the sync policy (always: fsync now; interval: at most once per wal.sync_interval; disabled: never).
  4. Advance the durable watermark to that sequence and wake every waiter.

Writer.AwaitDurable(seq) blocks until the durable watermark reaches seq, nudging the flusher so the wait is one flush cycle rather than a full interval. Because one fsync covers every record in the batch it wrote, concurrent acknowledged writers share fsyncs instead of paying one each.[3] A poisoned or closed writer fails the wait rather than stranding the waiter. Flushes are serialized by their own mutex, so one batch's write and sync always complete before the next batch's begin.

The barrier is only as strong as wal.sync_policy. With interval or disabled, an INGEST_ACK no longer means the record survived a power loss. The default is always.

Backpressure: the bounded buffer

wal.batch_size only decides when to nudge the flusher. The enforced bound is wal.max_buffer_bytes (4 MiB): when an append would exceed it, the caller blocks until the flusher drains, and if no room appears within wal.buffer_wait_timeout (2 s) the append is shed with ErrOverloaded, having buffered nothing.[4] Three details matter:

  • Admission comes before sequence allocation. A shed append consumes no sequence number. A number issued to a record that never lands would be a permanent hole that replay and the checkpoint would both read as missing data.
  • A split batch is admitted as one unit. AppendBatch checks room for all of its records up front, so a shed can never commit a prefix of a batch whose caller is told it failed.
  • Room appears at the buffer swap, not when the flush finishes, so producers refill while the slow write and fsync are still in flight. The price is a peak of about twice the bound (one buffer filling, one being written). The bound is per writer: budget roughly max_buffer_bytes × (shard_count + 1) for one node. An empty buffer always accepts one record, so a bound smaller than a record is a misconfiguration, not a silent outage.

Blocking is real flow control: the ingest goroutine stops reading its socket, so the client's TCP window closes. The shed exists only so a stalled device is not an outage with no diagnostic.

Poisoning

If writing a flushed batch to the segment fails on every retry (wal.max_retries, 3, with exponential backoff from wal.retry_base_delay, 10 ms) — or fails at all with ENOSPC, which is not retried — the batch is gone, yet Append already returned success for each of its records. The writer is then poisoned for the rest of its life: every later Append, Flush, AwaitDurable and Close returns ErrWriterPoisoned. A failed fsync poisons too, because on Linux the error may never be reported again on a later fsync. The node keeps serving reads; writes fail loudly rather than being acknowledged and dropped.[5]

Partial-write rollback

A write that fails partway leaves a record prefix in the segment, and the writer's retry re-sends the whole batch. If the prefix stayed, the retried batch would sit after it, and recovery would truncate at the prefix and discard the good batch. So on any write error Manager.AppendRecords truncates the segment back to its size before the write and seeks the file offset back too (a new segment is opened without O_APPEND, so its offset would otherwise leave a sparse hole).[6]

Directory durability

A segment's bytes and its name are two separate durability facts. An fsync of a newly created file does not persist its directory entry, so the manager fsyncs the directory after creating a segment, and once per round after a checkpoint unlinks segments (an unlink that is not durable can resurrect a reclaimed segment after a crash).[7] The storage side follows the same rule for every rename; see Indexes and the on-disk layout.

Recovery's corruption policy

Recovery reads every segment in index order (detail in Crash recovery). What it does with damage depends on where the damage is:[8]

Situation Action
A record fails to read or verify in the last segment, and no CRC-valid record follows Truncate the segment at that record and succeed — the expected result of a crash mid-write
A record fails in the last segment and a CRC-valid record follows it Refuse with ErrCorruptMidLog; truncate nothing — unless the span up to that record holds a whole 512-byte-aligned sector of zeros, a crash's out-of-order writeback of the unsynced final batch, which is truncated as a tear (classifyLastSegmentDamage)
A record fails anywhere in an earlier segment Refuse with ErrCorruptMidLog; truncate nothing
A segment header present but wrong (magic or version) Refuse with ErrCorruptSegment, wherever it is — a foreign file, never a torn write
The last segment shorter than its header Treat as a torn create and ignore it
An earlier segment shorter than its header Refuse

Until 2026-10-30 the last segment was truncated at the first record that failed, whatever followed it, so a bit flip in the active segment deleted every later record, acknowledged or not, and the node started without an error. A torn write damages only what was written last, so a valid record after the damage proves it is not a tear (TestRecover_CorruptionFollowedByValidRecordsInTheLastSegmentIsRefused, TestRecover_AZeroedSectorBeforeValidRecordsIsATornTail). The consequence: a node whose last segment rotted now fails to start, as one whose earlier segment rotted already did. A device that loses an fsynced write and reads back zeros is still truncated like a tear.

Tick WAL shards

Ticks are logged to wal/shard_<n>/, chosen by StreamID.Hash() % wal.shard_count (16 by default), so tick ingest for different streams does not contend on one writer. A shard_count of 0 or 1 sends ticks to the shared WAL. Each shard is a complete log — its own segments, lock, writer and sequence space — and each is recovered at startup exactly like the shared log. Every shard_<n> found on disk is recovered, configured or not; a shard beyond the current shard_count is replayed but never written or reclaimed again, with a warning. See Ticks.

Checkpoints: reclaiming the log

Without reclamation the WAL grows forever. Every wal.checkpoint_interval (15 minutes by default; 0 disables it and logs a warning) the node runs Dispatcher.Checkpoint:[9]

  1. For each stream, capture its cachedSeq under the append lock — a contiguous watermark, because sequence allocation and cache apply happen under one lock.
  2. Drain the stream's hot cache completely into a chunk (an ordinary flush keeps the newest bars in memory, so it proves nothing about the WAL) and flush its tick buffer.
  3. Promote the captured value to the stream's checkpointSafeSeq only if the chunk actually installed and no earlier evicted batch is still waiting for one.
  4. Take the minimum safe sequence across streams. The log is shared, so a segment can be removed only when every stream's records in it are redundant; one stream whose chunks keep failing holds the whole candle log, deliberately, and the node logs a warning.
  5. Manager.CheckpointTo(min) deletes completed segments, oldest first, whose highest sequence is at or below it. It stops at the first segment that is not safe — or whose high-water mark is unknown — rather than skipping it, because a hole behind a retained segment would trip recovery's mid-log check. The active segment is never removed.

Segment high-water marks are learned as records are appended. For segments a previous process wrote, recovery reports them and the manager adopts them (AdoptRecoveredHighs); without that step a restarted node would never reclaim anything again. Tick shards are checkpointed with the minimum tick watermark across streams, applied to every shard — conservative, never unsafe.

wal.retain_segments is parsed and validated, but the count-based cleanup it configures (Manager.Cleanup) is not called anywhere in the node. Segments are removed only by checkpoints. Setting it has no effect.

The cost of a checkpoint is one chunk per stream that had cached data, so a short interval trades smaller chunks for a shorter log and faster recovery. Nothing merges small chunks afterwards: index compaction only drops the oldest entries (see Indexes and the on-disk layout).

Where else the WAL format is used

The same Manager and record format back a copy's replica log in a cluster: a copy appends its primary's tail records verbatim into partition_<id>/replica.wal/, and a TailReader on the primary serves records after a watermark. Those logs are trimmed by seed progress rather than by checkpoints. See Replication.

References

Source

Tests

  • TestWriter_PhysicalSequenceOrder, TestWriter_ConcurrentFlushPreservesOrder — records land in sequence order.
  • TestAwaitDurable_GroupCommitSharesSyncs; TestServer_AckedCandleIngestIsInWALBeforeAck.
  • TestWriter_BufferIsBoundedUnderAStalledSink, TestWriter_BlockedAppendUnblocksOnDrain, TestWriter_AppendBatchIsAdmittedOrShedWhole.
  • TestWriter_PoisonedAfterPermanentFlushFailure.
  • TestManager_Append_PartialWriteRollsBack.
  • TestManager_NewSegmentDirectoryEntryIsDurable, TestManager_SegmentHasHeader.
  • TestRecover_MidLogCorruptionRefused, TestRecover_StopOnCorruption_FirstRecordUntouched, TestRecoverStream_StreamsRecords.
  • TestCheckpoint_ReclaimsSegmentsAndKeepsEveryCandle, TestCheckpoint_DoesNotAdvancePastAFailedPersist, TestCheckpoint_SurvivesCrashAfterCheckpoint.
  • TestRecovery_ACleanRestartKeepsFlushingAndReclaimingTheWAL, TestCheckpoint_ReclaimsAShardedTickWALAfterARestart.
  • TestRecovery_AShardedTickWALContinuesItsSequenceAcrossARestart.
  • TestCrash_KillDashNine.

Further reading

External

  • G. Castagnoli, S. Bräuer, M. Herrmann, "Optimization of Cyclic Redundancy-Check Codes with 24 and 32 Parity Bits", IEEE Transactions on Communications, 1993 — the CRC-32C polynomial: https://doi.org/10.1109/26.231911
  • 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
  • T. S. Pillai et al., "All File Systems Are Not Created Equal: On the Complexity of Crafting Crash-Consistent Applications", OSDI 2014 — why directory fsyncs matter: https://www.usenix.org/conference/osdi14/technical-sessions/presentation/pillai
  • PostgreSQL, "fsync errors" — why a failed fsync is treated as permanent: https://wiki.postgresql.org/wiki/Fsync_Errors

  1. Record.UnmarshalBinary in /internal/wal/record.go. ↩︎

  2. TestWriter_PhysicalSequenceOrder. ↩︎

  3. TestAwaitDurable_GroupCommitSharesSyncs. ↩︎

  4. TestWriter_BufferIsBoundedUnderAStalledSink, TestWriter_AppendBatchIsAdmittedOrShedWhole. ↩︎

  5. Writer.flushLocked; TestWriter_PoisonedAfterPermanentFlushFailure. ↩︎

  6. TestManager_Append_PartialWriteRollsBack. ↩︎

  7. TestManager_NewSegmentDirectoryEntryIsDurable. ↩︎

  8. applySegmentResult in /internal/wal/recovery.go; TestRecover_MidLogCorruptionRefused. ↩︎

  9. TestCheckpoint_DoesNotAdvancePastAFailedPersist, TestRecovery_ACleanRestartKeepsFlushingAndReclaimingTheWAL. ↩︎