Skip to main content

witness_store/
segment.rs

1//! Writing the archive in segments.
2//!
3//! A segment nominally covers `segment_ledgers` consecutive ledgers.
4//! Validations for one ledger arrive over several seconds and some are late,
5//! so a segment is not closed exactly at the range boundary but once a
6//! validation arrives `grace_ledgers` past it. Anything later than that goes
7//! into the next segment; every record carries its own ledger index, so
8//! readers are not affected.
9//!
10//! Data directory layout:
11//!
12//! ```text
13//! current.xwvj        journal of the open segment
14//! current.json        what this segment is: nominal start, open time
15//! segments/           closed segments: *.xwv.zst and seals *.seal.json
16//! ```
17//!
18//! The closing order is chosen so that a crash at any moment loses nothing:
19//! the compressed segment and the seal are written first (via temporary files
20//! and rename), and only then is the journal deleted. If the process dies
21//! between these steps, the seal already exists at startup, so the journal is
22//! treated as a duplicate and deleted.
23
24use std::collections::VecDeque;
25use std::fs;
26use std::path::{Path, PathBuf};
27
28use serde::{Deserialize, Serialize};
29use witness_core::sha512_half;
30
31use crate::journal::{Journal, MAGIC};
32use crate::record::Record;
33use crate::seal::{FORMAT, Seal, missing_ranges};
34use crate::{Error, Result};
35
36/// How many recent records to keep for the median: about 25 seconds of the
37/// mainnet stream. A shorter window gets knocked over by a burst: on
38/// 2026-10-23 at 14:20 UTC peers relayed a batch of devnet validations, and
39/// the median over 129 records (a second and a half of the stream) jumped to
40/// devnet numbers for three seconds. Knocking over a median of 2048 takes
41/// more than a thousand foreign records in a row.
42const RECENT: usize = 2048;
43
44/// How many records are needed before the median is trusted and a segment is
45/// opened. On live mainnet this is less than a second of the stream.
46const WARMUP: usize = 64;
47
48/// How far a ledger index may be from the median for the record to count as
49/// belonging to our network.
50///
51/// This is needed because validations from other networks leak into the
52/// mainnet stream through peer relaying: a measurement on one of our
53/// archivers on 2026-10-23 showed about 13% of the stream, with ledgers
54/// around 6.3 million (devnet) and 21.7 million (testnet). Their `network_id`
55/// field in the stream is the same as mainnet's, so they can only be told
56/// apart by ledger index. Such records are stored (they are signed data
57/// too), but they take no part in segment slicing or completeness
58/// accounting.
59const OUTLIER_WINDOW: u32 = 256;
60
61#[derive(Debug, Clone)]
62pub struct SegmentConfig {
63    pub dir: PathBuf,
64    pub source: String,
65    pub segment_ledgers: u32,
66    pub grace_ledgers: u32,
67    pub zstd_level: i32,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71struct OpenMeta {
72    nominal_first: u32,
73    opened_ms: u64,
74    /// The ledger from which the archive starts being responsible for
75    /// completeness, if it has not started yet: the first segment, or the
76    /// first one after re-slicing. This is the network's current ledger at
77    /// open time, not the oldest record: lagging validators send validations
78    /// a hundred ledgers back, and using those would make the archive report
79    /// as missing everything from before it started.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    coverage_from: Option<u32>,
82}
83
84/// Result of closing a segment, for the archiver's event log.
85#[derive(Debug, Clone)]
86pub struct Sealed {
87    pub seal: Seal,
88    pub path: PathBuf,
89    /// Size of the compressed file, for the log; not part of the seal.
90    pub zst_bytes: u64,
91}
92
93/// The numbering lineage the archive is responsible for keeping complete: the
94/// last ledger and when it was reported.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96struct Lineage {
97    last: u32,
98    at_ms: u64,
99}
100
101/// The network does not advance faster than this: a ledger closes every 3 to 4
102/// seconds, and we take twice the margin.
103const MIN_LEDGER_MS: u64 = 1_500;
104
105impl Lineage {
106    /// The reference ledger could have grown to `reference` in the elapsed
107    /// time, so this is a continuation of the same lineage, not a jump to
108    /// foreign numbering. Archiver downtime counts as a continuation: over
109    /// hours the network moves thousands of ledgers ahead, and the gap is
110    /// recorded honestly in the seal.
111    fn continued_by(&self, reference: u32, now_ms: u64) -> bool {
112        let elapsed = now_ms.saturating_sub(self.at_ms) / MIN_LEDGER_MS;
113        let reach = u64::from(self.last) + u64::from(OUTLIER_WINDOW) + elapsed;
114        reference.saturating_add(OUTLIER_WINDOW) >= self.last && u64::from(reference) <= reach
115    }
116}
117
118/// How many parked lineages to remember.
119const PARKED: usize = 4;
120
121#[derive(Debug)]
122pub struct SegmentWriter {
123    cfg: SegmentConfig,
124    journal: Journal,
125    open: Option<OpenMeta>,
126    seen: Vec<u32>,
127    records: u64,
128    /// Records far from the network's current ledger; see `OUTLIER_WINDOW`.
129    out_of_window: u64,
130    first: u32,
131    last: u32,
132    /// Ledger indexes of recent records; their median determines which ledger
133    /// is the network's current one.
134    recent: VecDeque<u32>,
135    /// Records received before the median became reliable.
136    warmup: Vec<Record>,
137    /// Hash of the previous seal; there is one hash chain for the whole archive.
138    prev_hash: Option<String>,
139    /// The numbering lineage we are currently responsible for. `None` means we
140    /// have not started yet.
141    lineage: Option<Lineage>,
142    /// Parked lineages: if the reference jumped to foreign numbering and came
143    /// back, responsibility resumes where it was parked instead of reporting
144    /// everything between the two numberings as missing.
145    parked: Vec<Lineage>,
146    /// How many bytes of torn tail were cut off at startup.
147    pub torn_bytes_at_start: u64,
148}
149
150impl SegmentWriter {
151    pub fn open(cfg: SegmentConfig) -> Result<SegmentWriter> {
152        if cfg.segment_ledgers == 0 {
153            return Err(Error::Format("segment_ledgers cannot be zero".into()));
154        }
155        fs::create_dir_all(cfg.dir.join("segments"))?;
156        let latest = latest_seal(&cfg.dir.join("segments"))?;
157        let lineage = latest
158            .as_ref()
159            .filter(|s| s.coverage_last > 0)
160            .map(|s| Lineage {
161                last: s.coverage_last,
162                at_ms: s.sealed_ms,
163            });
164        let prev_hash = latest.map(|s| s.seal_hash);
165
166        let meta_path = cfg.dir.join("current.json");
167        let journal_path = cfg.dir.join("current.xwvj");
168        let mut open: Option<OpenMeta> = match fs::read(&meta_path) {
169            Ok(b) => Some(serde_json::from_slice(&b)?),
170            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
171            Err(e) => return Err(e.into()),
172        };
173
174        // The journal was already sealed but not yet deleted: it is a duplicate.
175        if let Some(m) = &open
176            && seal_path(&cfg.dir, m.nominal_first, m.opened_ms).exists()
177        {
178            fs::remove_file(&journal_path).ok();
179            fs::remove_file(&meta_path).ok();
180            open = None;
181        }
182
183        let (journal, recovered) = Journal::open(&journal_path)?;
184        let mut w = SegmentWriter {
185            cfg,
186            journal,
187            open: None,
188            seen: Vec::new(),
189            records: 0,
190            out_of_window: 0,
191            first: u32::MAX,
192            last: 0,
193            recent: VecDeque::with_capacity(RECENT + 1),
194            warmup: Vec::new(),
195            prev_hash,
196            lineage,
197            parked: Vec::new(),
198            torn_bytes_at_start: recovered.torn_bytes,
199        };
200        match open {
201            Some(m) => {
202                // Whether records belong to the network is judged by the
203                // segment's own range, not by the current reference: the
204                // journal may have accumulated for up to an hour, and records
205                // from its start are more than a window away from the current
206                // ledger. On 2026-10-23 a restart reported 8 ledgers as
207                // missing this way, even though they were in the journal.
208                let lo = m.nominal_first.saturating_sub(OUTLIER_WINDOW);
209                let hi = m
210                    .nominal_first
211                    .saturating_add(w.cfg.segment_ledgers)
212                    .saturating_add(w.cfg.grace_ledgers)
213                    .saturating_add(OUTLIER_WINDOW);
214                for r in &recovered.records {
215                    w.remember(r.ledger_index);
216                    w.note_in(r.ledger_index, (lo..=hi).contains(&r.ledger_index));
217                }
218                w.open = Some(m);
219            }
220            None if !recovered.records.is_empty() => {
221                return Err(Error::Format(
222                    "journal has records but no segment description: needs manual inspection"
223                        .into(),
224                ));
225            }
226            None => {}
227        }
228        Ok(w)
229    }
230
231    fn remember(&mut self, ledger: u32) {
232        self.recent.push_back(ledger);
233        if self.recent.len() > RECENT {
234            self.recent.pop_front();
235        }
236    }
237
238    /// The network's current ledger: the median of recent records' ledger
239    /// indexes. Foreign networks are a minority in the stream, so the median
240    /// ignores them.
241    fn reference(&self) -> Option<u32> {
242        if self.recent.is_empty() {
243            return None;
244        }
245        let mut v: Vec<u32> = self.recent.iter().copied().collect();
246        let mid = v.len() / 2;
247        Some(*v.select_nth_unstable(mid).1)
248    }
249
250    fn note(&mut self, ledger: u32, reference: u32) {
251        self.note_in(ledger, ledger.abs_diff(reference) <= OUTLIER_WINDOW);
252    }
253
254    fn note_in(&mut self, ledger: u32, in_window: bool) {
255        self.records += 1;
256        if !in_window {
257            self.out_of_window += 1;
258            return;
259        }
260        self.seen.push(ledger);
261        self.first = self.first.min(ledger);
262        self.last = self.last.max(ledger);
263    }
264
265    fn nominal_start(&self, ledger: u32) -> u32 {
266        ledger - ledger % self.cfg.segment_ledgers
267    }
268
269    /// Picks the responsibility lineage for a new segment: continue the current
270    /// one, return to a parked one, or start over.
271    fn choose_lineage(&mut self, reference: u32, now: u64) {
272        if self.lineage.is_some_and(|l| l.continued_by(reference, now)) {
273            return;
274        }
275        if let Some(l) = self.lineage.take() {
276            self.parked.push(l);
277            if self.parked.len() > PARKED {
278                self.parked.remove(0);
279            }
280        }
281        if let Some(i) = self
282            .parked
283            .iter()
284            .rposition(|l| l.continued_by(reference, now))
285        {
286            self.lineage = Some(self.parked.remove(i));
287        }
288    }
289
290    fn open_segment(&mut self, reference: u32) -> Result<()> {
291        let now = witness_core::util::now_ms();
292        self.choose_lineage(reference, now);
293        let m = OpenMeta {
294            nominal_first: self.nominal_start(reference),
295            opened_ms: now,
296            coverage_from: self.lineage.is_none().then_some(reference),
297        };
298        witness_core::util::write_atomic(
299            &self.cfg.dir.join("current.json"),
300            &serde_json::to_vec(&m)?,
301        )?;
302        self.open = Some(m);
303        Ok(())
304    }
305
306    fn write(&mut self, rec: &Record, reference: u32) -> Result<()> {
307        self.journal.append(rec)?;
308        self.note(rec.ledger_index, reference);
309        Ok(())
310    }
311
312    /// Adds a record. If it is time to close the current segment, closes it and
313    /// returns its seal.
314    ///
315    /// After a start with an empty journal, the first `WARMUP` records are
316    /// buffered in memory while the median cannot be trusted yet: opening a
317    /// segment on a stray validation from a foreign network would slice the
318    /// archive in the wrong place. If that happens anyway, the segment
319    /// re-slices itself (see the `stale` condition below), and completeness
320    /// responsibility does not mix up lineages (see `Lineage`).
321    pub fn append(&mut self, rec: &Record) -> Result<Option<Sealed>> {
322        self.remember(rec.ledger_index);
323        let Some(reference) = self.reference() else {
324            return Ok(None);
325        };
326
327        if self.open.is_none() {
328            if self.recent.len() < WARMUP {
329                self.warmup.push(rec.clone());
330                return Ok(None);
331            }
332            self.open_segment(reference)?;
333            for early in std::mem::take(&mut self.warmup) {
334                self.write(&early, reference)?;
335            }
336            self.write(rec, reference)?;
337            return Ok(None);
338        }
339
340        let mut sealed = None;
341        if let Some(m) = &self.open {
342            let boundary = m
343                .nominal_first
344                .saturating_add(self.cfg.segment_ledgers)
345                .saturating_add(self.cfg.grace_ledgers);
346            // The second condition is self-healing. If the segment was opened
347            // in the wrong place (the archiver started during a burst of
348            // foreign-network validations and the median was wrong), or the
349            // network was restarted with different numbers, the current
350            // ledger ends up far below the open range. The segment is then
351            // closed as is and reopened from the network; otherwise slicing
352            // would be stuck forever.
353            let stale = reference.saturating_add(OUTLIER_WINDOW) < m.nominal_first;
354            if reference >= boundary || stale {
355                sealed = self.seal_current()?;
356                self.open_segment(reference)?;
357            }
358        }
359        self.write(rec, reference)?;
360        Ok(sealed)
361    }
362
363    /// Flushes the journal to disk.
364    pub fn sync(&mut self) -> Result<()> {
365        self.journal.sync()
366    }
367
368    /// Nominal start of the open segment and the number of records in it.
369    pub fn current(&self) -> Option<(u32, u64)> {
370        self.open.as_ref().map(|m| (m.nominal_first, self.records))
371    }
372
373    /// The network's current ledger, from the median of recent records.
374    pub fn network_ledger(&self) -> Option<u32> {
375        self.reference()
376    }
377
378    /// The record is far from the current ledger: a foreign network or very late.
379    pub fn is_out_of_window(&self, ledger: u32) -> bool {
380        self.reference()
381            .is_some_and(|r| ledger.abs_diff(r) > OUTLIER_WINDOW)
382    }
383
384    /// Size of the open segment's journal, including what has not been flushed.
385    pub fn journal_bytes(&self) -> u64 {
386        self.journal.len()
387    }
388
389    /// The highest ledger index among records in the open segment.
390    pub fn last_ledger(&self) -> Option<u32> {
391        (self.records > 0).then_some(self.last)
392    }
393
394    fn seal_current(&mut self) -> Result<Option<Sealed>> {
395        let Some(m) = self.open.clone() else {
396            return Ok(None);
397        };
398        self.journal.sync()?;
399        if self.journal.is_empty() {
400            return Ok(None);
401        }
402
403        let raw = fs::read(self.journal.path())?;
404        let zst = zstd::bulk::compress(&raw, self.cfg.zstd_level)?;
405        let seg_path = segment_path(&self.cfg.dir, m.nominal_first, m.opened_ms);
406        witness_core::util::write_atomic(&seg_path, &zst)?;
407
408        let nominal_last = m.nominal_first.saturating_add(self.cfg.segment_ledgers - 1);
409        let in_window = !self.seen.is_empty();
410        let (first, last) = if in_window {
411            (self.first, self.last)
412        } else {
413            (0, 0)
414        };
415        // Coverage spans are contiguous: each one starts right after the
416        // previous. A segment with no ledgers from our network is responsible
417        // for nothing (an empty span), and the next one continues from the
418        // same place.
419        let prev_last = self.lineage.map(|l| l.last);
420        let (coverage_first, coverage_last) = if in_window {
421            // A new lineage is responsible from the first ledger that actually
422            // landed in the segment, but not earlier than the reference at
423            // open time: below the reference are lagging validators, above it
424            // is whatever the median, while switching to this numbering,
425            // still assigned to the previous segment.
426            let from = match m.coverage_from {
427                Some(c) => c.max(first),
428                None => prev_last.map_or(first, |p| p.saturating_add(1)),
429            };
430            (from, last)
431        } else {
432            let p = prev_last.unwrap_or(0);
433            (p.saturating_add(1), p)
434        };
435        let seal = Seal {
436            format: FORMAT.into(),
437            source: self.cfg.source.clone(),
438            nominal_first: m.nominal_first,
439            nominal_last,
440            first_ledger: first,
441            last_ledger: last,
442            records: self.records,
443            out_of_window: self.out_of_window,
444            coverage_first,
445            coverage_last,
446            missing_ledgers: missing_ranges(coverage_first, coverage_last, &self.seen),
447            opened_ms: m.opened_ms,
448            sealed_ms: witness_core::util::now_ms(),
449            raw_bytes: raw.len() as u64,
450            raw_hash: hex::encode_upper(sha512_half(&raw)),
451            prev_seal_hash: self.prev_hash.clone(),
452            seal_hash: String::new(),
453        }
454        .finalize();
455        witness_core::util::write_atomic(
456            &seal_path(&self.cfg.dir, m.nominal_first, m.opened_ms),
457            &serde_json::to_vec_pretty(&seal)?,
458        )?;
459
460        // Only now, with the segment and the seal on disk, is the journal no longer needed.
461        fs::remove_file(self.cfg.dir.join("current.json"))?;
462        fs::remove_file(self.journal.path())?;
463        let (journal, _) = Journal::open(&self.cfg.dir.join("current.xwvj"))?;
464        self.journal = journal;
465        self.open = None;
466        self.seen.clear();
467        self.records = 0;
468        self.out_of_window = 0;
469        self.first = u32::MAX;
470        self.last = 0;
471        self.prev_hash = Some(seal.seal_hash.clone());
472        if in_window {
473            self.lineage = Some(Lineage {
474                last: seal.coverage_last,
475                at_ms: seal.sealed_ms,
476            });
477        }
478        Ok(Some(Sealed {
479            seal,
480            path: seg_path,
481            zst_bytes: zst.len() as u64,
482        }))
483    }
484}
485
486fn segment_path(dir: &Path, nominal_first: u32, opened_ms: u64) -> PathBuf {
487    dir.join("segments")
488        .join(format!("seg-{nominal_first:010}-{opened_ms}.xwv.zst"))
489}
490
491fn seal_path(dir: &Path, nominal_first: u32, opened_ms: u64) -> PathBuf {
492    dir.join("segments")
493        .join(format!("seg-{nominal_first:010}-{opened_ms}.seal.json"))
494}
495
496/// The most recently sealed seal in the segments directory.
497pub fn latest_seal(segments: &Path) -> Result<Option<Seal>> {
498    let mut best: Option<Seal> = None;
499    for entry in fs::read_dir(segments)? {
500        let path = entry?.path();
501        if !path.to_string_lossy().ends_with(".seal.json") {
502            continue;
503        }
504        let seal: Seal = serde_json::from_slice(&fs::read(&path)?)?;
505        if !seal.is_intact() {
506            return Err(Error::Format(format!(
507                "{}: seal is damaged",
508                path.display()
509            )));
510        }
511        if best.as_ref().is_none_or(|b| seal.sealed_ms > b.sealed_ms) {
512            best = Some(seal);
513        }
514    }
515    Ok(best)
516}
517
518/// Decompressed content of a closed segment: what the seal commits to.
519pub fn read_segment_raw(path: &Path) -> Result<Vec<u8>> {
520    Ok(zstd::stream::decode_all(&fs::read(path)?[..])?)
521}
522
523/// The segment matches its seal: the seal is intact and the content is the same.
524pub fn verify_segment(path: &Path, seal: &Seal) -> Result<bool> {
525    let raw = read_segment_raw(path)?;
526    Ok(seal.is_intact()
527        && raw.len() as u64 == seal.raw_bytes
528        && hex::encode_upper(sha512_half(&raw)) == seal.raw_hash)
529}
530
531/// Reads a closed segment in full.
532pub fn read_segment(path: &Path) -> Result<Vec<Record>> {
533    let raw = read_segment_raw(path)?;
534    if !raw.starts_with(MAGIC) {
535        return Err(Error::Format(format!(
536            "{}: not an xrpl-witness segment",
537            path.display()
538        )));
539    }
540    let mut out = Vec::new();
541    let mut at = MAGIC.len();
542    while let Some((rec, used)) = Record::decode(&raw[at..]).map_err(Error::Format)? {
543        out.push(rec);
544        at += used;
545    }
546    if at != raw.len() {
547        return Err(Error::Format(format!(
548            "{}: trailing data cannot be parsed",
549            path.display()
550        )));
551    }
552    Ok(out)
553}
554
555#[cfg(test)]
556mod tests {
557    use super::*;
558
559    /// Live mainnet has about 85 validations per ledger.
560    const PER_LEDGER: u8 = 85;
561
562    fn cfg(dir: &Path) -> SegmentConfig {
563        SegmentConfig {
564            dir: dir.to_owned(),
565            source: "test".into(),
566            segment_ledgers: 100,
567            grace_ledgers: 5,
568            zstd_level: 3,
569        }
570    }
571
572    fn rec(ledger: u32, n: u8) -> Record {
573        Record {
574            received_ms: u64::from(ledger) * 1000 + u64::from(n),
575            ledger_index: ledger,
576            data: vec![n; 233],
577        }
578    }
579
580    /// Feeds consecutive ledgers, `PER_LEDGER` validations each; collects the seals.
581    fn feed(w: &mut SegmentWriter, ledgers: impl Iterator<Item = u32>) -> Vec<Sealed> {
582        let mut out = Vec::new();
583        for l in ledgers {
584            for n in 0..PER_LEDGER {
585                if let Some(s) = w.append(&rec(l, n)).unwrap() {
586                    out.push(s);
587                }
588            }
589        }
590        out
591    }
592
593    fn check_chain(seals: &[Sealed]) {
594        for pair in seals.windows(2) {
595            let (a, b) = (&pair[0].seal, &pair[1].seal);
596            assert_eq!(b.prev_seal_hash.as_deref(), Some(a.seal_hash.as_str()));
597            // Coverage spans meet with no gaps or overlaps.
598            assert_eq!(b.coverage_first, a.coverage_last + 1);
599        }
600        for s in seals {
601            assert!(s.seal.is_intact());
602            let back = read_segment(&s.path).unwrap();
603            assert_eq!(back.len() as u64, s.seal.records);
604            assert!(verify_segment(&s.path, &s.seal).unwrap());
605        }
606    }
607
608    #[test]
609    fn segments_seal_with_a_hash_chain() {
610        let dir = tempfile::tempdir().unwrap();
611        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
612        let seals = feed(&mut w, 1000..1400);
613        assert!(seals.len() >= 3, "seals: {}", seals.len());
614        assert_eq!(seals[0].seal.prev_seal_hash, None);
615        check_chain(&seals);
616        for s in &seals {
617            assert!(
618                s.seal.missing_ledgers.is_empty(),
619                "{:?}",
620                s.seal.missing_ledgers
621            );
622            assert_eq!(s.seal.out_of_window, 0);
623        }
624        // No record is lost: everything is either in seals or in the open segment.
625        let sealed: u64 = seals.iter().map(|s| s.seal.records).sum();
626        let open = w.current().map(|c| c.1).unwrap_or(0);
627        assert_eq!(sealed + open, 400 * u64::from(PER_LEDGER));
628    }
629
630    #[test]
631    fn missing_ledgers_are_reported() {
632        let dir = tempfile::tempdir().unwrap();
633        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
634        let seals = feed(&mut w, (1000..1250).filter(|l| !(1040..=1042).contains(l)));
635        assert_eq!(seals[0].seal.missing_ledgers, vec![[1040, 1042]]);
636    }
637
638    #[test]
639    fn restart_continues_the_open_segment_and_the_chain() {
640        let dir = tempfile::tempdir().unwrap();
641        let first = {
642            let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
643            let seals = feed(&mut w, 1000..1160);
644            w.sync().unwrap();
645            seals
646        };
647        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
648        assert!(w.current().is_some(), "the open segment should continue");
649        let second = feed(&mut w, 1160..1400);
650        let all: Vec<Sealed> = first.into_iter().chain(second).collect();
651        check_chain(&all);
652        for s in &all {
653            assert!(
654                s.seal.missing_ledgers.is_empty(),
655                "{:?}",
656                s.seal.missing_ledgers
657            );
658        }
659    }
660
661    #[test]
662    fn foreign_network_validations_do_not_derail_the_archive() {
663        let dir = tempfile::tempdir().unwrap();
664        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
665        let mut seals = Vec::new();
666        let mut foreign = 0u64;
667        for l in 1000..1400u32 {
668            for n in 0..PER_LEDGER {
669                // Like the live stream: ~13% foreign networks, plus rare garbage from the future.
670                let ledger = match n {
671                    0..=5 => 6_348_163 + l,
672                    6..=10 => 21_757_096 + l,
673                    11 if l % 50 == 0 => 4_000_000_000,
674                    _ => l,
675                };
676                if ledger != l {
677                    foreign += 1;
678                }
679                if let Some(s) = w.append(&rec(ledger, n)).unwrap() {
680                    seals.push(s);
681                }
682            }
683        }
684        assert!(seals.len() >= 3);
685        check_chain(&seals);
686        for s in &seals {
687            let s = &s.seal;
688            // Slicing follows mainnet; foreign numbers did not throw it off.
689            assert!(
690                (1000..1400).contains(&s.nominal_first),
691                "{}",
692                s.nominal_first
693            );
694            assert!(s.last_ledger < 1400 && s.first_ledger >= 1000);
695            assert!(s.missing_ledgers.is_empty(), "{:?}", s.missing_ledgers);
696            assert!(s.out_of_window > 0);
697        }
698        let counted: u64 = seals.iter().map(|s| s.seal.out_of_window).sum();
699        assert!(counted <= foreign && counted > 0);
700    }
701
702    #[test]
703    fn archive_recovers_if_it_started_on_foreign_validations() {
704        let dir = tempfile::tempdir().unwrap();
705        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
706        // Worst start: the first few hundred records are all from a foreign network.
707        for n in 0..200u32 {
708            w.append(&rec(6_348_163 + n / 85, 0)).unwrap();
709        }
710        let seals = feed(&mut w, 1000..1400);
711        assert!(seals.len() >= 3, "seals: {}", seals.len());
712        // The first seal may be odd; after that slicing follows mainnet.
713        for s in &seals[1..] {
714            assert!(
715                (1000..1400).contains(&s.seal.nominal_first),
716                "{}",
717                s.seal.nominal_first
718            );
719            // Mainnet responsibility started afresh instead of continuing from
720            // foreign numbers: no false gaps and no span "from zero".
721            assert!(s.seal.coverage_first >= 1000, "{}", s.seal.coverage_first);
722            assert!(
723                s.seal.missing_ledgers.is_empty(),
724                "{:?}",
725                s.seal.missing_ledgers
726            );
727        }
728        // Hashes are linked through the whole chain, including the odd first seal.
729        assert_eq!(
730            seals[1].seal.prev_seal_hash.as_deref(),
731            Some(seals[0].seal.seal_hash.as_str())
732        );
733        check_chain(&seals[1..]);
734    }
735
736    #[test]
737    fn lagging_validators_do_not_fake_gaps_before_the_start() {
738        // Live mainnet, 2026-10-23: some validators lag and send validations
739        // dozens of ledgers back. Because of this, the first seal on one of our
740        // archivers reported 83 ledgers as missing that the archiver could
741        // never have seen.
742        let dir = tempfile::tempdir().unwrap();
743        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
744        let mut seals = Vec::new();
745        for l in 1000..1400u32 {
746            for n in 0..PER_LEDGER {
747                let ledger = if n < 3 { l - 90 } else { l };
748                if let Some(s) = w.append(&rec(ledger, n)).unwrap() {
749                    seals.push(s);
750                }
751            }
752        }
753        assert!(seals.len() >= 3);
754        check_chain(&seals);
755        assert_eq!(seals[0].seal.coverage_first, 1000);
756        // Lagging records are kept and show up in the first/last ledgers.
757        assert!(seals[0].seal.first_ledger < 1000);
758        for s in &seals {
759            assert!(
760                s.seal.missing_ledgers.is_empty(),
761                "{:?}",
762                s.seal.missing_ledgers
763            );
764        }
765    }
766
767    #[test]
768    fn restart_after_a_seal_reports_the_downtime() {
769        let dir = tempfile::tempdir().unwrap();
770        let first = {
771            let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
772            let seals = feed(&mut w, 1000..1110);
773            w.sync().unwrap();
774            seals
775        };
776        // Downtime: nobody recorded ledgers 1110..1120.
777        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
778        let second = feed(&mut w, 1120..1400);
779        let all: Vec<Sealed> = first.into_iter().chain(second).collect();
780        check_chain(&all);
781        let missing: Vec<[u32; 2]> = all
782            .iter()
783            .flat_map(|s| s.seal.missing_ledgers.clone())
784            .collect();
785        assert_eq!(missing, vec![[1110, 1119]]);
786    }
787
788    #[test]
789    fn leftover_journal_after_crash_mid_seal_is_dropped() {
790        let dir = tempfile::tempdir().unwrap();
791        let (journal_copy, meta_copy) = {
792            let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
793            let mut copies = None;
794            'outer: for l in 1000..1300 {
795                // Snapshot the journal once per ledger: what matters for the check
796                // is the description of the sealed segment, not how fresh the
797                // journal is.
798                w.sync().unwrap();
799                let j = fs::read(dir.path().join("current.xwvj")).ok();
800                let m = fs::read(dir.path().join("current.json")).ok();
801                for n in 0..PER_LEDGER {
802                    if w.append(&rec(l, n)).unwrap().is_some() {
803                        copies = j.clone().zip(m.clone());
804                        break 'outer;
805                    }
806                }
807            }
808            copies.unwrap()
809        };
810        // Crash after writing the seal but before deleting the journal: the
811        // journal and the description of the already sealed segment are back
812        // on disk.
813        fs::write(dir.path().join("current.xwvj"), &journal_copy).unwrap();
814        fs::write(dir.path().join("current.json"), &meta_copy).unwrap();
815
816        let w = SegmentWriter::open(cfg(dir.path())).unwrap();
817        assert_eq!(w.current(), None, "the sealed journal should be discarded");
818        assert!(latest_seal(&dir.path().join("segments")).unwrap().is_some());
819    }
820
821    #[test]
822    fn recompression_keeps_the_seal_and_tampering_breaks_it() {
823        let dir = tempfile::tempdir().unwrap();
824        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
825        let seals = feed(&mut w, 1000..1250);
826        let s = &seals[0];
827
828        // Recompressing at another level: different file, same seal.
829        let raw = read_segment_raw(&s.path).unwrap();
830        let before = fs::read(&s.path).unwrap();
831        let again = zstd::bulk::compress(&raw, 19).unwrap();
832        assert_ne!(before, again);
833        fs::write(&s.path, &again).unwrap();
834        assert!(verify_segment(&s.path, &s.seal).unwrap());
835
836        // Changing a single content byte fails the seal check.
837        let mut forged = raw.clone();
838        let last = forged.len() - 1;
839        forged[last] ^= 1;
840        fs::write(&s.path, zstd::bulk::compress(&forged, 9).unwrap()).unwrap();
841        assert!(!verify_segment(&s.path, &s.seal).unwrap());
842    }
843
844    // On the live network mainnet numbers are HIGHER than devnet and testnet
845    // numbers, and the tests below reproduce exactly that relationship.
846    const MAIN: u32 = 107_000_000;
847    const DEVNET: u32 = 6_350_000;
848
849    fn total_missing(seals: &[Sealed]) -> u64 {
850        seals
851            .iter()
852            .flat_map(|s| s.seal.missing_ledgers.iter())
853            .map(|[a, b]| u64::from(b - a) + 1)
854            .sum()
855    }
856
857    /// Consecutive mainnet ledgers, with a batch of `burst` devnet validations at ledger `at`.
858    fn feed_with_burst(w: &mut SegmentWriter, at: u32, burst: u32) -> Vec<Sealed> {
859        let mut out = Vec::new();
860        for l in MAIN..MAIN + 400 {
861            if l == MAIN + at {
862                for i in 0..burst {
863                    if let Some(s) = w.append(&rec(DEVNET + i / 85, 0)).unwrap() {
864                        out.push(s);
865                    }
866                }
867            }
868            for n in 0..PER_LEDGER {
869                if let Some(s) = w.append(&rec(l, n)).unwrap() {
870                    out.push(s);
871                }
872            }
873        }
874        out
875    }
876
877    #[test]
878    fn burst_of_foreign_validations_does_not_move_the_reference() {
879        // 800 records in a row: six times the old median window.
880        let dir = tempfile::tempdir().unwrap();
881        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
882        let seals = feed_with_burst(&mut w, 150, 800);
883        check_chain(&seals);
884        for s in &seals {
885            assert!(s.seal.nominal_first >= MAIN, "{}", s.seal.nominal_first);
886        }
887        assert_eq!(total_missing(&seals), 0);
888    }
889
890    #[test]
891    fn hijack_and_return_does_not_fake_a_gap() {
892        // A batch that does knock over the median. This happened on
893        // 2026-10-23: a seal reported a hundred million ledgers between the
894        // numberings as missing.
895        let dir = tempfile::tempdir().unwrap();
896        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
897        let seals = feed_with_burst(&mut w, 150, 6000);
898        assert!(
899            seals.iter().any(|s| s.seal.nominal_first < MAIN),
900            "the scenario should knock over the median"
901        );
902        for pair in seals.windows(2) {
903            assert_eq!(
904                pair[1].seal.prev_seal_hash.as_deref(),
905                Some(pair[0].seal.seal_hash.as_str())
906            );
907        }
908        // Gaps are only what really did not reach the mainnet lineage while the
909        // reference was off, not everything between the numberings.
910        let main: Vec<Sealed> = seals
911            .into_iter()
912            .filter(|s| s.seal.nominal_first >= MAIN)
913            .collect();
914        assert!(total_missing(&main) < 100, "{}", total_missing(&main));
915        for s in &main {
916            assert!(s.seal.coverage_first >= MAIN, "{}", s.seal.coverage_first);
917        }
918    }
919
920    #[test]
921    fn start_on_a_lower_numbered_foreign_network() {
922        let dir = tempfile::tempdir().unwrap();
923        let mut w = SegmentWriter::open(cfg(dir.path())).unwrap();
924        let mut seals = Vec::new();
925        for i in 0..3000u32 {
926            if let Some(s) = w.append(&rec(DEVNET + i / 85, 0)).unwrap() {
927                seals.push(s);
928            }
929        }
930        seals.extend(feed(&mut w, MAIN..MAIN + 400));
931        let main: Vec<Sealed> = seals
932            .into_iter()
933            .filter(|s| s.seal.nominal_first >= MAIN)
934            .collect();
935        assert!(main.len() >= 2);
936        // Mainnet responsibility started from mainnet instead of continuing from
937        // devnet numbers.
938        assert!(
939            main[0].seal.coverage_first >= MAIN,
940            "{}",
941            main[0].seal.coverage_first
942        );
943        assert_eq!(total_missing(&main), 0);
944    }
945
946    #[test]
947    fn restart_late_in_a_long_segment_keeps_its_early_ledgers() {
948        // 1024-ledger segments, restart 500 ledgers after opening: further from
949        // its start than the membership window.
950        let dir = tempfile::tempdir().unwrap();
951        let long = SegmentConfig {
952            segment_ledgers: 1024,
953            grace_ledgers: 32,
954            ..cfg(dir.path())
955        };
956        {
957            let mut w = SegmentWriter::open(long.clone()).unwrap();
958            assert!(feed(&mut w, 2048..2600).is_empty());
959            w.sync().unwrap();
960        }
961        let mut w = SegmentWriter::open(long).unwrap();
962        let seals = feed(&mut w, 2600..3300);
963        assert_eq!(seals.len(), 1);
964        assert_eq!(seals[0].seal.coverage_first, 2048);
965        assert!(
966            seals[0].seal.missing_ledgers.is_empty(),
967            "{:?}",
968            seals[0].seal.missing_ledgers
969        );
970    }
971}