moonpool-journal is a write-ahead journal built on nothing but the provider
traits and BlockFile. It
implements CLSTORE, the local storage layer of Protocol-Aware Recovery for
Consensus-Based Storage (Alagappan et al., FAST ‘18). It is a real crate:
production hands it TokioStorageProvider, tests hand it the simulator’s
disk, and the code is the same. It is also the worked example of testing a
storage engine under Chaos::Storage.
moonpool-journal, byte by byte on the website draws each file, record and header of the format from the code, with the commit protocol and the recovery rules.
The Problem It Solves
A log that finds a bad checksum usually truncates there. For a torn write at the tail that is correct: the entry was never acknowledged. For an entry that was acknowledged and later rotted, truncation silently throws away committed data. In a replicated system, the node that truncated can then win an election and erase that data cluster-wide. The two cases look identical if all the log has is the entry.
CLSTORE does three things about it. It detects damage (checksums, and a medium error read as damaged bytes). It disentangles a crash from corruption: every entry has a persist record stored far from it, and a damaged entry whose record survived was written, so it is corruption, not a torn write. And it identifies what was damaged: the record carries the entry’s identity, so a replication layer knows what to fetch from a peer.
Positions, Not Indexes
The journal knows no protocol. An entry is a u64 position and an
opaque 24-byte Id the caller chooses. A Paxos acceptor puts its slot in
the position and its ballot in the id. A Raft log puts its index and term.
Positions are written in any order, with gaps, and overwritten:
use moonpool_journal::{Batch, Journal, JournalConfig, JournalId};
let mut journal = Journal::create(provider, "wal", JournalId(0xACCE), JournalConfig::default(), b"promise=0").await?;
let mut batch = Batch::new();
batch
.put(7, ballot_id(3), "set x=7") // a new slot
.put(4, ballot_id(2), "set w=4") // a lagging acceptor catching up
.put(9, ballot_id(5), "set y=10") // a re-accept at a higher ballot
.set_meta("promise=5"); // the node-unique state
journal.commit(batch).await?;
That shape is what an acceptor or a lagging replica needs, and it is why the
journal stores state rather than a log of operations: there is no fold at
boot and no checkpoint. Batch::clear(range) removes positions (a Raft
suffix truncation). Batch::truncate_prefix(floor) drops everything below
a floor and frees whole segments from the front. Batch::set_meta replaces
the metainfo (at most META_MAX bytes, just under 4 KiB), kept in two
copies. There are no snapshots and no compaction.
A batch lands in one segment, so it must fit an empty one. A bigger batch is
refused with CommitError::BatchTooLarge before anything is written. A
caller with more to write than that (a replica catching up a long log) packs
its writes with Batch::fits_another:
let mut chunk = Batch::new();
for (position, payload) in puts {
if !chunk.fits_another(geometry, payload.len()) {
journal.commit(std::mem::take(&mut chunk)).await?; // every chunk fits
}
chunk.put(position, id, payload);
}
journal.commit(chunk).await?; // metainfo and floor go in the last one
Batch::fits(geometry) is the same bound for a staged batch. Both count
each write twice in the persist log. That is slack now: the room a retire
record once took in the same batch (below). The default
Geometry is a 64 MiB segment with persist and entry logs of the same size
(507,904 records and 31 MiB of entries). Every batch starts on a fresh block
in both logs, so a segment holds 7,936 batches of one small entry.
Geometry::small() is 512 records and 64 KiB of entries, so tests roll over
segments quickly. Journal::open refuses a geometry other than the one the
journal was created with.
Layout
<dir>/meta metainfo copy A (block 0), copy B (block 16)
<dir>/seg-<first batch>.wal allocated whole:
header A | persist log | guard gap | entry log | header B
<dir>/spare-<gen>-<n>.wal a dead segment's file, kept for the next roll
Each segment holds two append-only logs. The persist log is a run of
64-byte records: kind, position, id, the entry’s offset, length and CRC, the
batch, its record count and the record’s index. The entry log holds the
payloads in arrival order, each behind a 64-byte header that repeats the
record’s identity, so a misdirected entry never passes for the one a record
names, and an intact entry can rebuild a lost record. The header has its own
CRC, and it holds the CRC of its payload. It also holds a stamp: the
metainfo seq it was written under. The two header copies of a segment sit
at its two ends, so one fault on a run of blocks (a misdirected write, a bad
stretch of the medium) never reaches both. Every batch starts on
a fresh block in both logs, so no commit ever touches a sector holding
anything acknowledged. That one rule is what makes the crash model below
survivable. A record repair (below) is the one write that breaks it, and it
does so only where a torn write loses nothing.
The meta file is separate. It is the one structure rewritten in place, and
it must outlive every segment. Its two copies are written one after the
other, each a durable write (write_at_durable), so at most one is in flight and a single
rotted copy never rolls the metainfo back. Journal::peek_meta(&provider, dir, id) reads it without opening the journal: no recovery, no repair, no
sync, so a probe never changes what the next open finds. A directory with
segments and no meta file is a journal that lost its metainfo, not an empty
one: open, peek_meta and create all return MetaLost there. Only a
directory with no meta file and no segment is empty. create deletes a
spare or a file that a crashed creation left, because none of them is a
journal.
Committing: One Sync or Two
Durability picks the protocol, and every batch records which one it used:
| Mode | Protocol | Syncs | Last batch |
|---|---|---|---|
Batched |
write(entries), write(records), fsync |
1 | ambiguous |
Ordered (default) |
write_durable(entries), write_durable(records) |
2 | decided |
Batched is the paper’s protocol. With one sync, a crash can leave an intact
record beside a damaged entry exactly as corruption would. The paper’s
Appendix A proves the two cannot be told apart, so the last batch’s damaged
entries are reported State::Ambiguous and the replication layer decides.
The ambiguous tail stays ambiguous until the caller’s next batch
commits, then becomes Corrupt. The opens in between do not end it: the
metainfo records the first batch whose damage an open found ambiguous, and
neither the open’s own retire batch nor its high-water mark (below) counts
as the caller’s batch. Without that record, a second open would see the
batch below the mark the first open raised, and call a crash-torn entry that
nothing ever acknowledged Corrupt, which tells the caller that a peer has
it. Ordered writes the records only once the entries are
durable, so a record always proves its entry was synced.
Ordered issues each log’s write as one durable write
(StorageFile::write_at_durable): on Linux one pwritev2(RWF_DSYNC), which
on a direct-I/O segment whose blocks are written can become a single FUA
write instead of a write plus a cache flush. Two calls replace four, and the
durability argument is unchanged. A durable write covers its own range only,
and that range is the segment’s one unsynced write: every earlier commit was
durable before it returned, an open syncs every segment, a roll writes its
headers durably, and a failed commit poisons the journal. Data-only
durability is enough because a segment never changes size. Batched keeps
its plain writes and one sync: a durable write of the records alone would not
cover the entries.
A failed sync can leave pages clean in the page cache but not on the device
(fsyncgate): a later sync reports success, and reads serve the cached bytes.
Under one sync the device can then keep a record and lose its entry, a damaged
batch that no crash made. So a Batched commit whose sync fails writes its
batch again and syncs again, at most three syncs in all. The batch is not
acknowledged yet, so the rewrite is safe: a power loss during it can tear the
batch, which a power loss before the first sync could already do.
No Copy on the Way to the Disk
A commit encodes its batch in place. commit sizes the entry log’s
bytes first (Batch::fits already bounded them), allocates one zeroed,
block-aligned AlignedBuf, and encodes every entry header and payload
straight into it; the persist records go into a second one. Both move into
BlockFile::write_blocks_aligned / write_blocks_durable_aligned, which
hand them to the file’s owned write_at_aligned /
write_at_durable_aligned. On TokioStorageProvider the buffer moves into
the blocking task and back, so pwritev2(RWF_DSYNC) reads the journal’s own
memory: the bytes a caller staged are copied once, into the batch, and
never again. The segment headers, the metainfo copies and recovery’s
reads (the persist log, entries read in place) take the same owned path.
Before, a direct-I/O commit copied each log twice: from the journal’s
Vec into an aligned buffer, then into the provider’s bounce buffer.
let entries = std::mem::take(&mut batch.entries);
batch.entries = segment.write_durable(batch.entry_at, entries).await?; // moved, not copied
A buffer whose address missed a file’s memory alignment would be copied once into one that meets it; a block boundary meets every direct-I/O device the journal opens in practice.
Metainfo is written only after the batch is durable: copy A durably, then copy B durably. A crash can leave the batch durable without its metainfo, but never the metainfo without its batch. Anything true only once a batch is on disk (a chosen index, a watermark) can share that batch’s commit.
Hints Inside a Commit
The commit protocol names its dangerous moments with hint! from
moonpool-buggify. A batched commit names three:
batch.entries = segment.write(batch.entry_at, entries).await?;
// A power loss here tears entries no record points at yet.
moonpool_buggify::hint!("journal commit: entries written, not synced", COMMIT_HINT_PROB).await;
batch.records = segment.write(batch.persist_at, records).await?;
moonpool_buggify::hint!("journal commit: records written, not synced", COMMIT_HINT_PROB).await;
segment.sync().await?;
if let Some(meta) = meta {
moonpool_buggify::hint!("journal commit: batch synced, metainfo stale", COMMIT_HINT_PROB).await;
meta_file.update(meta).await?;
}
An ordered commit writes each log with one durable write, so the window
between a write and its sync lies inside a single call. The simulator names
it there: its write_at_durable (which the owned write_at_durable_aligned
calls by default) is write_at, then
hint!("storage: durable write landed, not synced") at the same 0.25, then
sync_data. The ordered commit keeps the metainfo moment of its own.
In production a hint is a no-op. In a simulation the HintSink decides
whether to crash the owning process at that exact moment, under the seed’s
attrition regime and swarm mask (see
hint!: Naming Fault Sites). The rate is
0.25 per call, higher than the default POINT_PROB, because a commit is
short and a cut inside it is the case recovery exists for. A harness with a
budget the simulator cannot see, such as the copies a replicated store can
lose before a crash is no longer survivable, publishes a HintVeto:
HintVeto::new(move |ip, label| copies_alive.load(Ordering::Relaxed) > quorum)
.publish(ctx.state());
The sink asks the veto last, after the regime admits the reboot, so a true
answer is a reboot.
Rolling Onto a Recycled Segment
When the active segment is full, the commit rolls onto a new one. How expensive should that be? A segment is 64 MiB. Write it with zeros and the commit waits for 64 MiB and two syncs; write it in a background task and the zeros still compete with every commit for the same disk. We measured a zero-fill running beside the commits: they ran five times slower, with 45 ms spikes.
So the journal writes no zeros at all. It does what PostgreSQL does with its
WAL: it recycles. When the floor, or later writes, leave the front
segment with nothing live, the journal renames that file to
spare-<generation>-<n>.wal and syncs the directory, instead of deleting
it. The next roll adopts the spare: it writes the two header blocks,
syncs them, renames the file to seg-<first batch>.wal and syncs the
directory. One small durable write and a rename. The file is already full
size, and every block in it was written before, so a commit into it costs
exactly what a commit into any written block costs.
With no spare (a journal that only grows), the roll creates the segment with
StorageFile::allocate, which is fallocate(2) on Linux: the space is
reserved, the range reads as zeros, and only the headers are written. A full
disk fails there, at the roll, and never inside a commit. A new segment’s
first pass does pay a little: the first durable write into each block also
records that the block is now written, a small metadata change. A recycled
segment pays none.
But a recycled file is full of old batches. Why are they not evidence?
- A batch older than its segment is stale. A segment named after its first batch only ever receives batches at or above that number, and batch numbers never repeat: the open generation lives in their high bits. Every record and entry a recycled file still holds is older than the segment it becomes, so the scan reads it like a never-written slot. The recovery table below is unchanged.
- No batch is written to a spare. Its headers are synced before its rename, so a crash during the adoption leaves the spare, or a whole empty segment, or the same file under either name. A recycled segment is renamed and its directory synced before anything is written into it, so it can never come back under its old name with new bytes in it.
- The commit acknowledges its batch only after the directory sync, so the segment’s name is durable before any batch in it is.
How many spares? JournalConfig::spares sets it (1 by default, at most
JournalConfig::MAX_SPARES), and a
journal that only grows never gets a dead segment to recycle. So
Journal::prepare_spares allocates spares ahead of the rolls: each one is a
whole file under a temporary name, synced, then renamed. Its headers read as
zeros, so it names no segment and holds no batch. Call it after an open, or
when the node is idle, and no commit pays for an allocation. etcd’s file
pipeline and canonical/raft’s uv_prepare do the same.
An open keeps up to spares whole spares it finds (Recovery::spares_kept)
and deletes the others (Recovery::spares_removed). Journal::rolls() counts the rolls
of each kind. The commit side names two moments with hint! (“journal roll:
spare headers synced, not renamed”, “journal roll: spare renamed, directory
not synced”).
Recovering
Opening reads the persist records, locates each batch, walks the entry log to match damaged records with their entries, and judges each one. The last segment is read whole. A sealed segment ends at the batch that the next segment’s header names, so opening reads its persist log only up to that batch; a record past it is not part of the segment. Blocks of zeros are skipped without a decode.
| Entry | Persist record | Verdict |
|---|---|---|
| intact | valid | live |
| intact | damaged | live; the record is rebuilt from the entry |
| damaged | valid | Corrupt, or Ambiguous in a Batched last batch, or from the batch the metainfo names as ambiguous on |
| damaged | damaged, named by a retire record | ignored |
| damaged | damaged, unwitnessed last batch of its open generation | torn by a crash: discarded and retired |
| payload damaged, header intact | damaged, witnessed, or earlier in its generation | Corrupt: the header names the entry |
| header damaged | damaged, witnessed, or earlier in its generation | OpenError::DoubleFault: refuse to open |
A slot whose record and entry are both damaged is what a crash in the middle of a commit leaves, and it is also what two faults leave on an acknowledged batch. The journal tells them apart only with a witness, something that proves the batch durable:
- The high-water mark. The metainfo records the batch of its last update (it is written only once that batch is durable), and every open records the last batch it found, once nothing in it is left to retire. A batch at or below the mark was durable.
- An intact
Orderedrecord. AnOrderedcommit syncs every entry before it writes any record, so one valid record proves every entry of its batch was durable.
In a witnessed batch, both parts damaged is DoubleFault and a damaged
entry under a valid record is Corrupt, never Ambiguous. But “both parts”
is often too strong. Most rot hits the payload, which is most of the bytes.
When the entry header is intact, it still names the entry: its position, its
id, its length. So a witnessed slot with a damaged record and a damaged
payload under an intact header is Corrupt, with its identity, and the open
goes on. The caller fetches the entry from a peer, as for any other
Corrupt entry. A later batch may have replaced that position already.
Then the slot is dead: the open does not report it, because a caller that
fetched it again would write the old value over the new one. The open
retires it instead.
Three rules keep the header honest. In an unwitnessed last batch, a damaged
payload is still torn: a crash can keep the header of a write and lose its
payload. The open never writes back a record rebuilt from a header alone,
because the header proves nothing of the payload. And only an intact record
witnesses an Ordered batch, never a header. Only an
acknowledged last batch that nothing witnesses can still be discarded: a
Batched commit (or an Ordered one with no intact record) that changed no
metainfo, with no open since. Its bytes look exactly like a torn commit. A
caller that needs a batch witnessed sets its metainfo in that batch.
What happens to a torn slot after the open discards it? It stays in its segment, half damaged, until the floor frees the segment. If one more fault hits what is left of it, the slot reads both damaged in a batch that is no longer the last: a double fault, from one fault. So the open writes down its verdict as a retire record. A retire record names one slot (its batch and index) and carries the offset where the entry walk goes on after it. It has a persist record and a 64-byte entry, as a tombstone has, so one fault on it is rebuilt. A lost slot that a retire record names is ignored, and an intact entry behind it is found again from the offset.
The open that retires is the delicate part. It scans, then starts its new generation durably but leaves the high-water mark where it was. Then it commits the retire batch with a metainfo write, and the normal commit path moves the mark to the retire batch once that batch is durable. A crash before the retire batch is durable leaves the torn batch above the mark and still the last of its generation, so the next open finds the same torn slots. A crash that tears the retire batch makes it the last of its generation, so its own lost slots are torn slots too. Only the last batch of a generation can be torn by a crash, because a failed commit poisons the journal.
What about a commit that never fails, because the caller stops waiting? A
timeout or a losing select! branch drops the commit future at an await.
The batch can then be on disk, whole or in part, while memory still names
the old tail. The next commit would write the same batch number at the same
offsets over it, and a crash during that write tears a batch that was
durable: an honest disk then reads as corrupt. So a commit poisons the
journal before its first await and clears the poison only once memory
follows the disk. A dropped commit is a failed commit, and the caller
reopens. A scrub’s copy rewrites and a record repair do the same.
A commit retires slots too. When a batch replaces, clears or drops below the
floor a position whose entry is known damaged (State::Corrupt, or a read
that returned ReadError::Damaged), the commit retires the old slot in a
batch of its own, once its batch is durable. The caller’s usual repair, a
new put of the position, then leaves nothing behind that a second fault can
turn into a refused open. Why not in the same batch? A crash can tear that
batch’s put and keep its retire record: the open would discard the put as
torn, ignore the old slot, and forget the only copy of an acknowledged
entry. A crash between the two batches leaves the old slot unretired: the
next open retires it when only its header is left, and otherwise it stays
one fault from a refused open, as a damaged slot nothing has replaced yet.
Two rules keep old or misplaced records from passing for evidence. Batch numbers grow with the place in the persist log, so a record after a batch boundary whose batch is not above the batch before it is old bytes, at every open. And the first record of a batch names the first entry of its own place: a records block written to the wrong block (a misdirected write) names another offset, so the open reads it as damaged and rebuilds the batch from its entries.
A batch missing while later ones exist, or a log ending before the batch the
metainfo proves durable, is LostBatch: that covers every record and the
first entry of a witnessed last batch damaged, where nothing on disk even
says the batch was there. Batch numbers have no gaps (an open generation
counts on from its first number), so a missing batch is found even when
the walk of the entries goes straight past it, as it does past an open’s
retire batch that the disk lost: its entry sat over the slot it discarded. A missing meta file beside segments, or two
damaged copies, is MetaLost. But what if the bytes are intact and only
the format version is not ours? That is a binary of another version, not a
lost disk: UnsupportedVersion { found, supported }. Each checksum covers
the version field, so damage never reads as another version. Two faults can also roll the metainfo back:
the device loses both copy writes of one update, or loses one while the
other rots, and the older value wins. Every batch number carries the open
generation that wrote it, and every open raises the generation in both
copies before it writes, so a batch of a later generation than the
metainfo’s proves the metainfo older than the log: MetaRolledBack. What
about a rollback inside one open generation? The stamps tell. Each batch is
stamped with the metainfo seq that is durable when it is written. So an
intact entry header stamped above the seq that reads back proves that the
metainfo lost an update: MetaUpdateLost. The batch that carries a metainfo
update holds the stamp before it, so a crash between that batch and its
metainfo write leaves nothing ahead. A batch number
holds the generation in its high 24 bits and the count in its low 40 bits,
so both have a limit. The 16,777,215th open is the last: the next one is
refused with OpenError::InvalidConfig. One open writes at most 2^40 - 1
batches: the next commit is refused with CommitError::BatchNumbersExhausted
before anything is written, and a reopen starts a new generation. Opening returns a Recovery that says
what it found and did: corrupt, ambiguous, torn, rebuilt, repair
(the persist blocks it wrote back, and those it left),
meta_repaired (a metainfo copy rewritten from its twin),
headers_repaired, segments_removed, spares_removed and spares_kept. Only the last batch’s entries are
read at open. The rest are checked when read: read(position) returns
ReadError::Damaged { position, id } with the identity its record kept, and
replay(range) reports a damaged entry in place and goes on. A replay reads
entries that follow each other in one segment with one read, up to 1 MiB, and
judges each entry as read does: under direct I/O, a replay of a few thousand
entries costs a few reads, not one read per entry.
A persist record is read only at open: read and replay judge an entry
against the record held in memory. A record that rots after the open is found
at the next one, and if its entry rots too before then, that open refuses.
verify_records(range) reads the records of the live positions in range
from disk, changes nothing, and returns the positions whose record no longer
matches. repair_records() is the scrub’s repair: it writes back each record
that is damaged while its entry is intact, in every segment. That covers the
records of tombstones and of positions a later batch replaced, which no caller
can write again. Each open does the same for the batches before the last one.
A repair writes a whole persist block, and only when the entry of each record
in that block is intact and is the entry its record names. A crash that tears
the write then leaves each record of the block rebuildable from its entry, as
it was before. A block with one damaged entry is not written: its valid record
is the only copy of that entry’s identity. RecordRepair counts the blocks
written and the blocks left.
But a record is only one of the structures with a twin. What about the
metainfo copies, the segment header copies, and the entries themselves? An
open reads each metainfo copy and header copy once, and then never again. An
entry is checked only when the caller reads it. So one rotted metainfo copy
waits, silent, for the next open. If its twin rots first, that open refuses
with MetaLost.
scrub(budget) closes that window, in the manner of TigerBeetle’s grid
scrubber. Each call checks the next run of live positions, at most budget
bytes of entries (and at least one entry), and goes on where the last call
stopped. Each pass starts with the metainfo copies and the header copies: a
copy that differs from the value the open holds is rewritten from it, one
durable write at a time, as a commit writes them. A failed rewrite poisons
the journal, as a failed commit does. Then each entry is checked
for its CRC and its identity, in place, without a copy of its payload. Each
record of the run is checked as verify_records does, and a mismatch runs
repair_records. A damaged entry has no local twin: Scrub::damaged names
it, with its identity, and the caller fetches it from a peer. A position that
the open already found damaged is not read again: the open reported it. The
scrub drops
the page cache of each file before it reads it, so it checks the device and
not a cached copy. Scrub::pass_done says when a pass ends.
Three rules keep recovery’s own writes honest, and the crash loops found
each of them. A fourth keeps them apart from the witness rule: an open never
writes back a rebuilt record of a batch that still has a torn slot no retire
record names. A rebuilt Ordered record is an intact record, which would make
the torn slot corruption if a crash came before the retire batch is durable.
What opening keeps, it syncs, because a process that
restarted without a power loss reads its predecessor’s unsynced writes from
the page cache. What opening reads, the device holds: a commit that failed
because the kernel could not write its pages back (fsyncgate) leaves them
marked clean in the cache, so no sync writes them and a restart would read
the failed batch as written. The next power loss would then show it as
Corrupt, or refuse the open with LostBatch. So an open syncs each file,
then calls StorageFile::drop_cache, before it reads it. A record never
reaches the disk before its entry, so a rebuilt record is written only
after the entries are synced, which that first sync does. What an open
declared the end stays the end: every open bumps an open generation in the
metainfo, and a record a crash left unreadable can never read back later as
evidence.
Testing It Under Chaos::Storage
The integration tests in tests/journal.rs run on SimWorld storage with
StorageConfiguration::fast_local(). One test per row of the recovery table
aims a bit flip with Journal::layout(position), which returns the record
and the entry as two LayoutRegions, each carrying the position as its
stripe. Journal::regions() lists every region a fault could hit, so a
harness aims faults by kind without knowing the format:
let focus = FaultFocus::new()
.background(0.1)
.layout(&journal.regions(), |region| {
if region.kind == Layout::RECORD { 8.0 } else { 4.0 }
});
The crash loops in tests/support/mod.rs commit random batches, cut the
writer off mid-commit with simulate_crash_for_process, sometimes crash
inside recovery itself, rot one persist record while the node is down, run
a scrub (scrub and repair_records) that a crash can cut, and judge every reopen against a ledger of what was
acknowledged and what was in flight. They run under two fault models:
- The paper’s: every unsynced sector ends up old or new, plus clean
crashes and correlated rollbacks (
clean_crash_probability,correlated_rollback_probability,garbage_fill_probability). - Moonpool’s full physics: sectors lost, latent read faults and shorn
writes on top (
crash_lost_probability,crash_latent_fault_probability,shorn_write_probability), with failed syncs and lost directory entries.
Both models also fail writebacks (writeback_error_probability, with each
reporting mode) and sometimes restart the process with no power loss right
after a failed commit. The restart must not read that commit’s batch or
metainfo from the page cache. Before opens dropped the cache, all six loops
failed on this.
The promise is the same under both: nothing acknowledged is lost, changed or
reported damaged, and only a Batched batch in flight may come back
ambiguous. Each model runs for Ordered, Batched and a mode drawn afresh
every round. Floor raises free segments, so crashes land around recycling
and commits roll onto recycled segments; each model asserts that commits
rolled onto a recycled segment and that an open kept a spare. JOURNAL_CRASH_SEEDS raises the seed count and
JOURNAL_CRASH_SEED replays one.
The full simulation is journal.rs in moonpool-sim-examples
(cargo xtask sim run journal). One process owns the journal.
Chaos::Attrition crashes it over and over with prob_wipe: 0.0, since a
wiped disk is data loss no local journal can recover from.
The node runs on two disks in turn. On the faulty disk,
Chaos::Storage(ChaosMode::Random) runs every fault family of the disk
underneath but a failed disk, which never answers again. Rot, EIO,
misdirected and phantom writes are on, and a JournalStrike fault injector
adds the double faults the random families almost never reach: it reads the
Journal::layout of the last acknowledged batch, rots one byte of a record
and one of its entry (or of every record and the first entry), then crashes
the node:
.storage_fault_mask(StorageFaultMask::all().without(StorageFault::DiskFailure))
.fault_factory(|| Box::new(JournalStrike))
Floor raises recycle segments under the crashes, so the run reaches “an open found a recycled spare segment” and “a commit rolled onto a recycled segment”.
The node’s memory dies with it, so what it acknowledged lives in a Ledger
published in the iteration’s StateHandle. A lone node cannot repair rot, so
the check is not “nothing is lost”. It is a reporting oracle: the
journal never hides damage. For each acknowledged (position, id), after
every open, the replay returns the exact payload, or ReadError::Damaged
with that position and that id, or the open refuses with an evidence variant
of OpenError. It never returns other bytes, an older id as the current one,
or nothing. For a write that was not acknowledged, absent, old and new are
all correct; a mixed payload is not. The one exception is the unwitnessed
last batch, which may read as before it:
assert_always!(written, "a position returns only its acknowledged value or one in flight");
assert_always!(at == position && named, "damage names the position and an id written there");
assert_always!(kept, "an acknowledged entry is returned or reported damaged, never forgotten");
The node then plays a replication layer from the ledger, as a peer would: it writes a damaged acknowledged entry again, clears a damaged entry nothing acknowledged, and rebuilds the whole journal when an open refuses. On the code before the witness rule, the oracle failed in a few seeds of every 50: two faults on a recorded last batch were discarded as a torn commit.
The reporting oracle has a blind spot: with rot always possible, every
damage report is plausible, also one the journal caused itself. So the node
runs a second time on an honest disk (Disk::Honest), which keeps only
the families that never change bytes a sync reported durable: crashes with
their torn, lost and shorn sectors, failed syncs and writebacks, short
transfers, lost directory entries and slow disks. Rot, misdirected and
phantom writes, EIO (a read that fails with EIO is the medium failing, and
the journal counts its blocks as damaged) and the strikes are off. Nothing
on this disk explains damage, so the oracle is strict:
assert_always!(disk == Disk::Faulty, "on an honest disk an open never refuses");
assert_always!(
self.disk == Disk::Faulty || !acknowledged,
"on an honest disk an acknowledged entry is never reported damaged"
);
and the unwitnessed last batch is never voided. The honest disk runs 500
seeds for the faulty disk’s 50, and Chaos::BuggifyKnobs spikes the rate of
failed writebacks on some of them.
A failed sync is an operating error, not a verdict: CommitError::Io says
whether the batch may be durable anyway (Durable::Unknown), and the journal
is poisoned. What the node does next is drawn: it opens the journal again in
place, or dies with the page cache kept (RebootKind::KillKeepCache), or
loses power. After the first two, the cache may still hold the batch of a
commit whose writeback failed, and the open must not read it as written
(see “What opening reads, the device holds” above). The run must reach that
state: the binary fails unless the simulator reports “disk: a kill kept
sectors that a failed writeback stranded” on the honest disk. With the
cache drop of the open removed, every run fails in about ten seeds of the
500. The node once crashed itself with a power loss on every I/O error.
The simulation had found this bug, and that change made the seeds pass
without a change to the journal: the simulation then could not see the bug
for a month. JOURNAL_SIM_SEEDS raises the seed count of each disk (a
nightly workflow runs 15,000) and JOURNAL_SIM_SEED replays one seed.
A value that is not a number stops the run, so a mistyped count never
runs the default seeds in its place.
Durable::No is a promise: no byte of the
batch was issued (the commit failed before its first write, for example when
it could not create its next segment). A failed entries write is always
Unknown, because recovery rebuilds a batch from its first entry, so even a
partial write can be live after a reopen. The example checks the promise:
assert_always!(
journal.floor() == floor && journal.meta() == meta.as_slice(),
"a commit that reported Durable::No is never live after a reopen"
);
On a Real Disk
accept_log.rs (cargo run -p moonpool-journal --example accept_log) runs
the same journal on the real filesystem through TokioStorageProvider, in a
temporary directory. A Paxos acceptor stores accepts at their slots in
arrival order with the ballot as identity and its promise as metainfo, then
restarts and replays. Then it flips one byte of an acknowledged accept
behind the journal’s back. Reading it reports the slot damaged with the
ballot its record kept, the acceptor writes a peer’s copy at the same slot,
and a final reopen comes back clean. Nothing in the crate names the
simulator: the provider is the only thing that changes.
Does the provider change the speed? backends.rs answers it. It runs the
same journal on Tokio and on compio, with the same payloads, buffered and
with direct I/O (cargo run --release -p moonpool-journal --features compio-providers --example backends). On a 4-vCPU cloud VM, compio commits
one writer’s small records about 15 to 20% faster. Each Tokio file
operation goes through the blocking pool, which costs about 17 syscalls per
append against 3.5 on io_uring. With 16 journals in flight, Tokio commits
25 to 72% more, because compio runs all 16 on one thread. Recovery
takes the same time on both. The tables, the environment and the caveats
are in
docs/benchmarks/journal-backends.md.
The VM very likely hides most of the cost of a sync, so measure on your own
disk.