Skip to main content

mira_core/
wal.rs

1//! The write-ahead log, which exists to decouple the acknowledgement from the
2//! seal.
3//!
4//! # Why this exists, given `docs/architecture/ingest.md` section 4 says "No WAL"
5//!
6//! section 4's argument is about *recovery*, and it is still correct: a block
7//! directory is renamed into place atomically, so there is no torn state and
8//! nothing for a log to replay. This log is not for recovery. It is for
9//! latency.
10//!
11//! Before it, an export was acknowledged only after the block *containing it*
12//! was durably published, so under light load the caller waited out
13//! `max_block_age` — a measured p50 of 657 ms and p99 of 2,647 ms (section 11). The
14//! block is sealed on a timer because nothing else bounds how long a
15//! half-filled block sits there, and that timer became the caller's latency.
16//! With the log in front, the seal triggers are unchanged and nobody is waiting
17//! on them: `max_block_age` goes back to being a statement about the shape of
18//! blocks on disk rather than a latency bound.
19//!
20//! # The durability this buys, stated precisely
21//!
22//! An append is acknowledged once `write(2)` has returned — the bytes are in
23//! the kernel's page cache, not on the platter. That survives everything that
24//! kills the *process*: a panic under `panic = "abort"`, SIGKILL, the OOM
25//! killer, a flusher that took the process down with it (section 1). It does **not**
26//! survive power loss or a kernel panic, because the page cache does not.
27//!
28//! This is a deliberate choice and it is the reason there is no `fsync` on the
29//! acknowledgement path. On the machine section 11 was measured on, one
30//! `F_FULLFSYNC` costs 4,230 us, so a durably-fsynced ack could not have a p50
31//! below 4.2 ms, let alone a p99 under 5 ms. The same trade is Kafka's
32//! `acks=1` and ClickHouse's default. [`Wal::sync`] exists and is called on a
33//! timer by a background task, which bounds how much is exposed to a power cut
34//! to one sync interval — it is never called by an appender.
35//!
36//! There is deliberately no userspace buffering. A `BufWriter` would batch the
37//! syscalls, but bytes sitting in a `Vec` in this process do not survive the
38//! process dying, which is exactly the failure this log is claiming to cover.
39//! That argument still holds and is the reason a buffer is not the fix below.
40//!
41//! # The append rate is not the ceiling; the serialised section is
42//!
43//! This paragraph used to finish the one above by pricing the syscall: one
44//! `write(2)` per export "at a few tens of microseconds", against 188 appends
45//! per second at the thirty-two-connection plateau, and concluded that "three
46//! digits of appends per second is not a rate a syscall per append can be the
47//! ceiling of". Measured, it is off by two orders of magnitude and it was the
48//! wrong quantity.
49//!
50//! [`crate::diag`] times the wait and the hold separately. At the plateau
51//! `wal.write` means 2.1–2.6 ms, not tens of microseconds, and `wal.held` —
52//! the whole critical section — means 2.2–3.0 ms, of which the write is ~95%.
53//! At 250–330 appends/s that is 73–78% occupancy of **one** mutex shared by
54//! all three signals and every shard, and `wal.lock_wait` is 77–89% of the
55//! whole of `submit` in every configuration measured. The arithmetic above
56//! omitted hold time and the fact that the lock is global, which together are
57//! the entire effect.
58//!
59//! Two consequences worth stating plainly. `Mutex` here resolves to the pthread
60//! backend, so a contended `lock()` parks the OS thread in the kernel — a
61//! parked tokio worker runs no other task and is not replaced, which is why
62//! `wal.inflight_max` comes out equal to the worker count exactly, and why a
63//! task that only sleeps 50 ms returns 110 ms late at 96 connections. And
64//! adding workers does not help: 12 to 48 moved throughput 2% and multiplied
65//! `wal.lock_wait` by six, because the ceiling is the serialised section rather
66//! than scheduling capacity.
67//!
68//! # …but the serialised section is not the ceiling either
69//!
70//! The paragraph above says where the time goes and it is right. It was then
71//! read as saying what the *rate* is, and that does not follow: a queue forms at
72//! whatever is slowest to acquire, which need not be what is slowest to finish.
73//! Both fixes it proposed were priced before either was believed.
74//!
75//! One log per signal was built, measured against the binary it replaces, and
76//! **rejected**: nine paired passes at 4/32/96 connections across three
77//! sittings, records/s signs split at every shape. It moves `wal.lock_wait` —
78//! 0.63x at four connections, 0.795x at thirty-two — and gives the whole of it
79//! back in `wal.write`, 1.94x and 2.39x at thirty-two and ninety-six with all
80//! nine passes agreeing. The volume does not absorb a second appender: two
81//! concurrent writers at this frame size return 0.98x the aggregate bandwidth of
82//! one and three return 0.86x, measured with no Mira code in the loop. The diff
83//! is kept on the `wal-per-signal` branch rather than deleted.
84//!
85//! Group commit needs no separate arm, because the *envelope* was measured
86//! directly: put the log on a RAM disk, change nothing else, and `wal.write`
87//! falls 89% to 0.245 ms, `wal.held` 83% to 0.395 ms and `wal.lock_wait` 93% to
88//! 1.245 ms — the serialised section effectively deleted — for **1.096x at
89//! thirty-two connections (3 of 3 passes) and 1.005x at ninety-six, signs
90//! split**. A perfect log fix is worth ten percent at one shape and nothing at
91//! the other, and group commit writes the same bytes down the same fd.
92//!
93//! What that run shows instead is where the queue re-forms once the log is free:
94//! `submit.admit`, 0.000–0.002 ms in the disk-backed dumps and ruled out there
95//! on that basis, becomes **44.05 ms of a 47.91 ms `submit.total`, 92%**. Admission
96//! blocks when no flusher queue slot frees, so the constraint behind the log is
97//! the block seal and publish path — the same device, writing Arrow IPC.
98//!
99//! ponytail: one global log with one mutex. The ceiling that matters is not
100//! this file's: `wal.lock_wait` is the largest term in `submit` and still worth
101//! ~10% at most, so the upgrade path here is bytes — the re-encode below is 790
102//! KiB a frame and compressing or eliding it is the only lever with room — and
103//! the upgrade path for *ingest* is the flusher, not the log. Do not re-propose
104//! group commit or a log per signal without a number that contradicts the two
105//! paragraphs above; see `docs/architecture/performance.md` section 11.
106//!
107//! # The frame is the OTLP request, in its canonical protobuf encoding
108//!
109//! Not the bytes off the wire. Mira has three ways in — gRPC, protobuf over
110//! HTTP, and KYAML over HTTP — and only one of them still has bytes by the time
111//! anything could log them: tonic decodes before the handler is called, and a
112//! KYAML body is not protobuf at all. So the frame body is `encode_to_vec` of
113//! the decoded request, which normalises all three transports to one format
114//! with one decoder on the replay side.
115//!
116//! That costs a re-encode. Measured on an 8,192-record log export (1.29 MiB):
117//! encode 1.49 ms at 864 MiB/s, against the decode already in the path at
118//! 5.29 ms and 244 MiB/s. section 11 measured the whole engine at 190.6 MiB/s, a
119//! 6.8 ms budget for that export, so the log adds about 22%. The alternative — a
120//! custom tonic `Codec` to keep the wire bytes — buys that 22% back for a codec Mira
121//! then owns forever, which is the wrong side of principle 1's trade until
122//! something measures it as the bottleneck.
123//!
124//! Replay feeds the decoded frame through the same `ingest::{logs,traces,
125//! metrics}` the network path calls, so there is no second decode path to
126//! write, to test or to keep in step with the first.
127//!
128//! ```text
129//! ┌────────┬─────┬────────┬─────┬─────────┬────────┬──────────┬────────┐
130//! │ magic  │ ver │ signal │ pad │ seq     │ len    │ body     │ crc32  │
131//! │ 4 B    │ 2 B │ 1 B    │ 1 B │ 8 B     │ 4 B    │ len B    │ 4 B    │
132//! └────────┴─────┴────────┴─────┴─────────┴────────┴──────────┴────────┘
133//!  └──────────────── covered by the CRC ──────────────────────┘
134//! ```
135//!
136//! The CRC covers the header as well as the body, so a corrupted length is
137//! caught by the checksum rather than by whatever it would otherwise index
138//! into. That is the same lesson as the block footer: a length read out of a
139//! file is attacker-controlled-equivalent, and validating it against the file's
140//! real extent is not optional.
141//!
142//! # Recovery, and why there is still no manifest
143//!
144//! Replay needs exactly one fact — which frames are already inside a published
145//! block — and the block directory carries it, so principle 4 survives intact.
146//! Block names gain a fifth field, `wal_hi`: an *exclusive* watermark, meaning
147//! every sequence of that signal below it is inside some published block. It is
148//! not this block's own maximum, because sibling shards are filling their own
149//! blocks from the same log — it is what [`Wal::watermark_for`] answers, the
150//! lowest still-unpublished sequence this block does not hold, or one past
151//! everything the log has handed out when this block holds them all. Boot
152//! recovery therefore stays what section 4 says it is: a `readdir`, the same
153//! one the read path already does, with no extra I/O and no
154//! metadata store to keep consistent. Each signal keeps its own watermark, and
155//! that costs nothing because an OTLP export belongs to exactly one signal —
156//! `/v1/logs`, `/v1/traces` and `/v1/metrics` are three endpoints.
157//!
158//! # What this breaks, and what pays for it
159//!
160//! Read-your-writes. section 11 notes it was free, and it was free *because* the ack
161//! waited for the publish — the same rename made the data durable and visible
162//! at once. A caller acked here and querying immediately would not see its data
163//! until the block seals, which is a latency the log was built to remove.
164//!
165//! The repair is the open-block query surface: [`crate::query::search_open`]
166//! takes the flusher's in-progress builder as a snapshot and scans it alongside
167//! the sealed blocks, so read-your-writes holds with the log on or off. It is
168//! not free — that snapshot is the one allocation the read path makes — and
169//! section 7.6 is why it is paid there rather than in the scan.
170
171use std::collections::BTreeSet;
172use std::fs::{self, File, OpenOptions};
173use std::io::{Read, Write};
174use std::os::fd::AsRawFd;
175use std::path::{Path, PathBuf};
176use std::sync::Mutex;
177
178use crate::error::{Error, IoContext, Result};
179
180/// `MIRAWAL0`, truncated. Present so a stray file in the WAL directory is
181/// rejected by name rather than parsed as a frame.
182const MAGIC: u32 = 0x4d_57_41_4c; // "MWAL"
183
184/// Bumped when the frame layout changes. A reader that does not recognise a
185/// version refuses the segment rather than guessing at its shape, which is the
186/// same rule the block format follows.
187pub const WAL_VERSION: u16 = 1;
188
189const HEADER_LEN: usize = 20;
190const CRC_LEN: usize = 4;
191
192/// The largest frame that will be written or believed on read.
193///
194/// This is not a tuning knob, it is a bound on trust. `len` is four bytes read
195/// out of a file that may have been corrupted, and without a ceiling a garbage
196/// value asks for an allocation of up to 4 GiB before the CRC that would have
197/// caught it has been checked. 64 MiB is four times the default
198/// `ingest.max_request_bytes`, so it cannot refuse a frame the ingest path
199/// would have accepted.
200const MAX_FRAME_BYTES: u32 = 64 << 20;
201
202/// Roll to a new segment past this size. Segments are the unit of deletion, so
203/// this trades how much dead log is retained past its watermark against how
204/// many files the directory holds. At section 11's measured 190.6 MiB/s a segment
205/// is about a third of a second of ingest.
206const SEGMENT_BYTES: u64 = 64 << 20;
207
208/// Which signal a frame belongs to.
209///
210/// Stored as one byte rather than the string the block directories use,
211/// because a frame header should be fixed-width — a variable-length field in
212/// front of a length field is how a parser gets confused about where the body
213/// starts.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
215#[repr(u8)]
216pub enum Signal {
217    Logs = 0,
218    Traces = 1,
219    Metrics = 2,
220}
221
222impl Signal {
223    /// The three, in the order their watermarks are indexed.
224    pub const ALL: [Signal; 3] = [Signal::Logs, Signal::Traces, Signal::Metrics];
225
226    /// The directory name `block::publish` uses for this signal. Kept in step
227    /// with the strings the block layer already writes; a mismatch here would
228    /// put a watermark on the wrong signal's blocks.
229    pub fn as_str(self) -> &'static str {
230        match self {
231            Signal::Logs => "logs",
232            Signal::Traces => "traces",
233            Signal::Metrics => "metrics",
234        }
235    }
236
237    /// The inverse of [`Signal::as_str`], so a caller holding a
238    /// [`crate::signal::SignalBuilder`]'s `SIGNAL` does not have to keep a
239    /// fourth copy of the mapping in step with the other three.
240    pub fn named(s: &str) -> Option<Signal> {
241        Signal::ALL.into_iter().find(|sig| sig.as_str() == s)
242    }
243
244    fn from_u8(b: u8) -> Option<Signal> {
245        match b {
246            0 => Some(Signal::Logs),
247            1 => Some(Signal::Traces),
248            2 => Some(Signal::Metrics),
249            _ => None,
250        }
251    }
252
253    /// Where this signal's watermark sits in [`Watermarks`].
254    pub fn index(self) -> usize {
255        self as usize
256    }
257}
258
259/// One past the last published sequence, per signal, indexed by
260/// [`Signal::index`]. Assembled from the block directory listing at boot; see
261/// the module docs.
262///
263/// Exclusive rather than inclusive on purpose. An inclusive "highest published
264/// sequence" has no value that means *nothing published*: zero is a real
265/// sequence, so the empty state and "sequence 0 is durable" are the same
266/// number, and the first export after every restart is silently dropped from
267/// the replay. Exclusive makes the empty state `0` and needs no sentinel.
268pub type Watermarks = [u64; 3];
269
270struct Inner {
271    file: File,
272    path: PathBuf,
273    /// Bytes written to the current segment, tracked rather than `stat`ed so
274    /// the roll check costs nothing.
275    written: u64,
276    /// The next sequence to hand out. Monotonic across segments and restarts.
277    next_seq: u64,
278    /// Set by `append`, cleared by `sync`. Without it a quiet server syncs an
279    /// unchanged file on every tick, which on macOS is a 4 ms barrier bought
280    /// for nothing.
281    dirty: bool,
282    /// Every sequence this log has handed out that no block has published yet,
283    /// per signal, indexed by [`Signal::index`].
284    ///
285    /// This is what makes more than one flusher per signal safe. A block claims
286    /// a watermark by name and [`crate::block::wal_watermarks`] takes the
287    /// maximum, which is only sound if frames reach blocks in sequence order —
288    /// see [`Wal::append_then`]. Shard a signal's flusher and they no longer
289    /// do: shard 1 can publish frame 6 while shard 0 still holds frame 5, and
290    /// the maximum would say 7. So the watermark stops being "one past what
291    /// this block holds" and becomes "the oldest frame nobody has published",
292    /// which is [`Wal::watermark_for`]. Frames leave the set only on a
293    /// *successful* publish, so a block that fails to land cannot be claimed
294    /// past either — a hole the single-flusher version had, because a failed
295    /// publish dropped its sequences and the next block's maximum stepped
296    /// straight over them.
297    ///
298    /// ponytail: a `BTreeSet` walked for its minimum, on the reasoning that it
299    /// holds one entry per *export* in flight — tens, not millions — and is
300    /// touched once per append under a lock the append already holds. If a
301    /// deployment ever runs deep enough queues for the removals to show up,
302    /// the shape that replaces it is a per-shard "oldest held" cell plus the
303    /// channel's own ordering.
304    pending: [BTreeSet<u64>; 3],
305    /// Segments that have been rolled past but not yet forced, handed to the
306    /// next [`Wal::sync`].
307    ///
308    /// This list exists because the obvious alternative — syncing the outgoing
309    /// segment inside `roll` — puts a 4 ms `F_FULLFSYNC` on one appender in
310    /// every `SEGMENT_BYTES`, and `benches/wal_bench.rs` measured exactly that:
311    /// at 1 MiB bodies a segment rolls every 64 appends, so the stall landed on
312    /// 1.5% of them and the p99 was 7.2 ms against a 5 ms SLA. A rare stall is
313    /// still a stall, and a tail latency is made of rare things.
314    retired: Vec<(PathBuf, File)>,
315}
316
317/// An append-only log of OTLP export bodies.
318///
319/// Every method is synchronous and at least one of them issues a syscall that
320/// can block under writeback pressure, so **callers must not invoke these from
321/// a tokio runtime worker** — section 5's rule that blocking work goes through
322/// `spawn_blocking` applies here for the same reason it applies to `publish`.
323///
324/// `pipeline::submit` breaks that rule, and `wal.lock_wait` is what it costs.
325/// It calls [`Wal::append_then`] directly from the worker handling the export,
326/// so the mutex below is contended by runtime workers and taken with a
327/// `lock()` that parks them in the kernel. Moving the call to `spawn_blocking`
328/// is not the fix: it would unpark the workers and leave the same single
329/// serialised section, now with a thread handoff per append on top.
330///
331/// Nor is shortening that section the fix, which is the reading the paragraph
332/// above used to invite. Both ways of shortening it were built and priced — one
333/// log per signal, and a RAM disk standing in for a perfect group commit — and
334/// the module docs above have the numbers: ~10% at one connection count and
335/// nothing at the other, because the queue re-forms at `submit.admit` the
336/// moment the log is free. What bounds ingest is the flusher, not this file.
337pub struct Wal {
338    inner: Mutex<Inner>,
339    dir: PathBuf,
340    node: u32,
341    /// Held open for the life of the log, and never read or written. See
342    /// [`lock_node`]: closing the fd is what releases the lock, so this field
343    /// existing is the whole mechanism.
344    _lock: File,
345}
346
347/// Take this node's writer lock under `dir`, or refuse to start.
348///
349/// Segments are named `{node}-{first_seq}`, so two processes over one
350/// directory with one node id read the same files, resume to the same number
351/// and then hand it out twice. `O_APPEND` keeps each frame whole, which is
352/// what makes the damage quiet rather than obvious: replay finds two different
353/// bodies at one sequence, and a block claiming the watermark for either
354/// covers both. `--node` has a default, so nothing has to be misconfigured for
355/// two replicas over one volume to land here.
356///
357/// Per node and not per directory, because a shared volume with one log per
358/// replica is the supported arrangement (section 12) — the collision is the id, not
359/// the path.
360///
361/// `flock` and not `fcntl`: the lock belongs to the open file description, so
362/// the kernel drops it when the fd closes, including for a process that died.
363/// A restart after a crash is never locked out by its own predecessor.
364fn lock_node(dir: &Path, node: u32) -> Result<File> {
365    let path = dir.join(format!("{node:08x}.lock"));
366    let file = OpenOptions::new()
367        .create(true)
368        .append(true)
369        .open(&path)
370        .ctx(&path)?;
371    // SAFETY: `file` is live for the whole call, so the descriptor is open and
372    // owned here. `flock` takes no pointer and writes nothing back; the only
373    // output is the return code, checked below.
374    if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
375        let e = std::io::Error::last_os_error();
376        // Anything else — a filesystem with no `flock`, most likely — is
377        // reported as what it is rather than as a second writer.
378        return match e.kind() {
379            std::io::ErrorKind::WouldBlock => Err(Error::WalLocked { path, node }),
380            _ => Err(e).ctx(path),
381        };
382    }
383    Ok(file)
384}
385
386impl Wal {
387    /// The writer identity this log's segments are named for.
388    ///
389    /// Recovery needs it to scope [`crate::block::wal_watermarks`] to the blocks
390    /// that absorbed *this* log's sequences — a number from another replica's
391    /// log is not comparable with one of ours. See that function.
392    pub fn node(&self) -> u32 {
393        self.node
394    }
395
396    /// Open (or create) the log under `<root>/.wal/`, resuming the sequence
397    /// counter past anything already on disk.
398    ///
399    /// Resuming from the *files* rather than from the block watermarks is
400    /// deliberate: a sequence that went backwards would let a replay confuse a
401    /// new frame for one a block already covers, and the watermark comparison
402    /// is `>`, so the failure would be silent data loss rather than an error.
403    pub fn open(root: &Path, node: u32) -> Result<Self> {
404        let dir = root.join(".wal");
405        fs::create_dir_all(&dir).ctx(&dir)?;
406        // Before anything is read, so the loser of the race never resumes a
407        // sequence it is not going to be allowed to use.
408        let _lock = lock_node(&dir, node)?;
409
410        let segments = Self::segments(&dir, node)?;
411        // The highest sequence actually present, which is not the same as the
412        // last segment's first sequence: a segment may be empty if the process
413        // died between creating it and its first append.
414        let mut next_seq = 0;
415        for (path, first) in &segments {
416            let mut torn = false;
417            for frame in FrameReader::open(path)? {
418                // A half-written frame at the tail is what a crash leaves, and
419                // it is the case `replay` is built to stop at rather than fail
420                // on. `open` has to agree with it: propagating the error here
421                // meant the ordinary crash this log exists to survive left a
422                // node that would not start at all.
423                let Ok(frame) = frame else {
424                    torn = true;
425                    break;
426                };
427                next_seq = next_seq.max(frame.seq + 1);
428            }
429            // Never resume onto the name of a segment that ended torn. Segments
430            // are named for their first sequence, so a crash during the *first*
431            // frame of a fresh segment leaves a file whose name is exactly the
432            // sequence being resumed at — and reopening it would append behind
433            // a tear that stops every future replay at it, losing frames that
434            // were acknowledged. One skipped sequence number costs nothing:
435            // nothing indexes by sequence, and the watermark comparisons are
436            // inequalities.
437            if torn {
438                next_seq = next_seq.max(first + 1);
439            }
440        }
441
442        let path = dir.join(format!("{node:08x}-{next_seq:020}.wal"));
443        let file = OpenOptions::new()
444            .create(true)
445            .append(true)
446            .open(&path)
447            .ctx(&path)?;
448        let written = file.metadata().ctx(&path)?.len();
449
450        Ok(Wal {
451            inner: Mutex::new(Inner {
452                file,
453                path,
454                written,
455                next_seq,
456                dirty: false,
457                pending: Default::default(),
458                retired: Vec::new(),
459            }),
460            dir,
461            node,
462            _lock,
463        })
464    }
465
466    /// Append one OTLP export body and return the sequence it was given.
467    ///
468    /// Returns once the bytes are in the page cache. This is the call the
469    /// acknowledgement waits on, and it does not fsync — see the module docs
470    /// for exactly what that does and does not survive.
471    pub fn append(&self, signal: Signal, body: &[u8]) -> Result<u64> {
472        self.append_then(signal, body, |_| {})
473    }
474
475    /// [`append`](Self::append), running `then` on the new sequence before the
476    /// log's lock is released.
477    ///
478    /// This exists to make one specific race impossible, and it is not a
479    /// general-purpose hook.
480    ///
481    /// A block's watermark is [`watermark_for`](Self::watermark_for)'s answer
482    /// over the sequences that block holds, and that call binary-searches them,
483    /// so a shard's list of them has to be ascending. Two exporters calling
484    /// `append` concurrently get their sequences in lock order but can be
485    /// preempted between the return and the enqueue, which would land 6 in a
486    /// shard's list ahead of 5. A binary search over an unsorted list is wrong
487    /// in both directions and one of them is a false hit: the watermark steps
488    /// over a frame no block holds, and the next replay skips it. That is
489    /// silent loss, the one failure this log exists to prevent.
490    ///
491    /// So the enqueue happens under the same lock. It costs nothing: the queue
492    /// hand-off is a pointer move into a reserved slot, next to a `write(2)`
493    /// that has already been paid for.
494    ///
495    /// `then` therefore must not block, must not `.await`, and must not touch
496    /// this log — re-entering `append` from inside it deadlocks.
497    pub fn append_then(&self, signal: Signal, body: &[u8], then: impl FnOnce(u64)) -> Result<u64> {
498        let len = u32::try_from(body.len())
499            .ok()
500            .filter(|n| *n <= MAX_FRAME_BYTES);
501        let Some(len) = len else {
502            return Err(Error::WalFrameTooLarge {
503                len: body.len(),
504                max: MAX_FRAME_BYTES,
505            });
506        };
507
508        // Three probes, described in `crate::diag`: how long this caller waits
509        // for the one mutex all three signals and every shard share, how long
510        // it then holds it, and how many callers are inside at once. Section
511        // 11's ingest plateau is diagnosed from the ratio between the first two
512        // and it is not reproducible without them.
513        let _inflight = crate::diag::wal_scope();
514        let t_enter = std::time::Instant::now();
515        let mut inner = self.lock();
516        crate::diag::WAL_LOCK_WAIT.record(t_enter.elapsed().as_nanos() as u64);
517        let t_held = std::time::Instant::now();
518
519        if inner.written >= SEGMENT_BYTES {
520            self.roll(&mut inner)?;
521        }
522
523        let seq = inner.next_seq;
524        let mut header = [0u8; HEADER_LEN];
525        header[0..4].copy_from_slice(&MAGIC.to_le_bytes());
526        header[4..6].copy_from_slice(&WAL_VERSION.to_le_bytes());
527        header[6] = signal as u8;
528        header[7] = 0;
529        header[8..16].copy_from_slice(&seq.to_le_bytes());
530        header[16..20].copy_from_slice(&len.to_le_bytes());
531
532        let mut hasher = crc32fast::Hasher::new();
533        hasher.update(&header);
534        hasher.update(body);
535        let crc = hasher.finalize();
536
537        // One `write_all` per region rather than one buffer built by
538        // concatenation: the body can be 16 MiB and copying it to prepend
539        // twenty bytes would double the memcpy the ingest path is already
540        // trying not to pay twice.
541        //
542        // A failure part-way leaves a torn frame — the case `FrameReader` is
543        // built to stop at — and nothing here can know how many bytes got out.
544        // So the segment ends at it: `written` is forced past the roll
545        // threshold, the next append opens a new file, and the tear is the
546        // *tail* that `open` and `replay` both already handle. Leaving it
547        // where it is instead buries every frame appended behind it, and those
548        // frames were acknowledged 200.
549        let t_write = std::time::Instant::now();
550        for part in [&header[..], body, &crc.to_le_bytes()[..]] {
551            let wrote = inner.file.write_all(part);
552            if wrote.is_err() {
553                inner.written = SEGMENT_BYTES;
554            }
555            wrote.ctx(&inner.path)?;
556        }
557        crate::diag::WAL_WRITE.record(t_write.elapsed().as_nanos() as u64);
558
559        inner.written += (HEADER_LEN + body.len() + CRC_LEN) as u64;
560        inner.next_seq += 1;
561        inner.dirty = true;
562        inner.pending[signal.index()].insert(seq);
563        then(seq);
564        crate::diag::WAL_HELD.record(t_held.elapsed().as_nanos() as u64);
565        Ok(seq)
566    }
567
568    /// Put a sequence this log already handed out back among the unpublished —
569    /// the replay path, where the frame is read off disk rather than appended.
570    ///
571    /// Without it a recovered frame is invisible to [`watermark_for`](Self::watermark_for),
572    /// so a block sealed beside it could claim a watermark that steps over it
573    /// and the next boot would not replay it a second time. That is the one
574    /// failure this log exists to prevent, and replay is exactly when it would
575    /// bite: the frames in flight are the ones a crash already nearly lost.
576    pub fn reframed(&self, signal: Signal, seq: u64) {
577        self.lock().pending[signal.index()].insert(seq);
578    }
579
580    /// A panic cannot leave the log's state inconsistent — every critical
581    /// section is a write and a counter — so poisoning carries no information.
582    fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
583        self.inner.lock().unwrap_or_else(|e| e.into_inner())
584    }
585
586    /// The watermark a block holding `seqs` may publish: the oldest sequence of
587    /// this signal that nobody has published, or, if this block is the last of
588    /// them, one past everything the log has handed out.
589    ///
590    /// `seqs` must be sorted. Called *before* the publish, because the answer
591    /// goes in the directory name; the sequences stay unpublished until
592    /// [`published`](Self::published) says otherwise, so a sibling shard sealing
593    /// at the same moment still counts this block's frames against its own
594    /// watermark and neither can claim the other's.
595    ///
596    /// It can be too low — a shard holding an old frame pins every sibling's
597    /// watermark behind it — and that is the direction it is allowed to be
598    /// wrong in: too low re-ingests a frame a block already has, too high loses
599    /// it. Nothing is pinned for long, because the shard holding the old frame
600    /// is at most `max_block_age` from sealing it.
601    pub fn watermark_for(&self, signal: Signal, seqs: &[u64]) -> u64 {
602        let inner = self.lock();
603        inner.pending[signal.index()]
604            .iter()
605            .find(|s| seqs.binary_search(s).is_err())
606            .copied()
607            .unwrap_or(inner.next_seq)
608    }
609
610    /// Retire the sequences a block has durably published.
611    ///
612    /// Only on success. A block that failed to land leaves its frames here, and
613    /// that is what keeps the next block's watermark from claiming them.
614    pub fn published(&self, signal: Signal, seqs: &[u64]) {
615        let mut inner = self.lock();
616        let pending = &mut inner.pending[signal.index()];
617        for s in seqs {
618            pending.remove(s);
619        }
620    }
621
622    /// Force everything appended so far onto the device.
623    ///
624    /// Called on a timer by a background task to bound power-loss exposure,
625    /// never from the acknowledgement path. On Apple targets this is
626    /// `F_FULLFSYNC` and costs about 4 ms, which is the whole reason it is not
627    /// on the ack path.
628    pub fn sync(&self) -> Result<()> {
629        // Everything this needs is collected under the lock and forced outside
630        // it. `F_FULLFSYNC` is 4,230 us on this machine and the timer fires
631        // four times a second, so holding the log's mutex across it stalled
632        // every appender in the process for milliseconds, four times a second,
633        // plus once more per segment rolled since the last tick. That does not
634        // move the mean — it is ~2% duty cycle — but it lands as a whole
635        // multiple of a 2.2 ms append on whichever exports are unlucky, and a
636        // tail latency is made of rare things (see `retired`, which exists for
637        // exactly this reason one level down).
638        //
639        // Nothing about the ordering guarantee needs the lock held: an fsync
640        // forces bytes `write(2)` already ordered, and forcing them late is
641        // indistinguishable from a tick that had not fired yet.
642        let (retired, live, dirty) = {
643            let mut inner = self.lock();
644            if !inner.dirty && inner.retired.is_empty() {
645                return Ok(());
646            }
647            // Taken out of the struct rather than iterated in place so a
648            // failure part-way through does not re-sync the ones that already
649            // succeeded on the next tick.
650            let retired = std::mem::take(&mut inner.retired);
651            let dirty = inner.dirty;
652            // Cleared before the force, not after. An append that lands while
653            // this is in flight sets it again and is covered by the next tick;
654            // clearing afterwards would instead swallow that append's flag and
655            // leave bytes nothing ever forces.
656            inner.dirty = false;
657            let live = dirty
658                .then(|| {
659                    inner
660                        .file
661                        .try_clone()
662                        .ctx(&inner.path)
663                        .map(|f| (inner.path.clone(), f))
664                })
665                .transpose()?;
666            (retired, live, dirty)
667        };
668
669        // Retired segments first: they are older, so they are what a power cut
670        // would lose the most of.
671        let force = || -> Result<()> {
672            for (path, file) in &retired {
673                crate::sync_data(file).ctx(path)?;
674            }
675            if let Some((path, file)) = &live {
676                crate::sync_data(file).ctx(path)?;
677            }
678            Ok(())
679        };
680        let forced = force();
681        // Put the flag back: these bytes are still unforced, and a tick that
682        // failed must not be the reason the next one skips them. Written flat
683        // rather than as `inspect_err` so that the part no test can reach is
684        // the one assignment and not a four-line closure: `sync_data` degrades
685        // to `fsync` rather than failing, so nothing short of a filesystem
686        // going away under the process gets here.
687        if dirty && forced.is_err() {
688            self.lock().dirty = true;
689        }
690        forced
691    }
692
693    /// The sequence that will be handed to the next append.
694    pub fn next_seq(&self) -> u64 {
695        self.inner
696            .lock()
697            .unwrap_or_else(|e| e.into_inner())
698            .next_seq
699    }
700
701    /// Delete whole segments whose every frame is below `covered`, the
702    /// smallest of the per-signal [`Watermarks`] — same exclusive convention.
703    ///
704    /// Returns how many segments were removed. Deletion is per segment rather
705    /// than per frame because a log is only append-only if nothing ever
706    /// rewrites its middle; reclaiming a prefix by truncation would mean
707    /// rewriting offsets that a concurrent reader is part-way through.
708    ///
709    /// The current segment is never removed, whatever its watermark, because
710    /// `append` holds it open and unlinking it would leave writes going to a
711    /// file with no name.
712    pub fn truncate(&self, covered: u64) -> Result<usize> {
713        let current = {
714            let inner = self.lock();
715            inner.path.clone()
716        };
717        let segments = Self::segments(&self.dir, self.node)?;
718        let mut removed = 0;
719
720        for (path, _) in &segments {
721            if *path == current {
722                continue;
723            }
724            // The last frame decides, not the first: a segment is only dead
725            // once everything in it is covered.
726            //
727            // A tear stops the scan rather than failing it, because that is
728            // what the other two readers of this log already do: a
729            // half-written frame was never acked, so no block covers it and no
730            // caller is waiting for it, and `replay` would stop there anyway.
731            // Propagating it aborted the entire sweep instead, and `segments`
732            // is ordered oldest-first — so one torn segment hid every younger
733            // one from reclamation for as long as the node lived, on the
734            // ordinary crash this log exists to survive.
735            let mut highest = None;
736            for frame in FrameReader::open(path)? {
737                let Ok(frame) = frame else { break };
738                highest = Some(frame.seq);
739            }
740            match highest {
741                // An empty segment is a crash artefact between create and
742                // first append; nothing references it and it will never be
743                // written to again, so it goes.
744                None => {}
745                Some(hi) if hi < covered => {}
746                Some(_) => continue,
747            }
748            fs::remove_file(path).ctx(path)?;
749            // Drop the retired handle too. Unlinking a file this process still
750            // has open is legal on Unix, but the inode — and its blocks —
751            // survive until the last descriptor closes, so leaving it there
752            // means `truncate` reports space it has not actually freed.
753            {
754                let mut inner = self.lock();
755                inner.retired.retain(|(p, _)| p != path);
756            }
757            removed += 1;
758        }
759
760        if removed > 0 {
761            // The unlinks are metadata on the WAL directory, and until that is
762            // flushed a crash brings the deleted segments back and replays
763            // frames a block already covers. The watermark makes that safe
764            // rather than wrong, but replaying gigabytes at every boot is its
765            // own outage.
766            crate::sync_all(&File::open(&self.dir).ctx(&self.dir)?).ctx(&self.dir)?;
767        }
768        Ok(removed)
769    }
770
771    /// Replay every frame not yet covered by a published block, oldest first.
772    ///
773    /// `watermarks` is the exclusive watermark per signal, taken from the block
774    /// directory listing: every sequence below it is inside a published block,
775    /// which is not the same as one past the last sequence published, because
776    /// shards publish out of order. A frame is handed to `f` only if its
777    /// sequence is at or above its own signal's watermark, so a block that
778    /// sealed while another signal's was still open does not cause a
779    /// re-ingest.
780    ///
781    /// A torn or corrupt frame ends the replay of that segment rather than
782    /// failing it: the tail of the last segment is exactly where a crash
783    /// leaves a half-written frame, and refusing to start because the last
784    /// write was interrupted would turn a normal crash into an outage. Frames
785    /// before the tear are complete and are replayed.
786    ///
787    /// `f` is handed the frame's own sequence, not a fresh one. Re-appending a
788    /// replayed frame would give it a number above every watermark, so the
789    /// block that stored it would claim the new sequence and leave the old one
790    /// uncovered — and the next boot would replay it again, forever. Carrying
791    /// the original through to the block is what makes replay converge.
792    pub fn replay(
793        root: &Path,
794        node: u32,
795        watermarks: Watermarks,
796        mut f: impl FnMut(Signal, u64, &[u8]) -> Result<()>,
797    ) -> Result<Replayed> {
798        let dir = root.join(".wal");
799        if !dir.is_dir() {
800            return Ok(Replayed::default());
801        }
802        let mut out = Replayed::default();
803
804        for (path, _) in Self::segments(&dir, node)? {
805            for frame in FrameReader::open(&path)? {
806                let Ok(frame) = frame else {
807                    out.torn_segments += 1;
808                    break;
809                };
810                if frame.seq < watermarks[frame.signal.index()] {
811                    out.skipped += 1;
812                    continue;
813                }
814                f(frame.signal, frame.seq, &frame.body)?;
815                out.replayed += 1;
816                out.bytes += frame.body.len() as u64;
817            }
818        }
819        Ok(out)
820    }
821
822    /// Segments for this node, oldest first.
823    ///
824    /// Ordered by the first sequence in the name rather than by mtime, because
825    /// mtime has a one-second resolution on some filesystems and two segments
826    /// can share it. Other nodes' segments are skipped: a shared volume (section 12)
827    /// has one log per replica and replaying another's would double-write its
828    /// data.
829    fn segments(dir: &Path, node: u32) -> Result<Vec<(PathBuf, u64)>> {
830        let prefix = format!("{node:08x}-");
831        let mut out = Vec::new();
832        let entries = match fs::read_dir(dir) {
833            Ok(entries) => entries,
834            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
835            Err(e) => {
836                return Err(Error::Io {
837                    path: dir.into(),
838                    source: e,
839                });
840            }
841        };
842        for entry in entries {
843            let entry = entry.ctx(dir)?;
844            let name = entry.file_name();
845            let Some(name) = name.to_str() else { continue };
846            let Some(rest) = name.strip_prefix(&prefix) else {
847                continue;
848            };
849            let Some(first) = rest.strip_suffix(".wal") else {
850                continue;
851            };
852            let Ok(first) = first.parse::<u64>() else {
853                continue;
854            };
855            out.push((entry.path(), first));
856        }
857        out.sort_by_key(|(_, first)| *first);
858        Ok(out)
859    }
860
861    /// Close the current segment and start the next one.
862    ///
863    /// Nothing is forced here — the outgoing segment goes on `retired` for the
864    /// background [`Wal::sync`] to deal with. See that field for the measured
865    /// reason. Opening the new file is two syscalls and does not touch the
866    /// device, so the appender that happens to trigger a roll pays microseconds
867    /// rather than milliseconds.
868    fn roll(&self, inner: &mut Inner) -> Result<()> {
869        let path = self
870            .dir
871            .join(format!("{:08x}-{:020}.wal", self.node, inner.next_seq));
872        let file = OpenOptions::new()
873            .create(true)
874            .append(true)
875            .open(&path)
876            .ctx(&path)?;
877        let old_file = std::mem::replace(&mut inner.file, file);
878        let old_path = std::mem::replace(&mut inner.path, path);
879        if inner.dirty {
880            inner.retired.push((old_path, old_file));
881            inner.dirty = false;
882        }
883        inner.written = 0;
884        Ok(())
885    }
886}
887
888/// What a [`Wal::replay`] did, for the line it gets logged on.
889#[derive(Debug, Default, PartialEq, Eq)]
890pub struct Replayed {
891    /// Frames handed to the callback.
892    pub replayed: u64,
893    /// Frames already covered by a published block.
894    pub skipped: u64,
895    /// Body bytes replayed.
896    pub bytes: u64,
897    /// Segments that ended in a torn or corrupt frame. One is normal after a
898    /// crash — it is the write that was in flight. More than one means
899    /// something else is wrong, which is why they are counted separately from
900    /// the frames rather than folded in.
901    pub torn_segments: u64,
902}
903
904#[cfg_attr(test, derive(Debug))]
905struct Frame {
906    signal: Signal,
907    seq: u64,
908    body: Vec<u8>,
909}
910
911/// Reads frames out of one segment, stopping at the first that is not whole.
912struct FrameReader {
913    file: File,
914    path: PathBuf,
915    done: bool,
916}
917
918impl FrameReader {
919    fn open(path: &Path) -> Result<FrameReader> {
920        Ok(FrameReader {
921            file: File::open(path).ctx(path)?,
922            path: path.to_path_buf(),
923            done: false,
924        })
925    }
926
927    /// `Ok(None)` is a clean end of segment; `Err` is a tear or corruption,
928    /// after which this reader yields nothing further.
929    fn next_frame(&mut self) -> Result<Option<Frame>> {
930        let mut header = [0u8; HEADER_LEN];
931        if !read_exact_or_eof(&mut self.file, &mut header).ctx(&self.path)? {
932            return Ok(None);
933        }
934
935        let magic = u32::from_le_bytes(header[0..4].try_into().unwrap_or_default());
936        let version = u16::from_le_bytes(header[4..6].try_into().unwrap_or_default());
937        let len = u32::from_le_bytes(header[16..20].try_into().unwrap_or_default());
938
939        if magic != MAGIC {
940            return Err(Error::WalCorrupt {
941                path: self.path.clone(),
942                why: "bad frame magic",
943            });
944        }
945        if version != WAL_VERSION {
946            return Err(Error::WalVersion {
947                path: self.path.clone(),
948                found: version,
949                expected: WAL_VERSION,
950            });
951        }
952        // Checked before the allocation, not after: the CRC that would catch a
953        // corrupt length is at the far end of the body this length describes.
954        if len > MAX_FRAME_BYTES {
955            return Err(Error::WalCorrupt {
956                path: self.path.clone(),
957                why: "frame length above the maximum",
958            });
959        }
960        let Some(signal) = Signal::from_u8(header[6]) else {
961            return Err(Error::WalCorrupt {
962                path: self.path.clone(),
963                why: "unknown signal in frame header",
964            });
965        };
966
967        let mut body = vec![0u8; len as usize];
968        if !read_exact_or_eof(&mut self.file, &mut body).ctx(&self.path)? {
969            return Err(Error::WalCorrupt {
970                path: self.path.clone(),
971                why: "truncated frame body",
972            });
973        }
974        let mut crc_bytes = [0u8; CRC_LEN];
975        if !read_exact_or_eof(&mut self.file, &mut crc_bytes).ctx(&self.path)? {
976            return Err(Error::WalCorrupt {
977                path: self.path.clone(),
978                why: "truncated frame checksum",
979            });
980        }
981
982        let mut hasher = crc32fast::Hasher::new();
983        hasher.update(&header);
984        hasher.update(&body);
985        if hasher.finalize() != u32::from_le_bytes(crc_bytes) {
986            return Err(Error::WalCorrupt {
987                path: self.path.clone(),
988                why: "frame checksum mismatch",
989            });
990        }
991
992        Ok(Some(Frame {
993            signal,
994            seq: u64::from_le_bytes(header[8..16].try_into().unwrap_or_default()),
995            body,
996        }))
997    }
998}
999
1000impl Iterator for FrameReader {
1001    type Item = Result<Frame>;
1002
1003    fn next(&mut self) -> Option<Result<Frame>> {
1004        if self.done {
1005            return None;
1006        }
1007        match self.next_frame() {
1008            Ok(Some(frame)) => Some(Ok(frame)),
1009            Ok(None) => {
1010                self.done = true;
1011                None
1012            }
1013            Err(e) => {
1014                self.done = true;
1015                Some(Err(e))
1016            }
1017        }
1018    }
1019}
1020
1021/// `true` if the buffer was filled, `false` on a clean EOF before any byte.
1022///
1023/// `Read::read_exact` cannot distinguish "the segment ends here" from "the
1024/// segment ends in the middle of a frame", and those are a normal end and a
1025/// tear respectively.
1026fn read_exact_or_eof(file: &mut impl Read, buf: &mut [u8]) -> std::io::Result<bool> {
1027    let mut filled = 0;
1028    while filled < buf.len() {
1029        match file.read(&mut buf[filled..]) {
1030            Ok(0) => return Ok(false),
1031            Ok(n) => filled += n,
1032            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
1033            Err(e) => return Err(e),
1034        }
1035    }
1036    Ok(true)
1037}
1038
1039#[cfg(test)]
1040mod tests {
1041    use super::*;
1042
1043    fn tmpdir(name: &str) -> PathBuf {
1044        let dir = std::env::temp_dir().join(format!("mira-wal-{name}-{}", std::process::id()));
1045        let _ = fs::remove_dir_all(&dir);
1046        fs::create_dir_all(&dir).unwrap();
1047        dir
1048    }
1049
1050    fn collect(root: &Path, node: u32, wm: Watermarks) -> (Vec<(Signal, Vec<u8>)>, Replayed) {
1051        let (got, _, stats) = collect_seqs(root, node, wm);
1052        (got, stats)
1053    }
1054
1055    #[allow(clippy::type_complexity)]
1056    fn collect_seqs(
1057        root: &Path,
1058        node: u32,
1059        wm: Watermarks,
1060    ) -> (Vec<(Signal, Vec<u8>)>, Vec<u64>, Replayed) {
1061        let (mut got, mut seqs) = (Vec::new(), Vec::new());
1062        let stats = Wal::replay(root, node, wm, |s, seq, b| {
1063            got.push((s, b.to_vec()));
1064            seqs.push(seq);
1065            Ok(())
1066        })
1067        .unwrap();
1068        (got, seqs, stats)
1069    }
1070
1071    #[test]
1072    fn a_frame_round_trips_through_replay() {
1073        let root = tmpdir("roundtrip");
1074        let wal = Wal::open(&root, 0xab).unwrap();
1075        assert_eq!(wal.append(Signal::Logs, b"one").unwrap(), 0);
1076        assert_eq!(wal.append(Signal::Traces, b"two").unwrap(), 1);
1077        assert_eq!(wal.append(Signal::Metrics, b"three").unwrap(), 2);
1078
1079        let (got, stats) = collect(&root, 0xab, [0, 0, 0]);
1080        // The regression this pins: sequence 0 is a real frame and watermark 0
1081        // means nothing is published, so an inclusive comparison drops the
1082        // first export of every restart. It did, until the watermark was made
1083        // exclusive.
1084        assert_eq!(stats.replayed, 3);
1085        assert_eq!(got[0], (Signal::Logs, b"one".to_vec()));
1086        assert_eq!(got[2], (Signal::Metrics, b"three".to_vec()));
1087    }
1088
1089    #[test]
1090    fn a_published_block_is_not_replayed_and_each_signal_counts_separately() {
1091        let root = tmpdir("watermark");
1092        let wal = Wal::open(&root, 1).unwrap();
1093        wal.append(Signal::Logs, b"l0").unwrap(); // seq 0
1094        wal.append(Signal::Traces, b"t1").unwrap(); // seq 1
1095        wal.append(Signal::Logs, b"l2").unwrap(); // seq 2
1096        wal.append(Signal::Traces, b"t3").unwrap(); // seq 3
1097
1098        // Logs sealed through seq 2 inclusive, traces only through seq 1. Only
1099        // the traces frame above its own watermark comes back — a logs seal
1100        // must not suppress an unsealed trace.
1101        let mut wm = [0u64; 3];
1102        wm[Signal::Logs.index()] = 3;
1103        wm[Signal::Traces.index()] = 2;
1104        let (got, stats) = collect(&root, 1, wm);
1105        assert_eq!(stats.replayed, 1);
1106        assert_eq!(stats.skipped, 3);
1107        assert_eq!(got, vec![(Signal::Traces, b"t3".to_vec())]);
1108    }
1109
1110    #[test]
1111    fn a_torn_tail_ends_the_segment_without_losing_what_came_before() {
1112        let root = tmpdir("torn");
1113        let wal = Wal::open(&root, 2).unwrap();
1114        wal.append(Signal::Logs, b"complete").unwrap();
1115        wal.append(Signal::Logs, b"also-complete").unwrap();
1116        wal.sync().unwrap();
1117        let path = {
1118            let inner = wal.inner.lock().unwrap();
1119            inner.path.clone()
1120        };
1121        drop(wal);
1122
1123        // Chop the last four bytes: the second frame now has no checksum,
1124        // which is exactly what a crash mid-write leaves behind.
1125        let len = fs::metadata(&path).unwrap().len();
1126        OpenOptions::new()
1127            .write(true)
1128            .open(&path)
1129            .unwrap()
1130            .set_len(len - 4)
1131            .unwrap();
1132
1133        let (got, stats) = collect(&root, 2, [0, 0, 0]);
1134        assert_eq!(
1135            stats.replayed, 1,
1136            "the whole frame before the tear survives"
1137        );
1138        assert_eq!(stats.torn_segments, 1);
1139        assert_eq!(got, vec![(Signal::Logs, b"complete".to_vec())]);
1140    }
1141
1142    #[test]
1143    fn a_flipped_bit_in_the_body_is_caught_by_the_checksum() {
1144        let root = tmpdir("bitrot");
1145        let wal = Wal::open(&root, 3).unwrap();
1146        wal.append(Signal::Logs, b"the-quick-brown-fox").unwrap();
1147        wal.sync().unwrap();
1148        let path = {
1149            let inner = wal.inner.lock().unwrap();
1150            inner.path.clone()
1151        };
1152        drop(wal);
1153
1154        let mut bytes = fs::read(&path).unwrap();
1155        bytes[HEADER_LEN + 3] ^= 0x40;
1156        fs::write(&path, &bytes).unwrap();
1157
1158        let (got, stats) = collect(&root, 3, [0, 0, 0]);
1159        assert!(
1160            got.is_empty(),
1161            "a corrupt frame is never handed to the callback"
1162        );
1163        assert_eq!(stats.torn_segments, 1);
1164    }
1165
1166    #[test]
1167    fn a_corrupt_length_is_refused_before_it_is_allocated() {
1168        let root = tmpdir("badlen");
1169        let wal = Wal::open(&root, 4).unwrap();
1170        wal.append(Signal::Logs, b"small").unwrap();
1171        wal.sync().unwrap();
1172        let path = {
1173            let inner = wal.inner.lock().unwrap();
1174            inner.path.clone()
1175        };
1176        drop(wal);
1177
1178        // A length field of 4 GiB. Without the MAX_FRAME_BYTES check this is a
1179        // 4 GiB allocation on a machine that may not have it, from four bytes
1180        // on disk — the same shape as the block-footer bug.
1181        let mut bytes = fs::read(&path).unwrap();
1182        bytes[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
1183        fs::write(&path, &bytes).unwrap();
1184
1185        let mut reader = FrameReader::open(&path).unwrap();
1186        let err = reader.next().unwrap().unwrap_err();
1187        assert!(
1188            matches!(&err, Error::WalCorrupt { why, .. } if why.contains("length")),
1189            "got {err:?}"
1190        );
1191    }
1192
1193    #[test]
1194    fn a_frame_larger_than_the_maximum_is_refused_on_append() {
1195        let root = tmpdir("toobig");
1196        let wal = Wal::open(&root, 5).unwrap();
1197        let huge = vec![0u8; MAX_FRAME_BYTES as usize + 1];
1198        assert!(matches!(
1199            wal.append(Signal::Logs, &huge),
1200            Err(Error::WalFrameTooLarge { .. })
1201        ));
1202    }
1203
1204    #[test]
1205    fn the_sequence_resumes_past_everything_on_disk_after_a_restart() {
1206        let root = tmpdir("resume");
1207        let wal = Wal::open(&root, 6).unwrap();
1208        wal.append(Signal::Logs, b"a").unwrap();
1209        wal.append(Signal::Logs, b"b").unwrap();
1210        wal.sync().unwrap();
1211        drop(wal);
1212
1213        // A sequence that restarted at 0 would collide with the frames already
1214        // there, and the watermark comparison would then skip new data as if
1215        // it were already published.
1216        let wal = Wal::open(&root, 6).unwrap();
1217        assert_eq!(wal.next_seq(), 2);
1218        assert_eq!(wal.append(Signal::Logs, b"c").unwrap(), 2);
1219
1220        let (got, _) = collect(&root, 6, [0, 0, 0]);
1221        assert_eq!(got.len(), 3);
1222    }
1223
1224    /// Replay hands back the sequence the frame already has, and `append_then`
1225    /// hands back the one it just assigned. Both are the same requirement seen
1226    /// from the two ends: a replayed export has to reach its block under its
1227    /// original number, or the block claims a copy, leaves the original
1228    /// uncovered, and the next boot replays it again — for ever.
1229    #[test]
1230    fn replay_carries_the_original_sequence_and_append_reports_it_under_the_lock() {
1231        let root = tmpdir("seqs");
1232        let wal = Wal::open(&root, 3).unwrap();
1233        let mut seen = Vec::new();
1234        for body in [b"a", b"b", b"c"] {
1235            wal.append_then(Signal::Traces, body, |seq| seen.push(seq))
1236                .unwrap();
1237        }
1238        assert_eq!(seen, [0, 1, 2]);
1239
1240        // Not 0..n of whatever survived the watermark: the first frame is
1241        // already published, so the two that replay keep 1 and 2.
1242        let mut wm = [0u64; 3];
1243        wm[Signal::Traces.index()] = 1;
1244        let (got, seqs, stats) = collect_seqs(&root, 3, wm);
1245        assert_eq!(seqs, [1, 2]);
1246        assert_eq!(got.len(), 2);
1247        assert_eq!(stats.skipped, 1);
1248    }
1249
1250    /// One node id over one directory is one writer, and the second is refused
1251    /// at startup rather than at 3am.
1252    ///
1253    /// Two processes here resume to the same sequence — the segment name is
1254    /// `{node}-{first_seq}`, so they read the same files and reach the same
1255    /// number — and then hand that number out twice. `O_APPEND` keeps each
1256    /// frame whole, which is what makes the damage quiet: replay reads two
1257    /// different bodies at one sequence, and a block that claims the watermark
1258    /// for one covers the other, so an export that was acknowledged is never
1259    /// replayed again. `--node` has a default, so this is the configuration
1260    /// reached by not choosing one.
1261    #[test]
1262    fn one_node_id_over_one_directory_is_one_writer() {
1263        let root = tmpdir("nodelock");
1264        let held = Wal::open(&root, 9).unwrap();
1265
1266        let Err(e) = Wal::open(&root, 9) else {
1267            panic!("a second writer over the same log was allowed");
1268        };
1269        let e = e.to_string();
1270        assert!(
1271            e.contains("--node"),
1272            "the message has to say what to fix: {e}"
1273        );
1274
1275        // `flock`, so the lock belongs to the open file description and the
1276        // kernel drops it when the fd closes — including for a process that
1277        // died. A restart is not locked out by the log its predecessor left.
1278        drop(held);
1279        Wal::open(&root, 9).unwrap();
1280    }
1281
1282    #[test]
1283    fn another_nodes_segments_are_left_alone() {
1284        let root = tmpdir("twonodes");
1285        let a = Wal::open(&root, 0x11).unwrap();
1286        let b = Wal::open(&root, 0x22).unwrap();
1287        a.append(Signal::Logs, b"from-a").unwrap();
1288        b.append(Signal::Logs, b"from-b").unwrap();
1289        a.sync().unwrap();
1290        b.sync().unwrap();
1291
1292        // Two replicas sharing a volume (section 12) each replay only their own log.
1293        // Replaying the other's would double-write data it already acked.
1294        let (got, _) = collect(&root, 0x11, [0, 0, 0]);
1295        assert_eq!(got, vec![(Signal::Logs, b"from-a".to_vec())]);
1296    }
1297
1298    #[test]
1299    fn truncate_removes_covered_segments_and_never_the_open_one() {
1300        let root = tmpdir("truncate");
1301        let wal = Wal::open(&root, 7).unwrap();
1302        wal.append(Signal::Logs, b"old").unwrap();
1303        {
1304            // Force a roll without writing 64 MiB.
1305            let mut inner = wal.inner.lock().unwrap();
1306            inner.written = SEGMENT_BYTES;
1307        }
1308        wal.append(Signal::Logs, b"new").unwrap();
1309        assert_eq!(Wal::segments(&wal.dir, 7).unwrap().len(), 2);
1310
1311        // Watermark covers seq 0, the first segment's only frame.
1312        assert_eq!(wal.truncate(1).unwrap(), 1);
1313        let segments = Wal::segments(&wal.dir, 7).unwrap();
1314        assert_eq!(segments.len(), 1, "the open segment is never unlinked");
1315
1316        let (got, _) = collect(&root, 7, [0, 0, 0]);
1317        assert_eq!(got, vec![(Signal::Logs, b"new".to_vec())]);
1318    }
1319
1320    #[test]
1321    fn truncate_keeps_a_segment_whose_tail_is_still_uncovered() {
1322        let root = tmpdir("truncate-partial");
1323        let wal = Wal::open(&root, 8).unwrap();
1324        wal.append(Signal::Logs, b"covered").unwrap(); // seq 0
1325        wal.append(Signal::Logs, b"not-yet").unwrap(); // seq 1
1326        {
1327            let mut inner = wal.inner.lock().unwrap();
1328            inner.written = SEGMENT_BYTES;
1329        }
1330        wal.append(Signal::Logs, b"newest").unwrap(); // seq 2, new segment
1331
1332        // The last frame decides. Dropping the first segment at a watermark of
1333        // 1 would lose seq 1, which no block covers yet.
1334        assert_eq!(wal.truncate(1).unwrap(), 0);
1335        assert_eq!(wal.truncate(2).unwrap(), 1);
1336    }
1337
1338    /// `open` and `replay` both treat a torn tail as the ordinary post-crash
1339    /// state and stop at it. `truncate` was the third reader and the only one
1340    /// that propagated it, which made the sweep abort — and because `segments`
1341    /// is ordered oldest-first, one crash meant no segment was ever reclaimed
1342    /// again for the life of the node. A WAL that cannot retire its own log is
1343    /// a disk that fills.
1344    #[test]
1345    fn truncate_reclaims_a_segment_whose_tail_is_torn() {
1346        let root = tmpdir("truncate-torn");
1347        let wal = Wal::open(&root, 0x7c).unwrap();
1348        wal.append(Signal::Logs, b"covered").unwrap(); // seq 0
1349        wal.append(Signal::Logs, b"never-acked").unwrap(); // seq 1
1350        wal.sync().unwrap();
1351        let first = {
1352            let inner = wal.inner.lock().unwrap();
1353            inner.path.clone()
1354        };
1355        {
1356            let mut inner = wal.inner.lock().unwrap();
1357            inner.written = SEGMENT_BYTES;
1358        }
1359        wal.append(Signal::Logs, b"newest").unwrap(); // seq 2, new segment
1360        assert_eq!(Wal::segments(&wal.dir, 0x7c).unwrap().len(), 2);
1361
1362        // Chop seq 1's checksum, which is what a crash mid-write leaves.
1363        let len = fs::metadata(&first).unwrap().len();
1364        OpenOptions::new()
1365            .write(true)
1366            .open(&first)
1367            .unwrap()
1368            .set_len(len - 4)
1369            .unwrap();
1370
1371        // seq 1 was torn, so it was never acked and no block can cover it.
1372        // A watermark past seq 0 therefore retires the whole segment.
1373        assert_eq!(wal.truncate(1).unwrap(), 1);
1374        assert!(!first.exists(), "a tear is not a reason to keep the file");
1375    }
1376
1377    /// A tear only stops at the tail if something stops the segment there.
1378    ///
1379    /// `write_all` can fail with the header already durable — ENOSPC on a
1380    /// volume the free-space floor has not caught, EDQUOT, EIO — and the frame
1381    /// is then correctly refused. But `written` and `next_seq` never advanced,
1382    /// so the *next* append does not roll: it writes a whole frame behind the
1383    /// tear, returns `Ok`, and is acknowledged 200. Every reader stops at the
1384    /// tear, so that frame is gone. Silent loss of acked data, which is the one
1385    /// failure this log exists to prevent, and the comment above the writes
1386    /// claimed it could not happen.
1387    #[test]
1388    fn a_failed_write_ends_the_segment_rather_than_burying_what_follows() {
1389        const TORN: &[u8] = b"the write that failed";
1390        let root = tmpdir("torn-mid-segment");
1391        let wal = Wal::open(&root, 0x5e).unwrap();
1392        wal.append(Signal::Logs, b"acked-before").unwrap(); // seq 0
1393        wal.append(Signal::Logs, TORN).unwrap(); // seq 1
1394        wal.sync().unwrap();
1395        let seg = wal.inner.lock().unwrap().path.clone();
1396
1397        // Chop seq 1's body and checksum: byte for byte what a `write_all` that
1398        // failed after the header leaves durable.
1399        let len = fs::metadata(&seg).unwrap().len();
1400        OpenOptions::new()
1401            .write(true)
1402            .open(&seg)
1403            .unwrap()
1404            .set_len(len - (TORN.len() + CRC_LEN) as u64)
1405            .unwrap();
1406
1407        // And the error that left it, from a handle nothing can be written to.
1408        wal.inner.lock().unwrap().file = File::open(&seg).unwrap();
1409        assert!(wal.append(Signal::Logs, b"refused").is_err());
1410
1411        // The condition clearing — the volume grew, the quota was raised. The
1412        // log is still open on the segment it tore, which is the whole problem.
1413        wal.inner.lock().unwrap().file = OpenOptions::new().append(true).open(&seg).unwrap();
1414        wal.append(Signal::Logs, b"acked-after").unwrap();
1415        wal.sync().unwrap();
1416
1417        let (got, _) = collect(&root, 0x5e, [0, 0, 0]);
1418        assert!(
1419            got.contains(&(Signal::Logs, b"acked-after".to_vec())),
1420            "a frame acked after a tear has to survive it: {got:?}"
1421        );
1422    }
1423
1424    #[test]
1425    fn a_wrong_frame_header_is_named_by_what_is_wrong_with_it() {
1426        // The header fields, one test, because the property is the set: a
1427        // reader that says "corrupt" for all of them is a reader nobody can
1428        // debug a real crash with. The body's two failures — a length above the
1429        // maximum, a checksum that does not match — have their own tests above,
1430        // since what matters about those is *when* they are checked.
1431        let root = tmpdir("corrupt-frames");
1432        let wal = Wal::open(&root, 0x11).unwrap();
1433        wal.append(Signal::Logs, b"body").unwrap();
1434        wal.sync().unwrap();
1435        let good = fs::read(root.join(".wal").join("00000011-00000000000000000000.wal")).unwrap();
1436        assert_eq!(good.len(), HEADER_LEN + 4 + CRC_LEN);
1437
1438        let broken = |f: &dyn Fn(&mut Vec<u8>)| -> Error {
1439            let mut bytes = good.clone();
1440            f(&mut bytes);
1441            let path = root.join("mangled.wal");
1442            fs::write(&path, &bytes).unwrap();
1443            let mut reader = FrameReader::open(&path).unwrap();
1444            let e = reader.next().unwrap().unwrap_err();
1445            // A reader that has yielded an error is finished: the bytes after a
1446            // frame it could not measure are not frames.
1447            assert!(reader.next().is_none());
1448            e
1449        };
1450        // `matches!` and not a `match` with a panicking arm: the arm that says
1451        // "that was not a corrupt frame at all" is a line no passing run
1452        // executes, and the assertion message carries the same information.
1453        let corrupt = |f: &dyn Fn(&mut Vec<u8>), want: &str| {
1454            let e = broken(f);
1455            assert!(
1456                matches!(&e, Error::WalCorrupt { why, .. } if *why == want),
1457                "expected {want:?}, got {e}"
1458            );
1459        };
1460
1461        corrupt(&|b| b[0] ^= 0xff, "bad frame magic");
1462        corrupt(&|b| b[6] = 0xfe, "unknown signal in frame header");
1463        corrupt(&|b| b.truncate(HEADER_LEN + 1), "truncated frame body");
1464
1465        // The version is the one that is not a `WalCorrupt`: a segment written
1466        // by a future Mira is intact, and saying "corrupt" about it would send
1467        // whoever downgraded looking for a disk fault.
1468        let e = broken(&|b| b[4..6].copy_from_slice(&(WAL_VERSION + 7).to_le_bytes()));
1469        assert!(
1470            matches!(&e, Error::WalVersion { found, expected, .. }
1471                if (*found, *expected) == (WAL_VERSION + 7, WAL_VERSION)),
1472            "expected a version error naming both sides, got {e}"
1473        );
1474    }
1475
1476    #[test]
1477    fn replaying_an_absent_directory_is_not_an_error() {
1478        let root = tmpdir("empty");
1479        let (got, stats) = collect(&root, 9, [0, 0, 0]);
1480        assert!(got.is_empty());
1481        assert_eq!(stats, Replayed::default());
1482    }
1483
1484    /// Bytes for a frame whose header promises more body than follows it —
1485    /// exactly what a crash between the header `write_all` and the body one
1486    /// leaves at the tail of a segment. Hand-built rather than produced by
1487    /// chopping a real segment, because a *first* frame has to be torn to reach
1488    /// the case where the segment's name is the sequence being resumed at.
1489    fn torn_frame_bytes(seq: u64) -> Vec<u8> {
1490        let mut bytes = Vec::new();
1491        bytes.extend_from_slice(&MAGIC.to_le_bytes());
1492        bytes.extend_from_slice(&WAL_VERSION.to_le_bytes());
1493        bytes.push(Signal::Logs as u8);
1494        bytes.push(0); // pad
1495        bytes.extend_from_slice(&seq.to_le_bytes());
1496        bytes.extend_from_slice(&64u32.to_le_bytes()); // promises 64 body bytes
1497        assert_eq!(bytes.len(), HEADER_LEN);
1498        bytes.extend_from_slice(b"only-a-few"); // ... and delivers ten
1499        bytes
1500    }
1501
1502    /// A crash mid-`write(2)` leaves half a frame at the tail of a segment, and
1503    /// the log has to *open* over it: refusing turns the ordinary crash this
1504    /// log exists to survive into a node that will not boot at all. What must
1505    /// not happen either is resuming onto the torn segment's own name —
1506    /// everything appended behind a tear is invisible to every later replay,
1507    /// which is the silent loss of acknowledged data the log exists to prevent.
1508    #[test]
1509    fn a_torn_tail_does_not_stop_the_log_opening_or_get_appended_behind() {
1510        // The tail of a segment that holds a whole frame before the tear.
1511        let root = tmpdir("open-torn-tail");
1512        let wal = Wal::open(&root, 0x4a).unwrap();
1513        wal.append(Signal::Logs, b"kept").unwrap();
1514        wal.append(Signal::Logs, b"in-flight").unwrap();
1515        wal.sync().unwrap();
1516        let path = {
1517            let inner = wal.inner.lock().unwrap();
1518            inner.path.clone()
1519        };
1520        drop(wal);
1521        let len = fs::metadata(&path).unwrap().len();
1522        OpenOptions::new()
1523            .write(true)
1524            .open(&path)
1525            .unwrap()
1526            .set_len(len - 4)
1527            .unwrap();
1528
1529        let wal = Wal::open(&root, 0x4a).expect("a torn tail is a boot condition, not an error");
1530        assert_eq!(wal.append(Signal::Logs, b"after").unwrap(), 1);
1531        wal.sync().unwrap();
1532        let (got, stats) = collect(&root, 0x4a, [0, 0, 0]);
1533        assert_eq!(
1534            got,
1535            vec![
1536                (Signal::Logs, b"kept".to_vec()),
1537                (Signal::Logs, b"after".to_vec())
1538            ],
1539            "the frame before the tear and the one after the restart both replay"
1540        );
1541        assert_eq!(stats.torn_segments, 1);
1542
1543        // The harder shape: the crash was during the very first frame of a
1544        // fresh segment, so the segment's name *is* the sequence a naive resume
1545        // would pick, and the new frame would be written behind the tear.
1546        let root = tmpdir("open-torn-head");
1547        let wal = Wal::open(&root, 0x4b).unwrap();
1548        wal.append(Signal::Logs, b"kept").unwrap(); // seq 0, segment ...000
1549        wal.sync().unwrap();
1550        drop(wal);
1551        let head = root
1552            .join(".wal")
1553            .join(format!("{:08x}-{:020}.wal", 0x4b, 1));
1554        fs::write(&head, torn_frame_bytes(1)).unwrap();
1555
1556        let wal = Wal::open(&root, 0x4b).unwrap();
1557        assert_eq!(
1558            wal.next_seq(),
1559            2,
1560            "the torn segment's own name is not reused"
1561        );
1562        wal.append(Signal::Logs, b"after").unwrap();
1563        wal.sync().unwrap();
1564        let (got, stats) = collect(&root, 0x4b, [0, 0, 0]);
1565        assert_eq!(
1566            got,
1567            vec![
1568                (Signal::Logs, b"kept".to_vec()),
1569                (Signal::Logs, b"after".to_vec())
1570            ],
1571            "a frame acked after the restart is still replayable"
1572        );
1573        assert_eq!(stats.torn_segments, 1, "the torn segment is still counted");
1574    }
1575
1576    /// A rolled segment is handed to the next `sync` instead of being forced by
1577    /// the appender that rolled it (see `Inner::retired` for the measured
1578    /// reason). If `sync` did not pick it up, a node that goes quiet after a
1579    /// roll would leave a whole 64 MiB segment exposed to a power cut for ever
1580    /// — the roll would have turned the timer off for the data it retired.
1581    #[test]
1582    fn the_next_sync_forces_a_segment_the_appender_rolled_away() {
1583        let root = tmpdir("retired");
1584        let wal = Wal::open(&root, 0x5a).unwrap();
1585        wal.append(Signal::Logs, b"in the outgoing segment")
1586            .unwrap();
1587        {
1588            // Rolled by hand: the alternative is 64 MiB of appends, and what is
1589            // under test is the hand-off, not the size trigger.
1590            let mut inner = wal.inner.lock().unwrap();
1591            wal.roll(&mut inner).unwrap();
1592            assert_eq!(inner.retired.len(), 1, "queued for the timer, not forced");
1593            assert!(!inner.dirty, "and the new segment has nothing in it");
1594        }
1595
1596        wal.sync().unwrap();
1597        {
1598            let inner = wal.inner.lock().unwrap();
1599            assert!(
1600                inner.retired.is_empty(),
1601                "taken, so a later tick does not pay for the same barrier again"
1602            );
1603        }
1604        // A quiet log stays quiet: with nothing dirty and nothing retired the
1605        // next tick must not issue a barrier at all, which is what makes the
1606        // 250 ms timer free on an idle node.
1607        wal.sync().unwrap();
1608
1609        let (got, _) = collect(&root, 0x5a, [0, 0, 0]);
1610        assert_eq!(
1611            got,
1612            vec![(Signal::Logs, b"in the outgoing segment".to_vec())],
1613            "rolling is not a truncation"
1614        );
1615    }
1616
1617    /// A segment created and never appended to is what a crash between `roll`
1618    /// and the first append leaves. It has no highest sequence, so a `truncate`
1619    /// that only deleted segments *below* the watermark would keep it for ever
1620    /// and leak one file per crash into the directory every boot scans.
1621    #[test]
1622    fn truncate_drops_the_empty_segment_a_crash_left_behind() {
1623        let root = tmpdir("empty-segment");
1624        let wal = Wal::open(&root, 0x6b).unwrap();
1625        wal.append(Signal::Logs, b"live").unwrap();
1626        let stale = root
1627            .join(".wal")
1628            .join(format!("{:08x}-{:020}.wal", 0x6b, 7));
1629        File::create(&stale).unwrap();
1630        assert_eq!(Wal::segments(&wal.dir, 0x6b).unwrap().len(), 2);
1631
1632        // Watermark 0: nothing at all is published, so the only reason this
1633        // file can go is that it holds no frames.
1634        assert_eq!(wal.truncate(0).unwrap(), 1);
1635        assert!(!stale.exists());
1636        let (got, _) = collect(&root, 0x6b, [0, 0, 0]);
1637        assert_eq!(
1638            got,
1639            vec![(Signal::Logs, b"live".to_vec())],
1640            "the open segment is untouched"
1641        );
1642    }
1643
1644    /// The WAL directory is a directory on somebody's volume: it collects
1645    /// half-renamed files, another replica's segments and whatever a backup
1646    /// tool drops. Each one mistaken for a segment is a spurious replay or a
1647    /// boot failure, so the filter is a correctness property and not tidiness
1648    /// — and the two ways `read_dir` fails have to stay distinguishable,
1649    /// because absent is a fresh volume and unreadable is a mount to shout
1650    /// about. Answering "no segments" for the second would skip the replay and
1651    /// silently drop everything the log was holding.
1652    #[test]
1653    fn segments_lists_only_this_nodes_well_formed_segments() {
1654        let root = tmpdir("listing");
1655        let wal = Wal::open(&root, 0x7c).unwrap();
1656        wal.append(Signal::Logs, b"real").unwrap();
1657        let dir = root.join(".wal");
1658        for junk in [
1659            "0000007c-00000000000000000009.log", // right shape, wrong suffix
1660            "0000007c-not-a-number.wal",         // suffix, but no sequence
1661            "0000007c-.wal",                     // empty sequence
1662            "readme.txt",                        // not ours in any way
1663            "0000007d-00000000000000000000.wal", // the other replica's
1664        ] {
1665            File::create(dir.join(junk)).unwrap();
1666        }
1667
1668        let listed = Wal::segments(&dir, 0x7c).unwrap();
1669        assert_eq!(listed.len(), 1, "only the real segment, got {listed:?}");
1670        assert_eq!(listed[0].1, 0);
1671
1672        // A directory that is not there yet is the first boot on a fresh
1673        // volume, and has to read as empty rather than as an error.
1674        assert!(
1675            Wal::segments(&root.join("never-created"), 0x7c)
1676                .unwrap()
1677                .is_empty()
1678        );
1679        // One that cannot be listed is a different thing and must say so.
1680        let notdir = root.join("a-file-not-a-dir");
1681        fs::write(&notdir, b"x").unwrap();
1682        assert!(matches!(
1683            Wal::segments(&notdir, 0x7c),
1684            Err(Error::Io { .. })
1685        ));
1686    }
1687
1688    /// A `read(2)` that fails is not the end of a segment. The two are one
1689    /// return value apart in `FrameReader` and a world apart in meaning: an
1690    /// EIO mistaken for a clean end would silently drop every frame behind it
1691    /// and let `truncate` delete the segment as if it had all been published.
1692    /// The error also has to name the file, because the operator's next move
1693    /// is to go and look at that one inode.
1694    #[test]
1695    fn a_failed_read_is_never_mistaken_for_the_end_of_a_segment() {
1696        let root = tmpdir("read-error");
1697        // Opening a directory read-only succeeds on Unix and the first `read`
1698        // on it fails with EISDIR: a descriptor whose reads really do fail,
1699        // driven through the real reader, with no fault injection to arrange.
1700        // ponytail: this reaches the header read only. The body and checksum
1701        // reads want a descriptor that succeeds for 20 bytes and then fails,
1702        // which needs a FUSE mount or an injected `Read` — worth it only if
1703        // those two lines ever diverge from this one.
1704        let notafile = root.join("a-directory");
1705        fs::create_dir_all(&notafile).unwrap();
1706        let mut reader =
1707            FrameReader::open(&notafile).expect("opening a directory is not itself the failure");
1708        let err = reader
1709            .next_frame()
1710            .expect_err("a failed read is an error, not an end of segment");
1711        match &err {
1712            Error::Io { path, source } => {
1713                assert_eq!(path, &notafile, "the error names the segment: {err}");
1714                assert!(
1715                    source.raw_os_error().is_some(),
1716                    "the errno is carried through rather than synthesised: {err}"
1717                );
1718            }
1719            other => panic!("a failing read is an io error, got {other}"),
1720        }
1721
1722        // And through the iterator, which is how `replay` and `truncate` see
1723        // it: an `Err` item, not the `None` that would end the segment.
1724        let mut reader = FrameReader::open(&notafile).unwrap();
1725        assert!(
1726            matches!(reader.next(), Some(Err(Error::Io { .. }))),
1727            "the failure is yielded, not swallowed into an end of segment"
1728        );
1729        assert!(reader.next().is_none(), "and the reader is spent after it");
1730
1731        // The clean end, for contrast, is the *only* thing that produces
1732        // `None`: a segment with no frames left in it.
1733        let empty = root.join("empty.wal");
1734        File::create(&empty).unwrap();
1735        assert!(
1736            FrameReader::open(&empty)
1737                .unwrap()
1738                .next_frame()
1739                .unwrap()
1740                .is_none(),
1741            "an end of file is `Ok(None)`, and only a tear is an `Err`"
1742        );
1743    }
1744
1745    #[test]
1746    fn signal_bytes_match_the_block_directory_names() {
1747        // These strings are the join between a WAL watermark and the block it
1748        // came from; a rename on one side only would silently put a watermark
1749        // on the wrong signal.
1750        assert_eq!(Signal::Logs.as_str(), "logs");
1751        assert_eq!(Signal::Traces.as_str(), "traces");
1752        assert_eq!(Signal::Metrics.as_str(), "metrics");
1753        for s in Signal::ALL {
1754            assert_eq!(Signal::from_u8(s as u8), Some(s));
1755        }
1756        assert_eq!(Signal::from_u8(3), None);
1757    }
1758
1759    /// The invariant [`Wal::append_then`] is built around, now that a signal has
1760    /// more than one flusher.
1761    ///
1762    /// With one flusher a block could take `max(seq) + 1` as its watermark,
1763    /// because a signal's frames reached their blocks in sequence order. With
1764    /// two, frame 5 can still be in shard 0's builder when shard 1 seals the
1765    /// block holding frame 6 — and `max + 1` would say 7, so the next boot
1766    /// would skip frame 5. That is silent loss, which is the one failure this
1767    /// log exists to prevent.
1768    #[test]
1769    fn a_shard_may_not_claim_a_watermark_over_a_frame_a_sibling_still_holds() {
1770        let root = tmpdir("watermark-for");
1771        let wal = Wal::open(&root, 7).unwrap();
1772        for b in [&b"l0"[..], b"l1", b"l2", b"l3"] {
1773            wal.append(Signal::Logs, b).unwrap();
1774        }
1775        // Shard 0 took 0 and 2, shard 1 took 1 and 3 — the stride `pipeline`
1776        // allocates with.
1777        let (even, odd) = (vec![0, 2], vec![1, 3]);
1778
1779        // Shard 1 seals first. Frame 0 is still in shard 0's builder, so the
1780        // highest honest watermark is 0: nothing is published.
1781        assert_eq!(wal.watermark_for(Signal::Logs, &odd), 0);
1782        wal.published(Signal::Logs, &odd);
1783        // And now shard 0's block covers everything left, so it may claim the
1784        // whole log — `next_seq`, not `max + 1`, which is the same number here
1785        // and would not be if a fifth frame were in flight.
1786        assert_eq!(wal.watermark_for(Signal::Logs, &even), 4);
1787
1788        // Signals do not see each other: a traces frame in flight cannot hold
1789        // back a logs watermark, which is what the per-signal array is for. The
1790        // logs watermark goes past it, and the traces one does not — a sequence
1791        // is global, and only the array makes skipping another signal's frame
1792        // safe.
1793        wal.append(Signal::Traces, b"t4").unwrap();
1794        assert_eq!(wal.watermark_for(Signal::Logs, &even), 5);
1795        assert_eq!(wal.watermark_for(Signal::Traces, &[]), 4);
1796    }
1797
1798    /// A block that failed to publish keeps its frames replayable.
1799    ///
1800    /// The bug this pins predates sharding: with `max(seq) + 1` the *next*
1801    /// block's watermark stepped over the failed one's frames, so a crash after
1802    /// a failed publish lost them. Retiring sequences only on success fixes
1803    /// both at once.
1804    #[test]
1805    fn a_block_that_never_landed_holds_the_watermark_where_it_was() {
1806        let root = tmpdir("watermark-fail");
1807        let wal = Wal::open(&root, 8).unwrap();
1808        for b in [&b"l0"[..], b"l1"] {
1809            wal.append(Signal::Logs, b).unwrap();
1810        }
1811        // The first block seals holding frame 0 and claims 1 — exclusive, so
1812        // that says "frame 0 is covered, frame 1 is not" — and then fails to
1813        // land, so nothing is retired.
1814        assert_eq!(wal.watermark_for(Signal::Logs, &[0]), 1);
1815        // The second one may not pretend the first succeeded.
1816        assert_eq!(
1817            wal.watermark_for(Signal::Logs, &[1]),
1818            0,
1819            "frame 0 is still unpublished, so no block may claim past it"
1820        );
1821        wal.published(Signal::Logs, &[1]);
1822        // And when the first block is retried, it covers the lot.
1823        assert_eq!(wal.watermark_for(Signal::Logs, &[0]), 2);
1824
1825        // Replay is the reason it matters: the frames are both still there.
1826        let (got, _) = collect(&root, 8, [0, 0, 0]);
1827        assert_eq!(got.len(), 2);
1828    }
1829
1830    /// Replay re-arms the pending set, or the frames a crash nearly lost are
1831    /// the ones the first seal after boot steps over.
1832    #[test]
1833    fn a_replayed_frame_counts_against_the_watermark_again() {
1834        let root = tmpdir("watermark-reframe");
1835        let wal = Wal::open(&root, 9).unwrap();
1836        for b in [&b"l0"[..], b"l1"] {
1837            wal.append(Signal::Logs, b).unwrap();
1838        }
1839        drop(wal);
1840
1841        let wal = Wal::open(&root, 9).unwrap();
1842        assert_eq!(
1843            wal.watermark_for(Signal::Logs, &[]),
1844            2,
1845            "a fresh log knows nothing is outstanding until replay says so"
1846        );
1847        let (_, seqs, _) = collect_seqs(&root, 9, [0, 0, 0]);
1848        for seq in &seqs {
1849            wal.reframed(Signal::Logs, *seq);
1850        }
1851        assert_eq!(seqs, vec![0, 1]);
1852        // Shard 1 gets frame 1 and seals it before shard 0 has flushed frame 0.
1853        assert_eq!(wal.watermark_for(Signal::Logs, &[1]), 0);
1854    }
1855}