znippy-common 0.11.0

Core logic and data structures for Znippy, a parallel chunked compression system.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! `HotView` — a hot archive read by **another process**: the one that does not
//! write it.
//!
//! It opens the blob file and the journal segments `<archive>.hot.NNNNN`
//! read-only and never creates, cuts or writes a file. [`refresh`](HotView::refresh)
//! reads only what changed since the last one:
//!
//! * each segment from where the last refresh left it, up to its last whole
//!   message (a message being written is left for the next refresh —
//!   [`valid_prefix`](crate::ipc_guard::valid_prefix));
//! * new segments whole;
//! * nothing at all when no segment grew.
//!
//! Anything that is not a pure growth — the file replaced, a segment gone or
//! shrunk, the journal removed by a seal, a sealed archive gone hot again —
//! makes it read everything again from nothing, which is always right.
//!
//! **A row is trusted only if the bytes it names lie in the file.** The writer
//! fsyncs the bytes before the journal message that names them, so the file is
//! looked at *after* the journal is read; a row naming bytes past its end is not
//! taken (and counted, [`HotViewStats::untrusted_rows`]). Every read checks the
//! bounds again against the file's length at the read.
//!
//! When the archive and its journal are both gone, the view keeps what it last
//! read (a stack renames a sealed layer away under its readers; [`StackView`]
//! follows it there).
//!
//! [`StackView`]: crate::StackView

use std::fs::File;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard};

use anyhow::{anyhow, ensure, Result};

use crate::archive::ZnippyReader;
use crate::hot::journal_segments;
use crate::rows::{
    changed_keys, own_bytes_end, Blob, Group, Lookup, RowEntry, RowIndex, SegmentCursor,
};
use crate::stack::LayerInfo;

/// Counters, for a bench to state what a refresh cost.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct HotViewStats {
    pub refreshes: u64,
    /// Refreshes that read everything again.
    pub rebuilds: u64,
    /// Journal bytes read, over all refreshes.
    pub journal_bytes_read: u64,
    /// Rows not taken because their bytes did not lie in the file.
    pub untrusted_rows: u64,
}

/// A read-only view of a hot (or sealed) archive. See the module docs.
pub struct HotView {
    archive: PathBuf,
    state: RwLock<ViewState>,
    read: Mutex<ReadState>,
}

#[derive(Default)]
struct ViewState {
    index: RowIndex,
    blobs: Option<Arc<File>>,
    layer: Option<LayerInfo>,
    sealed: bool,
}

#[derive(Default)]
struct ReadState {
    /// `(dev, ino)` of the blob file the state was read against.
    id: Option<(u64, u64)>,
    cursors: Vec<SegmentCursor>,
    /// Length of the sealed file the rows came from, when they came from a seal.
    sealed_len: Option<u64>,
    stats: HotViewStats,
}

impl HotView {
    /// Open a view and read the archive once.
    pub fn open(archive: &Path) -> Result<Self> {
        let v = Self {
            archive: archive.to_path_buf(),
            state: RwLock::new(ViewState::default()),
            read: Mutex::new(ReadState::default()),
        };
        v.refresh()?;
        Ok(v)
    }

    pub fn archive(&self) -> &Path {
        &self.archive
    }

    fn state(&self) -> RwLockReadGuard<'_, ViewState> {
        self.state.read().unwrap_or_else(|e| e.into_inner())
    }

    /// Read what changed since the last refresh. The keys whose state changed.
    pub fn refresh(&self) -> Result<Vec<(Group, String)>> {
        let mut rs = self.read.lock().unwrap_or_else(|e| e.into_inner());
        rs.stats.refreshes += 1;
        let segs = journal_segments(&self.archive)?;
        let meta = match std::fs::metadata(&self.archive) {
            Ok(m) => Some(m),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => return Err(anyhow!("hot view: {}: {e}", self.archive.display())),
        };
        if meta.is_none() && segs.is_empty() {
            return Ok(Vec::new());
        }
        let id = meta.as_ref().map(|m| (m.dev(), m.ino()));
        if segs.is_empty()
            && rs.sealed_len.is_some()
            && id == rs.id
            && meta.as_ref().map(|m| m.len()) == rs.sealed_len
        {
            return Ok(Vec::new());
        }
        let grows = !segs.is_empty()
            && id.is_some()
            && id == rs.id
            && rs.sealed_len.is_none()
            && segs[0].0 == 0
            && segs.len() >= rs.cursors.len()
            && rs
                .cursors
                .iter()
                .zip(&segs)
                .all(|(c, (n, _))| c.number == *n);
        if grows && let Ok(changed) = self.read_more(&mut rs, &segs) {
            return Ok(changed);
        }
        self.rebuild(&mut rs, &segs)
    }

    fn read_more(
        &self,
        rs: &mut ReadState,
        segs: &[(u32, PathBuf)],
    ) -> Result<Vec<(Group, String)>> {
        let mut fresh: Vec<RowEntry> = Vec::new();
        let mut bytes = 0u64;
        for c in rs.cursors.iter_mut() {
            let (e, n) = c.read_more(true)?;
            bytes += n;
            fresh.extend(e);
        }
        for (n, p) in &segs[rs.cursors.len()..] {
            let mut c = SegmentCursor::new(*n, p.clone());
            let (e, b) = c.read_more(true)?;
            bytes += b;
            fresh.extend(e);
            rs.cursors.push(c);
        }
        rs.stats.journal_bytes_read += bytes;
        let layer = layer_of(&rs.cursors)?;
        // The file AFTER the journal: the writer made the bytes durable first.
        let file_len = std::fs::metadata(&self.archive)?.len();
        let mut st = self.state.write().unwrap_or_else(|e| e.into_inner());
        st.layer = layer;
        let mut changed = Vec::with_capacity(fresh.len());
        for e in fresh {
            if own_bytes_end(&e) > file_len {
                rs.stats.untrusted_rows += 1;
                continue;
            }
            changed.push((e.group.clone(), e.name.clone()));
            st.index.apply(e);
        }
        Ok(changed)
    }

    fn rebuild(&self, rs: &mut ReadState, segs: &[(u32, PathBuf)]) -> Result<Vec<(Group, String)>> {
        rs.stats.rebuilds += 1;
        let file = match File::open(&self.archive) {
            Ok(f) => Some(f),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => return Err(anyhow!("hot view: {}: {e}", self.archive.display())),
        };
        let id = match &file {
            Some(f) => {
                let m = f.metadata()?;
                Some((m.dev(), m.ino()))
            }
            None => None,
        };
        // The seal is read only where it decides: no journal, or one cut short.
        let sealed = if segs.first().is_none_or(|(n, _)| *n != 0) {
            file.as_ref()
                .and_then(|f| crate::stack::load_sealed(f).ok())
        } else {
            None
        };
        let mut index = RowIndex::default();
        let mut layer = None;
        let mut cursors = Vec::new();
        let mut sealed_len = None;
        // A journal that does not start at 0 beside a sealed file is a seal whose
        // segment removal was cut: the seal is the truth (as the writer's open
        // decides).
        let journal = !segs.is_empty() && (segs[0].0 == 0 || sealed.is_none());
        if journal {
            let mut entries = Vec::new();
            for (n, p) in segs {
                let mut c = SegmentCursor::new(*n, p.clone());
                let (e, b) = c.read_more(true)?;
                rs.stats.journal_bytes_read += b;
                entries.extend(e);
                cursors.push(c);
            }
            layer = layer_of(&cursors)?;
            let file_len = match &file {
                Some(f) => f.metadata()?.len(),
                None => 0,
            };
            for e in entries {
                if own_bytes_end(&e) > file_len {
                    rs.stats.untrusted_rows += 1;
                    continue;
                }
                index.apply(e);
            }
        } else if let Some(s) = sealed {
            index = s.index;
            layer = s.section.and_then(|s| s.layer_info());
            sealed_len = Some(s.len);
        }
        let mut st = self.state.write().unwrap_or_else(|e| e.into_inner());
        let changed = changed_keys(&st.index, &index);
        *st = ViewState {
            index,
            blobs: file.map(Arc::new),
            layer,
            sealed: sealed_len.is_some(),
        };
        rs.id = id;
        rs.cursors = cursors;
        rs.sealed_len = sealed_len;
        Ok(changed)
    }

    /// What the archive says about `name` in `group`.
    pub fn lookup(&self, group: &Group, name: &str) -> Lookup {
        self.state().index.lookup(group, name)
    }

    /// The body of a live `name` whose bytes lie in this archive's file.
    pub fn get(&self, group: &Group, name: &str) -> Option<Blob> {
        let st = self.state();
        match st.index.lookup(group, name) {
            Lookup::Live(b) if b.pack.is_none() => {
                st.blobs.as_ref().map(|f| Blob::new(Arc::clone(f), b))
            }
            _ => None,
        }
    }

    /// Live names of `group`, in first-insertion order.
    pub fn names(&self, group: &Group) -> Vec<String> {
        self.state().index.names(group)
    }

    /// Every group that holds a row, in first-insertion order.
    pub fn groups(&self) -> Vec<Group> {
        self.state().index.groups().to_vec()
    }

    /// Live names over every group.
    pub fn rows(&self) -> u64 {
        self.state().index.live()
    }

    /// The stack place, when the archive is a stack layer.
    pub fn layer(&self) -> Option<LayerInfo> {
        self.state().layer
    }

    /// Whether the rows came from a sealed file (no journal).
    pub fn is_sealed(&self) -> bool {
        self.state().sealed
    }

    pub fn stats(&self) -> HotViewStats {
        self.read.lock().unwrap_or_else(|e| e.into_inner()).stats
    }

    pub(crate) fn file(&self) -> Option<Arc<File>> {
        self.state().blobs.clone()
    }

    pub(crate) fn with_index<R>(&self, f: impl FnOnce(&RowIndex) -> R) -> R {
        f(&self.state().index)
    }
}

/// The stack place the segments name — the same in each, or none.
fn layer_of(cursors: &[SegmentCursor]) -> Result<Option<LayerInfo>> {
    let mut found: Option<LayerInfo> = None;
    for c in cursors {
        if let Some(m) = &c.metadata
            && let Some(l) = LayerInfo::from_metadata(m)?
        {
            ensure!(
                found.is_none_or(|f| f == l),
                "hot view: the segments name two places in a stack"
            );
            found = Some(l);
        }
    }
    Ok(found)
}

/// The default group, as every [`ZnippyReader`] reads.
impl ZnippyReader for HotView {
    fn list_files(&self) -> Result<Vec<String>> {
        Ok(self.names(&Group::default()))
    }

    fn extract_file(&self, relative_path: &str) -> Result<Vec<u8>> {
        (self.get(&Group::default(), relative_path))
            .ok_or_else(|| anyhow!("file not found in archive: {relative_path}"))?
            .read()
    }

    fn contains(&self, relative_path: &str) -> bool {
        matches!(
            self.lookup(&Group::default(), relative_path),
            Lookup::Live(_)
        )
    }

    fn file_size(&self, relative_path: &str) -> Option<u64> {
        match self.lookup(&Group::default(), relative_path) {
            Lookup::Live(b) => Some(b.size()),
            _ => None,
        }
    }

    fn checksum(&self, relative_path: &str) -> Option<[u8; 32]> {
        match self.lookup(&Group::default(), relative_path) {
            Lookup::Live(b) => b.checksum(),
            _ => None,
        }
    }
}

#[cfg(all(test, feature = "openzl"))]
mod tests {
    use super::*;
    use crate::hot::segment_path;
    use crate::hot::stream_tests::noise;
    use crate::HotArchive;

    fn raw() -> crate::SkipPolicy {
        crate::SkipPolicy::already_compressed()
    }

    fn files(tag: &str, n: usize, seed: u64) -> Vec<(String, Vec<u8>)> {
        (0..n)
            .map(|i| (format!("{tag}/{i}"), noise(seed + i as u64, 200 + i as u64)))
            .collect()
    }

    /// What the writer appends, the view reads after a refresh — and the keys it
    /// reports are the ones that changed.
    #[test]
    fn a_view_reads_what_the_writer_appended() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        let first = files("one", 10, 1);
        h.append(&first).unwrap();
        let v = HotView::open(&path).unwrap();
        assert_eq!(v.rows(), 10);
        let second = files("two", 5, 100);
        h.append(&second).unwrap();
        h.end(&Group::default(), "one/0").unwrap();
        let changed = v.refresh().unwrap();
        assert_eq!(changed.len(), 6, "{changed:?}");
        assert!(!v.contains("one/0"));
        for (p, b) in first.iter().skip(1).chain(&second) {
            assert_eq!(&v.extract_file(p).unwrap(), b, "{p}");
        }
        assert_eq!(v.stats().rebuilds, 1, "growth is read as growth");
    }

    /// A refresh reads the journal bytes added since the last one and nothing
    /// else; a refresh with nothing new reads nothing.
    #[test]
    fn refresh_reads_only_what_was_added() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        h.append(&files("seed", 100, 1)).unwrap();
        let v = HotView::open(&path).unwrap();
        let read0 = v.stats().journal_bytes_read;
        let mut added = 0u64;
        for round in 0..20u64 {
            added += h
                .append(&files(&format!("r{round}"), 3, round * 7))
                .unwrap()
                .journal_bytes_added;
        }
        v.refresh().unwrap();
        assert_eq!(
            v.stats().journal_bytes_read - read0,
            added,
            "exactly the bytes appended"
        );
        let read1 = v.stats().journal_bytes_read;
        assert!(v.refresh().unwrap().is_empty());
        assert_eq!(
            v.stats().journal_bytes_read,
            read1,
            "nothing new, nothing read"
        );
        assert_eq!(v.stats().rebuilds, 1);
        assert_eq!(v.rows(), 160);
    }

    /// A message being written is not read; the next refresh reads it whole,
    /// without starting again.
    #[test]
    fn a_message_being_written_is_left_for_the_next_refresh() {
        let src = tempfile::tempdir().unwrap();
        let sp = src.path().join("a.znippy");
        let h = HotArchive::open(&sp, 3, raw()).unwrap();
        h.append(&files("a", 4, 1)).unwrap();
        let cut_at = std::fs::metadata(segment_path(&sp, 0)).unwrap().len();
        h.append(&files("b", 4, 50)).unwrap();
        let seg = std::fs::read(segment_path(&sp, 0)).unwrap();
        let blobs = std::fs::read(&sp).unwrap();

        let dst = tempfile::tempdir().unwrap();
        let dp = dst.path().join("a.znippy");
        std::fs::write(&dp, &blobs).unwrap();
        // The second message, half written.
        let half = cut_at as usize + (seg.len() - cut_at as usize) / 2;
        std::fs::write(segment_path(&dp, 0), &seg[..half]).unwrap();
        let v = HotView::open(&dp).unwrap();
        assert_eq!(v.rows(), 4, "only the whole message");
        std::fs::write(segment_path(&dp, 0), &seg).unwrap();
        // Same inode? `fs::write` truncates and rewrites in place: the segment
        // grew, so the refresh reads on from where it stopped.
        v.refresh().unwrap();
        assert_eq!(v.rows(), 8);
        assert_eq!(v.stats().rebuilds, 1);
        assert_eq!(v.extract_file("b/3").unwrap(), files("b", 4, 50)[3].1);
    }

    /// A row naming bytes past the end of the file is not taken.
    #[test]
    fn a_row_past_the_file_end_is_not_trusted() {
        let src = tempfile::tempdir().unwrap();
        let sp = src.path().join("a.znippy");
        let h = HotArchive::open(&sp, 3, raw()).unwrap();
        h.append(&files("a", 4, 1)).unwrap();
        let dst = tempfile::tempdir().unwrap();
        let dp = dst.path().join("a.znippy");
        let blobs = std::fs::read(&sp).unwrap();
        std::fs::write(&dp, &blobs[..blobs.len() - 10]).unwrap();
        std::fs::copy(segment_path(&sp, 0), segment_path(&dp, 0)).unwrap();
        let v = HotView::open(&dp).unwrap();
        assert_eq!(v.rows(), 3);
        assert_eq!(v.stats().untrusted_rows, 1);
        assert!(!v.contains("a/3"));
    }

    /// The view follows the writer through a seal (journal gone, rows from the
    /// seal) and a re-heat (journal back).
    #[test]
    fn the_view_follows_a_seal_and_a_reheat() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        h.append(&files("a", 6, 1)).unwrap();
        let v = HotView::open(&path).unwrap();
        h.seal(None).unwrap();
        v.refresh().unwrap();
        assert!(v.is_sealed());
        assert_eq!(v.rows(), 6);
        assert!(
            v.refresh().unwrap().is_empty(),
            "an unchanged seal is not read again"
        );
        assert_eq!(v.stats().rebuilds, 2);
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        h.append(&files("b", 2, 9)).unwrap();
        let changed = v.refresh().unwrap();
        assert!(!v.is_sealed());
        assert_eq!(changed.len(), 2, "{changed:?}");
        assert_eq!(v.rows(), 8);
        assert_eq!(v.extract_file("a/5").unwrap(), files("a", 6, 1)[5].1);
    }

    /// The view never creates, cuts or writes a file — not even the orphan the
    /// writer's next open would cut.
    #[test]
    fn the_view_never_writes() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        {
            let h = HotArchive::open(&path, 3, raw()).unwrap();
            h.append(&files("a", 3, 1)).unwrap();
            let _ = h.append_from(
                &Group::default(),
                "cut",
                &mut crate::hot::stream_tests::Noise { s: 1, left: 0 },
                &crate::Expect {
                    size: Some(5),
                    blake3: None,
                },
            );
        }
        // An orphan past the last row, and a torn message.
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(&path)
            .unwrap();
        std::io::Write::write_all(&mut f, b"orphan bytes").unwrap();
        let mut j = std::fs::OpenOptions::new()
            .append(true)
            .open(segment_path(&path, 0))
            .unwrap();
        std::io::Write::write_all(&mut j, &[0xff, 0xff, 0xff, 0xff, 0x40, 0, 0, 0, 1, 2]).unwrap();
        let snapshot = || {
            let mut v: Vec<(String, u64)> = std::fs::read_dir(dir.path())
                .unwrap()
                .map(|e| {
                    let e = e.unwrap();
                    (
                        e.file_name().into_string().unwrap(),
                        e.metadata().unwrap().len(),
                    )
                })
                .collect();
            v.sort();
            v
        };
        let before = snapshot();
        let v = HotView::open(&path).unwrap();
        v.refresh().unwrap();
        assert_eq!(v.rows(), 3);
        assert_eq!(snapshot(), before, "the view changed the directory");
    }

    /// A stored chunk whose bytes were changed fails the verified read at that
    /// chunk; the plain read still hands the bytes out.
    #[test]
    fn pieces_are_checked_per_chunk() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        let body = noise(3, 3 * crate::STREAM_PIECE as u64);
        h.append(&[("x".into(), body.clone())]).unwrap();
        drop(h);
        {
            use std::os::unix::fs::FileExt;
            let f = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
            f.write_all_at(&[body[100] ^ 1], 100).unwrap();
        }
        let v = HotView::open(&path).unwrap();
        let blob = v.get(&Group::default(), "x").unwrap();
        assert!(blob.read_verified().is_err());
        assert_eq!(blob.read().unwrap().len(), body.len());
        let pieces: Vec<_> = blob.pieces(crate::STREAM_PIECE, true).unwrap().collect();
        assert_eq!(
            pieces.len(),
            3,
            "the bad digest shows at the end of the one chunk"
        );
        assert!(pieces[..2].iter().all(|p| p.is_ok()));
        assert!(pieces[2].is_err());
    }
}