Skip to main content

znippy_plugin_git/
pushlog.rs

1//! The append-only **push log**: the one mechanism `__gunnar_refs__` and
2//! `__gunnar_secrets__` are both built from.
3//!
4//! ## Why there is no database here
5//!
6//! D18 removed redb: it was a database wedged between two archive formats, and
7//! it bought nothing that the formats did not already provide. What a ref update
8//! actually needs is *atomicity* — a push is visible whole or not at all — and
9//! Arrow IPC already frames its messages. So the transaction boundary is the
10//! **IPC frame boundary**, and the rule is one `RecordBatch` per push.
11//!
12//! ## The on-disk shape
13//!
14//! The live log is a concatenation of **self-contained** Arrow IPC streams, one
15//! per push:
16//!
17//! ```text
18//! [ schema | RecordBatch | EOS ]  ← push 1, fsynced
19//! [ schema | RecordBatch | EOS ]  ← push 2, fsynced
20//! [ schema | RecordBatch          ← push 3, TORN by a crash
21//! ```
22//!
23//! Repeating the schema per frame is what buys the property: every frame is
24//! independently parseable, so recovery needs no side-car, no length table and
25//! no journal.
26//!
27//! **What that costs, measured** (refs schema, 4 refs per push, 2026-08-03):
28//! a frame is 2056 bytes — 448 of schema (21.8%) and 1600 of batch (77.8%,
29//! i.e. 400 bytes per ref). So the schema repetition is the *smaller* half of
30//! the overhead; the larger half is Arrow's 64-byte buffer alignment paid six
31//! times over on a four-row batch. Merging frames into one stream would
32//! therefore recover only ~21.8%.
33//!
34//! The real win is compaction — folding many small batches into one large one,
35//! which amortises the padding as well as the schema. `gunnar-store`'s
36//! `arrow_log.rs` already does exactly this (`CompactionPolicy`, a staged
37//! rewrite plus rename, and a reflog archive for the history it retires), and
38//! its single-stream live log carries the schema once rather than per push.
39//! That is the shape to adopt here rather than reinvent; see the note in the
40//! commit that added this measurement. [`scan_frames`] reads forward while
41//! frames parse and stops at the first one that does not — push 3 above is
42//! discarded whole, pushes 1 and 2 survive intact. That is the crash story, and
43//! it is a property of the framing rather than of any code that has to run.
44//!
45//! A partially-written frame can never be mistaken for a complete one: Arrow
46//! prefixes every message with a continuation marker and a length, so a truncated
47//! frame ends in the middle of a message body and the reader errors instead of
48//! yielding a half-populated batch.
49//!
50//! ## Live log vs sealed archive
51//!
52//! znippy seals later. Until then the log is the file above. At seal, the
53//! recovered batches are folded into **one** reserved Arrow section that keeps
54//! one RecordBatch per push — so the push boundaries survive into the sealed
55//! archive, and DuckDB / Polars / DataFusion read the section straight out of its
56//! manifest byte range with no gunnar code.
57
58use std::fs::{File, OpenOptions};
59use std::io::{Cursor, Write};
60use std::path::{Path, PathBuf};
61use std::sync::Arc;
62
63use anyhow::{Result, anyhow};
64use znippy_common::arrow::datatypes::Schema;
65use znippy_common::arrow::ipc::reader::StreamReader;
66use znippy_common::arrow::ipc::writer::StreamWriter;
67use znippy_common::arrow::record_batch::RecordBatch;
68use znippy_common::{ReservedSection, read_reserved_section_bytes};
69
70/// What a scan of a log recovered, and what it had to throw away.
71#[derive(Debug, Default)]
72pub struct PushLogScan {
73    /// The complete frames, in push order. One entry per push.
74    pub pushes: Vec<RecordBatch>,
75    /// Bytes at the tail that did not form a complete frame — a push that was
76    /// interrupted. Zero for a cleanly closed log.
77    ///
78    /// Deliberately reported rather than silently dropped: "the last push did
79    /// not land" is information the caller may need, and a scan that quietly
80    /// swallowed it would be indistinguishable from a clean log.
81    pub torn_tail_bytes: u64,
82}
83
84impl PushLogScan {
85    pub fn is_clean(&self) -> bool {
86        self.torn_tail_bytes == 0
87    }
88}
89
90/// Serialize one push as a self-contained Arrow IPC stream frame.
91pub fn encode_frame(schema: &Arc<Schema>, batch: &RecordBatch) -> Result<Vec<u8>> {
92    let mut buf = Vec::new();
93    {
94        let mut w = StreamWriter::try_new(&mut buf, schema)
95            .map_err(|e| anyhow!("push log: opening a frame: {e}"))?;
96        w.write(batch).map_err(|e| anyhow!("push log: writing a frame: {e}"))?;
97        w.finish().map_err(|e| anyhow!("push log: closing a frame: {e}"))?;
98    }
99    Ok(buf)
100}
101
102/// Arrow's end-of-stream marker: the continuation marker `0xFFFFFFFF` followed
103/// by a zero metadata length. Its presence at the end of a frame is what proves
104/// the writer got all the way through `finish()`.
105const IPC_EOS: [u8; 8] = [0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00];
106
107/// Read forward over concatenated frames, stopping at the first that does not
108/// parse. Never errors on a torn tail — that is the expected state after a crash
109/// and the whole reason the framing was chosen.
110///
111/// ## Why "did the reader error?" is not enough
112///
113/// Arrow's `StreamReader` treats an unexpected EOF as a clean end of stream, so
114/// a frame truncated *inside* its record-batch message parses without error and
115/// simply yields no batch. Trusting the reader's verdict alone therefore
116/// accepted a torn push as a complete-but-empty frame and advanced past it —
117/// the torn bytes were silently swallowed, `torn_tail_bytes` reported 0, and a
118/// crashed push was indistinguishable from a clean log.
119///
120/// Two positive checks close that, and both must hold for a frame to count:
121///
122/// 1. it yielded **exactly one** `RecordBatch` — the format's invariant is one
123///    push, one batch, so zero batches is a truncation and two is not our frame;
124/// 2. its last eight bytes are [`IPC_EOS`] — proof the writer reached `finish()`
125///    rather than the reader reaching the end of the file.
126pub fn scan_frames(bytes: &[u8]) -> PushLogScan {
127    let mut out = PushLogScan::default();
128    let mut off = 0usize;
129
130    while off < bytes.len() {
131        // Only the whole, well-formed messages of the next frame reach arrow
132        // (the IPC guard's valid prefix stops at its end-of-stream marker): a
133        // hostile frame then reads as a torn one, never as an arrow panic or
134        // abort, and the checks below see exactly the bytes the reader consumed.
135        let rest = znippy_common::ipc_guard::valid_prefix(&bytes[off..]);
136        let Ok(mut reader) = StreamReader::try_new(Cursor::new(rest), None) else {
137            break;
138        };
139        let mut batches = Vec::new();
140        let mut errored = false;
141        loop {
142            match reader.next() {
143                Some(Ok(b)) => batches.push(b),
144                Some(Err(_)) => {
145                    errored = true;
146                    break;
147                }
148                None => break,
149            }
150        }
151        if errored {
152            break;
153        }
154        // The reader is unbuffered over a `Cursor`, so its position is exactly
155        // the bytes this frame consumed.
156        let consumed = reader.get_ref().position() as usize;
157
158        // A frame that consumed nothing would spin forever; one that did not end
159        // in EOS, or did not carry exactly one batch, was torn mid-write.
160        if consumed < IPC_EOS.len()
161            || batches.len() != 1
162            || rest[consumed - IPC_EOS.len()..consumed] != IPC_EOS
163        {
164            break;
165        }
166
167        out.pushes.append(&mut batches);
168        off += consumed;
169    }
170
171    out.torn_tail_bytes = (bytes.len() - off) as u64;
172    out
173}
174
175/// When a log should be compacted.
176///
177/// Compaction folds many small frames into one large one. The point is NOT the
178/// schema — measured, that is only 21.8% of a frame — but Arrow's 64-byte
179/// buffer alignment, which a four-row batch pays six times over and a
180/// twenty-thousand-row batch pays once.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub struct CompactionPolicy {
183    /// Compact once the log holds at least this many frames. Zero disables it.
184    pub after_frames: usize,
185}
186
187impl CompactionPolicy {
188    pub const fn never() -> Self {
189        Self { after_frames: 0 }
190    }
191
192    pub fn should_compact(&self, frames: usize) -> bool {
193        self.after_frames != 0 && frames >= self.after_frames
194    }
195}
196
197impl Default for CompactionPolicy {
198    fn default() -> Self {
199        Self { after_frames: 1024 }
200    }
201}
202
203/// What one compaction did.
204#[derive(Debug, Clone, PartialEq, Eq)]
205pub struct CompactionReport {
206    pub frames_before: usize,
207    pub frames_after: usize,
208    pub rows: usize,
209    pub bytes_before: u64,
210    pub bytes_after: u64,
211}
212
213/// The scratch name a compaction stages under, beside the live log so the
214/// rename cannot cross a filesystem boundary and stop being atomic.
215fn compacting_path(path: &Path) -> PathBuf {
216    let name = path
217        .file_name()
218        .map(|n| n.to_string_lossy().into_owned())
219        .unwrap_or_else(|| "log".to_owned());
220    path.with_file_name(format!("{name}.compacting"))
221}
222
223/// A rename is only durable once the *directory entry* is on the platter.
224fn sync_parent_dir(path: &Path) -> Result<()> {
225    let parent = match path.parent() {
226        Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
227        _ => PathBuf::from("."),
228    };
229    File::open(parent)?.sync_all()?;
230    Ok(())
231}
232
233/// Where a compaction is allowed to stop. Only the crash test constructs
234/// anything but [`Finish::Swap`].
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub enum Finish {
237    /// Stage the replacement, fsync it, and rename it into place.
238    Swap,
239    /// Stage and fsync, then stop. What a crash mid-compaction leaves on disk:
240    /// a complete replacement that nothing points at yet.
241    StopBeforeSwap,
242}
243
244/// An append-only log file. One [`append`](Self::append) call is one push.
245pub struct PushLog {
246    path: PathBuf,
247    schema: Arc<Schema>,
248    /// How many times this handle has read the whole file — the only `O(log)`
249    /// operation it has. Applied output, not a switch: a caller that claims a
250    /// push costs one append can assert this did not move, which is a fact a
251    /// clock cannot establish. See [`crate::refs::RefLog`].
252    scans: std::sync::atomic::AtomicU64,
253}
254
255impl PushLog {
256    pub fn new(path: impl Into<PathBuf>, schema: Arc<Schema>) -> Self {
257        Self {
258            path: path.into(),
259            schema,
260            scans: std::sync::atomic::AtomicU64::new(0),
261        }
262    }
263
264    /// Full passes over the file this handle has paid, since it was made.
265    pub fn scans(&self) -> u64 {
266        self.scans.load(std::sync::atomic::Ordering::Relaxed)
267    }
268
269    pub fn path(&self) -> &Path {
270        &self.path
271    }
272
273    pub fn schema(&self) -> &Arc<Schema> {
274        &self.schema
275    }
276
277    /// Append one push and fsync it. Returns the byte offset the frame starts
278    /// at.
279    ///
280    /// The frame is built **fully in memory first**, so the single `write_all`
281    /// is the only thing the crash window covers; and the `sync_all` is what
282    /// makes "the frame is complete on disk" — the durability claim this format
283    /// rests on — actually true rather than merely likely.
284    pub fn append(&self, batch: &RecordBatch) -> Result<u64> {
285        self.append_with(batch, true)
286    }
287
288    /// [`append`](Self::append), with the barrier as an argument.
289    ///
290    /// `durable = false` skips the `fsync` and **nothing else**: the frame is
291    /// still built whole in memory and written with one `write_all`, so it is
292    /// still whole-or-absent — that property comes from the framing, not from
293    /// the barrier. What is given up is only *when* it reaches the platter.
294    ///
295    /// The one caller is [`crate::refs::RefLog::push_rebuildable`], for a frame
296    /// whose content is re-derivable from a fact that is already durable
297    /// somewhere else. Anything a client was told landed goes through
298    /// [`append`](Self::append).
299    pub fn append_with(&self, batch: &RecordBatch, durable: bool) -> Result<u64> {
300        if batch.schema() != self.schema {
301            return Err(anyhow!(
302                "push log {}: batch schema does not match the log schema",
303                self.path.display()
304            ));
305        }
306        let frame = encode_frame(&self.schema, batch)?;
307        let mut f = OpenOptions::new()
308            .create(true)
309            .append(true)
310            .open(&self.path)
311            .map_err(|e| anyhow!("push log {}: {e}", self.path.display()))?;
312        let offset = f.metadata()?.len();
313        f.write_all(&frame)?;
314        if durable {
315            f.sync_all()?;
316        }
317        Ok(offset)
318    }
319
320    /// Recover the log. A missing file is an empty, clean log — a repository
321    /// that has never been pushed to is not an error.
322    pub fn scan(&self) -> Result<PushLogScan> {
323        self.scans.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
324        match std::fs::read(&self.path) {
325            Ok(b) => Ok(scan_frames(&b)),
326            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(PushLogScan::default()),
327            Err(e) => Err(anyhow!("push log {}: {e}", self.path.display())),
328        }
329    }
330
331    /// How many complete frames the log holds.
332    pub fn frame_count(&self) -> Result<usize> {
333        Ok(self.scan()?.pushes.len())
334    }
335
336    /// Fold every frame into one, atomically.
337    ///
338    /// ## What it costs and what it buys
339    ///
340    /// Rows are concatenated, never dropped: `push_seq` and `updated_ms` ride
341    /// in the columns, so the full history survives and [`crate::refs::fold`]
342    /// gives the identical answer before and after. What is given up is the
343    /// *frame* boundary as a record of where one push ended — after compaction
344    /// a frame is a run of pushes, and `push_seq` is the only thing that says
345    /// where the seams were. That is why the ordering key was never the frame
346    /// index.
347    ///
348    /// ## Compatibility — no migration, no version bump
349    ///
350    /// A compacted log is still exactly what an uncompacted one is: a sequence
351    /// of self-contained frames, each carrying one batch and ending in EOS.
352    /// There are simply fewer and larger ones. [`scan_frames`] already reads any
353    /// number of them and its one-batch-per-frame invariant still holds, so a
354    /// log written before this existed reads unchanged and a compacted log
355    /// reads on any reader that could read the old one. This is deliberately
356    /// **not** a versioned format change.
357    ///
358    /// ## Crash safety
359    ///
360    /// The same shape as `gunnar-store`'s `arrow_log.rs` — which owns the
361    /// mature version of this problem — and deliberately so, since the code
362    /// cannot be shared across the repository boundary: stage the whole
363    /// replacement under [`compacting_path`], fsync it, rename it over the live
364    /// log, then fsync the parent directory so the rename itself is durable.
365    /// The live log is never written in place, so an interruption at *any* byte
366    /// leaves the old log serving untouched; the worst outcome is a stray
367    /// `.compacting` file that the next compaction overwrites.
368    pub fn compact(&self) -> Result<CompactionReport> {
369        self.compact_with(Finish::Swap)
370    }
371
372    /// [`compact`](Self::compact), stopping where `finish` says. The crash test
373    /// is the only caller that passes anything but [`Finish::Swap`].
374    pub fn compact_with(&self, finish: Finish) -> Result<CompactionReport> {
375        let scan = self.scan()?;
376        let frames_before = scan.pushes.len();
377        let bytes_before = std::fs::metadata(&self.path).map(|m| m.len()).unwrap_or(0);
378
379        if frames_before == 0 {
380            return Ok(CompactionReport {
381                frames_before,
382                frames_after: frames_before,
383                rows: 0,
384                bytes_before,
385                bytes_after: bytes_before,
386            });
387        }
388
389        let merged = znippy_common::arrow::compute::concat_batches(&self.schema, scan.pushes.iter())
390            .map_err(|e| anyhow!("compacting {}: {e}", self.path.display()))?;
391        let rows = merged.num_rows();
392        let bytes = encode_frame(&self.schema, &merged)?;
393
394        // Stage the whole replacement first. Nothing points at it yet, so a
395        // crash anywhere in here is invisible to a reader.
396        let staged = compacting_path(&self.path);
397        {
398            let mut f = File::create(&staged)?;
399            f.write_all(&bytes)?;
400            f.sync_all()?;
401        }
402        if finish == Finish::StopBeforeSwap {
403            return Ok(CompactionReport {
404                frames_before,
405                frames_after: 1,
406                rows,
407                bytes_before,
408                bytes_after: bytes.len() as u64,
409            });
410        }
411
412        std::fs::rename(&staged, &self.path)?;
413        sync_parent_dir(&self.path)?;
414
415        Ok(CompactionReport {
416            frames_before,
417            frames_after: 1,
418            rows,
419            bytes_before,
420            bytes_after: bytes.len() as u64,
421        })
422    }
423
424    /// Compact if `policy` says the log has grown enough. Returns `None` when
425    /// it did not run.
426    pub fn maybe_compact(&self, policy: CompactionPolicy) -> Result<Option<CompactionReport>> {
427        if policy == CompactionPolicy::never() {
428            return Ok(None);
429        }
430        let frames = self.frame_count()?;
431        if !policy.should_compact(frames) {
432            return Ok(None);
433        }
434        self.compact().map(Some)
435    }
436
437    /// Fold the recovered pushes into the reserved section to seal into an
438    /// archive, preserving one RecordBatch per push.
439    pub fn seal_section(&self, module_name: &str) -> Result<ReservedSection> {
440        let scan = self.scan()?;
441        Ok(ReservedSection::arrow(module_name, self.schema.clone(), scan.pushes))
442    }
443}
444
445/// Read a sealed push-log section back out of an archive. `Ok(None)` when the
446/// archive carries no such section — distinct from a section with no pushes.
447pub fn read_sealed(archive: &Path, module_name: &str) -> Result<Option<Vec<RecordBatch>>> {
448    let Some(bytes) = read_reserved_section_bytes(archive, module_name)? else {
449        return Ok(None);
450    };
451    decode_sealed(module_name, &bytes).map(Some)
452}
453
454/// The batches of a sealed push-log section's bytes.
455fn decode_sealed(module_name: &str, bytes: &[u8]) -> Result<Vec<RecordBatch>> {
456    // Through the IPC guard: the section comes out of an archive.
457    let reader = znippy_common::ipc_guard::stream_reader(bytes)
458        .map_err(|e| anyhow!("{module_name}: {e}"))?;
459    let mut out = Vec::new();
460    for b in reader {
461        out.push(b.map_err(|e| anyhow!("{module_name}: {e}"))?);
462    }
463    Ok(out)
464}
465
466/// Truncate a log to `len` bytes — the crash simulator the tests need, and the
467/// only supported way to produce a torn tail deliberately.
468#[doc(hidden)]
469pub fn truncate_for_test(path: &Path, len: u64) -> Result<()> {
470    let f = File::options().write(true).open(path)?;
471    f.set_len(len)?;
472    Ok(())
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478
479    /// A sealed section is a section of an archive someone else may have
480    /// written: hostile bytes are an `Err`, never a panic or an abort.
481    #[test]
482    #[ignore = "run as a child by a_hostile_sealed_section_is_an_error"]
483    fn hostile_child() {
484        if crate::hostile_inputs::child_case().is_none() {
485            return;
486        }
487        let mut valid = Vec::new();
488        {
489            let b = batch(&["refs/heads/main", "refs/tags/v1"], 7);
490            let mut w = znippy_common::arrow::ipc::writer::StreamWriter::try_new(&mut valid, &schema()).unwrap();
491            w.write(&b).unwrap();
492            w.write(&batch(&["x"], 8)).unwrap();
493            w.finish().unwrap();
494        }
495        assert_eq!(decode_sealed("t", &valid).unwrap().len(), 2);
496        crate::hostile_inputs::sweep(&valid, |_, b| {
497            let _ = decode_sealed("t", b);
498        });
499    }
500
501    #[test]
502    fn a_hostile_sealed_section_is_an_error() {
503        crate::hostile_inputs::run_in_child("pushlog::tests::hostile_child", "sealed");
504    }
505    use znippy_common::arrow::array::{StringArray, UInt64Array};
506    use znippy_common::arrow::datatypes::{DataType, Field};
507
508    fn schema() -> Arc<Schema> {
509        Arc::new(Schema::new(vec![
510            Field::new("name", DataType::Utf8, false),
511            Field::new("seq", DataType::UInt64, false),
512        ]))
513    }
514
515    fn batch(names: &[&str], seq: u64) -> RecordBatch {
516        RecordBatch::try_new(
517            schema(),
518            vec![
519                Arc::new(StringArray::from(names.to_vec())),
520                Arc::new(UInt64Array::from(vec![seq; names.len()])),
521            ],
522        )
523        .unwrap()
524    }
525
526    fn tmpdir(tag: &str) -> PathBuf {
527        let ns = std::time::SystemTime::now()
528            .duration_since(std::time::UNIX_EPOCH)
529            .unwrap()
530            .as_nanos();
531        let d = std::env::temp_dir().join(format!("znippy_pushlog_{tag}_{ns}"));
532        std::fs::create_dir_all(&d).unwrap();
533        d
534    }
535
536    /// Each push is its own frame, and the boundaries survive the round trip —
537    /// three pushes come back as three batches, not one merged batch. If the
538    /// framing collapsed, `pushes.len()` would be 1 and the per-push transaction
539    /// boundary this format rests on would not exist.
540    #[test]
541    fn one_push_is_one_frame_is_one_batch() {
542        let dir = tmpdir("frames");
543        let log = PushLog::new(dir.join("refs.log"), schema());
544        log.append(&batch(&["a", "b"], 1)).unwrap();
545        log.append(&batch(&["c"], 2)).unwrap();
546        log.append(&batch(&["d", "e", "f"], 3)).unwrap();
547
548        let scan = log.scan().unwrap();
549        assert!(scan.is_clean(), "no crash happened, tail must be clean");
550        assert_eq!(scan.pushes.len(), 3, "one RecordBatch per push");
551        assert_eq!(scan.pushes[0].num_rows(), 2);
552        assert_eq!(scan.pushes[1].num_rows(), 1);
553        assert_eq!(scan.pushes[2].num_rows(), 3);
554
555        std::fs::remove_dir_all(&dir).ok();
556    }
557
558    /// The crash test. A push interrupted part-way must lose **that push and
559    /// only that push**; every earlier push stays readable.
560    ///
561    /// The truncation is swept across the whole final frame rather than taken at
562    /// one convenient offset, because a recovery that works at one cut point and
563    /// not another is not recovery. At every cut the two surviving pushes must
564    /// come back byte-identical, and the third must never appear in any partial
565    /// form.
566    #[test]
567    fn a_torn_final_frame_loses_only_that_push() {
568        let dir = tmpdir("torn");
569        let path = dir.join("refs.log");
570        let log = PushLog::new(&path, schema());
571        log.append(&batch(&["a", "b"], 1)).unwrap();
572        log.append(&batch(&["c"], 2)).unwrap();
573        let third_start = log.append(&batch(&["doomed"], 3)).unwrap();
574        let full_len = std::fs::metadata(&path).unwrap().len();
575        assert!(full_len > third_start, "third frame must have real bytes");
576
577        let intact = std::fs::read(&path).unwrap();
578
579        // Cut anywhere inside the third frame: 1 byte in, through 1 byte short.
580        for cut in (third_start + 1)..full_len {
581            std::fs::write(&path, &intact).unwrap();
582            truncate_for_test(&path, cut).unwrap();
583
584            let scan = log.scan().unwrap();
585            assert_eq!(
586                scan.pushes.len(),
587                2,
588                "cut at {cut}: the torn push must vanish whole, leaving exactly the two \
589                 that completed (got {} batches)",
590                scan.pushes.len()
591            );
592            assert_eq!(scan.pushes[0].num_rows(), 2, "cut at {cut}: push 1 damaged");
593            assert_eq!(scan.pushes[1].num_rows(), 1, "cut at {cut}: push 2 damaged");
594            assert_eq!(
595                scan.torn_tail_bytes,
596                cut - third_start,
597                "cut at {cut}: the torn tail must be reported, not silently swallowed"
598            );
599            let names = scan.pushes[0]
600                .column(0)
601                .as_any()
602                .downcast_ref::<StringArray>()
603                .unwrap();
604            assert_eq!(names.value(0), "a", "cut at {cut}: push 1 content damaged");
605            assert_eq!(names.value(1), "b");
606        }
607
608        // Restoring the full bytes brings the third push back — proving the loss
609        // was the truncation and not the scanner dropping a trailing frame.
610        std::fs::write(&path, &intact).unwrap();
611        let scan = log.scan().unwrap();
612        assert_eq!(scan.pushes.len(), 3);
613        assert!(scan.is_clean());
614
615        std::fs::remove_dir_all(&dir).ok();
616    }
617
618    /// Garbage appended after a clean log is a torn tail, not a parse failure
619    /// and not a panic: recovery must be total over arbitrary trailing bytes.
620    #[test]
621    fn trailing_garbage_is_a_torn_tail_not_an_error() {
622        let dir = tmpdir("garbage");
623        let path = dir.join("refs.log");
624        let log = PushLog::new(&path, schema());
625        log.append(&batch(&["a"], 1)).unwrap();
626
627        for junk in [
628            &b"\x00"[..],
629            &b"\xff\xff\xff\xff"[..],
630            &b"\xff\xff\xff\xff\x10\x00\x00\x00partial"[..],
631            &[0xAB; 4096][..],
632        ] {
633            let mut bytes = std::fs::read(&path).unwrap();
634            let clean_len = bytes.len();
635            bytes.extend_from_slice(junk);
636            let scan = scan_frames(&bytes);
637            assert_eq!(scan.pushes.len(), 1, "the complete push must survive {junk:?}");
638            assert_eq!(scan.torn_tail_bytes, (bytes.len() - clean_len) as u64);
639        }
640
641        std::fs::remove_dir_all(&dir).ok();
642    }
643
644    /// An empty / never-written log is clean and empty, not an error. A
645    /// repository that has never been pushed to is a normal state.
646    #[test]
647    fn a_missing_log_is_empty_and_clean() {
648        let dir = tmpdir("missing");
649        let log = PushLog::new(dir.join("nope.log"), schema());
650        let scan = log.scan().unwrap();
651        assert!(scan.pushes.is_empty());
652        assert!(scan.is_clean());
653        std::fs::remove_dir_all(&dir).ok();
654    }
655
656    /// Compaction preserves every row and every push_seq, so the fold is
657    /// identical before and after — and it must actually shrink the log, which
658    /// is the only reason to run it.
659    #[test]
660    fn compaction_preserves_every_row_and_its_order() {
661        let dir = tmpdir("compact");
662        let path = dir.join("refs.log");
663        let log = PushLog::new(&path, schema());
664        for i in 0..200u64 {
665            log.append(&batch(&["a", "b", "c", "d"], i)).unwrap();
666        }
667
668        let before = log.scan().unwrap();
669        let before_rows: usize = before.pushes.iter().map(|b| b.num_rows()).sum();
670        assert_eq!(before.pushes.len(), 200);
671
672        let report = log.compact().unwrap();
673        assert_eq!(report.frames_before, 200);
674        assert_eq!(report.frames_after, 1, "everything must fold into one frame");
675        assert_eq!(report.rows, before_rows, "compaction must not drop a row");
676
677        let after = log.scan().unwrap();
678        assert!(after.is_clean(), "a compacted log must scan clean");
679        assert_eq!(after.pushes.len(), 1);
680        assert_eq!(
681            after.pushes[0].num_rows(),
682            before_rows,
683            "the merged batch must carry every row the frames did"
684        );
685
686        std::fs::remove_dir_all(&dir).ok();
687    }
688
689    /// The reason compaction exists, as its own claim so that a mutation which
690    /// stops it saving space fails *here* rather than tripping a row-count
691    /// assertion first. Alignment padding paid 200 times collapses to once.
692    #[test]
693    fn compaction_actually_shrinks_the_log() {
694        let dir = tmpdir("compact_size");
695        let log = PushLog::new(dir.join("refs.log"), schema());
696        for i in 0..200u64 {
697            log.append(&batch(&["a", "b", "c", "d"], i)).unwrap();
698        }
699        let report = log.compact().unwrap();
700        assert!(
701            report.bytes_after * 2 < report.bytes_before,
702            "compaction saved almost nothing: {} -> {} bytes. It costs a rewrite and the \
703             frame boundaries; if it does not pay for them it should not run.",
704            report.bytes_before,
705            report.bytes_after
706        );
707        std::fs::remove_dir_all(&dir).ok();
708    }
709
710    /// **The crash bar.** A compaction interrupted at ANY byte must leave the
711    /// OLD log serving, whole.
712    ///
713    /// Mirrors `gunnar-store`'s `an_interrupted_compaction_leaves_the_old_log_
714    /// serving`, and swept across every byte rather than stopped at one point,
715    /// for the same reason the torn-push sweep is: a recovery that holds at one
716    /// offset and not another is not a recovery. A compaction that can lose a
717    /// ref is worse than the padding it saves.
718    ///
719    /// Seen red by making `compact_with` write the merged frame straight over
720    /// the live log instead of staging and renaming — the sweep then finds cuts
721    /// where the log holds a partial frame and the pushes are gone.
722    #[test]
723    fn an_interrupted_compaction_leaves_the_old_log_serving_at_every_cut() {
724        let dir = tmpdir("compact_crash");
725        let path = dir.join("refs.log");
726        let log = PushLog::new(&path, schema());
727        for i in 0..40u64 {
728            log.append(&batch(&["x", "y"], i)).unwrap();
729        }
730        let intact = std::fs::read(&path).unwrap();
731        let expected_rows: usize = log.scan().unwrap().pushes.iter().map(|b| b.num_rows()).sum();
732
733        // Stage a compaction and stop before the swap — what a crash leaves.
734        let report = log.compact_with(Finish::StopBeforeSwap).unwrap();
735        let staged = compacting_path(&path);
736        assert!(staged.exists(), "the staged replacement must exist to cut into");
737        let staged_bytes = std::fs::read(&staged).unwrap();
738        assert!(staged_bytes.len() > 32);
739
740        for cut in 0..staged_bytes.len() {
741            // A crash part-way through writing the replacement.
742            std::fs::write(&staged, &staged_bytes[..cut]).unwrap();
743
744            // The live log is untouched and still serves every push.
745            assert_eq!(
746                std::fs::read(&path).unwrap(),
747                intact,
748                "cut at {cut}: the LIVE log was modified by a compaction that never \
749                 completed — it must never be written in place"
750            );
751            let scan = log.scan().unwrap();
752            assert!(scan.is_clean(), "cut at {cut}: the live log stopped scanning clean");
753            assert_eq!(
754                scan.pushes.len(),
755                40,
756                "cut at {cut}: the live log lost pushes to an interrupted compaction"
757            );
758            let rows: usize = scan.pushes.iter().map(|b| b.num_rows()).sum();
759            assert_eq!(rows, expected_rows, "cut at {cut}: rows went missing");
760        }
761
762        // And finishing the compaction for real still works afterwards.
763        std::fs::remove_file(&staged).ok();
764        let done = log.compact().unwrap();
765        assert_eq!(done.frames_after, 1);
766        assert_eq!(done.rows, expected_rows);
767        assert_eq!(report.rows, expected_rows);
768
769        std::fs::remove_dir_all(&dir).ok();
770    }
771
772    /// A log written before compaction existed still reads, and a compacted log
773    /// reads on the same scanner. No migration, no version bump.
774    #[test]
775    fn compacted_and_uncompacted_logs_are_the_same_format() {
776        let dir = tmpdir("compat");
777        let path = dir.join("refs.log");
778        let log = PushLog::new(&path, schema());
779        for i in 0..8u64 {
780            log.append(&batch(&["a"], i)).unwrap();
781        }
782        let uncompacted = log.scan().unwrap();
783        log.compact().unwrap();
784        let compacted = log.scan().unwrap();
785
786        // Same rows, same order, read by the same scanner with no flag.
787        let flat = |s: &PushLogScan| -> Vec<u64> {
788            let mut v = Vec::new();
789            for b in &s.pushes {
790                let c = b.column(1).as_any().downcast_ref::<UInt64Array>().unwrap();
791                v.extend((0..c.len()).map(|i| c.value(i)));
792            }
793            v
794        };
795        assert_eq!(flat(&uncompacted), flat(&compacted), "compaction changed the row sequence");
796
797        // Appending after a compaction still works and stays readable.
798        log.append(&batch(&["z"], 99)).unwrap();
799        let after = log.scan().unwrap();
800        assert!(after.is_clean());
801        assert_eq!(after.pushes.len(), 2, "a compacted log must still accept appends");
802        assert_eq!(*flat(&after).last().unwrap(), 99);
803
804        std::fs::remove_dir_all(&dir).ok();
805    }
806
807    /// A batch whose schema is not the log's is refused at append. Writing it
808    /// would produce a frame the scanner parses happily but whose columns no
809    /// reader of this log expects.
810    #[test]
811    fn a_foreign_schema_is_refused_at_append() {
812        let dir = tmpdir("schema");
813        let log = PushLog::new(dir.join("refs.log"), schema());
814        let other = Arc::new(Schema::new(vec![Field::new("x", DataType::Utf8, false)]));
815        let foreign =
816            RecordBatch::try_new(other, vec![Arc::new(StringArray::from(vec!["v"]))]).unwrap();
817        let err = log.append(&foreign).unwrap_err().to_string();
818        assert!(err.contains("schema"), "expected a schema error, got: {err}");
819        std::fs::remove_dir_all(&dir).ok();
820    }
821}