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