This page is the journal's own documentation and code, read when the site builds. The tables of bytes come from the encode functions in format.rs, so they are the format the code writes.
A write-ahead journal that implements CLSTORE, the local storage layer of Protocol-Aware Recovery for Consensus-Based Storage (Alagappan et al., FAST ‘18).
The journal detects damage, tells a crash apart from corruption, and names what was damaged. A replication layer can then repair the damaged entry from its peers. It does not have to truncate the log.
A plain log that finds a bad checksum usually truncates there. That is correct for a torn write at the tail. It is wrong for an acknowledged entry that rotted: truncation can erase committed data across the whole cluster. CLSTORE keeps the identity of every entry in a persist record far from the entry. When the entry fails its checksum, the record proves that it was written and says which entry it was.
The journal uses only moonpool’s local provider traits
(LocalStorageProvider), which
every Send provider also implements. The same code runs over
TokioStorageProvider in production, over CompioStorageProvider on a
thread-per-core runtime, and over the simulator’s SimStorageProvider in
tests. Over a Send provider the journal and its futures are Send. It knows no protocol: an entry is a u64
position and an opaque Id that the caller chooses. A Paxos
acceptor stores its ballot in the Id, a Raft log stores its term.
The files
<dir>/meta metainfo copy A (block 0) and copy B (block 16)
<dir>/seg-<first batch>.wal allocated segments:
header A | persist log | guard gap | entry log | header B
<dir>/spare-<gen>-<n>.wal a dead segment's file, or one allocated ahead,
kept for a later roll
A spare is never evidence: no batch is written to it before it is
renamed to a segment, and the batches it still holds are older than any
it will hold. An open keeps up to JournalConfig::spares whole spares
and deletes the others (Recovery::spares_removed), and never keeps a spare whose header names
a listed segment: a crash in a roll left it as a second name of that
segment.
The meta file is separate because it is the one structure rewritten in
place, and it must outlive every segment (LogCabin, canonical/raft and
hashicorp/raft-wal keep it apart too). Each segment holds two
append-only logs:
- persist records of
RECORD_SIZEbytes: kind, position, id, and the entry’s offset, length and CRC (CLSTORE’s identifier and persist record in one); - entries: a 64-byte header that repeats the record’s identity, then
the payload. The header has its own CRC, and holds the payload’s CRC
and a stamp, the metainfo
seqit was written under.
Every batch starts on a fresh BLOCK in both logs, so a commit never
touches a sector that holds acknowledged data. The one exception is a
record repair (RecordRepair): it writes a persist block again only
when the entry of each record in it is intact, so a crash that tears the
write leaves each record rebuildable. A segment header links to the last
batch before it, so the journal never reads a missing segment as the end
of the log. Geometry::default is a 64 MiB segment;
Geometry::small rolls over quickly for tests and simulation.
- header A 1
- persist log 7936
- guard gap 512
- entry log 7936
- header B 1
- header A 1
- persist log 8
- guard gap 0
- entry log 16
- header B 1
The shape of every segment file: the persist log, a guard gap that keeps identifiers physically away from entries, and the entry log.
The two header copies are at the two ends of the file, so one fault that reaches a run of blocks (a misdirected write, a bad stretch of the medium) never reaches both.
Each persist block holds 64 records of 64 bytes. The meta file is 17 blocks: copy A in block 0, copy B in block 16, zeros between them.
Segments
One segment file: allocated whole, header copy A, the persist log, the
entry log, and header copy B in the last block (see Geometry).
A segment is created whole under a temporary name and published by a
rename (Segment::create), or adopted from a spare, a dead segment’s
file, whose headers are synced before the rename (Segment::adopt),
so a segment file either does not exist or has its full size and both
headers. It never changes size again. Both logs only ever append, and
every batch starts on a fresh block in each, so no commit ever touches a
sector holding an acknowledged record or entry. (A record repair writes a
persist block again, but only when each record in it can be rebuilt from
its intact entry: see crate::RecordRepair.) A recycled file’s old
batches are older than its first batch: the scan reads them as stale
(see crate::spare).
Byte by byte
Every integer is little-endian. Every structure ends with a CRC32C of what comes before it.
The persist record
One persist record (CLSTORE’s identifier and persist record in one): far from its entry, it says the entry was written and which one it was.
| at | bytes | field | what it holds |
|---|---|---|---|
| 0 | 1 | kind | 1 Put: An entry at a position. 2 Clear: A tombstone over position..end; end rides in the id's first word. 4 Retire: A retired slot of an earlier batch: torn by a crash, or dead with a damaged entry. |
| 1 | 1 | flags | The batch's flags. Bit 0: the batch was committed Ordered. |
| 2 | 2 | index | Index of this record within its batch. |
| 4 | 4 | len | Payload length. |
| 8 | 8 | batch | The batch number. Its high bits above bit 40 are the open generation that wrote it, so a number never repeats across opens. |
| 16 | 8 | position | The caller's position: where the entry sits in the log's space. |
| 24 | 4 | offset | Where the entry starts, from the start of the segment file. |
| 28 | 4 | entry_crc | The entry header's CRC: the entry this record names, exactly (the header holds its payload's CRC). |
| 32 | 24 | id | The caller's 24-byte identity of the entry (a ballot, a term). A Clear carries the end of its range in the first 8 bytes. |
| 56 | 2 | count | Records in its batch. |
| 60 | 4 | crc | CRC32C of every byte before it. |
The entry
The header in front of every entry’s payload: the entry’s own identity, so a stale or misdirected entry never passes for the one a record names, and an intact entry can rebuild a lost record whole.
The header has its own CRC, apart from the payload’s. An intact header with a damaged payload still proves which entry was written there, and how long it is, so the walk of the entries goes on past it.
The header CRC covers bytes 0..60 and starts from the journal’s tag, so an entry of another journal never reads as intact.
| at | bytes | field | what it holds |
|---|---|---|---|
| 0 | 4 | len | The payload's length. |
| 4 | 2 | index | This entry's index in its batch: the same as its record's. |
| 6 | 2 | count | The records in its batch. |
| 8 | 8 | batch | The batch number. Its high bits above bit 40 are the open generation that wrote it, so a number never repeats across opens. |
| 16 | 8 | position | The caller's position: where the entry sits in the log's space. |
| 24 | 1 | kind | 1 Put: An entry at a position. 2 Clear: A tombstone over position..end; end rides in the id's first word. 4 Retire: A retired slot of an earlier batch: torn by a crash, or dead with a damaged entry. |
| 25 | 1 | flags | The batch's flags. Bit 0: the batch was committed Ordered. |
| 26 | 6 | stamp | The low 48 bits of the metainfo's `seq` when the batch was written ([`stamp_of`]): a metainfo that reads back older than a stamp lost an update. |
| 32 | 24 | id | The caller's 24-byte identity of the entry (a ballot, a term). A Clear carries the end of its range in the first 8 bytes. |
| 56 | 4 | payload_crc | CRC32C of the payload. |
| 60 | 4 | crc | CRC32C of the 60 bytes before it, started from a CRC32C of the journal's id: an entry of another journal never passes for ours. The entry's persist record holds the same value. |
A batch on disk
A batch of n records takes the next ⌈64·n / 4096⌉ blocks of the persist log: record i at byte 64·i of them, the rest of the last block zeros. Its entries go back to back from the next free block of the entry log, each one 64 bytes of header, then the payload, padded to a multiple of 8. The next batch starts on a fresh block in both logs. A record's offset, len and entry_crc name its entry exactly, and the entry's header repeats the record's identity: either one can find and check the other.
The segment header
| at | bytes | field | what it holds |
|---|---|---|---|
| 0 | 4 | magic | "MPJS" in ASCII: what this structure is. |
| 4 | 2 | version | The format version, 6 today. |
| 8 | 16 | journal | The journal's id: a segment of another journal is never read as ours. |
| 24 | 8 | first_batch | The first batch it was created for (and is named after). |
| 32 | 4 | persist_blocks | Blocks in the persist log: 64 records each. |
| 36 | 4 | gap_blocks | Blocks of zeros between the persist log and the entry log. |
| 40 | 4 | entry_blocks | Blocks in the entry log. |
| 44 | 8 | prev_batch | The last batch of the log when it was created: the link to the segment before it, so a missing segment is never read as an end. |
| 52 | 4 | crc | CRC32C of every byte before it. |
The rest of the block is zeros. Both copies hold the same bytes.
The metainfo
The meta file: CLSTORE’s metainfo, in two checksummed copies far apart in one file.
The copies are written one after the other, each followed by a sync,
and only once the commit’s batch is durable. At most
one copy is ever in flight, so a crash tears at most the one being
written, and after a complete write both hold the same value, so a single
rotted copy never rolls the metainfo back (LogCabin and canonical/raft
alternate between their copies instead, which costs one write per update
and loses that guarantee).
Opening picks the valid copy with the higher sequence number and rewrites
the other from it; two valid copies of one sequence that disagree are
damage, and so are two damaged copies: OpenError::MetaLost.
| at | bytes | field | what it holds |
|---|---|---|---|
| 0 | 4 | magic | "MPJM" in ASCII: what this structure is. |
| 4 | 2 | version | The format version, 6 today. |
| 6 | 1 | copy | Which copy this is: 0 for A, 1 for B. A copy read in the other's place fails. |
| 8 | 16 | journal | The journal's id. |
| 24 | 8 | seq | Bumped by every metainfo write; the higher of two valid copies wins. |
| 32 | 8 | floor | Positions below this are gone. |
| 40 | 8 | last_batch | The highest batch durable before this copy was written: a log that ends below it lost its tail. |
| 48 | 4 | persist_blocks | Blocks in the persist log: 64 records each. |
| 52 | 4 | gap_blocks | Blocks of zeros between the persist log and the entry log. |
| 56 | 4 | entry_blocks | Blocks in the entry log. |
| 64 | 8 | open_last | The last batch that open found. A record of an older generation numbered above it was invisible to that open (torn, or a latent sector) and the log moved on: it is garbage if it ever reads back. |
| 72 | 4 | open_generation | The generation of the last open, which every open bumps durably before it writes anything. |
| 76 | 4 | len | The length of the caller's bytes. |
| 80 | 8 | ambiguous | The first batch whose damaged entries a crash may explain (0: none): an open found an entry of it damaged beside a valid record, in a `Batched` batch that nothing had witnessed, and no batch of the caller has committed since. Every batch from it on is judged as unwitnessed for that damage, whatever the high-water mark says: the opens' own batches and mark raises are not the caller's. |
| 88 | 4004 | bytes | The caller's metainfo bytes. |
| 4092 | 4 | crc | CRC32C of every byte before it, in the last 4 bytes of the block. |
Committing
Durability picks the protocol:
| Mode | Protocol | Syncs |
|---|---|---|
Batched (the paper’s) |
write(entries); write(records); fsync |
1 |
Ordered |
write(entries); fsync; write(records); fsync |
2 |
The protocol is recorded per batch, so it may change between opens. When
a batch changes the metainfo (with Batch::set_meta or a floor raise),
the journal writes it only after the batch’s last sync: copy A, sync,
copy B, sync. At most one copy is in flight at a time. A crash can leave a
batch durable without its metainfo, but never the metainfo without its
batch. The caller may therefore put in the metainfo anything that is true
only once the batch is on disk.
A failed commit poisons the journal: CommitError::Io says through
Durable whether the batch may be on disk anyway, and the caller
reopens. A commit future dropped before it returns (a timeout, a losing
select! branch) is a failed commit too: the journal stays poisoned from
the commit’s first await until memory follows the disk, so a dropped
commit never lets the next one write the same batch number over a batch
that is partly on disk.
The commit's writes, from journal.rs. The hint! lines name the moments where a simulation may crash the process:
async fn write_protocol<F: moonpool_core::LocalStorageFile>(
segment: &Segment<F>,
meta_file: &MetaFile<F>,
batch: &mut Prepared,
meta: Option<&Meta>,
ordered: bool,
) -> Result<(), (std::io::Error, Durable)> {
let unknown = |error| (error, Durable::Unknown);
let entries = std::mem::take(&mut batch.entries);
let records = std::mem::take(&mut batch.records);
if ordered {
// Each log's write is durable on return, entries first: two durable
// writes where a write and a sync each were four calls. A durable
// write covers its own blocks only, which is the whole barrier here:
// every earlier write to this segment is durable (each commit's
// writes are before it returns, open syncs every segment, a roll's
// headers are written durably, and a failed commit poisons the
// journal), and data-only durability suffices because a segment
// never changes size. The windows inside each write (bytes landed,
// not yet durable) are the storage layer's to name.
// A failed write can still have landed some bytes, and a failed
// durable write can have landed all of them: recovery rebuilds a
// batch from its first entry, so the batch is not known absent.
batch.entries = segment
.write_durable(batch.entry_at, entries)
.await
.map_err(unknown)?;
batch.records = segment
.write_durable(batch.persist_at, records)
.await
.map_err(unknown)?;
} else {
// One barrier for both logs: it must cover the entries too, which a
// durable write of the records alone would not.
batch.entries = segment
.write(batch.entry_at, entries)
.await
.map_err(unknown)?;
// 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
.map_err(unknown)?;
// The commit's window: a power loss here may tear the records,
// rebuild them from their entries, or leave the last batch
// ambiguous.
moonpool_buggify::hint!(
"journal commit: records written, not synced",
COMMIT_HINT_PROB
)
.await;
sync_batch(segment, batch).await.map_err(unknown)?;
}
if let Some(meta) = meta {
// The batch is durable and the metainfo still names the old one.
moonpool_buggify::hint!(
"journal commit: batch synced, metainfo stale",
COMMIT_HINT_PROB
)
.await;
meta_file.update(meta).await.map_err(unknown)?;
}
Ok(())
}Reads and EIO
Block I/O over owned, aligned buffers, and block reads that treat a failing medium as damaged bytes, CLSTORE’s treatment of EIO: the block is zero-filled, so whatever lived there fails its checksum and goes down the one detection path.
Every write and read here moves an AlignedBuf through
BlockFile’s zero-copy methods: the journal encodes a batch, a header
or the metainfo straight into the buffer the kernel transfers, and a
direct-I/O segment never copies it on the way.
Recovery
Opening reads the persist records and judges each one (last is the
last batch in the log). The last segment is read whole. A sealed segment
ends at the batch that the next segment’s header names: opening reads its
persist log only up to that batch, and a record past it is not part of
the segment.
| Entry | Persist record | Verdict |
|---|---|---|
| intact | valid | live |
| intact | damaged | live; the record is rebuilt from the entry, and written back before last |
| damaged | valid | State::Corrupt, or State::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, in an unwitnessed last batch of its open generation | torn by a crash: discarded and retired |
| payload damaged, header intact | damaged, in a witnessed batch, or before the last of its generation | State::Corrupt: the header names the entry; its record is never written back; replaced by a later batch, it is retired, not reported |
| header damaged | damaged, in a witnessed batch, or before the last of its generation | OpenError::DoubleFault: refuse to open |
A retire record names a slot of an earlier batch that holds nothing
the caller needs: a slot a crash tore, or the dead slot of a position
that a later batch replaced, cleared or dropped while its entry was known
damaged. Like a tombstone, it has a persist record and an entry, so one
fault on it is rebuilt. It carries the offset where the entry walk goes
on after the slot, so an intact entry behind a retired slot is found
again. An open that finds torn slots starts its new generation without
raising the high-water mark, commits one retire batch for them, and the
mark records that batch once it is durable: a crash anywhere in that
open leaves the slots judged the same way at the next one. A commit that
makes dead a slot whose entry is damaged (State::Corrupt, or a read
that returned ReadError::Damaged) retires it in a batch of its own,
written once the commit’s batch is durable. Never in the same batch: a
crash can tear that batch’s put and keep its retire record, and the open
would discard the put as torn and ignore the old slot, the only copy of
an acknowledged entry.
A batch is witnessed when something other than its own two damaged
parts proves it durable: the metainfo’s high-water mark records it (a
commit that changed the metainfo records its own batch, and every open
records the last batch it found once nothing in it is left to retire), or
it is an Ordered
batch with an intact record, whose entries were durable before any
record was written. A crash in the middle of a commit cannot leave a
witnessed batch with a slot whose record and entry are both damaged, so
there that is corruption, not a crash. In a witnessed batch, an entry
that is damaged while its record is valid is State::Corrupt too,
except one that an open already found damaged that way while the batch
was not witnessed: the metainfo names the first such batch, and its
entries stay State::Ambiguous until the caller commits a batch with a
write. An open’s own mark raise and retire batch witness the batch’s
intact slots, not the entry the crash had already torn.
Only the last batch of an open generation can be torn by a crash, because
a failed commit poisons the journal. The one batch that may still be
discarded is an acknowledged last batch that nothing witnesses: its bytes
look exactly like a torn commit.
An entry header has a CRC of its own, apart from its payload’s, so an
intact header with a damaged payload still names its entry and its
length. Three rules keep that from hiding a crash. In an unwitnessed last
batch it is still torn: a commit writes the header and the payload in one
write, and a crash can keep one without the other. A record is never
rebuilt from a header alone, because the header proves nothing of the
payload. And an Ordered batch is witnessed only by an intact record,
never by a header. A batch whose records are all damaged is located from
its first entry’s header, payload or not.
A record that the scan finds at a batch boundary but that names an entry other than the first entry of that boundary was written to the wrong block (a misdirected write): the open reads it as damaged and locates the batch from its first entry.
A batch missing while later ones exist, or a log that ends before the
batch the metainfo proves durable, is OpenError::LostBatch. 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: an open’s retire batch that the disk lost, say,
whose entry sat over the slot it discarded. A batch of
a later open generation than the metainfo’s proves the metainfo older
than the log (both copies lost an update): OpenError::MetaRolledBack.
Inside one open generation, the stamps tell: an intact entry header
stamped with a later metainfo seq than the one that reads back proves
that the metainfo lost an update (OpenError::MetaUpdateLost). A batch
is stamped with the metainfo that is durable when it is written, so the
batch that carries a metainfo update holds the stamp before it, and a
crash before the update leaves nothing ahead. The open checks the stamps
of the entries it reads: the last batch, and the entries that rebuild a
record or locate a batch. A batch
number holds the open generation in its high 24 bits and the count in
its low 40 bits: an open after generation 2^24 - 1 refuses
(OpenError::InvalidConfig), and a commit after 2^40 - 1 batches in
one open refuses (CommitError::BatchNumbersExhausted) before it
writes; a reopen starts a new generation. A medium
error reads as damaged bytes (CLSTORE’s treatment of EIO). A damaged or
missing file is a crash (OpenError::BadSegment,
OpenError::MetaLost). An intact metainfo or segment header written
by another version of the crate is not damage: it is
OpenError::UnsupportedVersion, because each checksum covers the
version field. Opening reads only the last batch’s entries; the
journal checks the rest when they are read (Journal::read,
Journal::replay). Opening syncs what it keeps before it returns,
and reads only what the device holds: it syncs each file, then drops its
cached pages, before it reads it (on Linux: see
StorageFile::drop_cache). A
commit that failed because the
kernel could not write its pages back (fsyncgate) leaves them marked
clean in the page cache, where a restart without a power loss would
otherwise read them as written.
The scan
Opening’s scan: CLSTORE’s detection, disentanglement and identification over the persist log and the entry log of every segment.
Pass 1, structure. Each segment’s persist log is parsed batch by
batch. A batch starts on a block; every record names its batch, its index
and the batch’s record count, so any one valid record locates its whole
batch. A batch with no valid record is found through its first entry (an
entry carries the same fields). A damaged record is matched with its
entry by walking the entry log: entries are packed back to back inside a
batch, and each batch’s entries start on the block after the last one’s.
A batch missing while later records exist is OpenError::LostBatch,
never an end; the persist log ends at the first block boundary after
which nothing valid follows. A record or entry of a batch older than its
segment is stale, not valid: a recycled file’s old bytes (see
crate::spare) read like never-written ones.
The rule of position. In one segment, batch numbers grow with the
place in the persist log. A valid record at or after the boundary the
scan is at, whose batch is not above the last batch found so far, is
old bytes too: it cannot prove that a batch is missing. (Known::is_stale
still covers old bytes exactly at the end of the log.)
A record at its own place. The first record of a batch names the first entry of the batch, and the scan knows where the entries of each boundary start. A first record that names another offset was written to the wrong block (a misdirected write): it reads as damaged, and the batch is located from its first entry.
Retired slots. A retire record (Retire) names a slot of an
earlier batch whose record may be lost: a slot a crash tore, or a dead
slot whose entry is damaged. It carries the offset where the entry walk
continues after that slot, so an intact entry behind a retired slot is
found again. The retire records come after their slots in the log, so
pass 1 runs again with them when it needs them: when a lost slot breaks
the walk of the slots after it, or when a batch whose first slot is
retired cannot be located (pass_one_retired).
Pass 2, verdicts (the table in the crate docs). A lost slot that a retire record names is ignored. Only the last batch and damaged records cost entry reads: the rest of the log is checked when it is read.
What the metainfo proves. Its high-water mark (Known::mark) is a
batch known durable: a slot of a batch at or below it whose record and
entry are both damaged is corruption, never a crash. Its open generation
(Known::generation) is above every batch number written so far: a
batch of a later generation proves the metainfo older than the log
(OpenError::MetaRolledBack).
Spares and recycled segments
The spare segment: a dead segment’s file, kept for the next roll instead of deleted, so a roll is a header write and a rename, with no byte of a new file written or allocated (PostgreSQL recycles its WAL segments the same way).
When the floor or later writes leave the front segment with nothing live,
the journal renames it to spare-<generation>-<n>.wal and syncs the
directory, if it keeps fewer spares than
JournalConfig::spares; else it deletes
it. The file keeps
its full size, its old header and its old batches, all durable. A roll
writes the new header into the spare, syncs it, renames it to its
segment name and syncs the directory
(see Segment::adopt).
Old bytes are stale, never evidence. A segment named after its first batch only ever receives batches at or above that number, and batch numbers never repeat (the open generation is in their high bits). Every batch a recycled file still holds is older than the segment it becomes, so its records and entries read as stale bytes, like never written ones, and recovery’s verdicts stay those of the crate docs.
A spare holds no batch of its own: no batch is written to it before its
rename. An open keeps up to spares whole spares it finds and deletes
the others.
A crash can leave one file two names. A rename whose directory sync did not happen may keep the old name, the new one, or both. Both is one file behind a spare’s name and a segment’s: a roll onto that spare would write into a live segment. So an open reads each spare’s header and deletes a spare that names a segment the directory lists. A real spare never does: a dead segment’s name is gone once it is a spare, and no later segment takes its first batch.
A spare can also be allocated ahead of a roll
(Journal::prepare_spares): a new file
of a whole segment’s size under a temporary name, synced, then renamed to
a spare name and the directory synced. Its headers read as zeros: no
header, so it names no segment and holds no batch. A crash leaves the
temporary name, which every open deletes, or a whole spare. The journal
keeps at most JournalConfig::spares
spares of either kind.
With no spare, a roll creates its segment with
allocate: the space is
reserved, reads as zeros, and nothing is written but the headers.
How it is tested
examples/accept_log.rs: a Paxos acceptor on the real filesystem finds one rotted accept, with its ballot, and repairs it.examples/bench.rs: commit throughput, latency percentiles and fairness on the real filesystem, per writer count, record size, batch size andDurability.tests/journal.rs: one test per row of the recovery table, aimed withJournal::layout, plus crash loops under two fault models.moonpool-sim-examples/src/journal.rs: the journal in a full simulation, one node crashed over and over by attrition.
The crash model behind these tests is the simulator's: Storage faults shows what a crash does to each sector written after the last sync.