rete-core 0.7.2

Core format types for the Rete cloud-native RDF graph file.
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
//! Reading a `0x06` file: the header and the root come with the first read;
//! everything else is built lazily from them — the dictionary and the index as
//! two-level directories whose leaves fault on demand and stay for the session,
//! the text index likewise, the label index and the quad index through their
//! own lazy machinery.

use std::sync::Arc;

use super::*;
use crate::derived;
use crate::dict::{ChunkLeaf, ChunkedSection, LeafedChunks, SectionMeta};
use crate::dictionary::Dictionary;
use crate::file::{decompress_bounded, ByteRange, FileError};
use crate::index::{GraphIndex, LeafFetch, LeafedTiles, TileLeaf, NUM_PERMS};
use crate::reader::RangeReader;

/// Coalescing gaps for the batched faults (as for `0x05`).
const TILE_GAP: u64 = 4096;
const DICT_GAP: u64 = 64 * 1024;

/// An open `0x06` file: its header and root, and the reader.
pub struct V06File {
    /// The 128-byte header.
    pub h: Header06,
    /// The decoded root block.
    pub root: Root06,
    /// Where everything else is read from.
    pub reader: Arc<dyn RangeReader + Send + Sync>,
}

/// Read `(offset, len)` ranges as one coalesced batch.
fn read_coalesced(
    r: &(dyn RangeReader + Send + Sync),
    ranges: &[(u64, u64)],
    gap: u64,
) -> Option<Vec<Vec<u8>>> {
    let rs: Vec<ByteRange> = ranges
        .iter()
        .map(|&(offset, len)| ByteRange { offset, len })
        .collect();
    crate::file::read_coalesced(r, &rs, gap)
}

/// [`read_coalesced`] for tiles far apart: the reader gets the exact ranges.
fn read_scattered(
    r: &(dyn RangeReader + Send + Sync),
    ranges: &[(u64, u64)],
) -> Option<Vec<Vec<u8>>> {
    let rs: Vec<ByteRange> = ranges
        .iter()
        .map(|&(offset, len)| ByteRange { offset, len })
        .collect();
    crate::file::read_coalesced_scattered(r, &rs, 0)
}

impl V06File {
    /// Open from `first`, the file's leading bytes (at least the header; the
    /// root is read from it when it fits, else fetched).
    pub fn open(
        reader: Arc<dyn RangeReader + Send + Sync>,
        first: &[u8],
    ) -> Result<Self, FileError> {
        let h = Header06::from_bytes(first)?;
        if h.file_len != reader.len() {
            return Err(FileError::Container(
                "0x06 file length does not match the header (truncated?)",
            ));
        }
        let rs = HEADER_LEN;
        let re = rs + h.root_len as usize;
        let root_bytes = if re <= first.len() {
            first[rs..re].to_vec()
        } else {
            reader.read_at(rs as u64, h.root_len as u64)?
        };
        if digest16(&root_bytes) != h.root_digest {
            return Err(FileError::Container("0x06 root digest mismatch"));
        }
        let root = Root06::decode(&root_bytes, h.internal_codec)?;
        for s in &root.sections {
            if h.version == VERSION_06 && kind::is_v07_only(s.kind) {
                return Err(FileError::Container(
                    "0x06 file has a section only 0x07 defines",
                ));
            }
            let a = s.abs(&h)?;
            let end = a.offset + a.len;
            let ok = if kind::is_front(s.kind) {
                a.offset >= h.front_base() && end <= h.data_offset
            } else {
                a.offset >= h.data_offset && end <= h.file_len - FOOTER.len() as u64
            };
            if !ok {
                return Err(FileError::Container("0x06 section out of its region"));
            }
        }
        Ok(V06File { h, root, reader })
    }

    /// The decompression bound of section `k`'s blocks: its recorded largest
    /// block, or [`BLOCK_CEILING`] where none is recorded.
    pub fn bound(&self, k: u8) -> u64 {
        section_bound(&self.root, k)
    }

    /// The absolute range of section `k`, if present.
    pub fn section(&self, k: u8) -> Option<ByteRange> {
        self.root.section(k).and_then(|s| s.abs(&self.h).ok())
    }

    /// A batched leaf fetcher over this file's reader (leaves are stored with
    /// the internal codec; decoding happens in the directory types).
    pub fn fetch(&self) -> LeafFetch {
        let r = self.reader.clone();
        Arc::new(move |ranges: &[(u64, u64)]| read_coalesced(&*r, ranges, 0))
    }

    /// The Dataset Card (decompressed), if the file has one.
    pub fn card(&self) -> Result<Option<Vec<u8>>, FileError> {
        let r = self.h.card_range();
        if r.len == 0 {
            return Ok(None);
        }
        let stored = self.reader.read_at(r.offset, r.len)?;
        if digest16(&stored) != self.h.card_digest {
            return Err(FileError::Container("0x06 card digest mismatch"));
        }
        Ok(Some(decompress_bounded(
            self.h.internal_codec,
            &stored,
            CARD_MAX,
        )?))
    }

    /// The build record (raw), if the file has one.
    pub fn build_record(&self) -> Result<Option<Vec<u8>>, FileError> {
        let r = self.h.build_range();
        if r.len == 0 {
            return Ok(None);
        }
        Ok(Some(self.reader.read_at(r.offset, r.len)?))
    }

    /// The label index's root node (`0x07`: its own cold section), digest
    /// checked. Fetched only when a label search runs.
    pub fn label_root_node(&self) -> Result<Vec<u8>, FileError> {
        let r = self
            .section(kind::LABEL_ROOT)
            .ok_or(FileError::Container("0x07 file has no label root section"))?;
        let b = self.reader.read_at(r.offset, r.len)?;
        check_digest(&self.root, kind::LABEL_ROOT, &b)?;
        Ok(b)
    }

    /// The card annex (raw JSON, decompressed), if the file has one.
    pub fn annex(&self) -> Result<Option<Vec<u8>>, FileError> {
        read_annex(&*self.reader, &self.h, &self.root)
    }

    /// The full card: the hot card with its annex merged back in.
    pub fn card_full(&self) -> Result<Option<Vec<u8>>, FileError> {
        let Some(hot) = self.card()? else {
            return Ok(None);
        };
        match self.annex()? {
            None => Ok(Some(hot)),
            Some(a) => annex::merge(&hot, &a)
                .map(Some)
                .map_err(|_| FileError::Container("0x07 card annex does not merge")),
        }
    }

    /// The stats + schema section, as the `0x05` SCHEMA section bytes
    /// (digest-prefixed) its decoder takes.
    pub fn schema_section_bytes(&self) -> Option<Vec<u8>> {
        let r = self.section(kind::SCHEMA)?;
        let stored = self.reader.read_at(r.offset, r.len).ok()?;
        let body =
            decompress_bounded(self.h.internal_codec, &stored, self.bound(kind::SCHEMA)).ok()?;
        let mut out = digest16(&body).to_vec();
        out.extend_from_slice(&body);
        Some(out)
    }

    /// The decoded stats + schema section.
    pub fn schema(&self) -> Option<crate::schema_section::SchemaMeta> {
        crate::schema_section::SchemaMeta::decode(&self.schema_section_bytes()?).ok()
    }

    /// The community pyramid's bytes.
    pub fn pyramid_bytes(&self) -> Option<Vec<u8>> {
        let r = self.section(kind::PYRAMID)?;
        self.reader.read_at(r.offset, r.len).ok()
    }

    /// The derived IRI families the root lists (SPEC.md section 5.3), checked
    /// against the header flag and the chunk count of the subject-only section.
    pub fn derived_families(&self, n_chunks: usize) -> Result<Vec<derived::Family>, FileError> {
        let flagged = self.h.flags & F_DERIVED != 0;
        let Some(unit) = self.root.unit(tag::DERIVED) else {
            if flagged {
                return Err(FileError::Container(
                    "0x08 derived-IRI flag without a derived-IRI root",
                ));
            }
            return Ok(Vec::new());
        };
        if !flagged || self.h.version < VERSION {
            return Err(FileError::Container(
                "derived-IRI root without the derived-IRI header flag",
            ));
        }
        derived::decode_families(unit, n_chunks)
            .map_err(|_| FileError::Container("0x08 derived-IRI root is malformed"))
    }

    /// The four dictionary sections, two-level, chunks faulted on demand.
    /// `want[si] == false` leaves that section empty (a search-only open).
    pub fn dictionary(&self, want: [bool; 4]) -> Result<Dictionary, FileError> {
        let unit = self
            .root
            .unit(tag::DICT)
            .ok_or(FileError::Container("0x06 file has no dictionary"))?;
        let roots = decode_dict_root(unit, self.h.version)?;
        let order = term_order(self.h.version);
        let fams = self.derived_families(roots[derived::SECTION].n_chunks)?;
        let elided = derived::elided_runs(&fams);
        let leaves_base = self.section(kind::DICT_LEAVES).map_or(0, |r| r.offset);
        let data_base = self.section(kind::DICT_DATA).map_or(0, |r| r.offset);
        let cache = crate::chunk_cache::ChunkCache::unlimited_arc();
        let codec = self.h.dict_codec;
        let max = self.bound(kind::DICT_DATA);
        let mut dirs: Vec<Option<Arc<LeafedChunks>>> = Vec::with_capacity(4);
        let mut sections = Vec::with_capacity(4);
        for (si, s) in roots.iter().enumerate() {
            let meta = SectionMeta {
                term_count: if want[si] { s.term_count } else { 0 },
                restart_interval: s.restart_interval.max(1),
                restart_offsets: Vec::new(),
            };
            if !want[si] {
                sections.push(
                    ChunkedSection::from_parts(meta, Vec::new(), None, cache.clone(), si as u8)
                        .with_order(order),
                );
                dirs.push(None);
                continue;
            }
            let leaves: Vec<ChunkLeaf> = s
                .leaves
                .iter()
                .map(|(l, run, coff, key)| ChunkLeaf {
                    first: l.first,
                    n: l.n,
                    first_run: *run,
                    key: key.clone(),
                    leaf: (leaves_base + l.off, l.len),
                    chunk_base: data_base + s.data_off + coff,
                })
                .collect();
            let dir = Arc::new(
                LeafedChunks::new(leaves, s.n_chunks, self.fetch(), self.h.internal_codec)
                    .with_max_block(self.bound(kind::DICT_LEAVES)),
            );
            let (r, d) = (self.reader.clone(), dir.clone());
            let loader: crate::dict::ChunkLoader = Box::new(move |ci| {
                let (off, len) = d.range(ci)?;
                let b = r.read_at(off, len).ok()?;
                decompress_bounded(codec, &b, max).ok()
            });
            let (r, d) = (self.reader.clone(), dir.clone());
            let bulk: crate::dict::ChunkBulkLoader = Box::new(move |cis| {
                d.ensure_leaves(&d.leaves_of(cis));
                let ranges: Option<Vec<(u64, u64)>> = cis.iter().map(|&ci| d.range(ci)).collect();
                let blobs = read_coalesced(&*r, &ranges?, DICT_GAP)?;
                blobs
                    .iter()
                    .map(|b| decompress_bounded(codec, b, max).ok())
                    .collect()
            });
            let mut section =
                ChunkedSection::leafed(meta, dir.clone(), loader, cache.clone(), si as u8)
                    .with_bulk_loader(bulk)
                    .with_order(order);
            if order == crate::term_order::TermOrder::Sparql {
                section = section.with_groups(s.groups);
            }
            if si == derived::SECTION {
                section = section.with_elided(elided.clone());
            }
            sections.push(section);
            dirs.push(Some(dir));
        }
        let arr: [ChunkedSection; 4] = sections
            .try_into()
            .map_err(|_| FileError::Container("expected 4 dictionary sections"))?;
        let r = self.reader.clone();
        let multi: crate::dict::MultiChunkBulkLoader = Box::new(move |pairs| {
            // Fault every section's leaves first (one batch), then the chunks.
            let mut per: [Vec<usize>; 4] = Default::default();
            for &(si, ci) in pairs {
                if let Some(v) = per.get_mut(si as usize) {
                    v.push(ci);
                }
            }
            // One read for the leaves of every section: a batch that names
            // terms in three sections used to cost three sequential reads here.
            let wanted: Vec<(usize, Vec<usize>)> = per
                .iter()
                .enumerate()
                .filter_map(|(si, cis)| Some((si, dirs.get(si)?.as_ref()?.leaves_of(cis))))
                .collect();
            let across: Vec<(&dyn crate::index::LeafDir, &[usize])> = wanted
                .iter()
                .filter_map(|(si, lis)| {
                    let d: &dyn crate::index::LeafDir = dirs.get(*si)?.as_deref()?;
                    Some((d, lis.as_slice()))
                })
                .collect();
            crate::index::ensure_leaves_across(&across);
            let ranges: Option<Vec<(u64, u64)>> = pairs
                .iter()
                .map(|&(si, ci)| dirs.get(si as usize)?.as_ref()?.range(ci))
                .collect();
            let blobs = read_coalesced(&*r, &ranges?, DICT_GAP)?;
            blobs
                .iter()
                .map(|b| decompress_bounded(codec, b, max).ok())
                .collect()
        });
        let mut dict = Dictionary::from_chunked_sections(arr).with_multi_bulk_loader(multi);
        dict.set_has_quoted_triples(self.h.flags & F_QUOTED != 0);
        if want[derived::SECTION] {
            dict = dict.with_derived(fams);
        }
        Ok(dict)
    }

    /// The class clusters the cluster root lists, checked against the index root:
    /// every run is whole leaves, and the runs cover the permutation.
    fn clusters(&self, perms: &[PermRoot]) -> Result<Vec<ClusterOrder>, FileError> {
        let Some(unit) = self.root.unit(tag::CLUSTER) else {
            if self.h.flags & F_CLUSTERED != 0 {
                return Err(FileError::Container(
                    "0x07 clustered file without a cluster root",
                ));
            }
            return Ok(Vec::new());
        };
        let orders = decode_cluster_root(unit)?;
        let quad = self.quad_root().transpose()?;
        for c in &orders {
            // The order's tile count and its leaves, `(first tile, tiles)`.
            let (n_tiles, leaves): (usize, Vec<(usize, usize)>) = if c.si == QUAD_SPOG {
                let o = quad
                    .as_ref()
                    .and_then(|q| q.orders.iter().find(|o| o.si == c.si))
                    .ok_or(FileError::Container(
                        "0x07 cluster root names an order the quad index lacks",
                    ))?;
                (
                    o.n_tiles,
                    o.leaves.iter().map(|(l, _, _, _)| (l.first, l.n)).collect(),
                )
            } else {
                let p = perms
                    .iter()
                    .find(|p| p.si == c.si)
                    .ok_or(FileError::Container(
                        "0x07 cluster root names a permutation the index lacks",
                    ))?;
                (
                    p.n_tiles,
                    p.leaves.iter().map(|(l, _, _, _)| (l.first, l.n)).collect(),
                )
            };
            if c.run_tiles.iter().sum::<usize>() != n_tiles {
                return Err(FileError::Container(
                    "0x07 cluster runs do not cover the tiles",
                ));
            }
            // A leaf holds the tiles of one run.
            let mut ends = Vec::with_capacity(c.run_tiles.len());
            let mut at = 0usize;
            for &n in &c.run_tiles {
                at += n;
                ends.push(at);
            }
            for (first, n) in leaves {
                let r = ends.partition_point(|&e| e <= first);
                if first + n > ends[r.min(ends.len() - 1)] {
                    return Err(FileError::Container(
                        "0x07 a directory leaf spans two cluster runs",
                    ));
                }
            }
        }
        Ok(orders)
    }

    /// The default graph's index, two-level, tiles faulted on demand.
    pub fn index(&self, read_concurrency: usize) -> Result<GraphIndex, FileError> {
        let unit = self
            .root
            .unit(tag::INDEX)
            .ok_or(FileError::Container("0x06 file has no index"))?;
        let perms_root = decode_index_root(unit)?;
        let leaves_base = self.section(kind::INDEX_LEAVES).map_or(0, |r| r.offset);
        let data_base = self.section(kind::INDEX_DATA).map_or(0, |r| r.offset);
        let perms = self.h.perms();
        let mut lists: [Option<Arc<LeafedTiles>>; NUM_PERMS] = Default::default();
        for p in &perms_root {
            if p.si >= NUM_PERMS {
                return Err(FileError::Container("0x06 index: bad permutation"));
            }
            let leaves: Vec<TileLeaf> = p
                .leaves
                .iter()
                .map(|(l, mn, mx, toff)| TileLeaf {
                    first: l.first,
                    n: l.n,
                    min_a: *mn,
                    max_a: *mx,
                    leaf: (leaves_base + l.off, l.len),
                    tile_base: data_base + p.data_off + toff,
                })
                .collect();
            lists[p.si] = Some(Arc::new(
                LeafedTiles::new(
                    leaves,
                    p.n_tiles,
                    p.data_len,
                    self.fetch(),
                    self.h.internal_codec,
                )
                .with_max_block(self.bound(kind::INDEX_LEAVES)),
            ));
        }
        for perm in perms.iter() {
            if lists[perm.section_index()].is_none() {
                return Err(FileError::Container(
                    "0x06 index lacks a stored permutation",
                ));
            }
        }
        let codec = self.h.block_codec;
        let max = self.bound(kind::INDEX_DATA);
        let (r, l) = (self.reader.clone(), lists.clone());
        let loader: crate::index::TileLoader = Box::new(move |si, ti| {
            let (off, len) = l.get(si)?.as_ref()?.range(ti)?;
            let b = r.read_at(off, len).ok()?;
            decompress_bounded(codec, &b, max).ok()
        });
        let (r, l) = (self.reader.clone(), lists.clone());
        let bulk: crate::index::TileBulkLoader = Box::new(move |si, tis| {
            let list = l.get(si)?.as_ref()?;
            if let (Some(&a), Some(&b)) = (tis.first(), tis.last()) {
                list.ensure_span(a, b + 1);
            }
            let ranges: Option<Vec<(u64, u64)>> = tis.iter().map(|&ti| list.range(ti)).collect();
            let blobs = read_coalesced(&*r, &ranges?, TILE_GAP)?;
            blobs
                .iter()
                .map(|b| decompress_bounded(codec, b, max).ok())
                .collect()
        });
        let (r, l) = (self.reader.clone(), lists.clone());
        let scattered: crate::index::TileBulkLoader = Box::new(move |si, tis| {
            let list = l.get(si)?.as_ref()?;
            let ranges: Option<Vec<(u64, u64)>> = tis.iter().map(|&ti| list.range(ti)).collect();
            let blobs = read_scattered(&*r, &ranges?)?;
            blobs
                .iter()
                .map(|b| decompress_bounded(codec, b, max).ok())
                .collect()
        });
        let mut index = GraphIndex::from_leafed(lists, perms, loader)
            .with_bulk_loader(bulk)
            .with_scattered_loader(scattered);
        for c in self
            .clusters(&perms_root)?
            .into_iter()
            .filter(|c| c.si < NUM_PERMS)
        {
            index = index.with_clusters(
                c.si,
                crate::index::ClusterRuns::new(c.classes, &c.run_tiles),
            );
        }
        index.set_read_concurrency(read_concurrency);
        Ok(index)
    }

    /// The text index (leafed token table), if the file has one.
    pub fn text_index(&self) -> Option<Result<crate::text_index::TextIndex, FileError>> {
        let unit = self.root.unit(tag::TEXT)?;
        Some((|| {
            let t = decode_text_root(unit)?;
            let leaves_base = self.section(kind::TEXT_LEAVES).map_or(0, |r| r.offset);
            let data = self
                .section(kind::TEXT_DATA)
                .unwrap_or(ByteRange { offset: 0, len: 0 });
            let leaves = t
                .leaves
                .iter()
                .map(|(l, tok)| crate::text_index::TokenLeaf {
                    first: l.first,
                    n: l.n,
                    first_token: String::from_utf8_lossy(tok).into_owned(),
                    leaf: (leaves_base + l.off, l.len),
                })
                .collect();
            let tokens = Arc::new(
                crate::text_index::LeafedTokens::new(
                    leaves,
                    t.n_tokens,
                    self.fetch(),
                    self.h.internal_codec,
                )
                .with_max_block(self.bound(kind::TEXT_LEAVES)),
            );
            let r = self.reader.clone();
            let loader = Box::new(move |off: u64, len: u64| {
                if off.checked_add(len)? > data.len {
                    return None;
                }
                r.read_at(data.offset + off, len).ok()
            });
            crate::text_index::TextIndex::leafed(tokens, &t.scope, loader)
        })())
    }

    /// Stored bytes of the token table (all leaves) — what a substring search
    /// would read; a word lookup reads one leaf.
    pub fn token_table_bytes(&self) -> Option<u64> {
        self.root.unit(tag::TEXT)?;
        Some(self.section(kind::TEXT_LEAVES).map_or(0, |r| r.len))
    }

    /// The label index, if the file has one.
    pub fn label_index(&self) -> Option<Result<crate::label_index::LabelIndex, FileError>> {
        let unit = self.root.unit(tag::LABELS)?;
        Some((|| {
            let mut l = decode_label_root(unit)?;
            if self.section(kind::LABEL_ROOT).is_some() {
                l.head.extend_from_slice(&self.label_root_node()?);
            }
            let data = self
                .section(kind::LABEL_DATA)
                .unwrap_or(ByteRange { offset: 0, len: 0 });
            let nodes = self
                .section(kind::LABEL_LEAVES)
                .unwrap_or(ByteRange { offset: 0, len: 0 });
            if data.len != l.data_len {
                return Err(FileError::Container("0x06 label data length mismatch"));
            }
            let head_len = l.head.len() as u64;
            let section_len = head_len + data.len + nodes.len;
            let r = self.reader.clone();
            let head = l.head.clone();
            let loader = Box::new(move |off: u64, len: u64| -> Option<Vec<u8>> {
                let end = off.checked_add(len)?;
                if end <= head_len {
                    return head.get(off as usize..end as usize).map(<[u8]>::to_vec);
                }
                let bo = off.checked_sub(head_len)?;
                if bo + len <= data.len {
                    r.read_at(data.offset + bo, len).ok()
                } else if bo >= data.len && bo - data.len + len <= nodes.len {
                    r.read_at(nodes.offset + (bo - data.len), len).ok()
                } else {
                    None
                }
            });
            let max = self
                .bound(kind::LABEL_LEAVES)
                .max(self.bound(kind::LABEL_DATA));
            crate::label_index::LabelIndex::from_head(
                &l.head,
                section_len,
                self.h.block_codec,
                loader,
            )
            .map(|li| li.with_max_block(max))
        })())
    }

    /// The label index's entry count, from the root alone.
    pub fn label_entry_count(&self) -> Option<u64> {
        let l = decode_label_root(self.root.unit(tag::LABELS)?).ok()?;
        crate::label_index::LabelIndexPreamble::parse(&l.head)
            .ok()
            .map(|p| p.entry_count)
    }

    /// The quad index's root, if the file has named graphs.
    pub fn quad_root(&self) -> Option<Result<QuadRoot, FileError>> {
        self.root.unit(tag::QUAD).map(decode_quad_root)
    }

    /// The named graphs (quad index), if any.
    pub(crate) fn quad(
        &self,
        read_concurrency: usize,
    ) -> Option<Result<crate::quad::QuadNamed, FileError>> {
        let root = match self.quad_root()? {
            Ok(r) => r,
            Err(e) => return Some(Err(e)),
        };
        let leaves = self.section(kind::QUAD_LEAVES).map_or(0, |r| r.offset);
        let data = self.section(kind::QUAD_DATA).map_or(0, |r| r.offset);
        // The class runs of SPOG, when the file clusters it.
        let clusters = match self.root.unit(tag::CLUSTER).map(decode_cluster_root) {
            Some(Ok(c)) => c,
            Some(Err(e)) => return Some(Err(e)),
            None => Vec::new(),
        };
        Some(
            crate::quad::V06Quad::new(
                &root,
                leaves,
                data,
                self.h.internal_codec,
                has_v07(self.h.version),
            )
            .and_then(|v| v.with_clusters(&clusters))
            .map(|mut v| {
                v.tile_max = self.bound(kind::QUAD_DATA);
                v.leaf_max = self.bound(kind::QUAD_LEAVES);
                crate::quad::QuadNamed::new_v06(
                    self.reader.clone(),
                    v,
                    self.h.block_codec,
                    self.h.perms(),
                    read_concurrency,
                )
            }),
        )
    }

    /// Verify every digest: the root, the card, each section (streamed), and
    /// the content hash. `only` restricts the section checks to one kind.
    /// `Ok(false)` names nothing; [`verify_report`](Self::verify_report) does.
    pub fn verify(&self, only: Option<u8>) -> Result<bool, FileError> {
        Ok(self.verify_report(only)?.is_empty())
    }

    /// Like [`verify`](Self::verify), returning what failed (empty = all good).
    pub fn verify_report(&self, only: Option<u8>) -> Result<Vec<String>, FileError> {
        const SLICE: u64 = 8 << 20;
        let mut bad = Vec::new();
        if content_hash(&self.h) != self.h.content_hash {
            bad.push("content hash".to_string());
        }
        let card = self.h.card_range();
        if only.is_none() && card.len > 0 {
            let stored = self.reader.read_at(card.offset, card.len)?;
            if digest16(&stored) != self.h.card_digest {
                bad.push("card".to_string());
            }
        }
        for s in &self.root.sections {
            if only.is_some_and(|k| k != s.kind) {
                continue;
            }
            let a = s.abs(&self.h)?;
            let mut h = blake3::Hasher::new();
            let mut at = a.offset;
            while at < a.offset + a.len {
                let n = (a.offset + a.len - at).min(SLICE);
                h.update(&self.reader.read_at(at, n)?);
                at += n;
            }
            if h.finalize().as_bytes()[..16] != s.digest {
                bad.push(kind::name(s.kind).to_string());
            }
        }
        if only.is_none() {
            let want = footer(self.h.version);
            let foot = self
                .reader
                .read_at(self.h.file_len - want.len() as u64, want.len() as u64)?;
            if foot != want {
                bad.push("footer".to_string());
            }
        }
        Ok(bad)
    }
}

/// Is this file (by its first bytes) a `0x06` or `0x07` file?
pub fn is_v06(first: &[u8]) -> bool {
    first.len() > 4 && first[0..4] == crate::header::MAGIC && reads(first[4])
}

/// Read a `0x06` file's header and root through any reader (two reads at most;
/// over a seeded or prefix-holding reader, none).
pub fn read_front<R: RangeReader + ?Sized>(r: &R) -> Result<(Header06, Root06), FileError> {
    let head = r.read_at(0, HEADER_LEN as u64)?;
    let h = Header06::from_bytes(&head)?;
    let root_bytes = r.read_at(HEADER_LEN as u64, h.root_len as u64)?;
    if digest16(&root_bytes) != h.root_digest {
        return Err(FileError::Container("0x06 root digest mismatch"));
    }
    let root = Root06::decode(&root_bytes, h.internal_codec)?;
    Ok((h, root))
}

/// The stored bytes of section `k`, if present.
pub fn read_section<R: RangeReader + ?Sized>(
    r: &R,
    h: &Header06,
    root: &Root06,
    k: u8,
) -> Result<Option<Vec<u8>>, FileError> {
    match root.section(k) {
        Some(s) => {
            let a = s.abs(h)?;
            Ok(Some(r.read_at(a.offset, a.len)?))
        }
        None => Ok(None),
    }
}

/// The card (decompressed) and the build record (raw): one read of the card
/// region, which sits right after the root.
#[allow(clippy::type_complexity)]
pub fn read_card_build<R: RangeReader + ?Sized>(
    r: &R,
    h: &Header06,
) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>), FileError> {
    read_card_build_with(r, h, true)
}

/// [`read_card_build`], reading the build record only when `want_build`: a
/// caller that never prints it stops its read at the end of the card.
#[allow(clippy::type_complexity)]
pub fn read_card_build_with<R: RangeReader + ?Sized>(
    r: &R,
    h: &Header06,
    want_build: bool,
) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>), FileError> {
    let c = h.card_range();
    let mut b = h.build_range();
    if !want_build {
        b.len = 0;
    }
    if c.len == 0 && b.len == 0 {
        return Ok((None, None));
    }
    let lo = if c.len == 0 {
        b.offset
    } else if b.len == 0 {
        c.offset
    } else {
        c.offset.min(b.offset)
    };
    let hi = (c.offset + c.len).max(b.offset + b.len);
    let span = r.read_at(lo, hi - lo)?;
    let card = if c.len > 0 {
        let stored = &span[(c.offset - lo) as usize..(c.offset - lo + c.len) as usize];
        if digest16(stored) != h.card_digest {
            return Err(FileError::Container("0x06 card digest mismatch"));
        }
        Some(decompress_bounded(h.internal_codec, stored, CARD_MAX)?)
    } else {
        None
    };
    let build = (b.len > 0)
        .then(|| span[(b.offset - lo) as usize..(b.offset - lo + b.len) as usize].to_vec());
    Ok((card, build))
}

/// Section `k`'s decompression bound in `root`: its recorded largest block,
/// or [`BLOCK_CEILING`].
pub fn section_bound(root: &Root06, k: u8) -> u64 {
    root.section(k)
        .map(|s| s.max_block as u64)
        .filter(|&m| m > 0)
        .unwrap_or(BLOCK_CEILING)
}

/// The stats + schema section as the digest-prefixed bytes its decoder takes.
pub fn read_schema_bytes<R: RangeReader + ?Sized>(r: &R) -> Result<Option<Vec<u8>>, FileError> {
    let (h, root) = read_front(r)?;
    let Some(stored) = read_section(r, &h, &root, kind::SCHEMA)? else {
        return Ok(None);
    };
    let body = decompress_bounded(
        h.internal_codec,
        &stored,
        section_bound(&root, kind::SCHEMA),
    )?;
    let mut out = digest16(&body).to_vec();
    out.extend_from_slice(&body);
    Ok(Some(out))
}

/// The community pyramid's bytes, if any.
pub fn read_pyramid<R: RangeReader + ?Sized>(r: &R) -> Result<Option<Vec<u8>>, FileError> {
    let (h, root) = read_front(r)?;
    read_section(r, &h, &root, kind::PYRAMID)
}

/// Stored bytes of the text index's token table (all leaves).
pub fn read_token_table_bytes<R: RangeReader + ?Sized>(r: &R) -> Option<u64> {
    let (_, root) = read_front(r).ok()?;
    root.unit(tag::TEXT)?;
    Some(root.section(kind::TEXT_LEAVES).map_or(0, |s| s.len))
}

/// A reader holding only some ranges of a file in memory (the borrowed-reader
/// opens of a `0x06` file read what they need into one of these).
pub struct SparseReader {
    len: u64,
    parts: Vec<(u64, Vec<u8>)>,
}

impl SparseReader {
    /// Fetch `ranges` from `r` (plus the first bytes `first`) into memory —
    /// the ones `first` does not already hold, in one batch.
    pub fn fetch<R: RangeReader + ?Sized>(
        r: &R,
        first: Vec<u8>,
        ranges: &[ByteRange],
    ) -> Result<Self, FileError> {
        let held = first.len() as u64;
        let want: Vec<(u64, u64)> = ranges
            .iter()
            .filter(|g| g.len > 0 && g.offset.saturating_add(g.len) > held)
            .map(|g| (g.offset, g.len))
            .collect();
        let mut parts = vec![(0u64, first)];
        if !want.is_empty() {
            for ((o, _), b) in want.iter().zip(r.read_many(&want)?) {
                parts.push((*o, b));
            }
        }
        Ok(SparseReader {
            len: r.len(),
            parts,
        })
    }
}

/// A borrowed reader whose first bytes are already in memory: reads inside
/// them cost nothing, the rest go to `r`.
pub struct Prefixed<'a, R: RangeReader + ?Sized> {
    /// The file's first bytes.
    pub first: &'a [u8],
    /// The reader behind them.
    pub r: &'a R,
}

impl<R: RangeReader + ?Sized> RangeReader for Prefixed<'_, R> {
    fn is_local(&self) -> bool {
        self.r.is_local()
    }

    fn len(&self) -> u64 {
        self.r.len()
    }

    fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
        match offset.checked_add(len) {
            Some(end) if end <= self.first.len() as u64 => {
                Ok(self.first[offset as usize..end as usize].to_vec())
            }
            _ => self.r.read_at(offset, len),
        }
    }
}

impl RangeReader for SparseReader {
    fn len(&self) -> u64 {
        self.len
    }

    fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
        for (o, b) in &self.parts {
            if offset >= *o && offset + len <= o + b.len() as u64 {
                let s = (offset - o) as usize;
                return Ok(b[s..s + len as usize].to_vec());
            }
        }
        Err(std::io::Error::other("0x06: range not held by this reader"))
    }
}

/// What the card's measured signals need from a `0x06` file's root: the text
/// index's `(bytes, token-table bytes)` and the label index's `(bytes, entries)`.
#[allow(clippy::type_complexity)]
pub fn read_signals<R: RangeReader + ?Sized>(
    r: &R,
) -> Result<(Option<(u64, u64)>, Option<(u64, Option<u64>)>), FileError> {
    let (_, root) = read_front(r)?;
    let len = |k: u8| root.section(k).map_or(0, |s| s.len);
    let text = root.unit(tag::TEXT).map(|_| {
        (
            len(kind::TEXT_LEAVES) + len(kind::TEXT_DATA),
            len(kind::TEXT_LEAVES),
        )
    });
    let labels = match root.unit(tag::LABELS) {
        None => None,
        Some(u) => {
            let l = decode_label_root(u)?;
            let entries = crate::label_index::LabelIndexPreamble::parse(&l.head)
                .ok()
                .map(|p| p.entry_count);
            Some((
                l.head.len() as u64
                    + len(kind::LABEL_ROOT)
                    + len(kind::LABEL_DATA)
                    + len(kind::LABEL_LEAVES),
                entries,
            ))
        }
    };
    Ok((text, labels))
}

/// Check `bytes` against the digest the root records for section `k`.
pub fn check_digest(root: &Root06, k: u8, bytes: &[u8]) -> Result<(), FileError> {
    match root.section(k) {
        Some(s) if s.digest == digest16(bytes) => Ok(()),
        Some(_) => Err(FileError::Container("0x07 section digest mismatch")),
        None => Ok(()),
    }
}

/// The card annex of a `0x07` file (raw JSON, decompressed, digest checked).
pub fn read_annex<R: RangeReader + ?Sized>(
    r: &R,
    h: &Header06,
    root: &Root06,
) -> Result<Option<Vec<u8>>, FileError> {
    let Some(stored) = read_section(r, h, root, kind::CARD_ANNEX)? else {
        return Ok(None);
    };
    check_digest(root, kind::CARD_ANNEX, &stored)?;
    let max = root
        .section(kind::CARD_ANNEX)
        .map(|s| s.max_block as u64)
        .filter(|&m| m > 0)
        .unwrap_or(ANNEX_MAX);
    Ok(Some(decompress_bounded(h.internal_codec, &stored, max)?))
}

/// The card of the file read through `r` with its annex merged back in (what
/// `rete card --full` shows), and whether an annex was merged.
pub fn read_card_full<R: RangeReader + ?Sized>(
    r: &R,
) -> Result<(Option<Vec<u8>>, bool), FileError> {
    let (h, root) = read_front(r)?;
    let Some(hot) = read_card_build(r, &h)?.0 else {
        return Ok((None, false));
    };
    match read_annex(r, &h, &root)? {
        None => Ok((Some(hot), false)),
        Some(a) => annex::merge(&hot, &a)
            .map(|c| (Some(c), true))
            .map_err(|_| FileError::Container("0x07 card annex does not merge")),
    }
}