znippy-common 0.10.9

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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! **Rows**: which name, in which group, names which bytes, in which file — the one
//! model the hot path ([`crate::HotArchive`]), its read-only view ([`crate::HotView`])
//! and a stack's layers ([`crate::stack`]) share.
//!
//! * A **group** is a data sub-index: one package type in one repository
//!   ([`Group`], sealed under [`GroupKey`]`{pkg_type, repo}`). Names are unique per
//!   group, so one archive holds many repositories of many types, and the same name
//!   may live in two of them.
//! * A row names its bytes by [`BlobRef`]: the chunks (`ChunkLoc`s, as every znippy
//!   index row has them) and the **pack** — the stack layer whose file holds them,
//!   `None` for the file the row lies in. Two rows may name one blob; neither owns it.
//! * A name can be **ended** (a tombstone): in a layer it hides the name below.
//!
//! One codec for the three places rows are written — a journal message, a sealed
//! data sub-index, a layer's links section — so a row cannot be written one way and
//! read another (LAW 5). A journal written before groups existed (the eight base
//! columns, "V1") reads as rows of the default group in their own file.

use std::collections::HashMap;
use std::fs::File;
use std::io::{Cursor, Read, Write};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::{anyhow, bail, ensure, Result};
use arrow::array::{
    Array, BooleanArray, BooleanBuilder, FixedSizeBinaryArray, FixedSizeBinaryBuilder, Int8Array,
    Int8Builder, StringArray, StringBuilder, UInt32Array, UInt32Builder, UInt64Array,
    UInt64Builder,
};
use arrow::datatypes::{DataType, Field, Schema};
use arrow::ipc::reader::StreamReader;
use arrow::record_batch::RecordBatch;

use crate::index::{data_subindex_schema, ChunkLoc, RESERVED_PKG_TYPE};
use crate::meta_sink::GroupKey;

/// A data sub-index: one package type in one repository.
///
/// The default group `(0, "")` is what every path-only call uses (`append`, the
/// [`ZnippyReader`](crate::ZnippyReader) methods), and the key a plain archive's one
/// data sub-index has always been sealed under — so an archive that never names a
/// group is byte for byte what it was.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct Group {
    pub pkg_type: i8,
    pub repo: String,
}

impl Group {
    pub fn new(pkg_type: i8, repo: impl Into<String>) -> Self {
        Self {
            pkg_type,
            repo: repo.into(),
        }
    }

    /// The group of every path-only call.
    pub fn is_default(&self) -> bool {
        self.pkg_type == 0 && self.repo.is_empty()
    }

    /// The manifest key this group's data sub-index is sealed under.
    pub fn key(&self) -> GroupKey {
        GroupKey {
            pkg_type: self.pkg_type,
            repo: self.repo.clone(),
            module_name: String::new(),
        }
    }

    /// `RESERVED_PKG_TYPE` marks the archive's own sections; a data group never has it.
    pub(crate) fn check(&self) -> Result<()> {
        ensure!(
            self.pkg_type != RESERVED_PKG_TYPE,
            "pkg_type {} is reserved for the archive's own sections",
            RESERVED_PKG_TYPE
        );
        Ok(())
    }
}

/// Where the bytes of a row lie.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlobRef {
    /// The stack layer (by generation) whose file holds the bytes; `None` = the
    /// file this row lies in. A plain archive's rows are all `None`.
    pub pack: Option<u64>,
    /// The chunks, in `fdata_offset` order. One for a whole body; more when a body
    /// was compressed in pieces.
    pub chunks: Vec<ChunkLoc>,
}

impl BlobRef {
    /// The body's length: where its furthest chunk ends.
    pub fn size(&self) -> u64 {
        (self.chunks.iter())
            .map(|c| c.fdata_offset.saturating_add(c.uncompressed_size))
            .max()
            .unwrap_or(0)
    }

    /// Bytes the body takes in its file (compressed or stored).
    pub fn stored_bytes(&self) -> u64 {
        self.chunks.iter().map(|c| c.blob_size).sum()
    }

    /// **The stored BLAKE3 of the whole body**, when one is stored: a body kept in
    /// one chunk carries the BLAKE3 of all of it. A body in pieces carries one per
    /// piece and none for the whole: `None`.
    pub fn checksum(&self) -> Option<[u8; 32]> {
        match self.chunks.as_slice() {
            [c] if c.fdata_offset == 0 => Some(c.checksum),
            _ => None,
        }
    }

    /// One past the furthest byte the chunks name in their file.
    pub(crate) fn end(&self) -> u64 {
        (self.chunks.iter())
            .map(|c| c.blob_offset.saturating_add(c.blob_size))
            .max()
            .unwrap_or(0)
    }
}

/// What a layer (or an archive) says about a name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Lookup {
    /// Nothing: ask the layer below.
    Absent,
    /// The name was ended here: it is gone, whatever lies below.
    Ended,
    Live(BlobRef),
}

/// One name's new state, as one journal message or a links section carries it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RowEntry {
    pub group: Group,
    pub name: String,
    /// `None`: the name is ended.
    pub slot: Option<BlobRef>,
}

/// What setting a name replaced.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Was {
    New,
    Live,
    Ended,
}

/// The rows of one archive or layer, by group, each group in first-insertion order.
/// A replaced or ended name keeps its place, so a seal emits rows in the order they
/// first came (which is what makes hot-then-seal byte-identical to `create_archive`).
#[derive(Debug, Default, Clone)]
pub(crate) struct RowIndex {
    order: Vec<Group>,
    groups: HashMap<Group, GroupRows>,
    live: u64,
    ended: u64,
}

#[derive(Debug, Default, Clone)]
struct GroupRows {
    names: Vec<String>,
    slots: Vec<Option<BlobRef>>,
    at: HashMap<String, usize>,
}

impl RowIndex {
    pub fn lookup(&self, group: &Group, name: &str) -> Lookup {
        let Some(rows) = self.groups.get(group) else {
            return Lookup::Absent;
        };
        match rows.at.get(name) {
            None => Lookup::Absent,
            Some(&i) => match &rows.slots[i] {
                Some(b) => Lookup::Live(b.clone()),
                None => Lookup::Ended,
            },
        }
    }

    pub fn set(&mut self, group: Group, name: String, slot: Option<BlobRef>) -> Was {
        if !self.groups.contains_key(&group) {
            self.order.push(group.clone());
        }
        let rows = self.groups.entry(group).or_default();
        let now_live = slot.is_some();
        let was = match rows.at.get(&name).copied() {
            Some(i) => {
                let was = if rows.slots[i].is_some() {
                    Was::Live
                } else {
                    Was::Ended
                };
                rows.slots[i] = slot;
                was
            }
            None => {
                rows.at.insert(name.clone(), rows.names.len());
                rows.names.push(name);
                rows.slots.push(slot);
                Was::New
            }
        };
        match was {
            Was::Live => self.live -= 1,
            Was::Ended => self.ended -= 1,
            Was::New => {}
        }
        if now_live {
            self.live += 1;
        } else {
            self.ended += 1;
        }
        was
    }

    pub fn apply(&mut self, e: RowEntry) -> Was {
        self.set(e.group, e.name, e.slot)
    }

    /// Live names.
    pub fn live(&self) -> u64 {
        self.live
    }

    /// Whether any name was set at all (live or ended).
    pub fn has_rows(&self) -> bool {
        self.live + self.ended > 0
    }

    /// Groups in first-insertion order.
    pub fn groups(&self) -> &[Group] {
        &self.order
    }

    /// Live names of `group`, in first-insertion order.
    pub fn names(&self, group: &Group) -> Vec<String> {
        let Some(rows) = self.groups.get(group) else {
            return Vec::new();
        };
        (rows.names.iter().zip(&rows.slots))
            .filter(|(_, s)| s.is_some())
            .map(|(n, _)| n.clone())
            .collect()
    }

    /// Every name of `group` with its state (live or ended), in order.
    pub fn slots(&self, group: &Group) -> impl Iterator<Item = (&str, &Option<BlobRef>)> {
        (self.groups.get(group).into_iter())
            .flat_map(|rows| rows.names.iter().map(String::as_str).zip(&rows.slots))
    }

    /// The same names in the same states, whatever the order.
    pub fn same_as(&self, other: &RowIndex) -> bool {
        if self.live != other.live || self.ended != other.ended {
            return false;
        }
        (self.order.iter()).all(|g| {
            self.slots(g).all(|(name, slot)| {
                let theirs = other.lookup(g, name);
                match slot {
                    Some(b) => theirs == Lookup::Live(b.clone()),
                    None => theirs == Lookup::Ended,
                }
            })
        })
    }
}

/// Every key whose state differs between `old` and `new` (set, replaced, ended,
/// or gone), each once.
pub(crate) fn changed_keys(old: &RowIndex, new: &RowIndex) -> Vec<(Group, String)> {
    let mut out = Vec::new();
    for g in new.groups() {
        for (name, slot) in new.slots(g) {
            let now = match slot {
                Some(b) => Lookup::Live(b.clone()),
                None => Lookup::Ended,
            };
            if old.lookup(g, name) != now {
                out.push((g.clone(), name.to_string()));
            }
        }
    }
    for g in old.groups() {
        for (name, _) in old.slots(g) {
            if new.lookup(g, name) == Lookup::Absent {
                out.push((g.clone(), name.to_string()));
            }
        }
    }
    out
}

/// One past the furthest byte `e` names in its own file (0 for an end or for
/// bytes of another layer).
pub(crate) fn own_bytes_end(e: &RowEntry) -> u64 {
    e.slot
        .as_ref()
        .filter(|b| b.pack.is_none())
        .map_or(0, BlobRef::end)
}

// ── the codec ───────────────────────────────────────────────────────────────

/// Columns a V2 journal message (and a links section) carries after the eight
/// base columns.
pub(crate) const COL_GROUP_TYPE: &str = "group_type";
pub(crate) const COL_GROUP_REPO: &str = "group_repo";
pub(crate) const COL_PACK: &str = "pack";
pub(crate) const COL_ENDED: &str = "ended";

/// The schema of a V2 journal segment and of a links section: the data sub-index
/// columns (and its metadata, so the format version travels) plus the group, the
/// pack and the end mark. `extra` joins the schema metadata (a layer's facts).
pub(crate) fn rows_schema(extra: &HashMap<String, String>) -> Arc<Schema> {
    let base = data_subindex_schema();
    let mut fields: Vec<Field> = base.fields().iter().map(|f| f.as_ref().clone()).collect();
    fields.push(Field::new(COL_GROUP_TYPE, DataType::Int8, false));
    fields.push(Field::new(COL_GROUP_REPO, DataType::Utf8, false));
    fields.push(Field::new(COL_PACK, DataType::UInt64, true));
    fields.push(Field::new(COL_ENDED, DataType::Boolean, false));
    let mut metadata = base.metadata().clone();
    metadata.extend(extra.iter().map(|(k, v)| (k.clone(), v.clone())));
    Arc::new(Schema::new_with_metadata(fields, metadata))
}

/// Whether `schema` carries the V2 columns.
pub(crate) fn is_v2(schema: &Schema) -> bool {
    schema.field_with_name(COL_ENDED).is_ok()
}

/// Whether `entries` can be written as V1 (the eight base columns): default group,
/// bytes in their own file, nothing ended.
pub(crate) fn fits_v1(entries: &[RowEntry]) -> bool {
    (entries.iter())
        .all(|e| e.group.is_default() && e.slot.as_ref().is_some_and(|b| b.pack.is_none()))
}

/// One batch of `entries` under `schema` (V1 or V2): one row per chunk, one row
/// per ended name.
pub(crate) fn rows_batch(schema: &Arc<Schema>, entries: &[RowEntry]) -> Result<RecordBatch> {
    if !is_v2(schema) {
        ensure!(
            fits_v1(entries),
            "a V1 journal holds only own rows of the default group"
        );
        let mut paths = Vec::new();
        let mut locs = Vec::new();
        for e in entries {
            for c in &e.slot.as_ref().expect("checked by fits_v1").chunks {
                paths.push(e.name.clone());
                locs.push(c.clone());
            }
        }
        let order: Vec<usize> = (0..paths.len()).collect();
        return crate::meta_sink_append::base_batch_permuted(
            Arc::clone(schema),
            &paths,
            &locs,
            &order,
        );
    }
    let n: usize = entries
        .iter()
        .map(|e| e.slot.as_ref().map_or(1, |b| b.chunks.len()))
        .sum();
    let mut path_b = StringBuilder::with_capacity(n, n * 16);
    let mut seq_b = UInt32Builder::with_capacity(n);
    let mut fdata_b = UInt64Builder::with_capacity(n);
    let mut comp_b = BooleanBuilder::with_capacity(n);
    let mut usz_b = UInt64Builder::with_capacity(n);
    let mut boff_b = UInt64Builder::with_capacity(n);
    let mut bsz_b = UInt64Builder::with_capacity(n);
    let mut ck_b = FixedSizeBinaryBuilder::with_capacity(n, 32);
    let mut gt_b = Int8Builder::with_capacity(n);
    let mut gr_b = StringBuilder::with_capacity(n, n * 4);
    let mut pack_b = UInt64Builder::with_capacity(n);
    let mut end_b = BooleanBuilder::with_capacity(n);
    let ended = ChunkLoc {
        chunk_seq: 0,
        fdata_offset: 0,
        blob_offset: 0,
        blob_size: 0,
        uncompressed_size: 0,
        compressed: false,
        checksum: [0u8; 32],
    };
    for e in entries {
        let (pack, chunks, is_end) = match &e.slot {
            Some(b) => (b.pack, b.chunks.as_slice(), false),
            None => (None, std::slice::from_ref(&ended), true),
        };
        for c in chunks {
            path_b.append_value(&e.name);
            seq_b.append_value(c.chunk_seq);
            fdata_b.append_value(c.fdata_offset);
            comp_b.append_value(c.compressed);
            usz_b.append_value(c.uncompressed_size);
            boff_b.append_value(c.blob_offset);
            bsz_b.append_value(c.blob_size);
            ck_b.append_value(c.checksum)?;
            gt_b.append_value(e.group.pkg_type);
            gr_b.append_value(&e.group.repo);
            pack_b.append_option(pack);
            end_b.append_value(is_end);
        }
    }
    Ok(RecordBatch::try_new(
        Arc::clone(schema),
        vec![
            Arc::new(path_b.finish()),
            Arc::new(seq_b.finish()),
            Arc::new(fdata_b.finish()),
            Arc::new(comp_b.finish()),
            Arc::new(usz_b.finish()),
            Arc::new(boff_b.finish()),
            Arc::new(bsz_b.finish()),
            Arc::new(ck_b.finish()),
            Arc::new(gt_b.finish()),
            Arc::new(gr_b.finish()),
            Arc::new(pack_b.finish()),
            Arc::new(end_b.finish()),
        ],
    )?)
}

/// One decoded row: a chunk of a name, or an end.
pub(crate) struct FlatRow {
    pub group: Group,
    pub name: String,
    pub pack: Option<u64>,
    /// `None`: the name is ended.
    pub chunk: Option<ChunkLoc>,
}

fn column<'b, T: 'static>(batch: &'b RecordBatch, name: &str) -> Result<&'b T> {
    let c = (batch.column_by_name(name)).ok_or_else(|| anyhow!("rows: no column {name}"))?;
    (c.as_any().downcast_ref::<T>())
        .ok_or_else(|| anyhow!("rows: column {name} is of another type"))
}

fn optional<'b, T: 'static>(batch: &'b RecordBatch, name: &str) -> Result<Option<&'b T>> {
    match batch.column_by_name(name) {
        None => Ok(None),
        Some(c) => (c.as_any().downcast_ref::<T>())
            .map(Some)
            .ok_or_else(|| anyhow!("rows: column {name} is of another type")),
    }
}

/// The rows of one batch. A batch without the V2 columns (a V1 journal message, a
/// sealed data sub-index) gives rows of `group`, in their own file, none ended.
pub(crate) fn decode_flat(batch: &RecordBatch, group: &Group) -> Result<Vec<FlatRow>> {
    let paths = column::<StringArray>(batch, "relative_path")?;
    let seq = column::<UInt32Array>(batch, "chunk_seq")?;
    let fdata = column::<UInt64Array>(batch, "fdata_offset")?;
    let comp = column::<BooleanArray>(batch, "compressed")?;
    let usz = column::<UInt64Array>(batch, "uncompressed_size")?;
    let boff = column::<UInt64Array>(batch, "blob_offset")?;
    let bsz = column::<UInt64Array>(batch, "blob_size")?;
    let ck = column::<FixedSizeBinaryArray>(batch, "checksum")?;
    ensure!(
        ck.value_length() == 32,
        "rows: checksum is {} bytes wide, not 32",
        ck.value_length()
    );
    let gt = optional::<Int8Array>(batch, COL_GROUP_TYPE)?;
    let gr = optional::<StringArray>(batch, COL_GROUP_REPO)?;
    let pack = optional::<UInt64Array>(batch, COL_PACK)?;
    let ended = optional::<BooleanArray>(batch, COL_ENDED)?;
    let mut out = Vec::with_capacity(batch.num_rows());
    for i in 0..batch.num_rows() {
        let group = match (gt, gr) {
            (Some(t), Some(r)) => Group {
                pkg_type: t.value(i),
                repo: r.value(i).to_string(),
            },
            _ => group.clone(),
        };
        let chunk = if ended.is_some_and(|e| e.value(i)) {
            None
        } else {
            let mut checksum = [0u8; 32];
            checksum.copy_from_slice(ck.value(i));
            Some(ChunkLoc {
                chunk_seq: seq.value(i),
                fdata_offset: fdata.value(i),
                blob_offset: boff.value(i),
                blob_size: bsz.value(i),
                uncompressed_size: usz.value(i),
                compressed: comp.value(i),
                checksum,
            })
        };
        out.push(FlatRow {
            group,
            name: paths.value(i).to_string(),
            pack: pack.and_then(|p| (!p.is_null(i)).then(|| p.value(i))),
            chunk,
        });
    }
    Ok(out)
}

/// Rows as the writer wrote them, one name after another: a row with `chunk_seq`
/// 0 (or an end) starts the name anew; a later chunk joins the name just started.
/// This is the shape of a journal message and of a links section.
pub(crate) fn entries_in_order(rows: Vec<FlatRow>) -> Result<Vec<RowEntry>> {
    let mut out: Vec<RowEntry> = Vec::new();
    for r in rows {
        match r.chunk {
            None => out.push(RowEntry {
                group: r.group,
                name: r.name,
                slot: None,
            }),
            Some(c) if c.chunk_seq == 0 => out.push(RowEntry {
                group: r.group,
                name: r.name,
                slot: Some(BlobRef {
                    pack: r.pack,
                    chunks: vec![c],
                }),
            }),
            Some(c) => {
                let last = out
                    .last_mut()
                    .filter(|e| e.group == r.group && e.name == r.name);
                let Some(b) = last
                    .and_then(|e| e.slot.as_mut())
                    .filter(|b| b.pack == r.pack)
                else {
                    bail!(
                        "rows: chunk {} of {} comes without its chunk 0",
                        c.chunk_seq,
                        r.name
                    );
                };
                b.chunks.push(c);
            }
        }
    }
    for e in &mut out {
        if let Some(b) = &mut e.slot {
            b.chunks.sort_by_key(|c| c.fdata_offset);
        }
    }
    Ok(out)
}

/// Decode a whole Arrow IPC stream (already through the guard) into entries, and
/// its schema metadata. `tolerant`: stop at the first batch arrow refuses, as a log
/// reader must; otherwise that batch is an error.
pub(crate) fn decode_stream(
    bytes: &[u8],
    tolerant: bool,
) -> Result<(Vec<RowEntry>, HashMap<String, String>)> {
    let reader = StreamReader::try_new(Cursor::new(bytes), None)
        .map_err(|e| anyhow!("rows: stream: {e}"))?;
    let metadata = reader.schema().metadata().clone();
    let mut out = Vec::new();
    for batch in reader {
        match batch {
            Ok(b) => out.extend(entries_in_order(decode_flat(&b, &Group::default())?)?),
            Err(_) if tolerant => break,
            Err(e) => bail!("rows: batch: {e}"),
        }
    }
    Ok((out, metadata))
}

// ── reading a journal segment as it grows ──────────────────────────────────

/// One journal segment `<archive>.hot.NNNNN`, read as it grows: each call reads only
/// the bytes added since the last, up to the last whole message. The schema message
/// is kept and put in front of the new messages, so arrow reads them under it and
/// the segment is never read again from its start.
pub(crate) struct SegmentCursor {
    pub number: u32,
    pub path: PathBuf,
    /// The schema message's bytes, once they landed.
    schema: Vec<u8>,
    /// Bytes of whole messages read so far (schema included).
    consumed: u64,
    /// The schema's metadata, once it landed.
    pub metadata: Option<HashMap<String, String>>,
}

impl SegmentCursor {
    pub fn new(number: u32, path: PathBuf) -> Self {
        Self {
            number,
            path,
            schema: Vec::new(),
            consumed: 0,
            metadata: None,
        }
    }

    /// The entries in the whole messages added since the last call, and how many
    /// bytes were read. An error when the segment is gone or shrank: the caller
    /// starts again from nothing.
    pub fn read_more(&mut self, tolerant: bool) -> Result<(Vec<RowEntry>, u64)> {
        let file =
            File::open(&self.path).map_err(|e| anyhow!("journal {}: {e}", self.path.display()))?;
        let len = file.metadata()?.len();
        ensure!(
            len >= self.consumed,
            "journal {} shrank",
            self.path.display()
        );
        if len == self.consumed {
            return Ok((Vec::new(), 0));
        }
        let mut fresh = vec![0u8; usize::try_from(len - self.consumed)?];
        file.read_exact_at(&mut fresh, self.consumed)?;
        let read = fresh.len() as u64;
        if self.schema.is_empty() {
            let whole = crate::ipc_guard::valid_prefix(&fresh);
            let Some(schema_len) = crate::ipc_guard::first_message_len(whole) else {
                // The schema message has not landed whole yet: nothing to read.
                return Ok((Vec::new(), read));
            };
            let (entries, metadata) = decode_stream(whole, tolerant)?;
            self.schema = whole[..schema_len].to_vec();
            self.metadata = Some(metadata);
            self.consumed = whole.len() as u64;
            return Ok((entries, read));
        }
        let mut buf = Vec::with_capacity(self.schema.len() + fresh.len());
        buf.extend_from_slice(&self.schema);
        buf.extend_from_slice(&fresh);
        let whole = crate::ipc_guard::valid_prefix(&buf);
        if whole.len() <= self.schema.len() {
            return Ok((Vec::new(), read));
        }
        let (entries, _) = decode_stream(whole, tolerant)?;
        self.consumed += (whole.len() - self.schema.len()) as u64;
        Ok((entries, read))
    }
}

// ── reading the bytes a row names ──────────────────────────────────────────

/// Pieces a raw chunk is read in, and the most a body is held in memory as it is
/// written from a reader: 4 MiB.
pub const STREAM_PIECE: usize = 4 << 20;

/// The bytes one row names, in the file that holds them. Read whole, or a piece at
/// a time ([`pieces`](Self::pieces)) so a big body is never in memory at once.
///
/// Every read checks that the bytes a chunk names lie in the file (its length, read
/// when the read starts) and opens a compressed chunk under the allocation budget
/// of what its row declares. With `verify`, every chunk's BLAKE3 is checked as it
/// is read; a bad chunk ends the read with an error at that chunk.
#[derive(Clone)]
pub struct Blob {
    file: Arc<File>,
    at: BlobRef,
}

impl std::fmt::Debug for Blob {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Blob").field("at", &self.at).finish()
    }
}

impl Blob {
    pub(crate) fn new(file: Arc<File>, at: BlobRef) -> Self {
        Self { file, at }
    }

    pub fn location(&self) -> &BlobRef {
        &self.at
    }

    pub(crate) fn file(&self) -> &File {
        &self.file
    }

    pub fn size(&self) -> u64 {
        self.at.size()
    }

    /// The stored BLAKE3 of the whole body (see [`BlobRef::checksum`]).
    pub fn checksum(&self) -> Option<[u8; 32]> {
        self.at.checksum()
    }

    /// The whole body.
    pub fn read(&self) -> Result<Vec<u8>> {
        self.collect(false)
    }

    /// The whole body, every chunk's BLAKE3 checked.
    pub fn read_verified(&self) -> Result<Vec<u8>> {
        self.collect(true)
    }

    fn collect(&self, verify: bool) -> Result<Vec<u8>> {
        // The declared size is the index's word: reserve no more than the file holds.
        let cap = self.size().min(self.file.metadata()?.len()).min(64 << 20);
        let mut out = Vec::with_capacity(usize::try_from(cap)?);
        self.write_to(&mut out, verify)?;
        Ok(out)
    }

    /// Write the body to `out`, one piece in memory at a time. The bytes written.
    pub fn write_to(&self, out: &mut dyn Write, verify: bool) -> Result<u64> {
        let mut n = 0u64;
        for piece in self.pieces(STREAM_PIECE, verify)? {
            let piece = piece?;
            out.write_all(&piece)?;
            n += piece.len() as u64;
        }
        Ok(n)
    }

    /// The body in pieces of at most `piece` bytes, each read when it is pulled.
    pub fn pieces(&self, piece: usize, verify: bool) -> Result<Pieces> {
        let file_len = self.file.metadata()?.len();
        Ok(Pieces {
            file: Arc::clone(&self.file),
            chunks: self.at.chunks.clone(),
            piece: piece.max(1),
            verify,
            file_len,
            i: 0,
            at: 0,
            hasher: blake3::Hasher::new(),
            pending: Vec::new(),
            pending_at: 0,
            done: false,
        })
    }
}

/// A body read a piece at a time ([`Blob::pieces`]).
pub struct Pieces {
    file: Arc<File>,
    chunks: Vec<ChunkLoc>,
    piece: usize,
    verify: bool,
    file_len: u64,
    /// The chunk being read, and how far into it (a stored chunk).
    i: usize,
    at: u64,
    hasher: blake3::Hasher,
    /// A compressed chunk, opened whole, handed out a piece at a time.
    pending: Vec<u8>,
    pending_at: usize,
    done: bool,
}

impl Pieces {
    fn step(&mut self) -> Result<Option<Vec<u8>>> {
        loop {
            if self.pending_at < self.pending.len() {
                let end = (self.pending_at + self.piece).min(self.pending.len());
                let out = self.pending[self.pending_at..end].to_vec();
                self.pending_at = end;
                return Ok(Some(out));
            }
            let Some(c) = self.chunks.get(self.i).cloned() else {
                return Ok(None);
            };
            let end = c.blob_offset.checked_add(c.blob_size);
            ensure!(
                end.is_some_and(|end| end <= self.file_len),
                "chunk {} names bytes {}+{} past the file's end {}",
                c.chunk_seq,
                c.blob_offset,
                c.blob_size,
                self.file_len
            );
            if c.compressed {
                let mut blob = vec![0u8; usize::try_from(c.blob_size)?];
                self.file.read_exact_at(&mut blob, c.blob_offset)?;
                let most = usize::try_from(c.uncompressed_size)?;
                let mut out = Vec::new();
                let n = crate::codec::decompress_into_budgeted(&blob, &mut out, most)?;
                out.truncate(n);
                ensure!(
                    out.len() as u64 == c.uncompressed_size,
                    "chunk {} opens to {} bytes, its row says {}",
                    c.chunk_seq,
                    out.len(),
                    c.uncompressed_size
                );
                if self.verify && *blake3::hash(&out).as_bytes() != c.checksum {
                    bail!("chunk {}: the bytes are not its BLAKE3", c.chunk_seq);
                }
                self.pending = out;
                self.pending_at = 0;
                self.i += 1;
                continue;
            }
            ensure!(
                c.blob_size == c.uncompressed_size,
                "stored chunk {} is {} bytes, its row says {}",
                c.chunk_seq,
                c.blob_size,
                c.uncompressed_size
            );
            let left = c.blob_size - self.at;
            let n = usize::try_from(left).map_or(self.piece, |l| l.min(self.piece));
            let mut out = vec![0u8; n];
            self.file.read_exact_at(&mut out, c.blob_offset + self.at)?;
            if self.verify {
                self.hasher.update(&out);
            }
            self.at += n as u64;
            if self.at == c.blob_size {
                if self.verify && *self.hasher.finalize().as_bytes() != c.checksum {
                    bail!("chunk {}: the bytes are not its BLAKE3", c.chunk_seq);
                }
                self.hasher = blake3::Hasher::new();
                self.at = 0;
                self.i += 1;
            }
            if n > 0 {
                return Ok(Some(out));
            }
        }
    }
}

impl Iterator for Pieces {
    type Item = Result<Vec<u8>>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        match self.step() {
            Ok(Some(p)) => Some(Ok(p)),
            Ok(None) => {
                self.done = true;
                None
            }
            Err(e) => {
                self.done = true;
                Some(Err(e))
            }
        }
    }
}

/// Read until `buf` is full or the reader ends; the bytes read.
pub(crate) fn fill(body: &mut dyn Read, buf: &mut [u8]) -> Result<usize> {
    let mut n = 0;
    while n < buf.len() {
        match body.read(&mut buf[n..]) {
            Ok(0) => break,
            Ok(k) => n += k,
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(e) => return Err(anyhow!("reading the body: {e}")),
        }
    }
    Ok(n)
}

/// A newly created or renamed or removed file is durable only once its directory is.
pub(crate) fn sync_dir_of(path: &Path) {
    let parent = match path.parent() {
        Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
        _ => PathBuf::from("."),
    };
    if let Ok(f) = File::open(parent) {
        let _ = f.sync_all();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn loc(seq: u32, at: u64, n: u64) -> ChunkLoc {
        ChunkLoc {
            chunk_seq: seq,
            fdata_offset: u64::from(seq) * n,
            blob_offset: at,
            blob_size: n,
            uncompressed_size: n,
            compressed: false,
            checksum: [seq as u8; 32],
        }
    }

    /// A V2 batch carries every kind of row and reads back as written: a name in
    /// pieces, a second name on another file's bytes, an end, in three groups.
    #[test]
    fn v2_rows_read_back_as_written() {
        let entries = vec![
            RowEntry {
                group: Group::new(1, "7"),
                name: "a".into(),
                slot: Some(BlobRef {
                    pack: None,
                    chunks: vec![loc(0, 0, 10), loc(1, 10, 10)],
                }),
            },
            RowEntry {
                group: Group::new(2, "9"),
                name: "a".into(),
                slot: Some(BlobRef {
                    pack: Some(3),
                    chunks: vec![loc(0, 40, 5)],
                }),
            },
            RowEntry {
                group: Group::default(),
                name: "gone".into(),
                slot: None,
            },
        ];
        let schema = rows_schema(&HashMap::new());
        let batch = rows_batch(&schema, &entries).unwrap();
        assert_eq!(batch.num_rows(), 4);
        let back = entries_in_order(decode_flat(&batch, &Group::default()).unwrap()).unwrap();
        assert_eq!(back, entries);
    }

    /// The eight base columns (a journal of before groups, a data sub-index) read as
    /// rows of the group the caller names, in their own file.
    #[test]
    fn base_columns_read_as_the_group_named() {
        let entries = vec![RowEntry {
            group: Group::default(),
            name: "x".into(),
            slot: Some(BlobRef {
                pack: None,
                chunks: vec![loc(0, 0, 3)],
            }),
        }];
        let batch = rows_batch(&data_subindex_schema(), &entries).unwrap();
        assert_eq!(batch.num_columns(), 8, "V1 is the base columns alone");
        let back = decode_flat(&batch, &Group::new(1, "r")).unwrap();
        assert_eq!(back[0].group, Group::new(1, "r"));
        assert_eq!(back[0].pack, None);
        assert!(
            rows_batch(
                &data_subindex_schema(),
                &[RowEntry {
                    group: Group::new(1, "r"),
                    name: "y".into(),
                    slot: None
                }]
            )
            .is_err(),
            "V1 cannot carry a group or an end"
        );
    }

    /// A chunk that comes without its chunk 0 is refused, not joined to another name.
    #[test]
    fn a_lone_later_chunk_is_refused() {
        let rows = vec![FlatRow {
            group: Group::default(),
            name: "a".into(),
            pack: None,
            chunk: Some(loc(1, 0, 1)),
        }];
        assert!(entries_in_order(rows).is_err());
    }

    /// The index keeps a name's place when it is replaced or ended, and counts.
    #[test]
    fn the_index_keeps_places_and_counts() {
        let mut ix = RowIndex::default();
        let b = |at| {
            Some(BlobRef {
                pack: None,
                chunks: vec![loc(0, at, 1)],
            })
        };
        let g = Group::default();
        assert_eq!(ix.set(g.clone(), "a".into(), b(0)), Was::New);
        assert_eq!(ix.set(g.clone(), "b".into(), b(1)), Was::New);
        assert_eq!(ix.set(g.clone(), "a".into(), b(2)), Was::Live);
        assert_eq!(ix.set(g.clone(), "b".into(), None), Was::Live);
        assert_eq!(ix.names(&g), ["a"]);
        assert_eq!(ix.live(), 1);
        assert_eq!(ix.lookup(&g, "b"), Lookup::Ended);
        assert_eq!(ix.set(g.clone(), "b".into(), b(3)), Was::Ended);
        assert_eq!(ix.names(&g), ["a", "b"], "b keeps its first place");
        assert_eq!(ix.live(), 2);
        let mut other = RowIndex::default();
        other.set(g.clone(), "b".into(), b(3));
        other.set(g.clone(), "a".into(), b(2));
        assert!(ix.same_as(&other));
    }
}