1use crate::dictionary::Dictionary;
18use crate::header::{
19 Header, Section, SectionKind, FLAG_HAS_QUADS, FLAG_HAS_QUOTED_TRIPLES, FLAG_TILE_SYNOPSIS,
20 HEADER_LEN, MAGIC,
21};
22use crate::index::{GraphIndex, IndexPermutation, Pattern, PermSet, NUM_PERMS};
23use crate::meta::{ClassNode, CommunityDescriptor, LevelLinks, LevelRollup, PyramidMeta};
24use crate::pyramid::{build_dendrogram, project_graph, PyramidAlgo};
25use crate::reader::RangeReader;
26use crate::tiling::{choose_round_for_budget, summarize, SuperEdge};
27use crate::triples::Triple;
28use crate::varint::{read_uvarint, write_uvarint};
29
30#[cfg(test)]
31mod hardening_tests;
32
33pub const DEFAULT_TILE_BUDGET: usize = 64 * 1024;
35
36pub fn build_pyramid_meta(
45 dict: &Dictionary,
46 triples: &[(u32, u32, u32)],
47 budget: usize,
48) -> (Vec<u8>, u16) {
49 build_pyramid_meta_with(dict, triples, budget, None)
50}
51
52pub fn build_pyramid_meta_with(
56 dict: &Dictionary,
57 triples: &[(u32, u32, u32)],
58 budget: usize,
59 type_override: Option<&str>,
60) -> (Vec<u8>, u16) {
61 build_pyramid_meta_algo(dict, triples, budget, type_override, PyramidAlgo::Louvain)
62}
63
64pub fn build_pyramid_meta_algo(
71 dict: &Dictionary,
72 triples: &[(u32, u32, u32)],
73 budget: usize,
74 type_override: Option<&str>,
75 algo: PyramidAlgo,
76) -> (Vec<u8>, u16) {
77 build_pyramid_meta_layout(
78 dict,
79 triples,
80 budget,
81 type_override,
82 algo,
83 PyramidLayout::Combined,
84 )
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
89pub enum PyramidLayout {
90 #[default]
94 Combined,
95 CommunityOnly,
100}
101
102pub fn build_pyramid_meta_layout(
104 dict: &Dictionary,
105 triples: &[(u32, u32, u32)],
106 budget: usize,
107 type_override: Option<&str>,
108 algo: PyramidAlgo,
109 layout: PyramidLayout,
110) -> (Vec<u8>, u16) {
111 let timing = std::env::var_os("RETE_BUILD_TIMING").is_some();
117 let mut t = timing.then(std::time::Instant::now);
118 let mut lap = |label: &str| {
119 if let Some(t0) = &mut t {
120 eprintln!(
121 " [pyramid] {label}: {:.0} ms",
122 t0.elapsed().as_secs_f64() * 1000.0
123 );
124 *t0 = std::time::Instant::now();
125 }
126 };
127
128 let louvain = |lap: &mut dyn FnMut(&str)| {
130 let g = project_graph(dict, triples);
131 lap("project_graph");
132 let d = build_dendrogram(&g);
133 lap("build_dendrogram (Louvain)");
134 d
135 };
136 let dend = match algo {
137 PyramidAlgo::Louvain => louvain(&mut lap),
138 PyramidAlgo::Types => {
139 match crate::schema_pyramid::build_type_dendrogram(dict, triples, type_override) {
140 Some(d) => {
141 lap("build_type_dendrogram");
142 d
143 }
144 None => {
145 eprintln!(
146 " [pyramid] --pyramid-algo types: no usable rdf:type \
147 predicate — falling back to louvain"
148 );
149 louvain(&mut lap)
150 }
151 }
152 }
153 };
154 let round = choose_round_for_budget(dict, triples, &dend, budget);
155 lap("choose_round_for_budget");
156 let summary = summarize(dict, triples, &dend, round);
157 lap("summarize");
158 if layout == PyramidLayout::CommunityOnly {
163 let descriptors = crate::schema_pyramid::build_community_descriptors(
166 dict,
167 triples,
168 &dend,
169 round,
170 type_override,
171 );
172 lap("build_community_descriptors");
173 let meta = PyramidMeta::new(round as u32, summary, &[]).with_schema(
174 Vec::new(),
175 Vec::new(),
176 Vec::new(),
177 descriptors,
178 Vec::new(),
179 Vec::new(),
180 Vec::new(),
181 );
182 let out = (meta.encode(), dend.rounds() as u16);
183 lap("encode");
184 return out;
185 }
186 let sp = crate::schema_pyramid::build_schema_pyramid_with(
187 dict,
188 triples,
189 &dend,
190 round,
191 type_override,
192 );
193 lap("build_schema_pyramid");
194 let predicate_stats = compute_predicate_stats(triples);
195 lap("compute_predicate_stats");
196 let char_sets = compute_char_sets(triples);
197 lap("compute_char_sets");
198 let label_index = compute_label_index(dict, triples);
199 lap("compute_label_index");
200 let meta = PyramidMeta::new(round as u32, summary, &[])
201 .with_schema(
202 sp.class_hierarchy,
203 sp.level_rollups,
204 sp.level_links,
205 sp.descriptors,
206 sp.subclass_cycles,
207 sp.disjoint_pairs,
208 sp.equivalent_pairs,
209 )
210 .with_predicate_stats(predicate_stats)
211 .with_char_sets(char_sets)
212 .with_label_index(label_index);
213 let out = (meta.encode(), dend.rounds() as u16);
214 lap("encode");
215 out
216}
217
218const LABEL_PREDICATES: &[&str] = crate::label_index::DIRECT_LABEL_PREDICATES;
223
224fn compute_label_index(
232 dict: &Dictionary,
233 triples: &[(u32, u32, u32)],
234) -> Vec<crate::meta::LabelEntry> {
235 use crate::terms::{is_literal, literal_lexical};
236 use std::collections::{HashMap, HashSet};
237 const MAX_LABELS: usize = 8192;
238
239 let label_pids: HashSet<u32> = LABEL_PREDICATES
241 .iter()
242 .filter_map(|p| dict.predicate_id(p))
243 .collect();
244 if label_pids.is_empty() {
245 return Vec::new();
246 }
247 let mut degree: HashMap<u32, u32> = HashMap::new();
249 for &(s, _p, _o) in triples {
250 *degree.entry(s).or_insert(0) += 1;
251 }
252 let mut seen: HashSet<(u32, String)> = HashSet::new();
254 let mut candidates: Vec<(u32, String, u32)> = Vec::new(); for &(s, p, o) in triples {
256 if !label_pids.contains(&p) {
257 continue;
258 }
259 let Some(term) = dict.object_term(o) else {
260 continue;
261 };
262 if !is_literal(&term) {
263 continue;
264 }
265 let Some(label) = literal_lexical(&term) else {
266 continue;
267 };
268 if label.is_empty() {
269 continue;
270 }
271 if seen.insert((s, label.to_lowercase())) {
272 candidates.push((*degree.get(&s).unwrap_or(&0), label, s));
273 }
274 }
275 if candidates.len() > MAX_LABELS {
278 candidates.sort_by(|a, b| {
279 b.0.cmp(&a.0)
280 .then_with(|| a.2.cmp(&b.2))
281 .then_with(|| a.1.cmp(&b.1))
282 });
283 candidates.truncate(MAX_LABELS);
284 }
285 candidates.sort_by(|a, b| {
287 a.1.to_lowercase()
288 .cmp(&b.1.to_lowercase())
289 .then_with(|| a.1.cmp(&b.1))
290 .then_with(|| a.2.cmp(&b.2))
291 });
292 candidates
293 .into_iter()
294 .map(|(_deg, label, subject)| crate::meta::LabelEntry { label, subject })
295 .collect()
296}
297
298pub fn compute_text_index(dict: &Dictionary, triples: &[(u32, u32, u32)]) -> Vec<u8> {
307 crate::text_index::build_section(
308 dict,
309 &crate::text_index::TextIndexScope::default(),
310 triples,
311 std::iter::empty(),
312 writer_codec(),
313 )
314}
315
316fn compute_char_sets(triples: &[(u32, u32, u32)]) -> Vec<crate::meta::CharSet> {
321 use std::collections::{BTreeSet, HashMap};
322 const MAX_CHAR_SETS: usize = 128;
323 let mut by_subject: HashMap<u32, BTreeSet<u32>> = HashMap::new();
324 for &(s, p, _o) in triples {
325 by_subject.entry(s).or_default().insert(p);
326 }
327 let mut shapes: HashMap<Vec<u32>, u64> = HashMap::new();
328 for set in by_subject.into_values() {
329 *shapes.entry(set.into_iter().collect()).or_insert(0) += 1;
330 }
331 let mut v: Vec<crate::meta::CharSet> = shapes
332 .into_iter()
333 .map(|(predicates, subjects)| crate::meta::CharSet {
334 predicates,
335 subjects,
336 })
337 .collect();
338 v.sort_by(|a, b| {
339 b.subjects
340 .cmp(&a.subjects)
341 .then_with(|| a.predicates.cmp(&b.predicates))
342 });
343 v.truncate(MAX_CHAR_SETS);
344 v
345}
346
347fn compute_predicate_stats(triples: &[(u32, u32, u32)]) -> Vec<crate::meta::PredStat> {
353 use std::collections::HashMap;
354 #[allow(clippy::type_complexity)]
355 let mut acc: HashMap<u32, (HashMap<u32, u32>, HashMap<u32, u32>, u64)> = HashMap::new();
356 for &(s, p, o) in triples {
357 let e = acc.entry(p).or_default();
358 *e.0.entry(s).or_insert(0) += 1;
359 *e.1.entry(o).or_insert(0) += 1;
360 e.2 += 1;
361 }
362 let mut stats: Vec<crate::meta::PredStat> = acc
363 .into_iter()
364 .map(|(predicate, (subj, obj, count))| crate::meta::PredStat {
365 predicate,
366 count,
367 distinct_subjects: subj.len() as u64,
368 distinct_objects: obj.len() as u64,
369 max_objects_per_subject: subj.values().copied().max().unwrap_or(0),
370 max_subjects_per_object: obj.values().copied().max().unwrap_or(0),
371 })
372 .collect();
373 stats.sort_by_key(|p| p.predicate);
374 stats
375}
376
377pub const CODEC_NONE: u8 = 0;
379pub const CODEC_ZSTD: u8 = 1;
381
382#[derive(Debug, thiserror::Error)]
383#[non_exhaustive]
384pub enum FileError {
385 #[error("header: {0}")]
386 Header(#[from] crate::header::HeaderError),
387 #[error("malformed container: {0}")]
388 Container(&'static str),
389 #[error("unknown codec: {0}")]
390 UnknownCodec(u8),
391 #[error("decompression failed: {0}")]
392 Decompress(std::io::Error),
393 #[error("io: {0}")]
394 Io(#[from] std::io::Error),
395}
396
397pub fn writer_codec() -> u8 {
400 if cfg!(feature = "compression") {
401 CODEC_ZSTD
402 } else {
403 CODEC_NONE
404 }
405}
406
407fn intersect_sorted(a: &[u32], b: &[u32]) -> Vec<u32> {
410 let mut out = Vec::with_capacity(a.len().min(b.len()));
411 let (mut i, mut j) = (0, 0);
412 while i < a.len() && j < b.len() {
413 match a[i].cmp(&b[j]) {
414 std::cmp::Ordering::Less => i += 1,
415 std::cmp::Ordering::Greater => j += 1,
416 std::cmp::Ordering::Equal => {
417 out.push(a[i]);
418 i += 1;
419 j += 1;
420 }
421 }
422 }
423 out
424}
425
426pub(crate) fn compress(codec: u8, bytes: &[u8]) -> Vec<u8> {
427 match codec {
428 #[cfg(feature = "compression")]
431 CODEC_ZSTD => {
432 let level = crate::write_opts::zstd_level();
433 match crate::write_opts::frame_shape() {
434 crate::write_opts::FrameShape::Stream => zstd::encode_all(bytes, level),
435 crate::write_opts::FrameShape::Sized => zstd::bulk::compress(bytes, level),
436 }
437 .expect("zstd encode is infallible in-memory")
438 }
439 _ => bytes.to_vec(),
440 }
441}
442
443#[cfg(not(target_arch = "wasm32"))]
461pub(crate) fn compress_to(
462 codec: u8,
463 src_len: u64,
464 src: &mut dyn std::io::Read,
465 dst: &mut dyn std::io::Write,
466) -> std::io::Result<()> {
467 match codec {
468 #[cfg(feature = "compression")]
469 CODEC_ZSTD => zstd_stream(src_len, src, dst),
470 _ => {
471 let _ = src_len;
472 std::io::copy(src, dst).map(|_| ())
473 }
474 }
475}
476
477pub(crate) fn compress_streamed(codec: u8, bytes: &[u8]) -> Vec<u8> {
483 match codec {
484 #[cfg(feature = "compression")]
485 CODEC_ZSTD => {
486 let mut out = Vec::with_capacity(bytes.len() / 4 + 64);
487 zstd_stream(bytes.len() as u64, &mut &bytes[..], &mut out)
488 .expect("zstd encode is infallible in-memory");
489 out
490 }
491 _ => bytes.to_vec(),
492 }
493}
494
495#[cfg(feature = "compression")]
497fn zstd_stream(
498 src_len: u64,
499 src: &mut dyn std::io::Read,
500 dst: &mut dyn std::io::Write,
501) -> std::io::Result<()> {
502 let mut enc = zstd::stream::Encoder::new(dst, crate::write_opts::zstd_level())?;
503 if crate::write_opts::frame_shape() == crate::write_opts::FrameShape::Sized {
504 enc.set_pledged_src_size(Some(src_len))?;
505 enc.include_contentsize(true)?;
506 }
507 let copied = std::io::copy(src, &mut enc)?;
508 if copied != src_len {
509 return Err(std::io::Error::other(format!(
510 "zstd stream: {copied} bytes read, {src_len} announced"
511 )));
512 }
513 enc.finish()?;
514 Ok(())
515}
516
517pub(crate) fn decompress(codec: u8, bytes: &[u8]) -> Result<Vec<u8>, FileError> {
518 match codec {
519 CODEC_NONE => Ok(bytes.to_vec()),
520 #[cfg(feature = "compression")]
529 CODEC_ZSTD => zstd::decode_all(bytes).map_err(FileError::Decompress),
530 #[cfg(not(feature = "compression"))]
535 CODEC_ZSTD => {
536 use std::io::Read;
537 let mut dec = ruzstd::decoding::StreamingDecoder::new(bytes)
538 .map_err(|e| FileError::Decompress(std::io::Error::other(e.to_string())))?;
539 let mut out = Vec::new();
540 dec.read_to_end(&mut out).map_err(FileError::Decompress)?;
541 Ok(out)
542 }
543 other => Err(FileError::UnknownCodec(other)),
544 }
545}
546
547pub(crate) fn zstd_frame_content_size(b: &[u8]) -> Option<u64> {
551 if b.len() < 5 || b[..4] != [0x28, 0xB5, 0x2F, 0xFD] {
552 return None;
553 }
554 let fhd = b[4];
555 let fcs_flag = fhd >> 6;
556 let single_segment = fhd & 0x20 != 0;
557 let did_size = [0usize, 1, 2, 4][(fhd & 0x03) as usize];
558 let mut pos = 5 + usize::from(!single_segment) + did_size;
559 let fcs_size = match (fcs_flag, single_segment) {
560 (0, false) => return None,
561 (0, true) => 1,
562 (1, _) => 2,
563 (2, _) => 4,
564 _ => 8,
565 };
566 let f = b.get(pos..pos + fcs_size)?;
567 pos += fcs_size;
568 let _ = pos;
569 let mut v = 0u64;
570 for (i, x) in f.iter().enumerate() {
571 v |= (*x as u64) << (8 * i);
572 }
573 Some(if fcs_size == 2 { v + 256 } else { v })
574}
575
576pub(crate) fn decompress_bounded(codec: u8, bytes: &[u8], max: u64) -> Result<Vec<u8>, FileError> {
582 let too_big = |n: u64| {
583 FileError::Decompress(std::io::Error::other(format!(
584 "a block of {n} bytes exceeds its section's {max}-byte maximum"
585 )))
586 };
587 match codec {
588 CODEC_NONE => {
589 if bytes.len() as u64 > max {
590 return Err(too_big(bytes.len() as u64));
591 }
592 Ok(bytes.to_vec())
593 }
594 CODEC_ZSTD => {
595 let declared = zstd_frame_content_size(bytes);
596 if let Some(n) = declared.filter(|&n| n > max) {
597 return Err(too_big(n));
598 }
599 #[cfg(feature = "compression")]
600 {
601 if let Some(n) = declared {
602 return zstd::bulk::decompress(bytes, n as usize)
605 .map_err(FileError::Decompress);
606 }
607 use std::io::Read;
608 let mut out = Vec::new();
609 let mut dec = zstd::stream::read::Decoder::with_buffer(bytes)
610 .map_err(FileError::Decompress)?;
611 dec.window_log_max(27).map_err(FileError::Decompress)?;
612 dec.take(max.saturating_add(1))
613 .read_to_end(&mut out)
614 .map_err(FileError::Decompress)?;
615 if out.len() as u64 > max {
616 return Err(too_big(out.len() as u64));
617 }
618 Ok(out)
619 }
620 #[cfg(not(feature = "compression"))]
621 {
622 use std::io::Read;
623 let dec = ruzstd::decoding::StreamingDecoder::new(bytes)
624 .map_err(|e| FileError::Decompress(std::io::Error::other(e.to_string())))?;
625 let mut out = Vec::new();
626 dec.take(max.saturating_add(1))
627 .read_to_end(&mut out)
628 .map_err(FileError::Decompress)?;
629 if out.len() as u64 > max {
630 return Err(too_big(out.len() as u64));
631 }
632 Ok(out)
633 }
634 }
635 other => Err(FileError::UnknownCodec(other)),
636 }
637}
638
639pub(crate) fn block_raw_len(codec: u8, bytes: &[u8], ceiling: u64) -> Result<u64, FileError> {
643 match codec {
644 CODEC_NONE => Ok(bytes.len() as u64),
645 CODEC_ZSTD => match zstd_frame_content_size(bytes) {
646 Some(n) => Ok(n),
647 None => Ok(decompress_bounded(codec, bytes, ceiling)?.len() as u64),
648 },
649 other => Err(FileError::UnknownCodec(other)),
650 }
651}
652
653const TILE_COALESCE_GAP: u64 = 4096;
657
658const DICT_COALESCE_GAP: u64 = 64 * 1024;
664
665pub const DEFAULT_EXPORT_BUDGET_MB: u64 = 4096;
672
673pub const DEFAULT_QUERY_BUDGET_MB: u64 = DEFAULT_EXPORT_BUDGET_MB;
685
686pub fn spill_threshold_for(budget: u64) -> u64 {
690 budget / 8
691}
692
693const MIN_DICT_CACHE_CAP: u64 = 64 << 20; const TRANSIENT_RESERVE_MAX: u64 = 128 << 20; #[derive(Debug, Clone, Copy)]
714pub struct MemoryBudget {
715 pub block_cache: u64,
717 pub dict_cache: u64,
719 pub tile_cache: u64,
721}
722
723pub fn split_memory_budget(total: u64) -> MemoryBudget {
734 if total == u64::MAX {
735 return MemoryBudget {
736 block_cache: u64::MAX,
737 dict_cache: u64::MAX,
738 tile_cache: u64::MAX,
739 };
740 }
741 let block_cache = (total / 8).min(crate::block_cache::DEFAULT_CACHE_CAP);
744 let tile_cache = (total / 16).min(256 << 20);
747 let reserve = (total / 32).min(TRANSIENT_RESERVE_MAX);
753 let dict_cache = total
756 .saturating_sub(block_cache)
757 .saturating_sub(tile_cache)
758 .saturating_sub(reserve)
759 .max(MIN_DICT_CACHE_CAP);
760 MemoryBudget {
761 block_cache,
762 dict_cache,
763 tile_cache,
764 }
765}
766
767#[derive(Debug, Clone, Copy, Default)]
770pub struct FixedOverhead {
771 pub dict_directory: u64,
773 pub index_directory: u64,
775 pub named_graphs: u64,
777}
778
779impl FixedOverhead {
780 pub fn total(&self) -> u64 {
782 self.dict_directory + self.index_directory + self.named_graphs
783 }
784}
785
786fn fmt_cap(cap: u64) -> String {
788 if cap == u64::MAX {
789 "unlimited".to_string()
790 } else {
791 format!("{}MiB", cap >> 20)
792 }
793}
794
795pub(crate) fn read_coalesced<R: RangeReader + ?Sized>(
801 reader: &R,
802 ranges: &[ByteRange],
803 gap: u64,
804) -> Option<Vec<Vec<u8>>> {
805 coalesced(reader, ranges, gap, false)
806}
807
808pub(crate) fn read_coalesced_scattered<R: RangeReader + ?Sized>(
812 reader: &R,
813 ranges: &[ByteRange],
814 gap: u64,
815) -> Option<Vec<Vec<u8>>> {
816 coalesced(reader, ranges, gap, true)
817}
818
819fn coalesced<R: RangeReader + ?Sized>(
820 reader: &R,
821 ranges: &[ByteRange],
822 gap: u64,
823 scattered: bool,
824) -> Option<Vec<Vec<u8>>> {
825 let mut spans: Vec<(u64, u64)> = Vec::new();
828 let mut span_of: Vec<usize> = Vec::with_capacity(ranges.len());
829 let mut i = 0;
830 while i < ranges.len() {
831 let start = ranges[i].offset;
832 let mut end = ranges[i].offset.checked_add(ranges[i].len)?;
833 let mut j = i + 1;
834 while j < ranges.len() {
835 let r = &ranges[j];
836 if r.offset < end || r.offset - end > gap {
837 break;
838 }
839 end = r.offset.checked_add(r.len)?;
840 j += 1;
841 }
842 let si = spans.len();
843 spans.push((start, end - start));
844 for _ in i..j {
845 span_of.push(si);
846 }
847 i = j;
848 }
849 let blobs = if scattered {
850 reader.read_many_scattered(&spans)
851 } else {
852 reader.read_many(&spans)
853 }
854 .ok()?;
855 if blobs.len() != spans.len() {
856 return None;
857 }
858 let mut out = Vec::with_capacity(ranges.len());
859 for (k, r) in ranges.iter().enumerate() {
860 let (span_start, _) = spans[span_of[k]];
861 let blob = &blobs[span_of[k]];
862 out.push(checked_slice(blob, r.offset - span_start, r.len)?.to_vec());
863 }
864 Some(out)
865}
866
867fn content_hash(parts: &[&[u8]]) -> [u8; 16] {
870 let mut h = blake3::Hasher::new();
871 for p in parts {
872 h.update(p);
873 }
874 let mut out = [0u8; 16];
875 out.copy_from_slice(&h.finalize().as_bytes()[..16]);
876 out
877}
878
879pub type TermTriple = (String, String, String);
881
882#[derive(Debug, Clone, Copy, PartialEq, Eq)]
885pub struct DumpPlan {
886 pub scan: Option<crate::index::ScanPlan>,
890 pub dictionary_bytes: u64,
899}
900
901#[derive(Debug, Clone)]
905pub struct LayoutSegment {
906 pub kind: &'static str,
907 pub label: String,
908 pub offset: u64,
909 pub len: u64,
910}
911
912#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
914pub struct ByteRange {
915 pub offset: u64,
916 pub len: u64,
917}
918
919impl ByteRange {
920 pub fn end(self) -> u64 {
921 self.offset + self.len
922 }
923}
924
925#[derive(Debug, Clone, PartialEq, Eq)]
927pub struct TripleProvenance {
928 pub terms: TermTriple,
930 pub ids: Triple,
932 pub graph: Option<String>,
934 pub matched_pattern: Pattern,
936 pub index_permutation: IndexPermutation,
938 pub dictionary_range: ByteRange,
940 pub index_range: ByteRange,
942 pub index_section_range: ByteRange,
945 pub pyramid_range: Option<ByteRange>,
947 pub tile: Option<String>,
951 pub tile_range: Option<ByteRange>,
954}
955
956fn encode_container(sections: &[&[u8]], codec: u8) -> Vec<u8> {
960 let mut out = Vec::new();
961 write_uvarint(&mut out, sections.len() as u64);
962 for s in sections {
963 let payload = compress(codec, s);
964 write_uvarint(&mut out, payload.len() as u64);
965 out.extend_from_slice(&payload);
966 }
967 out
968}
969
970fn decode_container(bytes: &[u8], codec: u8) -> Result<Vec<Vec<u8>>, FileError> {
972 let (n, mut pos) = read_uvarint(bytes).ok_or(FileError::Container("truncated count"))?;
973 let n = wire_usize(n, "section count too large")?;
977 let mut out = Vec::with_capacity(n.min(bytes.len()));
978 for _ in 0..n {
979 let (len, used) = read_uvarint(bytes.get(pos..).unwrap_or(&[]))
980 .ok_or(FileError::Container("truncated length"))?;
981 pos += used;
982 let end = pos
985 .checked_add(wire_usize(len, "section length too large")?)
986 .filter(|&end| end <= bytes.len())
987 .ok_or(FileError::Container("section overruns buffer"))?;
988 out.push(decompress(codec, &bytes[pos..end])?);
989 pos = end;
990 }
991 Ok(out)
992}
993
994fn checked_end(off: u64, len: u64) -> Result<u64, FileError> {
995 off.checked_add(len)
996 .ok_or(FileError::Container("section range overflows"))
997}
998
999fn wire_usize(v: u64, what: &'static str) -> Result<usize, FileError> {
1003 usize::try_from(v).map_err(|_| FileError::Container(what))
1004}
1005
1006fn checked_slice(bytes: &[u8], off: u64, len: u64) -> Option<&[u8]> {
1009 let start = usize::try_from(off).ok()?;
1010 let end = start.checked_add(usize::try_from(len).ok()?)?;
1011 bytes.get(start..end)
1012}
1013
1014const DICT_CHUNK_BUDGET: usize = crate::write_opts::DEFAULT_DICT_CHUNK_BYTES;
1017
1018fn encode_chunked_dict_section(raw: &[u8], codec: u8) -> Vec<u8> {
1035 let meta = crate::dict::parse_meta(raw).unwrap_or(crate::dict::SectionMeta {
1036 term_count: 0,
1037 restart_interval: 1,
1038 restart_offsets: Vec::new(),
1039 });
1040 let body_start = meta
1041 .restart_offsets
1042 .first()
1043 .copied()
1044 .unwrap_or(raw.len() as u64);
1045 let header = &raw[..(body_start.min(raw.len() as u64)) as usize];
1046
1047 let chunk_budget = crate::write_opts::dict_chunk_budget() as u64;
1049 let n_runs = meta.restart_offsets.len();
1050 let mut bounds: Vec<(usize, u64, u64)> = Vec::new(); let mut r = 0;
1052 while r < n_runs {
1053 let start = meta.restart_offsets[r];
1054 let mut r2 = r + 1;
1055 while r2 < n_runs && meta.restart_offsets[r2] - start < chunk_budget {
1056 r2 += 1;
1057 }
1058 let end = if r2 < n_runs {
1059 meta.restart_offsets[r2]
1060 } else {
1061 raw.len() as u64
1062 };
1063 bounds.push((r, start, end));
1064 r = r2;
1065 }
1066
1067 #[cfg(feature = "parallel")]
1071 let compressed: Vec<Vec<u8>> = {
1072 use rayon::prelude::*;
1073 bounds
1074 .par_iter()
1075 .map(|&(_, s, e)| compress(codec, &raw[s as usize..e as usize]))
1076 .collect()
1077 };
1078 #[cfg(not(feature = "parallel"))]
1079 let compressed: Vec<Vec<u8>> = bounds
1080 .iter()
1081 .map(|&(_, s, e)| compress(codec, &raw[s as usize..e as usize]))
1082 .collect();
1083 let mut out = Vec::new();
1084 write_uvarint(&mut out, header.len() as u64);
1085 out.extend_from_slice(header);
1086 write_uvarint(&mut out, bounds.len() as u64);
1087 let mut prev_run = 0usize;
1088 let mut prev_last: Option<Vec<u8>> = None;
1092 for (i, (&(first_run, start, end), comp)) in bounds.iter().zip(&compressed).enumerate() {
1093 let key = if i == 0 {
1094 Vec::new()
1096 } else {
1097 let first = crate::dict::run_first_term(raw, start as usize).unwrap_or_default();
1098 match &prev_last {
1099 None => first,
1102 Some(pl) => crate::dict::shortest_separator(pl, &first),
1103 }
1104 };
1105 if i + 1 < bounds.len() {
1106 let last_run_off = meta.restart_offsets[bounds[i + 1].0 - 1] as usize;
1108 prev_last = crate::dict::run_last_term(raw, last_run_off, end as usize);
1109 }
1110 write_uvarint(&mut out, (first_run - prev_run) as u64);
1111 write_uvarint(&mut out, key.len() as u64);
1112 out.extend_from_slice(&key);
1113 write_uvarint(&mut out, comp.len() as u64);
1114 prev_run = first_run;
1115 }
1116 for comp in &compressed {
1117 out.extend_from_slice(comp);
1118 }
1119 out
1120}
1121
1122pub(crate) struct DictChunkEntry {
1126 pub(crate) first_run: usize,
1127 pub(crate) key: Vec<u8>,
1128 body_start: u64,
1129 pub(crate) start: u64,
1130 pub(crate) end: u64,
1131}
1132
1133fn parse_chunked_dict_dir(
1137 bytes: &[u8],
1138 total_len: u64,
1139) -> Result<(crate::dict::SectionMeta, Vec<DictChunkEntry>), FileError> {
1140 let mut pos = 0usize;
1141 let take = |pos: &mut usize| -> Result<u64, FileError> {
1142 let (v, n) = read_uvarint(bytes.get(*pos..).unwrap_or(&[]))
1143 .ok_or(FileError::Container("truncated dict chunk directory"))?;
1144 *pos += n;
1145 Ok(v)
1146 };
1147 let header_len = wire_usize(take(&mut pos)?, "dict header too large")?;
1148 let header = bytes
1149 .get(pos..pos.saturating_add(header_len))
1150 .ok_or(FileError::Container("truncated dict header"))?;
1151 let meta = crate::dict::parse_meta(header)
1152 .map_err(|_| FileError::Container("malformed dict header"))?;
1153 pos += header_len;
1154
1155 let num_chunks = wire_usize(take(&mut pos)?, "dict chunk count too large")?;
1156 let mut entries = Vec::with_capacity(num_chunks.min(bytes.len()));
1157 let mut lens = Vec::with_capacity(num_chunks.min(bytes.len()));
1158 let mut prev_run = 0usize;
1159 for i in 0..num_chunks {
1160 let drun = wire_usize(take(&mut pos)?, "dict chunk run too large")?;
1161 let klen = wire_usize(take(&mut pos)?, "dict chunk key too large")?;
1162 let key = bytes
1163 .get(pos..pos.saturating_add(klen))
1164 .ok_or(FileError::Container("truncated dict chunk key"))?
1165 .to_vec();
1166 pos += klen;
1167 let clen = take(&mut pos)?;
1168 let first_run = next_chunk_run(i, prev_run, drun)?;
1169 let body_start = meta
1170 .restart_offsets
1171 .get(first_run)
1172 .copied()
1173 .ok_or(FileError::Container("dict chunk run out of range"))?;
1174 entries.push(DictChunkEntry {
1175 first_run,
1176 key,
1177 body_start,
1178 start: 0,
1179 end: 0,
1180 });
1181 lens.push(clen);
1182 prev_run = first_run;
1183 }
1184 let mut start = pos as u64;
1185 for (e, len) in entries.iter_mut().zip(lens) {
1186 let end = start
1187 .checked_add(len)
1188 .filter(|&e| e <= total_len)
1189 .ok_or(FileError::Container("dict chunk overruns section"))?;
1190 e.start = start;
1191 e.end = end;
1192 start = end;
1193 }
1194 Ok((meta, entries))
1195}
1196
1197fn next_chunk_run(i: usize, prev_run: usize, drun: usize) -> Result<usize, FileError> {
1204 match (i, drun) {
1205 (0, 0) => Ok(0),
1206 (0, _) => Err(FileError::Container(
1207 "first dict chunk does not start at run 0",
1208 )),
1209 (_, 0) => Err(FileError::Container("dict chunk runs do not ascend")),
1210 _ => prev_run
1211 .checked_add(drun)
1212 .ok_or(FileError::Container("dict chunk run overflows")),
1213 }
1214}
1215
1216pub(crate) fn read_dict_dir_ranged<R: RangeReader + ?Sized>(
1228 reader: &R,
1229 section: ByteRange,
1230) -> Result<(crate::dict::SectionMeta, Vec<DictChunkEntry>), FileError> {
1231 let total = section.len;
1232 let init = 8192.min(total); let head = reader.read_at(section.offset, init)?;
1240 let (header_len, n0) =
1241 read_uvarint(&head).ok_or(FileError::Container("truncated dict header len"))?;
1242 let hbase = n0; let (term_count, n1) = read_uvarint(head.get(hbase..).unwrap_or(&[]))
1244 .ok_or(FileError::Container("truncated dict term_count"))?;
1245 let (restart_interval, _n2) = read_uvarint(head.get(hbase + n1..).unwrap_or(&[]))
1246 .ok_or(FileError::Container("truncated dict interval"))?;
1247 if restart_interval == 0 {
1248 return Err(FileError::Container("zero restart interval"));
1249 }
1250 let dir_start = (hbase as u64)
1253 .checked_add(header_len)
1254 .filter(|&d| d <= total)
1255 .ok_or(FileError::Container("dict header overruns section"))?;
1256 let dir_total = total - dir_start;
1257 let meta = crate::dict::SectionMeta {
1258 term_count: u32::try_from(term_count)
1259 .map_err(|_| FileError::Container("dict term count too large"))?,
1260 restart_interval: u32::try_from(restart_interval)
1261 .map_err(|_| FileError::Container("dict restart interval too large"))?,
1262 restart_offsets: Vec::new(),
1263 };
1264 let num_runs = (meta.term_count as usize).div_ceil(meta.restart_interval as usize);
1266 let finish = |mut entries: Vec<DictChunkEntry>| {
1267 for e in &mut entries {
1268 e.start += dir_start; e.end += dir_start;
1270 }
1271 (meta.clone(), entries)
1272 };
1273 let mut have: Vec<u8> = Vec::new();
1277 if dir_start < head.len() as u64 {
1278 match parse_chunk_dir_only(&head[dir_start as usize..], dir_total, num_runs)? {
1279 ChunkDirParse::Done(entries) => return Ok(finish(entries)),
1280 ChunkDirParse::Truncated { .. } => have = head[dir_start as usize..].to_vec(),
1281 }
1282 }
1283 let mut want = 4096u64.min(dir_total).max(1);
1296 loop {
1297 let held = have.len() as u64;
1298 if want > held {
1299 let extra = reader.read_at(section.offset + dir_start + held, want - held)?;
1300 if extra.is_empty() {
1301 return Err(FileError::Container("truncated dict chunk directory"));
1302 }
1303 have.extend_from_slice(&extra);
1304 }
1305 let held = have.len() as u64;
1306 match parse_chunk_dir_only(&have, dir_total, num_runs)? {
1307 ChunkDirParse::Done(entries) => return Ok(finish(entries)),
1308 ChunkDirParse::Truncated { .. } if held >= dir_total => {
1309 return Err(FileError::Container("truncated dict chunk directory"));
1310 }
1311 ChunkDirParse::Truncated {
1312 parsed,
1313 used,
1314 total,
1315 } => {
1316 let est = if parsed >= 16 && used > 0 {
1321 let whole = ((used as u64) / (parsed as u64)).saturating_mul(total as u64);
1322 whole.saturating_add(whole / 8).saturating_add(64)
1323 } else {
1324 held.saturating_mul(2)
1326 };
1327 want = est
1328 .max(held.saturating_add(1))
1329 .min(held.saturating_mul(4))
1330 .min(dir_total);
1331 }
1332 }
1333 }
1334}
1335
1336enum ChunkDirParse {
1341 Done(Vec<DictChunkEntry>),
1342 Truncated {
1343 parsed: usize,
1345 used: usize,
1347 total: usize,
1349 },
1350}
1351
1352fn parse_chunk_dir_only(
1362 dir: &[u8],
1363 dir_total: u64,
1364 num_runs: usize,
1365) -> Result<ChunkDirParse, FileError> {
1366 let mut pos = 0usize;
1367 let take = |pos: &mut usize| -> Option<u64> {
1368 let (v, n) = read_uvarint(dir.get(*pos..).unwrap_or(&[]))?;
1369 *pos += n;
1370 Some(v)
1371 };
1372 let Some(num_chunks) = take(&mut pos) else {
1373 return Ok(ChunkDirParse::Truncated {
1374 parsed: 0,
1375 used: 0,
1376 total: 0,
1377 });
1378 };
1379 let num_chunks = wire_usize(num_chunks, "dict chunk count too large")?;
1380 let mut entries = Vec::with_capacity(num_chunks.min(dir.len()));
1381 let mut lens: Vec<u64> = Vec::with_capacity(num_chunks.min(dir.len()));
1382 let mut prev_run = 0usize;
1383 for i in 0..num_chunks {
1384 let entry_start = pos;
1385 let short = ChunkDirParse::Truncated {
1386 parsed: entries.len(),
1387 used: entry_start,
1388 total: num_chunks,
1389 };
1390 let (Some(drun), Some(klen)) = (take(&mut pos), take(&mut pos)) else {
1391 return Ok(short);
1392 };
1393 let drun = wire_usize(drun, "dict chunk run too large")?;
1394 let klen = wire_usize(klen, "dict chunk key too large")?;
1395 let Some(key) = dir.get(pos..pos.saturating_add(klen)) else {
1396 return Ok(short);
1397 };
1398 let key = key.to_vec();
1399 pos += klen;
1400 let Some(clen) = take(&mut pos) else {
1401 return Ok(short);
1402 };
1403 let first_run = next_chunk_run(i, prev_run, drun)?;
1404 if first_run >= num_runs {
1405 return Err(FileError::Container("dict chunk run out of range"));
1406 }
1407 entries.push(DictChunkEntry {
1408 first_run,
1409 key,
1410 body_start: 0,
1411 start: 0,
1412 end: 0,
1413 });
1414 lens.push(clen);
1415 prev_run = first_run;
1416 }
1417 let mut start = pos as u64;
1418 for (e, len) in entries.iter_mut().zip(lens) {
1419 let end = start
1420 .checked_add(len)
1421 .filter(|&e| e <= dir_total)
1422 .ok_or(FileError::Container("dict chunk overruns section"))?;
1423 e.start = start;
1424 e.end = end;
1425 start = end;
1426 }
1427 Ok(ChunkDirParse::Done(entries))
1428}
1429
1430fn decode_chunked_dict_section(
1434 payload: &[u8],
1435 codec: u8,
1436 cache: std::sync::Arc<crate::chunk_cache::ChunkCache>,
1437 section_index: u8,
1438) -> Result<crate::dict::ChunkedSection, FileError> {
1439 let (meta, entries) = parse_chunked_dict_dir(payload, payload.len() as u64)?;
1440 let chunks = entries
1441 .into_iter()
1442 .map(|e| {
1443 let body = decompress(codec, &payload[e.start as usize..e.end as usize])?;
1444 Ok((
1445 crate::dict::SectionChunk::new(e.first_run, e.key, e.body_start),
1446 body,
1447 ))
1448 })
1449 .collect::<Result<Vec<_>, FileError>>()?;
1450 Ok(crate::dict::ChunkedSection::resident(
1451 meta,
1452 chunks,
1453 cache,
1454 section_index,
1455 ))
1456}
1457
1458fn decode_dictionary_container(bytes: &[u8], codec: u8) -> Result<Dictionary, FileError> {
1459 let dsecs = decode_container(bytes, CODEC_NONE)?;
1460 if dsecs.len() != 4 {
1461 return Err(FileError::Container("expected 4 dictionary sections"));
1462 }
1463 let cache = crate::chunk_cache::ChunkCache::unlimited_arc();
1466 let mut sections = Vec::with_capacity(4);
1467 for (si, sec) in dsecs.iter().enumerate() {
1468 sections.push(decode_chunked_dict_section(
1469 sec,
1470 codec,
1471 cache.clone(),
1472 si as u8,
1473 )?);
1474 }
1475 let arr: [crate::dict::ChunkedSection; 4] = sections
1476 .try_into()
1477 .map_err(|_| FileError::Container("expected 4 dictionary sections"))?;
1478 Ok(Dictionary::from_chunked_sections(arr))
1479}
1480
1481fn encode_tiled_section(index: &GraphIndex, si: usize, codec: u8) -> Vec<u8> {
1487 let tiles = index.tile_sections()[si];
1488 let n = tiles.len();
1489 #[cfg(feature = "parallel")]
1496 let compressed: Vec<Vec<u8>> = {
1497 use rayon::prelude::*;
1498 (0..n)
1499 .into_par_iter()
1500 .map(|ti| compress(codec, &index.tile_body(si, ti)))
1501 .collect()
1502 };
1503 #[cfg(not(feature = "parallel"))]
1504 let compressed: Vec<Vec<u8>> = (0..n)
1505 .map(|ti| compress(codec, &index.tile_body(si, ti)))
1506 .collect();
1507 let mut out = Vec::new();
1508 write_uvarint(&mut out, tiles.len() as u64);
1509 let mut prev_min = 0u32;
1510 for (tile, comp) in tiles.iter().zip(&compressed) {
1511 let (min_a, max_a) = tile.leading_range();
1512 write_uvarint(&mut out, (min_a - prev_min) as u64);
1513 write_uvarint(&mut out, (max_a - min_a) as u64);
1514 write_uvarint(&mut out, comp.len() as u64);
1515 prev_min = min_a;
1516 }
1517 for comp in &compressed {
1518 out.extend_from_slice(comp);
1519 }
1520 for ti in 0..n {
1528 let body = index.tile_body(si, ti);
1529 let (min_b, max_b, min_c, max_c) = match crate::triples::TripleBlock::parse(&body) {
1530 Ok(b) => {
1531 let z = b.zone();
1532 (z.min_b, z.max_b, z.min_c, z.max_c)
1533 }
1534 Err(_) => (0, u32::MAX, 0, u32::MAX),
1535 };
1536 write_uvarint(&mut out, min_b as u64);
1537 write_uvarint(&mut out, (max_b - min_b) as u64);
1538 write_uvarint(&mut out, min_c as u64);
1539 write_uvarint(&mut out, (max_c - min_c) as u64);
1540 }
1541 out
1542}
1543
1544pub(crate) struct TileDirEntry {
1547 pub(crate) min_a: u32,
1548 pub(crate) max_a: u32,
1549 pub(crate) start: u64,
1550 pub(crate) end: u64,
1551}
1552
1553type TileSynopsis = (u32, u32, u32, u32);
1555
1556fn parse_tile_synopsis(
1564 payload: &[u8],
1565 trailer_start: usize,
1566 num_tiles: usize,
1567) -> Option<Vec<TileSynopsis>> {
1568 let mut pos = trailer_start;
1569 let take = |pos: &mut usize| -> Option<u32> {
1570 let (v, n) = read_uvarint(payload.get(*pos..)?)?;
1571 *pos += n;
1572 u32::try_from(v).ok()
1573 };
1574 let mut out = Vec::with_capacity(num_tiles.min(payload.len()));
1575 for _ in 0..num_tiles {
1576 let min_b = take(&mut pos)?;
1577 let max_b = min_b.checked_add(take(&mut pos)?)?;
1578 let min_c = take(&mut pos)?;
1579 let max_c = min_c.checked_add(take(&mut pos)?)?;
1580 out.push((min_b, max_b, min_c, max_c));
1581 }
1582 Some(out)
1583}
1584
1585fn parse_tile_directory(bytes: &[u8], total_len: u64) -> Result<Vec<TileDirEntry>, FileError> {
1590 let mut pos = 0usize;
1591 let take = |pos: &mut usize| -> Result<u64, FileError> {
1592 let (v, n) = read_uvarint(bytes.get(*pos..).unwrap_or(&[]))
1593 .ok_or(FileError::Container("truncated tile directory"))?;
1594 *pos += n;
1595 Ok(v)
1596 };
1597 let num_tiles = wire_usize(take(&mut pos)?, "tile count too large")?;
1598 let mut entries = Vec::with_capacity(num_tiles.min(bytes.len()));
1599 let mut prev_min = 0u32;
1600 let mut lens = Vec::with_capacity(num_tiles.min(bytes.len()));
1601 let id = |v: u64| u32::try_from(v).map_err(|_| FileError::Container("tile id out of range"));
1605 for _ in 0..num_tiles {
1606 let dmin = id(take(&mut pos)?)?;
1607 let span = id(take(&mut pos)?)?;
1608 let len = take(&mut pos)?;
1609 let min_a = prev_min
1610 .checked_add(dmin)
1611 .ok_or(FileError::Container("tile id out of range"))?;
1612 let max_a = min_a
1613 .checked_add(span)
1614 .ok_or(FileError::Container("tile id out of range"))?;
1615 entries.push(TileDirEntry {
1616 min_a,
1617 max_a,
1618 start: 0,
1619 end: 0,
1620 });
1621 lens.push(len);
1622 prev_min = min_a;
1623 }
1624 let mut start = pos as u64;
1625 for (e, len) in entries.iter_mut().zip(lens) {
1626 let end = start
1627 .checked_add(len)
1628 .filter(|&e| e <= total_len)
1629 .ok_or(FileError::Container("tile overruns section"))?;
1630 e.start = start;
1631 e.end = end;
1632 start = end;
1633 }
1634 Ok(entries)
1635}
1636
1637pub(crate) fn read_tile_directory_ranged<R: RangeReader + ?Sized>(
1641 reader: &R,
1642 section: ByteRange,
1643) -> Result<Vec<TileDirEntry>, FileError> {
1644 let total = section.len;
1645 let mut prefetch = 4096u64.min(total);
1646 loop {
1647 let prefix = reader.read_at(section.offset, prefetch)?;
1648 match parse_tile_directory(&prefix, total) {
1649 Ok(dir) => return Ok(dir),
1650 Err(_) if prefetch < total => prefetch = prefetch.saturating_mul(2).min(total),
1651 Err(e) => return Err(e),
1652 }
1653 }
1654}
1655
1656pub(crate) fn read_tile_synopsis_ranged<R: RangeReader + ?Sized>(
1663 reader: &R,
1664 section: ByteRange,
1665 dir: &[TileDirEntry],
1666) -> Vec<Option<TileSynopsis>> {
1667 let n = dir.len();
1668 let none = vec![None; n];
1669 let trailer_start = dir.iter().map(|e| e.end).max().unwrap_or(0);
1670 let total = section.len;
1671 if n == 0 || trailer_start >= total {
1672 return none; }
1674 let max_trailer = (n as u64).saturating_mul(4 * 5);
1678 let trailer_len = (total - trailer_start).min(max_trailer);
1679 let Some(offset) = section.offset.checked_add(trailer_start) else {
1680 return none;
1681 };
1682 let Ok(bytes) = reader.read_at(offset, trailer_len) else {
1683 return none;
1684 };
1685 match parse_tile_synopsis(&bytes, 0, n) {
1686 Some(v) => v.into_iter().map(Some).collect(),
1687 None => none,
1688 }
1689}
1690
1691fn tile_file_ranges(
1695 index_bytes: &[u8],
1696 container_offset: u64,
1697 section_ranges: &[ByteRange; NUM_PERMS],
1698) -> [Vec<(u32, u32, ByteRange)>; NUM_PERMS] {
1699 let mut out: [Vec<(u32, u32, ByteRange)>; NUM_PERMS] = Default::default();
1700 for (section, range) in out.iter_mut().zip(section_ranges) {
1701 if range.len == 0 || range.offset < container_offset {
1705 continue;
1706 }
1707 let Some(payload) = checked_slice(index_bytes, range.offset - container_offset, range.len)
1708 else {
1709 continue;
1710 };
1711 if let Ok(dir) = parse_tile_directory(payload, payload.len() as u64) {
1712 *section = dir
1713 .into_iter()
1714 .map(|e| {
1715 (
1716 e.min_a,
1717 e.max_a,
1718 ByteRange {
1719 offset: range.offset + e.start,
1720 len: (e.end - e.start),
1721 },
1722 )
1723 })
1724 .collect();
1725 }
1726 }
1727 out
1728}
1729
1730fn decode_tiled_section(payload: &[u8], codec: u8) -> Result<Vec<(u32, u32, Vec<u8>)>, FileError> {
1733 parse_tile_directory(payload, payload.len() as u64)?
1734 .into_iter()
1735 .map(|e| {
1736 Ok((
1737 e.min_a,
1738 e.max_a,
1739 decompress(codec, &payload[e.start as usize..e.end as usize])?,
1740 ))
1741 })
1742 .collect()
1743}
1744
1745fn decode_index_container(
1755 bytes: &[u8],
1756 codec: u8,
1757 perms: PermSet,
1758) -> Result<GraphIndex, FileError> {
1759 let isecs = decode_container(bytes, CODEC_NONE)?;
1760 if isecs.len() != perms.len() {
1761 return Err(FileError::Container(
1762 "index container section count does not match the header permutation mask",
1763 ));
1764 }
1765 decode_index_sections(isecs, codec, perms)
1766}
1767
1768fn decode_index_sections(
1769 mut isecs: Vec<Vec<u8>>,
1770 codec: u8,
1771 perms: PermSet,
1772) -> Result<GraphIndex, FileError> {
1773 let mut sections: [Vec<(u32, u32, Vec<u8>)>; NUM_PERMS] = Default::default();
1774 for (perm, sec) in perms.iter().zip(isecs.iter_mut()) {
1775 sections[perm.section_index()] = decode_tiled_section(sec, codec)?;
1776 }
1777 Ok(GraphIndex::from_tiles(sections, perms))
1778}
1779
1780fn decode_root_index_container(
1785 bytes: &[u8],
1786 header: &Header,
1787) -> Result<(GraphIndex, Option<[u8; 16]>), FileError> {
1788 if !header.has_quad_index() {
1789 return Ok((
1790 decode_index_container(bytes, header.block_codec, header.perms)?,
1791 None,
1792 ));
1793 }
1794 let mut isecs = decode_container(bytes, CODEC_NONE)?;
1795 if isecs.len() != header.index_container_sections() {
1796 return Err(FileError::Container(
1797 "index container section count does not match the header permutation mask",
1798 ));
1799 }
1800 let seal = isecs.pop().unwrap_or_default();
1801 let digest = crate::quad::parse_seal(&seal)?;
1802 Ok((
1803 decode_index_sections(isecs, header.block_codec, header.perms)?,
1804 Some(digest),
1805 ))
1806}
1807
1808fn check_named_layout(header: &Header) -> Result<(), FileError> {
1813 let quad = header.quad_index_section().is_some();
1814 if header.has_quad_index() {
1815 if !quad {
1816 return Err(FileError::Container(
1817 "quad-index flag set but the file has no quad-index section",
1818 ));
1819 }
1820 if header.named_graphs_len > 0 {
1821 return Err(FileError::Container(
1822 "a file cannot carry both a quad index and a named-graphs section",
1823 ));
1824 }
1825 crate::quad::check_perms(header.perms)?;
1826 } else if quad {
1827 return Err(FileError::Container(
1828 "quad-index section present but the header does not flag it",
1829 ));
1830 }
1831 Ok(())
1832}
1833
1834fn container_section_payload_ranges(
1835 bytes: &[u8],
1836 container_offset: u64,
1837 expected_sections: usize,
1838) -> Result<Vec<ByteRange>, FileError> {
1839 let (section_count, mut pos) =
1840 read_uvarint(bytes).ok_or(FileError::Container("truncated count"))?;
1841 let section_count = usize::try_from(section_count)
1842 .map_err(|_| FileError::Container("section count too large"))?;
1843 if section_count != expected_sections {
1844 return Err(FileError::Container("unexpected section count"));
1845 }
1846
1847 let mut ranges = Vec::with_capacity(section_count);
1848 for _ in 0..section_count {
1849 let remaining = bytes
1850 .get(pos..)
1851 .ok_or(FileError::Container("truncated length"))?;
1852 let (payload_len, used) =
1853 read_uvarint(remaining).ok_or(FileError::Container("truncated length"))?;
1854 pos = pos
1855 .checked_add(used)
1856 .ok_or(FileError::Container("section range overflows"))?;
1857 let payload_len_usize = usize::try_from(payload_len)
1858 .map_err(|_| FileError::Container("section length too large"))?;
1859 let payload_end = pos
1860 .checked_add(payload_len_usize)
1861 .ok_or(FileError::Container("section range overflows"))?;
1862 if payload_end > bytes.len() {
1863 return Err(FileError::Container("section overruns buffer"));
1864 }
1865 ranges.push(ByteRange {
1866 offset: checked_end(container_offset, pos as u64)?,
1867 len: payload_len,
1868 });
1869 pos = payload_end;
1870 }
1871
1872 Ok(ranges)
1873}
1874
1875fn decode_index_section_ranges(
1879 bytes: &[u8],
1880 container_offset: u64,
1881 perms: PermSet,
1882 sections: usize,
1883) -> Result<[ByteRange; NUM_PERMS], FileError> {
1884 let ranges = container_section_payload_ranges(bytes, container_offset, sections)?;
1885 let mut out = [ByteRange { offset: 0, len: 0 }; NUM_PERMS];
1886 for (perm, range) in perms.iter().zip(ranges) {
1887 out[perm.section_index()] = range;
1888 }
1889 Ok(out)
1890}
1891
1892fn read_uvarint_at<R: RangeReader + ?Sized>(
1893 reader: &R,
1894 absolute_offset: u64,
1895 container_end: u64,
1896) -> Result<(u64, u64), FileError> {
1897 if absolute_offset >= container_end {
1898 return Err(FileError::Container("truncated container varint"));
1899 }
1900 let remaining = container_end - absolute_offset;
1901 let probe_len = remaining.min(10);
1902 let bytes = reader.read_at(absolute_offset, probe_len)?;
1903 read_uvarint(&bytes)
1904 .map(|(value, used)| (value, used as u64))
1905 .ok_or(FileError::Container("truncated container varint"))
1906}
1907
1908pub(crate) fn locate_container_section_ranged<R: RangeReader + ?Sized>(
1911 reader: &R,
1912 container_offset: u64,
1913 container_len: u64,
1914 section_index: usize,
1915 expected_sections: u64,
1916) -> Result<ByteRange, FileError> {
1917 let container_end = checked_end(container_offset, container_len)?;
1918 let (section_count, used) = read_uvarint_at(reader, container_offset, container_end)?;
1919 if section_count != expected_sections {
1920 return Err(FileError::Container("unexpected container section count"));
1921 }
1922 if section_index >= section_count as usize {
1923 return Err(FileError::Container(
1924 "container section index out of bounds",
1925 ));
1926 }
1927
1928 let mut pos = checked_end(container_offset, used)?;
1929 for i in 0..section_count as usize {
1930 let (payload_len, len_used) = read_uvarint_at(reader, pos, container_end)?;
1931 pos = checked_end(pos, len_used)?;
1932 let payload_end = checked_end(pos, payload_len)?;
1933 if payload_end > container_end {
1934 return Err(FileError::Container("section overruns buffer"));
1935 }
1936 if i == section_index {
1937 return Ok(ByteRange {
1938 offset: pos,
1939 len: payload_len,
1940 });
1941 }
1942 pos = payload_end;
1943 }
1944 Err(FileError::Container("container section not found"))
1945}
1946
1947#[allow(clippy::type_complexity)]
1957fn open_index_container_lazy(
1958 reader: &std::sync::Arc<dyn RangeReader + Send + Sync>,
1959 container: ByteRange,
1960 block_codec: u8,
1961 has_synopsis: bool,
1962 read_concurrency: usize,
1963 perms: PermSet,
1964 sections: usize,
1965) -> Result<
1966 (
1967 GraphIndex,
1968 [ByteRange; NUM_PERMS],
1969 [Vec<(u32, u32, ByteRange)>; NUM_PERMS],
1970 ),
1971 FileError,
1972> {
1973 let mut index_section_ranges = [ByteRange { offset: 0, len: 0 }; NUM_PERMS];
1974 let mut tile_ranges: [Vec<(u32, u32, ByteRange)>; NUM_PERMS] = Default::default();
1975 #[allow(clippy::type_complexity)]
1976 let mut directories: [Vec<(u32, u32, Option<TileSynopsis>)>; NUM_PERMS] = Default::default();
1977 for (pos, perm) in perms.iter().enumerate() {
1978 let si = perm.section_index();
1979 let section = locate_container_section_ranged(
1980 reader,
1981 container.offset,
1982 container.len,
1983 pos,
1984 sections as u64,
1985 )?;
1986 index_section_ranges[si] = section;
1987 let dir = read_tile_directory_ranged(reader, section)?;
1988 let syn = if has_synopsis {
1991 read_tile_synopsis_ranged(reader, section, &dir)
1992 } else {
1993 vec![None; dir.len()]
1994 };
1995 directories[si] = dir
1996 .iter()
1997 .zip(syn)
1998 .map(|(e, s)| (e.min_a, e.max_a, s))
1999 .collect();
2000 tile_ranges[si] = dir
2001 .into_iter()
2002 .map(|e| {
2003 (
2004 e.min_a,
2005 e.max_a,
2006 ByteRange {
2007 offset: section.offset + e.start,
2008 len: (e.end - e.start),
2009 },
2010 )
2011 })
2012 .collect();
2013 }
2014
2015 let codec = block_codec;
2025 let loader_ranges = tile_ranges.clone();
2026 let loader_reader = reader.clone();
2027 let loader: crate::index::TileLoader = Box::new(move |si, ti| {
2028 let (_, _, range) = loader_ranges.get(si)?.get(ti)?;
2029 let bytes = loader_reader.read_at(range.offset, range.len).ok()?;
2030 if bytes.len() as u64 != range.len {
2031 return None;
2032 }
2033 checked_tile(codec, &bytes)
2034 });
2035 let bulk_ranges = tile_ranges.clone();
2036 let bulk_reader = reader.clone();
2037 let bulk: crate::index::TileBulkLoader = Box::new(move |si, tis| {
2038 let section = bulk_ranges.get(si)?;
2039 let want: Option<Vec<ByteRange>> = tis
2040 .iter()
2041 .map(|&ti| section.get(ti).map(|&(_, _, r)| r))
2042 .collect();
2043 let blobs = read_coalesced(bulk_reader.as_ref(), &want?, TILE_COALESCE_GAP)?;
2044 blobs.iter().map(|b| checked_tile(codec, b)).collect()
2045 });
2046 let mut index =
2047 GraphIndex::from_remote_directories(directories, perms, loader).with_bulk_loader(bulk);
2048 index.set_tile_lens(std::array::from_fn(|si| {
2051 tile_ranges[si]
2052 .iter()
2053 .map(|&(_, _, r)| r.len.min(u32::MAX as u64) as u32)
2054 .collect()
2055 }));
2056 index.set_read_concurrency(read_concurrency);
2060 Ok((index, index_section_ranges, tile_ranges))
2061}
2062
2063fn checked_tile(codec: u8, bytes: &[u8]) -> Option<Vec<u8>> {
2067 let tile = decompress(codec, bytes).ok()?;
2068 crate::triples::TripleBlock::parse(&tile).ok()?;
2069 Some(tile)
2070}
2071
2072pub fn write_file(
2079 dict: &Dictionary,
2080 index: &GraphIndex,
2081 has_quads: bool,
2082 pyramid_meta: &[u8],
2083 pyramid_levels: u16,
2084) -> Vec<u8> {
2085 write_dataset(dict, index, &[], has_quads, pyramid_meta, pyramid_levels)
2086}
2087
2088#[doc(hidden)]
2093pub fn write_file_v05(
2094 dict: &Dictionary,
2095 index: &GraphIndex,
2096 has_quads: bool,
2097 pyramid_meta: &[u8],
2098 pyramid_levels: u16,
2099) -> Vec<u8> {
2100 write_dataset_v05(dict, index, &[], has_quads, pyramid_meta, pyramid_levels)
2101}
2102
2103fn into_v06(image: Vec<u8>) -> Vec<u8> {
2106 crate::build_record::finish_in_ram(image, None)
2107 .unwrap_or_else(|e| panic!("writing format 0x06: {e}"))
2108}
2109
2110pub(crate) fn encode_index_container(index: &GraphIndex, codec: u8) -> Vec<u8> {
2116 encode_index_container_sealed(index, codec, None)
2117}
2118
2119fn encode_index_container_sealed(index: &GraphIndex, codec: u8, seal: Option<&[u8]>) -> Vec<u8> {
2124 let payloads: Vec<Vec<u8>> = index
2125 .perms()
2126 .iter()
2127 .map(|perm| encode_tiled_section(index, perm.section_index(), codec))
2128 .collect();
2129 let mut refs: Vec<&[u8]> = payloads.iter().map(|p| p.as_slice()).collect();
2130 if let Some(seal) = seal {
2131 refs.push(seal);
2132 }
2133 encode_container(&refs, CODEC_NONE)
2134}
2135
2136fn encode_named_graphs(named: &[(String, GraphIndex)], codec: u8) -> Vec<u8> {
2138 let mut out = Vec::new();
2139 write_uvarint(&mut out, named.len() as u64);
2140 for (iri, index) in named {
2141 write_uvarint(&mut out, iri.len() as u64);
2142 out.extend_from_slice(iri.as_bytes());
2143 let container = encode_index_container(index, codec);
2144 write_uvarint(&mut out, container.len() as u64);
2145 out.extend_from_slice(&container);
2146 }
2147 out
2148}
2149
2150fn decode_named_graphs(
2151 bytes: &[u8],
2152 codec: u8,
2153 perms: PermSet,
2154) -> Result<Vec<(String, GraphIndex)>, FileError> {
2155 let (n, mut pos) = read_uvarint(bytes).ok_or(FileError::Container("truncated graph count"))?;
2156 let bound = |start: usize, len: u64| -> Result<usize, FileError> {
2159 usize::try_from(len)
2160 .ok()
2161 .and_then(|len| start.checked_add(len))
2162 .filter(|&e| e <= bytes.len())
2163 .ok_or(FileError::Container("named-graph field overruns buffer"))
2164 };
2165 let n = wire_usize(n, "named-graph count too large")?;
2166 let mut out = Vec::with_capacity(n.min(bytes.len()));
2167 for _ in 0..n {
2168 let (ilen, u1) = read_uvarint(bytes.get(pos..).unwrap_or(&[]))
2169 .ok_or(FileError::Container("truncated iri len"))?;
2170 pos += u1;
2171 let iend = bound(pos, ilen)?;
2172 let iri = String::from_utf8_lossy(&bytes[pos..iend]).into_owned();
2173 pos = iend;
2174 let (clen, u2) = read_uvarint(bytes.get(pos..).unwrap_or(&[]))
2175 .ok_or(FileError::Container("truncated container len"))?;
2176 pos += u2;
2177 let cend = bound(pos, clen)?;
2178 let index = decode_index_container(&bytes[pos..cend], codec, perms)?;
2179 index.set_size_hint(u64::from(index.triple_count()));
2182 out.push((iri, index));
2183 pos = cend;
2184 }
2185 Ok(out)
2186}
2187
2188pub fn write_dataset(
2193 dict: &Dictionary,
2194 default_index: &GraphIndex,
2195 named: &[(String, GraphIndex)],
2196 has_quads: bool,
2197 pyramid_meta: &[u8],
2198 pyramid_levels: u16,
2199) -> Vec<u8> {
2200 write_dataset_with_metadata(
2201 dict,
2202 default_index,
2203 named,
2204 has_quads,
2205 pyramid_meta,
2206 pyramid_levels,
2207 &[],
2208 &[],
2209 )
2210}
2211
2212#[doc(hidden)]
2214pub fn write_dataset_v05(
2215 dict: &Dictionary,
2216 default_index: &GraphIndex,
2217 named: &[(String, GraphIndex)],
2218 has_quads: bool,
2219 pyramid_meta: &[u8],
2220 pyramid_levels: u16,
2221) -> Vec<u8> {
2222 write_dataset_with_metadata_v05(
2223 dict,
2224 default_index,
2225 named,
2226 has_quads,
2227 pyramid_meta,
2228 pyramid_levels,
2229 &[],
2230 &[],
2231 )
2232}
2233
2234pub(crate) fn encode_dict_container(dict: &Dictionary, codec: u8) -> Vec<u8> {
2239 let raw_sections = dict.sections();
2240 let dict_payloads: Vec<Vec<u8>> = raw_sections
2241 .iter()
2242 .map(|raw| encode_chunked_dict_section(raw, codec))
2243 .collect();
2244 encode_container(
2245 &[
2246 dict_payloads[0].as_slice(),
2247 dict_payloads[1].as_slice(),
2248 dict_payloads[2].as_slice(),
2249 dict_payloads[3].as_slice(),
2250 ],
2251 CODEC_NONE,
2252 )
2253}
2254
2255#[allow(clippy::too_many_arguments)]
2266pub fn write_dataset_with_metadata(
2267 dict: &Dictionary,
2268 default_index: &GraphIndex,
2269 named: &[(String, GraphIndex)],
2270 has_quads: bool,
2271 pyramid_meta: &[u8],
2272 pyramid_levels: u16,
2273 metadata: &[u8],
2274 text_index: &[u8],
2275) -> Vec<u8> {
2276 into_v06(write_dataset_with_metadata_v05(
2277 dict,
2278 default_index,
2279 named,
2280 has_quads,
2281 pyramid_meta,
2282 pyramid_levels,
2283 metadata,
2284 text_index,
2285 ))
2286}
2287
2288#[doc(hidden)]
2291#[allow(clippy::too_many_arguments)]
2292pub fn write_dataset_with_metadata_v05(
2293 dict: &Dictionary,
2294 default_index: &GraphIndex,
2295 named: &[(String, GraphIndex)],
2296 has_quads: bool,
2297 pyramid_meta: &[u8],
2298 pyramid_levels: u16,
2299 metadata: &[u8],
2300 text_index: &[u8],
2301) -> Vec<u8> {
2302 let codec = writer_codec();
2303 let dict_container = encode_dict_container(dict, codec);
2304 let scope = (!text_index.is_empty())
2308 .then(|| crate::text_index::TextIndex::from_section(text_index, codec).ok())
2309 .flatten()
2310 .map(|ti| ti.scope().clone());
2311 let text_index_partial = scope
2312 .as_ref()
2313 .is_some_and(crate::text_index::TextIndexScope::restricts_predicates);
2314 let text_index_named = scope
2315 .as_ref()
2316 .is_some_and(crate::text_index::TextIndexScope::covers_named_graphs);
2317 write_dataset_from_parts(
2318 &dict_container,
2319 dict.term_count() as u64,
2320 default_index,
2321 NamedPart::PerGraph(named),
2322 has_quads,
2323 dict.has_quoted_triples(),
2324 pyramid_meta,
2325 pyramid_levels,
2326 metadata,
2327 text_index,
2328 text_index_partial,
2329 text_index_named,
2330 codec,
2331 )
2332}
2333
2334pub(crate) enum NamedPart<'a> {
2337 PerGraph(&'a [(String, GraphIndex)]),
2338 Quad(&'a crate::quad::EncodedQuadIndex),
2339}
2340
2341#[allow(clippy::too_many_arguments)]
2346pub(crate) fn write_dataset_from_parts(
2347 dict_container: &[u8],
2348 term_count: u64,
2349 default_index: &GraphIndex,
2350 named: NamedPart<'_>,
2351 has_quads: bool,
2352 has_quoted_triples: bool,
2353 pyramid_meta: &[u8],
2354 pyramid_levels: u16,
2355 metadata: &[u8],
2356 text_index: &[u8],
2357 text_index_partial: bool,
2358 text_index_named: bool,
2359 codec: u8,
2360) -> Vec<u8> {
2361 let (named_section, quad, named_quads) = match named {
2365 NamedPart::PerGraph(named) => (
2366 if named.is_empty() {
2367 Vec::new()
2368 } else {
2369 encode_named_graphs(named, codec)
2370 },
2371 None,
2372 named
2373 .iter()
2374 .map(|(_, idx)| idx.triple_count() as u64)
2375 .sum::<u64>(),
2376 ),
2377 NamedPart::Quad(q) if q.graph_count == 0 => (Vec::new(), None, 0),
2378 NamedPart::Quad(q) => (Vec::new(), Some(q), q.quad_count),
2379 };
2380 let seal = quad.map(|q| crate::quad::encode_seal(crate::quad::digest(&q.bytes)));
2381 let index_container = encode_index_container_sealed(default_index, codec, seal.as_deref());
2382 let text_index_partial = text_index_partial && !text_index.is_empty();
2387 let digested;
2388 let text_index: &[u8] = if text_index_partial {
2389 digested = crate::text_index::with_partial_digest(text_index);
2390 &digested
2391 } else {
2392 text_index
2393 };
2394
2395 let meta_section_len = metadata.len() as u64;
2398 let dict_offset = HEADER_LEN as u64 + meta_section_len;
2399 let dict_len = dict_container.len() as u64;
2400 let index_offset = dict_offset + dict_len;
2401 let index_len = index_container.len() as u64;
2402 let pyr_offset = index_offset + index_len;
2403 let pyr_len = pyramid_meta.len() as u64;
2404 let text_offset = pyr_offset + pyr_len;
2406 let text_len = text_index.len() as u64;
2407 let named_offset = text_offset + text_len;
2408 let named_len = named_section.len() as u64;
2409 let quad_len = quad.map_or(0, |q| q.bytes.len() as u64);
2412
2413 let mut parts: Vec<&[u8]> = Vec::with_capacity(5);
2419 if meta_section_len > 0 {
2420 parts.push(metadata);
2421 }
2422 parts.push(dict_container);
2423 parts.push(&index_container);
2424 parts.push(pyramid_meta);
2425 if text_len > 0 && !text_index_partial {
2426 parts.push(text_index);
2427 }
2428 if named_len > 0 {
2429 parts.push(&named_section);
2430 }
2431
2432 let schema_meta_len = crate::meta::schema_block_len(pyramid_meta);
2435
2436 let header = Header {
2440 version: crate::header::LEGACY_FORMAT_VERSION,
2441 flags: FLAG_TILE_SYNOPSIS
2442 | if has_quads { FLAG_HAS_QUADS } else { 0 }
2443 | if quad.is_some() {
2444 crate::header::FLAG_QUAD_INDEX
2445 } else {
2446 0
2447 }
2448 | if has_quoted_triples {
2449 FLAG_HAS_QUOTED_TRIPLES
2450 } else {
2451 0
2452 }
2453 | if text_len > 0 && text_index_named {
2454 crate::header::FLAG_TEXT_INDEX_NAMED_GRAPHS
2455 } else {
2456 0
2457 },
2458 metadata_offset: HEADER_LEN as u64,
2459 metadata_len: meta_section_len,
2460 dictionary_offset: dict_offset,
2461 dictionary_len: dict_len,
2462 root_dir_offset: index_offset,
2463 root_dir_len: index_len,
2464 pyramid_meta_offset: if pyr_len > 0 { pyr_offset } else { 0 },
2465 pyramid_meta_len: pyr_len,
2466 dict_codec: codec,
2467 block_codec: codec,
2468 pyramid_levels,
2469 id_widths: 0,
2470 perms: default_index.perms(),
2474 quad_count: default_index.triple_count() as u64 + named_quads,
2475 term_count,
2476 content_hash: content_hash(&parts),
2477 named_graphs_offset: if named_len > 0 { named_offset } else { 0 },
2478 named_graphs_len: named_len,
2479 schema_meta_len,
2480 text_index_offset: if text_len > 0 { text_offset } else { 0 },
2481 text_index_len: text_len,
2482 text_index_partial: text_len > 0 && text_index_partial,
2483 build_info_offset: 0,
2484 build_info_len: 0,
2485 extra_sections: if quad_len > 0 {
2486 vec![crate::header::Section {
2487 kind: crate::header::SectionKind::QuadIndex,
2488 flags: 0,
2489 offset: named_offset,
2490 length: quad_len,
2491 }]
2492 } else {
2493 Vec::new()
2494 },
2495 };
2496
2497 let mut out = Vec::with_capacity(
2498 HEADER_LEN
2499 + metadata.len()
2500 + dict_container.len()
2501 + index_container.len()
2502 + pyramid_meta.len()
2503 + text_index.len()
2504 + named_section.len()
2505 + quad_len as usize
2506 + MAGIC.len(),
2507 );
2508 out.extend_from_slice(&header.to_bytes());
2509 if meta_section_len > 0 {
2510 out.extend_from_slice(metadata);
2511 }
2512 out.extend_from_slice(dict_container);
2513 out.extend_from_slice(&index_container);
2514 out.extend_from_slice(pyramid_meta);
2515 if text_len > 0 {
2516 out.extend_from_slice(text_index);
2517 }
2518 if named_len > 0 {
2519 out.extend_from_slice(&named_section);
2520 }
2521 if let Some(q) = quad {
2522 out.extend_from_slice(&q.bytes);
2523 }
2524 out.extend_from_slice(&MAGIC); out
2526}
2527
2528pub const RDF_TYPE: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";
2530
2531pub fn schema_summary(rete: &Rete) -> Vec<(String, String, String, u32)> {
2538 use std::collections::{BTreeMap, HashMap};
2539 let triples = rete.dump(None);
2540
2541 let mut class_of: HashMap<&str, &str> = HashMap::new();
2542 for (s, p, o) in &triples {
2543 if p == RDF_TYPE {
2544 class_of.insert(s.as_str(), o.as_str());
2545 }
2546 }
2547 let classify = |t: &str| -> String {
2548 if let Some(c) = class_of.get(t) {
2549 (*c).to_string()
2550 } else if t.starts_with('"') {
2551 "(literal)".to_string()
2552 } else {
2553 "(untyped)".to_string()
2554 }
2555 };
2556
2557 let mut counts: BTreeMap<(String, String, String), u32> = BTreeMap::new();
2558 for (s, p, o) in &triples {
2559 if p == RDF_TYPE {
2560 continue; }
2562 *counts
2563 .entry((classify(s), p.clone(), classify(o)))
2564 .or_default() += 1;
2565 }
2566 counts
2567 .into_iter()
2568 .map(|((a, p, b), c)| (a, p, b, c))
2569 .collect()
2570}
2571
2572pub fn schema_classes(rete: &Rete) -> Vec<(String, u32)> {
2576 use std::collections::BTreeMap;
2577 let mut counts: BTreeMap<String, u32> = BTreeMap::new();
2578 for (_s, p, o) in rete.dump(None) {
2579 if p == RDF_TYPE {
2580 *counts.entry(o).or_default() += 1;
2581 }
2582 }
2583 let mut out: Vec<(String, u32)> = counts.into_iter().collect();
2584 out.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
2585 out
2586}
2587
2588pub fn read_metadata_ranged<R: RangeReader>(reader: &R) -> Result<Option<Vec<u8>>, FileError> {
2598 let head = reader.read_at(0, HEADER_LEN as u64)?;
2599 if crate::v06::open::is_v06(&head) {
2600 let h = crate::v06::Header06::from_bytes(&head)?;
2601 return Ok(crate::v06::open::read_card_build(reader, &h)?.0);
2602 }
2603 let header = Header::from_bytes(&head)?;
2604 if header.metadata_len == 0 {
2605 return Ok(None);
2606 }
2607 let bytes = reader.read_at(header.metadata_offset, header.metadata_len)?;
2608 Ok(Some(bytes))
2609}
2610
2611pub fn read_card_full_ranged<R: RangeReader>(reader: &R) -> Result<Option<Vec<u8>>, FileError> {
2616 let head = reader.read_at(0, HEADER_LEN as u64)?;
2617 if crate::v06::open::is_v06(&head) {
2618 return Ok(crate::v06::open::read_card_full(reader)?.0);
2619 }
2620 read_metadata_ranged(reader)
2621}
2622
2623#[allow(clippy::type_complexity)]
2633pub fn read_card_and_build_info_ranged<R: RangeReader>(
2634 reader: &R,
2635) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>), FileError> {
2636 read_card_and_build_info_with_header(reader).map(|(_, m, b)| (m, b))
2637}
2638
2639#[allow(clippy::type_complexity)]
2650pub fn read_card_and_build_info_with_header<R: RangeReader>(
2651 reader: &R,
2652) -> Result<(Header, Option<Vec<u8>>, Option<Vec<u8>>), FileError> {
2653 let head = reader.read_at(0, HEADER_LEN as u64)?;
2654 let header = Header::from_bytes(&head)?;
2655 if crate::v06::reads(header.version) {
2656 let h = crate::v06::Header06::from_bytes(&head)?;
2657 let (card, build) = crate::v06::open::read_card_build(reader, &h)?;
2658 return Ok((header, card, build));
2659 }
2660 let meta = (header.metadata_offset, header.metadata_len);
2661 let build = (header.build_info_offset, header.build_info_len);
2662 if meta.1 > 0 && build.1 > 0 && build.0 == meta.0 + meta.1 {
2663 let both = reader.read_at(meta.0, meta.1 + build.1)?;
2665 let (m, b) = usize::try_from(meta.1)
2666 .ok()
2667 .and_then(|mid| both.split_at_checked(mid))
2668 .ok_or(FileError::Container("short card read"))?;
2669 return Ok((header, Some(m.to_vec()), Some(b.to_vec())));
2670 }
2671 let fetch = |off: u64, len: u64| -> Result<Option<Vec<u8>>, FileError> {
2672 if len == 0 {
2673 return Ok(None);
2674 }
2675 Ok(Some(reader.read_at(off, len)?))
2676 };
2677 Ok((header, fetch(meta.0, meta.1)?, fetch(build.0, build.1)?))
2678}
2679
2680pub fn read_build_info(bytes: &[u8]) -> Result<Option<Vec<u8>>, FileError> {
2685 if crate::v06::open::is_v06(bytes) {
2686 let h = crate::v06::Header06::from_bytes(bytes)?;
2687 let r = crate::reader::SliceReader::new(bytes);
2688 return Ok(crate::v06::open::read_card_build(&r, &h)?.1);
2689 }
2690 let header = Header::from_bytes(bytes)?;
2691 if header.build_info_len == 0 {
2692 return Ok(None);
2693 }
2694 let section = checked_slice(bytes, header.build_info_offset, header.build_info_len)
2695 .ok_or(FileError::Container("build-info section overruns buffer"))?;
2696 Ok(Some(section.to_vec()))
2697}
2698
2699#[derive(Debug, Clone, PartialEq, Eq)]
2708pub struct BuildInfoPlan {
2709 pub header: [u8; HEADER_LEN],
2711 pub insert: u64,
2714 pub tail_start: u64,
2718 pub new_len: u64,
2720}
2721
2722pub fn plan_build_info(
2744 head: &[u8],
2745 file_len: u64,
2746 info_len: u64,
2747) -> Result<BuildInfoPlan, FileError> {
2748 let mut header = Header::from_bytes(head)?;
2749 let insert = if header.metadata_len > 0 {
2754 header
2755 .metadata_offset
2756 .checked_add(header.metadata_len)
2757 .filter(|&end| header.metadata_offset >= HEADER_LEN as u64 && end <= file_len)
2758 .ok_or(FileError::Container(
2759 "the metadata section lies outside the file",
2760 ))?
2761 } else {
2762 HEADER_LEN as u64
2763 };
2764 let old_len = header.build_info_len;
2765 if old_len > 0 && header.build_info_offset != insert {
2766 return Err(FileError::Container(
2767 "existing build-info section is not adjacent to the metadata",
2768 ));
2769 }
2770 let tail_start = insert.saturating_add(old_len);
2771 if tail_start > file_len || insert > file_len {
2772 return Err(FileError::Container("build-info splice out of bounds"));
2773 }
2774
2775 let shift = |off: &mut u64, len: u64| {
2777 if len > 0 && *off >= tail_start {
2778 *off = *off - old_len + info_len;
2779 }
2780 };
2781 shift(&mut header.dictionary_offset, header.dictionary_len);
2782 shift(&mut header.root_dir_offset, header.root_dir_len);
2783 shift(&mut header.pyramid_meta_offset, header.pyramid_meta_len);
2784 shift(&mut header.named_graphs_offset, header.named_graphs_len);
2785 shift(&mut header.text_index_offset, header.text_index_len);
2786 for s in &mut header.extra_sections {
2787 if s.length > 0 && s.offset >= tail_start {
2788 s.offset = s.offset - old_len + info_len;
2789 }
2790 }
2791 if info_len == 0 {
2792 header.build_info_offset = 0;
2793 header.build_info_len = 0;
2794 } else {
2795 header.build_info_offset = insert;
2796 header.build_info_len = info_len;
2797 }
2798
2799 Ok(BuildInfoPlan {
2800 header: header.to_bytes(),
2801 insert,
2802 tail_start,
2803 new_len: file_len - old_len + info_len,
2804 })
2805}
2806
2807pub fn attach_build_info(image: &[u8], info: &[u8]) -> Result<Vec<u8>, FileError> {
2813 if crate::v06::open::is_v06(image) {
2814 return crate::v06::write::replace_card_with(
2816 image,
2817 crate::v06::write::NewCard::Keep,
2818 (!info.is_empty()).then_some(info),
2819 );
2820 }
2821 let plan = plan_build_info(image, image.len() as u64, info.len() as u64)?;
2822 let mut out = Vec::with_capacity(plan.new_len as usize);
2823 out.extend_from_slice(&plan.header);
2824 out.extend_from_slice(&image[HEADER_LEN..plan.insert as usize]);
2825 out.extend_from_slice(info);
2826 out.extend_from_slice(&image[plan.tail_start as usize..]);
2827 debug_assert_eq!(out.len() as u64, plan.new_len);
2828 Ok(out)
2829}
2830
2831pub fn replace_metadata(image: &[u8], metadata: &[u8]) -> Result<Vec<u8>, FileError> {
2851 if crate::v06::open::is_v06(image) {
2852 let h = crate::v06::Header06::from_bytes(image)?;
2854 let (_, build) =
2855 crate::v06::open::read_card_build(&crate::reader::SliceReader::new(image), &h)?;
2856 return crate::v06::write::replace_card(
2857 image,
2858 (!metadata.is_empty()).then_some(metadata),
2859 build.as_deref(),
2860 );
2861 }
2862 let mut header = Header::from_bytes(image)?;
2863 let insert = HEADER_LEN as u64;
2866 if header.metadata_len > 0 && header.metadata_offset != insert {
2867 return Err(FileError::Container(
2868 "metadata section does not sit immediately after the header",
2869 ));
2870 }
2871 let old_len = header.metadata_len;
2872 let tail_start = (insert + old_len) as usize;
2873 if tail_start > image.len() {
2874 return Err(FileError::Container("metadata splice out of bounds"));
2875 }
2876 let new_len = metadata.len() as u64;
2877
2878 let shift = |off: &mut u64, len: u64| {
2879 if len > 0 && *off >= insert + old_len {
2880 *off = *off - old_len + new_len;
2881 }
2882 };
2883 shift(&mut header.dictionary_offset, header.dictionary_len);
2884 shift(&mut header.root_dir_offset, header.root_dir_len);
2885 shift(&mut header.pyramid_meta_offset, header.pyramid_meta_len);
2886 shift(&mut header.named_graphs_offset, header.named_graphs_len);
2887 shift(&mut header.text_index_offset, header.text_index_len);
2888 shift(&mut header.build_info_offset, header.build_info_len);
2889 for s in &mut header.extra_sections {
2890 if s.length > 0 && s.offset >= insert + old_len {
2891 s.offset = s.offset - old_len + new_len;
2892 }
2893 }
2894 header.metadata_offset = insert;
2895 header.metadata_len = new_len;
2896
2897 let mut out = Vec::with_capacity(image.len() - old_len as usize + metadata.len());
2898 out.extend_from_slice(&header.to_bytes());
2899 out.extend_from_slice(metadata);
2900 out.extend_from_slice(&image[tail_start..]);
2901 header.content_hash = hash_of_sections(&header, &out)?;
2905 out[..HEADER_LEN].copy_from_slice(&header.to_bytes());
2906 Ok(out)
2907}
2908
2909fn hash_of_sections(header: &Header, bytes: &[u8]) -> Result<[u8; 16], FileError> {
2915 let slice = |off: u64, len: u64| -> Result<&[u8], FileError> {
2916 checked_slice(bytes, off, len).ok_or(FileError::Container("section overruns buffer"))
2925 };
2926 let parts = content_hash_parts(header)
2927 .into_iter()
2928 .map(|(off, len)| slice(off, len))
2929 .collect::<Result<Vec<&[u8]>, FileError>>()?;
2930 Ok(content_hash(&parts))
2931}
2932
2933pub fn content_hash_parts(header: &Header) -> Vec<(u64, u64)> {
2946 let mut parts: Vec<(u64, u64)> = Vec::with_capacity(6);
2947 if header.metadata_len > 0 {
2948 parts.push((header.metadata_offset, header.metadata_len));
2949 }
2950 parts.push((header.dictionary_offset, header.dictionary_len));
2951 parts.push((header.root_dir_offset, header.root_dir_len));
2952 if header.pyramid_meta_len > 0 {
2955 parts.push((header.pyramid_meta_offset, header.pyramid_meta_len));
2956 }
2957 if header.text_index_len > 0 && !header.text_index_partial {
2959 parts.push((header.text_index_offset, header.text_index_len));
2960 }
2961 if header.named_graphs_len > 0 {
2962 parts.push((header.named_graphs_offset, header.named_graphs_len));
2963 }
2964 parts
2965}
2966
2967pub fn verify_ranged_v06(
2970 reader: &dyn crate::reader::RangeReader,
2971 head: &[u8],
2972 only: Option<u8>,
2973) -> Result<Vec<String>, FileError> {
2974 const SLICE: u64 = 8 << 20;
2975 let h = crate::v06::Header06::from_bytes(head)?;
2976 if h.file_len != reader.len() {
2977 return Ok(vec!["file length".to_string()]);
2978 }
2979 let mut bad = Vec::new();
2980 let root_bytes = reader.read_at(crate::v06::HEADER_LEN as u64, h.root_len as u64)?;
2981 if crate::v06::digest16(&root_bytes) != h.root_digest {
2982 bad.push("root".to_string());
2983 return Ok(bad);
2984 }
2985 let root = crate::v06::Root06::decode(&root_bytes, h.internal_codec)?;
2986 if crate::v06::content_hash(&h) != h.content_hash {
2987 bad.push("content hash".to_string());
2988 }
2989 let card = h.card_range();
2990 if only.is_none() && card.len > 0 {
2991 let stored = reader.read_at(card.offset, card.len)?;
2992 if crate::v06::digest16(&stored) != h.card_digest {
2993 bad.push("card".to_string());
2994 }
2995 }
2996 for s in &root.sections {
2997 if only.is_some_and(|k| k != s.kind) {
2998 continue;
2999 }
3000 let a = match s.abs(&h) {
3001 Ok(a) if a.offset + a.len <= h.file_len => a,
3002 _ => {
3003 bad.push(crate::v06::kind::name(s.kind).to_string());
3004 continue;
3005 }
3006 };
3007 let mut hs = blake3::Hasher::new();
3008 let mut at = a.offset;
3009 while at < a.offset + a.len {
3010 let n = (a.offset + a.len - at).min(SLICE);
3011 hs.update(&reader.read_at(at, n)?);
3012 at += n;
3013 }
3014 if hs.finalize().as_bytes()[..16] != s.digest {
3015 bad.push(crate::v06::kind::name(s.kind).to_string());
3016 }
3017 }
3018 if only.is_none() {
3019 let n = crate::v06::FOOTER.len() as u64;
3020 if reader.read_at(h.file_len - n, n)? != crate::v06::footer(h.version) {
3021 bad.push("footer".to_string());
3022 }
3023 }
3024 Ok(bad)
3025}
3026
3027pub fn verify(bytes: &[u8]) -> Result<bool, FileError> {
3035 if crate::v06::open::is_v06(bytes) {
3036 let r: std::sync::Arc<dyn RangeReader + Send + Sync> =
3037 std::sync::Arc::new(crate::reader::BytesReader(std::sync::Arc::from(bytes)));
3038 return crate::v06::open::V06File::open(r, bytes)?.verify(None);
3039 }
3040 let header = Header::from_bytes(bytes)?;
3041 if hash_of_sections(&header, bytes)? != header.content_hash {
3042 return Ok(false);
3043 }
3044 if header.has_quad_index() || header.quad_index_section().is_some() {
3047 check_named_layout(&header)?;
3048 let slice = |off: u64, len: u64| -> Result<&[u8], FileError> {
3049 checked_slice(bytes, off, len).ok_or(FileError::Container("section overruns buffer"))
3050 };
3051 let root = slice(header.root_dir_offset, header.root_dir_len)?;
3052 let ranges = container_section_payload_ranges(
3053 root,
3054 header.root_dir_offset,
3055 header.index_container_sections(),
3056 )?;
3057 let seal = ranges
3058 .last()
3059 .ok_or(FileError::Container("missing quad-index seal"))?;
3060 let want = crate::quad::parse_seal(slice(seal.offset, seal.len)?)?;
3061 let q = header
3062 .quad_index_section()
3063 .ok_or(FileError::Container("missing quad-index section"))?;
3064 if crate::quad::digest(slice(q.offset, q.length)?) != want {
3065 return Ok(false);
3066 }
3067 }
3068 for s in self_digested_sections(&header) {
3069 let section = checked_slice(bytes, s.offset, s.length)
3070 .ok_or(FileError::Container("section overruns buffer"))?;
3071 if !crate::label_index::digest_ok(section) {
3072 return Ok(false);
3073 }
3074 }
3075 Ok(true)
3076}
3077
3078fn self_digested_sections(header: &Header) -> Vec<Section> {
3082 [
3083 header.label_index_section(),
3084 header.schema_section(),
3085 header
3086 .section(crate::header::SectionKind::TextIndexPartial)
3087 .filter(|s| s.length > 0),
3088 ]
3089 .into_iter()
3090 .flatten()
3091 .collect()
3092}
3093
3094pub fn append_sections(
3102 image: &[u8],
3103 sections: &[(SectionKind, &[u8])],
3104) -> Result<Vec<u8>, FileError> {
3105 let lens: Vec<(SectionKind, u64)> =
3106 sections.iter().map(|(k, b)| (*k, b.len() as u64)).collect();
3107 let (header, body_end) = plan_append(image, image.len() as u64, &lens)?;
3108 let extra: usize = sections.iter().map(|(_, b)| b.len()).sum();
3109 let mut out = Vec::with_capacity(image.len() + extra);
3110 out.extend_from_slice(&header.to_bytes());
3111 out.extend_from_slice(&image[HEADER_LEN..body_end as usize]);
3112 for (_, b) in sections {
3113 out.extend_from_slice(b);
3114 }
3115 out.extend_from_slice(&MAGIC);
3116 Ok(out)
3117}
3118
3119fn plan_append(
3121 head: &[u8],
3122 file_len: u64,
3123 sections: &[(SectionKind, u64)],
3124) -> Result<(Header, u64), FileError> {
3125 let mut header = Header::from_bytes(head)?;
3126 if header.expected_file_len() != Some(file_len) {
3127 return Err(FileError::Container(
3128 "cannot append sections: the file length does not match its header",
3129 ));
3130 }
3131 let body_end = file_len - MAGIC.len() as u64;
3132 let mut at = body_end;
3133 for &(kind, len) in sections {
3134 if !matches!(kind, SectionKind::LabelIndex | SectionKind::Schema) {
3135 return Err(FileError::Container(
3136 "only LABEL_INDEX and SCHEMA sections can be appended",
3137 ));
3138 }
3139 if len == 0 {
3140 continue;
3141 }
3142 if header.section(kind).is_some_and(|s| s.length > 0) {
3143 return Err(FileError::Container(
3144 "the file already carries that section",
3145 ));
3146 }
3147 header = header.with_section(kind, at, len);
3148 at += len;
3149 }
3150 Ok((header, body_end))
3151}
3152
3153#[cfg(not(target_arch = "wasm32"))]
3158pub(crate) fn open_dictionary_lazy<R: RangeReader + Send + Sync + 'static>(
3159 reader: R,
3160) -> Result<Dictionary, FileError> {
3161 let head = reader.read_at(0, HEADER_LEN as u64)?;
3162 let header = Header::from_bytes(&head)?;
3163 ranged_chunked_dictionary(&std::sync::Arc::new(reader), &header, [true; 4])
3164}
3165
3166pub fn verify_ranged(reader: &dyn crate::reader::RangeReader) -> Result<bool, FileError> {
3172 const SLICE: u64 = 8 << 20;
3175 let len = reader.len();
3176 if len < HEADER_LEN as u64 {
3177 return Err(FileError::Container("file shorter than its header"));
3178 }
3179 let head = reader.read_at(0, HEADER_LEN as u64)?;
3180 if crate::v06::open::is_v06(&head) {
3181 return verify_ranged_v06(reader, &head, None).map(|bad| bad.is_empty());
3182 }
3183 let header = Header::from_bytes(&head)?;
3184 let mut h = blake3::Hasher::new();
3185 for (off, n) in content_hash_parts(&header) {
3186 if off.checked_add(n).is_none_or(|end| end > len) {
3189 return Err(FileError::Container("section overruns buffer"));
3190 }
3191 let mut at = off;
3192 while at < off + n {
3193 let take = (off + n - at).min(SLICE);
3194 h.update(&reader.read_at(at, take)?);
3195 at += take;
3196 }
3197 }
3198 let mut out = [0u8; 16];
3199 out.copy_from_slice(&h.finalize().as_bytes()[..16]);
3200 if out != header.content_hash {
3201 return Ok(false);
3202 }
3203 if header.has_quad_index() || header.quad_index_section().is_some() {
3206 check_named_layout(&header)?;
3207 let sections = header.index_container_sections();
3208 let seal = locate_container_section_ranged(
3209 reader,
3210 header.root_dir_offset,
3211 header.root_dir_len,
3212 sections - 1,
3213 sections as u64,
3214 )?;
3215 let want = crate::quad::parse_seal(&reader.read_at(seal.offset, seal.len)?)?;
3216 let q = header
3217 .quad_index_section()
3218 .ok_or(FileError::Container("missing quad-index section"))?;
3219 if q.offset.checked_add(q.length).is_none_or(|end| end > len) {
3220 return Err(FileError::Container("section overruns buffer"));
3221 }
3222 let mut h = blake3::Hasher::new();
3223 let mut at = q.offset;
3224 while at < q.offset + q.length {
3225 let take = (q.offset + q.length - at).min(SLICE);
3226 h.update(&reader.read_at(at, take)?);
3227 at += take;
3228 }
3229 let mut got = [0u8; 16];
3230 got.copy_from_slice(&h.finalize().as_bytes()[..16]);
3231 if got != want {
3232 return Ok(false);
3233 }
3234 }
3235 for s in self_digested_sections(&header) {
3237 if s.length < 16 || s.offset.checked_add(s.length).is_none_or(|end| end > len) {
3238 return Err(FileError::Container("section overruns buffer"));
3239 }
3240 let want = reader.read_at(s.offset, 16)?;
3241 let mut h = blake3::Hasher::new();
3242 let mut at = s.offset + 16;
3243 while at < s.offset + s.length {
3244 let take = (s.offset + s.length - at).min(SLICE);
3245 h.update(&reader.read_at(at, take)?);
3246 at += take;
3247 }
3248 if h.finalize().as_bytes()[..16] != want[..] {
3249 return Ok(false);
3250 }
3251 }
3252 Ok(true)
3253}
3254
3255type PyramidLoader = Box<dyn Fn() -> Option<PyramidMeta> + Send + Sync>;
3257
3258enum PyramidSlot {
3264 Resident(Option<PyramidMeta>),
3265 Lazy {
3266 loader: PyramidLoader,
3267 cell: std::sync::OnceLock<Option<PyramidMeta>>,
3268 },
3269}
3270
3271pub(crate) enum SectionSlot<T> {
3276 Resident(Option<T>),
3277 Lazy {
3278 loader: Box<dyn Fn() -> Option<T> + Send + Sync>,
3279 cell: std::sync::OnceLock<Option<T>>,
3280 },
3281}
3282
3283impl<T> SectionSlot<T> {
3284 pub(crate) fn get(&self) -> Option<&T> {
3286 match self {
3287 SectionSlot::Resident(v) => v.as_ref(),
3288 SectionSlot::Lazy { loader, cell } => cell.get_or_init(loader).as_ref(),
3289 }
3290 }
3291
3292 pub(crate) fn get_if_loaded(&self) -> Option<&T> {
3294 match self {
3295 SectionSlot::Resident(v) => v.as_ref(),
3296 SectionSlot::Lazy { cell, .. } => cell.get().and_then(|o| o.as_ref()),
3297 }
3298 }
3299}
3300
3301fn resident_label_slot<'a>(
3303 header: &Header,
3304 region: &dyn Fn(u64, u64) -> Result<&'a [u8], FileError>,
3305) -> SectionSlot<crate::label_index::LabelIndex> {
3306 SectionSlot::Resident(header.label_index_section().and_then(|s| {
3307 let bytes = region(s.offset, s.length).ok()?;
3308 crate::label_index::LabelIndex::from_section(bytes, header.block_codec).ok()
3309 }))
3310}
3311
3312fn resident_schema_slot<'a>(
3314 header: &Header,
3315 region: &dyn Fn(u64, u64) -> Result<&'a [u8], FileError>,
3316) -> SectionSlot<crate::schema_section::SchemaMeta> {
3317 SectionSlot::Resident(header.schema_section().and_then(|s| {
3318 crate::schema_section::SchemaMeta::decode(region(s.offset, s.length).ok()?).ok()
3319 }))
3320}
3321
3322fn ranged_label_slot<R: RangeReader + Send + Sync + 'static>(
3326 reader: &std::sync::Arc<R>,
3327 header: &Header,
3328) -> SectionSlot<crate::label_index::LabelIndex> {
3329 let Some(s) = header.label_index_section() else {
3330 return SectionSlot::Resident(None);
3331 };
3332 let r = reader.clone();
3333 let codec = header.block_codec;
3334 SectionSlot::Lazy {
3335 loader: Box::new(move || {
3336 let head = r
3337 .read_at(s.offset, crate::label_index::HEAD_READ.min(s.length))
3338 .ok()?;
3339 let rr = r.clone();
3340 let loader = Box::new(move |off: u64, len: u64| rr.read_at(s.offset + off, len).ok());
3341 crate::label_index::LabelIndex::from_head(&head, s.length, codec, loader).ok()
3342 }),
3343 cell: std::sync::OnceLock::new(),
3344 }
3345}
3346
3347fn ranged_schema_slot<R: RangeReader + Send + Sync + 'static>(
3349 reader: &std::sync::Arc<R>,
3350 header: &Header,
3351) -> SectionSlot<crate::schema_section::SchemaMeta> {
3352 let Some(s) = header.schema_section() else {
3353 return SectionSlot::Resident(None);
3354 };
3355 let r = reader.clone();
3356 SectionSlot::Lazy {
3357 loader: Box::new(move || {
3358 let bytes = r.read_at(s.offset, s.length).ok()?;
3359 crate::schema_section::SchemaMeta::decode(&bytes).ok()
3360 }),
3361 cell: std::sync::OnceLock::new(),
3362 }
3363}
3364
3365pub fn read_schema_ranged<R: RangeReader + ?Sized>(
3369 reader: &R,
3370) -> Result<Option<crate::schema_section::SchemaMeta>, FileError> {
3371 let head = reader.read_at(0, HEADER_LEN as u64)?;
3372 let header = Header::from_bytes(&head)?;
3373 Ok(read_schema_with_header(reader, &header))
3374}
3375
3376fn read_schema_with_header<R: RangeReader + ?Sized>(
3377 reader: &R,
3378 header: &Header,
3379) -> Option<crate::schema_section::SchemaMeta> {
3380 if crate::v06::reads(header.version) {
3381 let b = crate::v06::open::read_schema_bytes(reader).ok()??;
3382 return crate::schema_section::SchemaMeta::decode(&b).ok();
3383 }
3384 let s = header.schema_section()?;
3385 let bytes = reader.read_at(s.offset, s.length).ok()?;
3386 crate::schema_section::SchemaMeta::decode(&bytes).ok()
3387}
3388
3389type TextIndexLoader = Box<dyn Fn() -> Option<crate::text_index::TextIndex> + Send + Sync>;
3392
3393type TokenTableProbe = Box<dyn Fn() -> Option<u64> + Send + Sync>;
3396
3397enum TextIndexSlot {
3407 Resident {
3408 index: Option<crate::text_index::TextIndex>,
3409 token_table_len: Option<u64>,
3412 },
3413 Lazy {
3414 loader: TextIndexLoader,
3415 cell: std::sync::OnceLock<Option<crate::text_index::TextIndex>>,
3416 token_table: TokenTableProbe,
3418 token_table_cell: std::sync::OnceLock<Option<u64>>,
3419 },
3420}
3421
3422impl TextIndexSlot {
3423 fn index(&self) -> Option<&crate::text_index::TextIndex> {
3425 match self {
3426 TextIndexSlot::Resident { index, .. } => index.as_ref(),
3427 TextIndexSlot::Lazy { loader, cell, .. } => cell.get_or_init(loader).as_ref(),
3428 }
3429 }
3430
3431 fn token_table_len(&self) -> Option<u64> {
3434 match self {
3435 TextIndexSlot::Resident {
3436 token_table_len, ..
3437 } => *token_table_len,
3438 TextIndexSlot::Lazy {
3439 token_table,
3440 token_table_cell,
3441 ..
3442 } => *token_table_cell.get_or_init(token_table),
3443 }
3444 }
3445}
3446
3447fn resident_text_index_slot(section: Option<&[u8]>, codec: u8) -> Result<TextIndexSlot, FileError> {
3450 let Some(section) = section else {
3451 return Ok(TextIndexSlot::Resident {
3452 index: None,
3453 token_table_len: None,
3454 });
3455 };
3456 Ok(TextIndexSlot::Resident {
3457 index: Some(
3458 crate::text_index::TextIndex::from_section(section, codec)
3459 .map_err(|_| FileError::Container("malformed text index"))?,
3460 ),
3461 token_table_len: crate::text_index::TextIndex::postings_base(section).map(|b| b as u64),
3462 })
3463}
3464
3465pub fn read_text_index_token_table_len_ranged<R: RangeReader + ?Sized>(
3478 reader: &R,
3479 header: &Header,
3480) -> Option<u64> {
3481 if crate::v06::reads(header.version) {
3482 return crate::v06::open::read_token_table_bytes(reader);
3483 }
3484 let (ti_off, ti_len) = header.text_index_payload();
3485 if ti_len == 0 {
3486 return None;
3487 }
3488 read_token_table_len(reader, ti_off, ti_len)
3489}
3490
3491fn read_token_table_len<R: RangeReader + ?Sized>(reader: &R, off: u64, len: u64) -> Option<u64> {
3495 let head = reader.read_at(off, 10u64.min(len)).ok()?;
3496 let (ttlen, n) = crate::varint::read_uvarint(&head)?;
3497 Some((n as u64 + ttlen).min(len))
3498}
3499
3500const NAMED_GRAPH_RESIDENT_MAX: u64 = 1 << 20; pub const TRANSIENT_GRAPH_QUADS: u64 = 1024;
3512
3513const NAMED_SLAB: usize = 1024;
3518
3519const NAMED_WALK_CHUNK: u64 = 64 * 1024;
3523
3524const NAMED_WALK_CHUNK_MAX: u64 = 8 * 1024 * 1024;
3537
3538#[derive(Default)]
3540struct NamedEntry {
3541 meta: std::sync::OnceLock<(String, ByteRange)>,
3544 index: std::sync::OnceLock<Box<GraphIndex>>,
3547}
3548
3549#[derive(Default)]
3553struct NamedWalk {
3554 next: usize,
3556 pos: u64,
3560 buf: Vec<u8>,
3567 buf_off: u64,
3568 chunk: u64,
3575 big_seen: bool,
3582}
3583
3584struct LazyNamedGraphs {
3598 reader: std::sync::Arc<dyn RangeReader + Send + Sync>,
3599 section: ByteRange,
3601 codec: u8,
3602 has_synopsis: bool,
3603 read_concurrency: usize,
3604 perms: PermSet,
3607 #[allow(clippy::type_complexity)]
3611 dir: std::sync::OnceLock<(usize, Box<[std::sync::OnceLock<Box<[NamedEntry]>>]>)>,
3612 walk: std::sync::Mutex<NamedWalk>,
3613 failed: std::sync::atomic::AtomicBool,
3614 tile_cap: std::sync::atomic::AtomicU64,
3620}
3621
3622impl LazyNamedGraphs {
3623 fn new(
3624 reader: std::sync::Arc<dyn RangeReader + Send + Sync>,
3625 section: ByteRange,
3626 codec: u8,
3627 has_synopsis: bool,
3628 read_concurrency: usize,
3629 perms: PermSet,
3630 ) -> Self {
3631 LazyNamedGraphs {
3632 reader,
3633 section,
3634 codec,
3635 has_synopsis,
3636 read_concurrency,
3637 perms,
3638 dir: std::sync::OnceLock::new(),
3639 walk: std::sync::Mutex::new(NamedWalk::default()),
3640 failed: std::sync::atomic::AtomicBool::new(false),
3641 tile_cap: std::sync::atomic::AtomicU64::new(u64::MAX),
3642 }
3643 }
3644
3645 fn set_tile_cap(&self, cap: u64) {
3649 self.tile_cap
3650 .store(cap, std::sync::atomic::Ordering::Relaxed);
3651 self.for_each_opened(|g| {
3652 if g.is_lazy() {
3653 g.set_cache_cap(cap);
3654 }
3655 });
3656 }
3657
3658 fn fail(&self) {
3660 self.failed
3661 .store(true, std::sync::atomic::Ordering::Relaxed);
3662 }
3663
3664 #[allow(clippy::type_complexity)]
3666 fn directory(&self) -> Option<&(usize, Box<[std::sync::OnceLock<Box<[NamedEntry]>>]>)> {
3667 if let Some(d) = self.dir.get() {
3668 return Some(d);
3669 }
3670 let end = self.section.offset.checked_add(self.section.len)?;
3671 let (n, used) = match read_uvarint_at(&self.reader, self.section.offset, end) {
3672 Ok(v) => v,
3673 Err(_) => {
3674 self.fail();
3675 return None;
3676 }
3677 };
3678 if n > self.section.len / 2 {
3681 self.fail();
3682 return None;
3683 }
3684 let Ok(n) = usize::try_from(n) else {
3685 self.fail();
3686 return None;
3687 };
3688 let slabs = n.div_ceil(NAMED_SLAB);
3689 let table: Box<[std::sync::OnceLock<Box<[NamedEntry]>>]> =
3690 (0..slabs).map(|_| std::sync::OnceLock::new()).collect();
3691 let _ = self.dir.set((n, table));
3692 {
3693 let mut w = self.walk.lock().unwrap();
3696 if w.pos == 0 {
3697 w.pos = self.section.offset + used;
3698 }
3699 }
3700 self.dir.get()
3701 }
3702
3703 fn count(&self) -> usize {
3704 self.directory().map(|(n, _)| *n).unwrap_or(0)
3705 }
3706
3707 fn entry(&self, i: usize) -> Option<&NamedEntry> {
3709 let (n, table) = self.directory()?;
3710 if i >= *n {
3711 return None;
3712 }
3713 let slab = table[i / NAMED_SLAB].get_or_init(|| {
3714 let len = NAMED_SLAB.min(n - (i / NAMED_SLAB) * NAMED_SLAB);
3715 (0..len).map(|_| NamedEntry::default()).collect()
3716 });
3717 slab.get(i % NAMED_SLAB)
3718 }
3719
3720 fn next_read_len(w: &mut NamedWalk, pos: u64, end: u64, need: u64) -> u64 {
3728 let cur = w.chunk.max(NAMED_WALK_CHUNK);
3729 w.chunk = (cur * 2).min(NAMED_WALK_CHUNK_MAX);
3730 cur.max(need).min(end - pos)
3731 }
3732
3733 fn ensure_meta(&self, upto: usize, exhaustive: bool) -> Option<()> {
3748 let target = self.entry(upto)?;
3749 if target.meta.get().is_some() {
3750 return Some(());
3751 }
3752 let end = self.section.offset.checked_add(self.section.len)?;
3753 let mut w = self.walk.lock().unwrap();
3754 if exhaustive && !w.big_seen {
3755 w.chunk = NAMED_WALK_CHUNK_MAX;
3756 }
3757 while w.next <= upto {
3758 let pos = w.pos;
3759 if pos >= end {
3760 self.fail();
3762 return None;
3763 }
3764 let have =
3767 |b: &[u8], off: u64, need: u64| pos >= off && pos + need <= off + b.len() as u64;
3768 if !have(&w.buf, w.buf_off, 20.min(end - pos)) {
3769 let len = Self::next_read_len(&mut w, pos, end, 20.min(end - pos));
3770 w.buf = match self.reader.read_at(pos, len) {
3771 Ok(b) => b,
3772 Err(_) => {
3773 self.fail();
3774 return None;
3775 }
3776 };
3777 w.buf_off = pos;
3778 }
3779 let rel = (pos - w.buf_off) as usize;
3782 let Some((ilen, u1)) = w.buf.get(rel..).and_then(read_uvarint) else {
3783 self.fail();
3784 return None;
3785 };
3786 let Some(iri_end) = (u1 as u64)
3787 .checked_add(ilen)
3788 .and_then(|n| pos.checked_add(n))
3789 .filter(|&e| e <= end)
3790 else {
3791 self.fail(); return None;
3793 };
3794 let header_need = (iri_end - pos).saturating_add(10);
3796 if !have(&w.buf, w.buf_off, header_need.min(end - pos)) {
3797 let len = Self::next_read_len(&mut w, pos, end, header_need);
3798 w.buf = match self.reader.read_at(pos, len) {
3799 Ok(b) => b,
3800 Err(_) => {
3801 self.fail();
3802 return None;
3803 }
3804 };
3805 w.buf_off = pos;
3806 }
3807 let rel = (pos - w.buf_off) as usize;
3808 let istart = rel + u1;
3809 let Some(iend) = usize::try_from(ilen)
3810 .ok()
3811 .and_then(|l| istart.checked_add(l))
3812 .filter(|&e| e <= w.buf.len())
3813 else {
3814 self.fail(); return None;
3816 };
3817 let iri = String::from_utf8_lossy(&w.buf[istart..iend]).into_owned();
3818 let Some((clen, u2)) = read_uvarint(&w.buf[iend..]) else {
3819 self.fail();
3820 return None;
3821 };
3822 let cend = match iri_end
3823 .checked_add(u2 as u64)
3824 .and_then(|cstart| cstart.checked_add(clen))
3825 {
3826 Some(e) if e <= end => e,
3827 _ => {
3828 self.fail(); return None;
3830 }
3831 };
3832 if clen > NAMED_GRAPH_RESIDENT_MAX {
3833 w.big_seen = true;
3838 w.chunk = NAMED_WALK_CHUNK;
3839 }
3840 let range = ByteRange {
3841 offset: cend - clen,
3842 len: clen,
3843 };
3844 if let Some(e) = self.entry(w.next) {
3845 let _ = e.meta.set((iri, range));
3846 }
3847 w.pos = cend;
3848 w.next += 1;
3849 }
3850 Some(())
3851 }
3852
3853 fn name_at(&self, i: usize, exhaustive: bool) -> Option<&str> {
3856 self.ensure_meta(i, exhaustive)?;
3857 self.entry(i)?.meta.get().map(|(iri, _)| iri.as_str())
3858 }
3859
3860 fn graph_at(&self, i: usize, exhaustive: bool) -> Option<(&str, &GraphIndex)> {
3863 self.ensure_meta(i, exhaustive)?;
3864 let e = self.entry(i)?;
3865 let (iri, range) = e.meta.get()?;
3866 if e.index.get().is_none() {
3867 let opened = self.open_graph(*range)?;
3868 let _ = e.index.set(Box::new(opened));
3869 }
3870 Some((iri.as_str(), e.index.get()?.as_ref()))
3871 }
3872
3873 fn container_bytes(&self, range: ByteRange) -> Option<Vec<u8>> {
3877 {
3878 let w = self.walk.lock().unwrap();
3879 let buf_end = w.buf_off + w.buf.len() as u64;
3880 if range.offset >= w.buf_off && range.offset + range.len <= buf_end {
3881 let a = (range.offset - w.buf_off) as usize;
3882 return Some(w.buf[a..a + range.len as usize].to_vec());
3883 }
3884 }
3885 match self.reader.read_at(range.offset, range.len) {
3886 Ok(b) if b.len() as u64 == range.len => Some(b),
3888 _ => {
3889 self.fail();
3890 None
3891 }
3892 }
3893 }
3894
3895 fn open_graph(&self, range: ByteRange) -> Option<GraphIndex> {
3900 if range.len <= NAMED_GRAPH_RESIDENT_MAX {
3901 let bytes = self.container_bytes(range)?;
3902 match decode_index_container(&bytes, self.codec, self.perms) {
3903 Ok(g) => {
3904 g.set_size_hint(u64::from(g.triple_count()));
3907 Some(g)
3908 }
3909 Err(_) => {
3910 self.fail();
3911 None
3912 }
3913 }
3914 } else {
3915 match open_index_container_lazy(
3916 &self.reader,
3917 range,
3918 self.codec,
3919 self.has_synopsis,
3920 self.read_concurrency,
3921 self.perms,
3922 self.perms.len(),
3923 ) {
3924 Ok((g, _, _)) => {
3925 let cap = self.tile_cap.load(std::sync::atomic::Ordering::Relaxed);
3929 if cap != u64::MAX {
3930 g.set_cache_cap(cap);
3931 }
3932 Some(g)
3933 }
3934 Err(_) => {
3935 self.fail();
3936 None
3937 }
3938 }
3939 }
3940 }
3941
3942 fn release(&mut self, iri: &str) {
3948 let Some((_, table)) = self.dir.get_mut() else {
3949 return;
3950 };
3951 for slab in table.iter_mut() {
3952 let Some(entries) = slab.get_mut() else {
3953 continue;
3954 };
3955 for e in entries.iter_mut() {
3956 let matches = e
3957 .meta
3958 .get()
3959 .map(|(name, _)| name.as_str() == iri)
3960 .unwrap_or(false);
3961 if matches {
3962 e.index.take();
3963 return;
3964 }
3965 }
3966 }
3967 }
3968
3969 fn for_each_opened(&self, mut f: impl FnMut(&GraphIndex)) {
3971 if let Some((_, table)) = self.dir.get() {
3972 for slab in table.iter().filter_map(|s| s.get()) {
3973 for e in slab.iter() {
3974 if let Some(g) = e.index.get() {
3975 f(g);
3976 }
3977 }
3978 }
3979 }
3980 }
3981}
3982
3983enum NamedGraphsSlot {
3988 Resident(Vec<(String, GraphIndex)>),
3989 Lazy(LazyNamedGraphs),
3990 Quad(crate::quad::QuadNamed),
3993}
3994
3995impl NamedGraphsSlot {
3996 fn directory_bytes(&self) -> u64 {
4000 match self {
4001 NamedGraphsSlot::Resident(v) => v
4002 .iter()
4003 .map(|(iri, g)| iri.capacity() as u64 + g.directory_bytes())
4004 .sum(),
4005 NamedGraphsSlot::Lazy(l) => {
4006 let mut bytes = l.walk.lock().map(|w| w.buf.capacity() as u64).unwrap_or(0);
4007 if let Some((_, table)) = l.dir.get() {
4008 bytes += table.len() as u64
4009 * std::mem::size_of::<std::sync::OnceLock<Box<[NamedEntry]>>>() as u64;
4010 for slab in table.iter().filter_map(|s| s.get()) {
4011 bytes += slab.len() as u64 * std::mem::size_of::<NamedEntry>() as u64;
4012 for e in slab.iter() {
4013 if let Some((iri, _)) = e.meta.get() {
4014 bytes += iri.capacity() as u64;
4015 }
4016 if let Some(g) = e.index.get() {
4017 bytes += g.directory_bytes();
4018 }
4019 }
4020 }
4021 }
4022 bytes
4023 }
4024 NamedGraphsSlot::Quad(q) => q.directory_bytes(),
4025 }
4026 }
4027
4028 fn count(&self) -> usize {
4029 match self {
4030 NamedGraphsSlot::Resident(v) => v.len(),
4031 NamedGraphsSlot::Lazy(l) => l.count(),
4032 NamedGraphsSlot::Quad(q) => q.count(),
4033 }
4034 }
4035
4036 fn name_at<'a>(&'a self, dict: &Dictionary, i: usize, exhaustive: bool) -> Option<&'a str> {
4040 match self {
4041 NamedGraphsSlot::Resident(v) => v.get(i).map(|(iri, _)| iri.as_str()),
4042 NamedGraphsSlot::Lazy(l) => l.name_at(i, exhaustive),
4043 NamedGraphsSlot::Quad(q) => q.name_at(dict, i, exhaustive),
4044 }
4045 }
4046
4047 fn name_owned(&self, dict: &Dictionary, i: usize, exhaustive: bool) -> Option<String> {
4050 match self {
4051 NamedGraphsSlot::Quad(q) => q.name_owned(dict, i, exhaustive),
4052 _ => self.name_at(dict, i, exhaustive).map(str::to_owned),
4053 }
4054 }
4055
4056 fn graph_at<'a>(
4057 &'a self,
4058 dict: &Dictionary,
4059 i: usize,
4060 exhaustive: bool,
4061 ) -> Option<(&'a str, &'a GraphIndex)> {
4062 match self {
4063 NamedGraphsSlot::Resident(v) => v.get(i).map(|(iri, g)| (iri.as_str(), g)),
4064 NamedGraphsSlot::Lazy(l) => l.graph_at(i, exhaustive),
4065 NamedGraphsSlot::Quad(q) => q.graph_at(dict, i, exhaustive),
4066 }
4067 }
4068
4069 fn find<'a>(&'a self, dict: &Dictionary, iri: &str) -> Option<&'a GraphIndex> {
4070 match self {
4071 NamedGraphsSlot::Quad(q) => q.find(dict, iri),
4072 NamedGraphsSlot::Resident(v) => v.iter().find(|(name, _)| name == iri).map(|(_, g)| g),
4073 NamedGraphsSlot::Lazy(l) => {
4074 for i in 0..l.count() {
4079 if l.name_at(i, false)? == iri {
4080 return l.graph_at(i, false).map(|(_, g)| g);
4081 }
4082 }
4083 None
4084 }
4085 }
4086 }
4087
4088 fn load_incomplete(&self) -> bool {
4089 match self {
4090 NamedGraphsSlot::Resident(v) => v.iter().any(|(_, g)| g.load_incomplete()),
4091 NamedGraphsSlot::Lazy(l) => {
4092 if l.failed.load(std::sync::atomic::Ordering::Relaxed) {
4093 return true;
4094 }
4095 let mut bad = false;
4096 l.for_each_opened(|g| bad |= g.load_incomplete());
4097 bad
4098 }
4099 NamedGraphsSlot::Quad(q) => q.load_incomplete(),
4100 }
4101 }
4102
4103 fn reset_load_failures(&self) {
4104 match self {
4105 NamedGraphsSlot::Resident(v) => {
4106 for (_, g) in v {
4107 g.reset_load_failure();
4108 }
4109 }
4110 NamedGraphsSlot::Lazy(l) => {
4111 l.failed.store(false, std::sync::atomic::Ordering::Relaxed);
4112 l.for_each_opened(|g| g.reset_load_failure());
4113 }
4114 NamedGraphsSlot::Quad(q) => q.reset_load_failures(),
4115 }
4116 }
4117
4118 fn resident(
4122 header: &Header,
4123 quad_section: impl FnOnce(u64, u64) -> Result<Vec<u8>, FileError>,
4124 per_graph: impl FnOnce() -> Result<Vec<(String, GraphIndex)>, FileError>,
4125 ) -> Result<Self, FileError> {
4126 check_named_layout(header)?;
4127 if let Some(q) = header.quad_index_section() {
4128 let bytes = quad_section(q.offset, q.length)?;
4129 return Ok(NamedGraphsSlot::Quad(crate::quad::QuadNamed::resident(
4130 bytes,
4131 header.block_codec,
4132 header.perms,
4133 )));
4134 }
4135 Ok(NamedGraphsSlot::Resident(if header.named_graphs_len > 0 {
4136 per_graph()?
4137 } else {
4138 Vec::new()
4139 }))
4140 }
4141}
4142
4143pub struct Rete {
4145 header: Header,
4146 dict: Dictionary,
4147 index: GraphIndex,
4148 index_section_ranges: [ByteRange; NUM_PERMS],
4149 tile_ranges: [Vec<(u32, u32, ByteRange)>; NUM_PERMS],
4153 pyramid: PyramidSlot,
4154 text_index: TextIndexSlot,
4155 labels: SectionSlot<crate::label_index::LabelIndex>,
4157 schema: SectionSlot<crate::schema_section::SchemaMeta>,
4159 named_graphs: NamedGraphsSlot,
4160 metadata: Vec<u8>,
4165 service_client: Option<Box<dyn crate::service::ServiceClient>>,
4170 service_error: std::sync::Mutex<Option<String>>,
4174 spill_threshold: std::sync::atomic::AtomicU64,
4177 v06: Option<std::sync::Arc<crate::v06::open::V06File>>,
4179}
4180
4181impl Rete {
4182 pub fn open(bytes: &[u8]) -> Result<Self, FileError> {
4185 #[cfg(feature = "v06-parity")]
4186 if let Some(v6) = parity_image(bytes) {
4187 return Self::open(&v6);
4188 }
4189 if crate::v06::open::is_v06(bytes) {
4190 let r: std::sync::Arc<dyn RangeReader + Send + Sync> =
4193 std::sync::Arc::new(crate::reader::BytesReader(std::sync::Arc::from(bytes)));
4194 let mut rete = Self::open_v06(r, bytes, false)?;
4195 rete.metadata = rete
4196 .v06
4197 .as_ref()
4198 .and_then(|f| f.card().ok().flatten())
4199 .unwrap_or_default();
4200 return Ok(rete);
4201 }
4202 let header = Header::from_bytes(bytes)?;
4203
4204 let region = |off: u64, len: u64| -> Result<&[u8], FileError> {
4208 checked_slice(bytes, off, len)
4209 .ok_or(FileError::Container("section range out of bounds"))
4210 };
4211
4212 let dict = decode_dictionary_container(
4213 region(header.dictionary_offset, header.dictionary_len)?,
4214 header.dict_codec,
4215 )?;
4216
4217 check_named_layout(&header)?;
4218 let index_bytes = region(header.root_dir_offset, header.root_dir_len)?;
4219 let (index, _) = decode_root_index_container(index_bytes, &header)?;
4220 let index_section_ranges = decode_index_section_ranges(
4221 index_bytes,
4222 header.root_dir_offset,
4223 header.perms,
4224 header.index_container_sections(),
4225 )?;
4226
4227 let pyramid = PyramidSlot::Resident(if header.pyramid_meta_len > 0 {
4228 Some(
4229 PyramidMeta::decode(region(header.pyramid_meta_offset, header.pyramid_meta_len)?)
4230 .map_err(|_| FileError::Container("malformed pyramid meta"))?,
4231 )
4232 } else {
4233 None
4234 });
4235
4236 let (ti_off, ti_len) = header.text_index_payload();
4239 let text_index = resident_text_index_slot(
4240 if ti_len > 0 {
4241 Some(region(ti_off, ti_len)?)
4242 } else {
4243 None
4244 },
4245 header.block_codec,
4246 )?;
4247 let labels = resident_label_slot(&header, ®ion);
4248 let schema = resident_schema_slot(&header, ®ion);
4249
4250 let named_graphs = NamedGraphsSlot::resident(
4251 &header,
4252 |off, len| Ok(region(off, len)?.to_vec()),
4253 || {
4254 decode_named_graphs(
4255 region(header.named_graphs_offset, header.named_graphs_len)?,
4256 header.block_codec,
4257 header.perms,
4258 )
4259 },
4260 )?;
4261
4262 let metadata = if header.metadata_len > 0 {
4263 region(header.metadata_offset, header.metadata_len)?.to_vec()
4264 } else {
4265 Vec::new()
4266 };
4267
4268 let tile_ranges =
4269 tile_file_ranges(index_bytes, header.root_dir_offset, &index_section_ranges);
4270 Ok(Self {
4271 header,
4272 dict,
4273 index,
4274 index_section_ranges,
4275 tile_ranges,
4276 pyramid,
4277 text_index,
4278 labels,
4279 schema,
4280 named_graphs,
4281 metadata,
4282 service_client: None,
4283 service_error: std::sync::Mutex::new(None),
4284 spill_threshold: std::sync::atomic::AtomicU64::new(u64::MAX),
4285 v06: None,
4286 })
4287 }
4288
4289 pub fn set_service_client(&mut self, client: Box<dyn crate::service::ServiceClient>) {
4294 self.service_client = Some(client);
4295 }
4296
4297 pub(crate) fn service_client(&self) -> Option<&dyn crate::service::ServiceClient> {
4298 self.service_client.as_deref()
4299 }
4300
4301 pub(crate) fn record_service_error(&self, msg: &str) {
4303 let mut e = self.service_error.lock().unwrap();
4304 if e.is_none() {
4305 *e = Some(msg.to_string());
4306 }
4307 }
4308
4309 pub(crate) fn take_service_error(&self) -> Option<String> {
4312 self.service_error.lock().unwrap().take()
4313 }
4314
4315 pub fn header(&self) -> &Header {
4316 &self.header
4317 }
4318
4319 pub fn file_layout(&self) -> Vec<LayoutSegment> {
4325 if let Some(f) = &self.v06 {
4326 return v06_layout(f);
4327 }
4328 let h = &self.header;
4329 let seg = |kind: &'static str, label: String, offset: u64, len: u64| LayoutSegment {
4330 kind,
4331 label,
4332 offset,
4333 len,
4334 };
4335 let mut out = vec![seg(
4341 "header",
4342 format!("header (fixed {} bytes)", crate::header::HEADER_LEN),
4343 0,
4344 crate::header::HEADER_LEN as u64,
4345 )];
4346 if h.metadata_len > 0 {
4347 out.push(seg(
4348 "metadata",
4349 "metadata (dataset card)".into(),
4350 h.metadata_offset,
4351 h.metadata_len,
4352 ));
4353 }
4354 out.push(seg(
4355 "dictionary",
4356 "dictionary (4 front-coded term sections)".into(),
4357 h.dictionary_offset,
4358 h.dictionary_len,
4359 ));
4360 for (si, perm) in crate::index::ALL_PERMS.into_iter().enumerate() {
4361 let sec = self.index_section_ranges[si];
4362 if sec.len == 0 {
4363 continue;
4364 }
4365 let first_tile = self.tile_ranges[si]
4366 .first()
4367 .map(|&(_, _, r)| r.offset)
4368 .unwrap_or(sec.offset + sec.len);
4369 if first_tile > sec.offset {
4370 out.push(seg(
4371 "directory",
4372 format!("{} tile directory", perm.name()),
4373 sec.offset,
4374 first_tile - sec.offset,
4375 ));
4376 }
4377 for (ti, &(min_a, max_a, r)) in self.tile_ranges[si].iter().enumerate() {
4378 out.push(seg(
4379 "tile",
4380 format!("{} tile {ti} (leading ids {min_a}..{max_a})", perm.name()),
4381 r.offset,
4382 r.len,
4383 ));
4384 }
4385 }
4386 if h.pyramid_meta_len > 0 {
4387 out.push(seg(
4388 "pyramid",
4389 "pyramid summary (communities + superedges)".into(),
4390 h.pyramid_meta_offset,
4391 h.pyramid_meta_len,
4392 ));
4393 }
4394 if h.named_graphs_len > 0 {
4395 out.push(seg(
4396 "named-graphs",
4397 format!("named graphs ({})", self.named_graphs.count()),
4398 h.named_graphs_offset,
4399 h.named_graphs_len,
4400 ));
4401 }
4402 if let Some(s) = h.label_index_section() {
4403 let label = match self.labels.get_if_loaded() {
4404 Some(li) => format!("label index ({} entries)", li.entry_count()),
4405 None => "label index".to_string(),
4406 };
4407 out.push(seg("label-index", label, s.offset, s.length));
4408 }
4409 if let Some(s) = h.schema_section() {
4410 out.push(seg(
4411 "schema",
4412 "schema (classes, query_stats, shapes)".into(),
4413 s.offset,
4414 s.length,
4415 ));
4416 }
4417 if let Some(q) = h.quad_index_section() {
4418 out.push(seg(
4419 "quad-index",
4420 format!("quad index ({} named graphs)", self.named_graphs.count()),
4421 q.offset,
4422 q.length,
4423 ));
4424 }
4425 out.sort_by_key(|s| s.offset);
4426 out
4427 }
4428
4429 pub fn metadata(&self) -> Option<&[u8]> {
4434 if self.metadata.is_empty() {
4435 None
4436 } else {
4437 Some(&self.metadata)
4438 }
4439 }
4440
4441 pub fn dictionary(&self) -> &Dictionary {
4442 &self.dict
4443 }
4444
4445 pub fn pyramid(&self) -> Option<&PyramidMeta> {
4447 match &self.pyramid {
4448 PyramidSlot::Resident(p) => p.as_ref(),
4449 PyramidSlot::Lazy { loader, cell } => cell.get_or_init(loader).as_ref(),
4451 }
4452 }
4453
4454 pub fn pyramid_if_loaded(&self) -> Option<&PyramidMeta> {
4459 match &self.pyramid {
4460 PyramidSlot::Resident(p) => p.as_ref(),
4461 PyramidSlot::Lazy { cell, .. } => cell.get().and_then(|o| o.as_ref()),
4462 }
4463 }
4464
4465 pub fn schema(&self) -> Option<&crate::schema_section::SchemaMeta> {
4471 self.schema.get()
4472 }
4473
4474 pub fn schema_or_pyramid(
4478 &self,
4479 ) -> Option<std::borrow::Cow<'_, crate::schema_section::SchemaMeta>> {
4480 if let Some(s) = self.schema() {
4481 return Some(std::borrow::Cow::Borrowed(s));
4482 }
4483 self.pyramid()
4484 .map(|p| std::borrow::Cow::Owned(crate::schema_section::SchemaMeta::from_pyramid(p)))
4485 }
4486
4487 pub fn predicate_stats(&self) -> &[crate::meta::PredStat] {
4492 if let Some(s) = self.schema().filter(|s| !s.predicate_stats.is_empty()) {
4493 return &s.predicate_stats;
4494 }
4495 self.pyramid_if_loaded()
4496 .map(|p| p.predicate_stats.as_slice())
4497 .unwrap_or(&[])
4498 }
4499
4500 pub(crate) fn planner_stats(&self, fault: bool) -> &[crate::meta::PredStat] {
4505 let schema = if fault {
4506 self.schema.get()
4507 } else {
4508 self.schema.get_if_loaded()
4509 };
4510 if let Some(s) = schema.filter(|s| !s.predicate_stats.is_empty()) {
4511 return &s.predicate_stats;
4512 }
4513 self.pyramid_if_loaded()
4514 .map(|p| p.predicate_stats.as_slice())
4515 .unwrap_or(&[])
4516 }
4517
4518 pub fn char_sets(&self) -> &[crate::meta::CharSet] {
4521 if let Some(s) = self.schema().filter(|s| !s.char_sets.is_empty()) {
4522 return &s.char_sets;
4523 }
4524 self.pyramid_if_loaded()
4525 .map(|p| p.char_sets.as_slice())
4526 .unwrap_or(&[])
4527 }
4528
4529 pub fn label_index(&self) -> &[crate::meta::LabelEntry] {
4535 self.pyramid_if_loaded()
4536 .map(|p| p.label_index.as_slice())
4537 .unwrap_or(&[])
4538 }
4539
4540 pub fn has_label_index(&self) -> bool {
4542 self.header.label_index_section().is_some()
4543 }
4544
4545 pub fn label_index_section(&self) -> Option<&crate::label_index::LabelIndex> {
4547 self.labels.get()
4548 }
4549
4550 pub fn prefix_search(&self, prefix: &str, limit: usize) -> Vec<(String, String)> {
4557 if let Some(li) = self.labels.get() {
4558 return li.prefix_search(prefix, limit);
4559 }
4560 let Some(pyr) = self.pyramid() else {
4561 return Vec::new();
4562 };
4563 resolve_label_hits(&self.dict, pyr.prefix_search(prefix, limit))
4564 }
4565
4566 pub(crate) fn text_index(&self) -> Option<&crate::text_index::TextIndex> {
4569 self.text_index.index()
4570 }
4571
4572 pub fn has_text_index(&self) -> bool {
4575 self.header.text_index_len > 0
4576 }
4577
4578 pub fn text_index_scope(&self) -> Option<crate::text_index::TextIndexScope> {
4582 self.text_index().map(|ti| ti.scope().clone())
4583 }
4584
4585 pub fn text_index_token_table_len(&self) -> Option<u64> {
4600 self.text_index.token_table_len()
4601 }
4602
4603 pub fn text_search(&self, words: &[&str], prefix: Option<&str>, limit: usize) -> Vec<String> {
4613 text_search_in(self.text_index(), &self.dict, words, prefix, limit)
4614 }
4615
4616 pub fn default_index(&self) -> &GraphIndex {
4618 &self.index
4619 }
4620
4621 pub fn dump(&self, graph: Option<&str>) -> Vec<TermTriple> {
4623 let index = match graph {
4624 None => &self.index,
4625 Some(g) => match self.graph_index(g) {
4626 Some(i) => i,
4627 None => return Vec::new(),
4628 },
4629 };
4630 index
4631 .match_pattern((None, None, None))
4632 .into_iter()
4633 .filter_map(|(s, p, o)| {
4634 Some((
4635 self.dict.subject_term(s)?,
4636 self.dict.predicate_term(p)?,
4637 self.dict.object_term(o)?,
4638 ))
4639 })
4640 .collect()
4641 }
4642
4643 pub fn dump_each<F: FnMut(&str, &str, &str)>(&self, graph: Option<&str>, f: F) {
4659 self.dump_filtered_each(graph, None, None, None, f)
4660 }
4661
4662 pub fn dump_filtered_each<F: FnMut(&str, &str, &str)>(
4733 &self,
4734 graph: Option<&str>,
4735 s: Option<&str>,
4736 p: Option<&str>,
4737 o: Option<&str>,
4738 mut f: F,
4739 ) {
4740 let index = match graph {
4741 None => Some(&self.index),
4742 Some(g) => self.graph_index(g),
4743 };
4744 let Some(index) = index else { return };
4745 let Some(pattern) = self.resolve_query_pattern(s, p, o) else {
4748 return;
4749 };
4750 let dict = &self.dict;
4751 const WINDOW: usize = 4096;
4796 let cap = dict.cache_cap();
4807 let prefetch_window =
4808 cap == u64::MAX || cap >= (WINDOW as u64) * 2 * (DICT_CHUNK_BUDGET as u64);
4809 const PREFETCH_BATCH: usize = 64;
4816 let prefetch_batch = if cap == u64::MAX {
4817 usize::MAX
4818 } else {
4819 PREFETCH_BATCH
4820 };
4821 let mut ids: Vec<(u32, u32, u32)> = Vec::with_capacity(WINDOW);
4822 let mut nodes: Vec<u32> = Vec::with_capacity(WINDOW * 2);
4823 let mut preds: Vec<u32> = Vec::with_capacity(WINDOW);
4824 let mut resolver = crate::dictionary::WindowResolver::default();
4825 let mut flush = |ids: &mut Vec<(u32, u32, u32)>,
4826 resolver: &mut crate::dictionary::WindowResolver,
4827 f: &mut F| {
4828 if ids.is_empty() {
4829 return;
4830 }
4831 if prefetch_window {
4835 nodes.clear();
4836 preds.clear();
4837 for &(s, p, o) in ids.iter() {
4838 nodes.push(dict.subject_node(s));
4839 nodes.push(dict.object_node(o));
4840 preds.push(p);
4841 }
4842 dict.prefetch_terms_batched(&nodes, &preds, prefetch_batch);
4843 }
4844 dict.resolve_window(ids, resolver, |s, p, o| f(s, p, o));
4845 ids.clear();
4846 };
4847 for t in index.scan_iter(pattern) {
4848 ids.push(t);
4849 if ids.len() == WINDOW {
4850 flush(&mut ids, &mut resolver, &mut f);
4851 }
4852 }
4853 flush(&mut ids, &mut resolver, &mut f);
4854 }
4855
4856 pub fn dump_plan(
4864 &self,
4865 graph: Option<&str>,
4866 s: Option<&str>,
4867 p: Option<&str>,
4868 o: Option<&str>,
4869 ) -> DumpPlan {
4870 let index = match graph {
4871 None => Some(&self.index),
4872 Some(g) => self.graph_index(g),
4873 };
4874 let scan = index
4875 .zip(self.resolve_query_pattern(s, p, o))
4876 .map(|(ix, pattern)| ix.scan_plan(pattern));
4877 DumpPlan {
4878 scan,
4879 dictionary_bytes: match &self.v06 {
4880 Some(f) => f.section(crate::v06::kind::DICT_DATA).map_or(0, |r| r.len),
4881 None => self.header.dictionary_len,
4882 },
4883 }
4884 }
4885
4886 pub fn dump_iter(&self, graph: Option<&str>) -> impl Iterator<Item = TermTriple> + '_ {
4904 self.query_iter(graph, None, None, None)
4905 }
4906
4907 pub fn query_iter(
4918 &self,
4919 graph: Option<&str>,
4920 s: Option<&str>,
4921 p: Option<&str>,
4922 o: Option<&str>,
4923 ) -> impl Iterator<Item = TermTriple> + '_ {
4924 let index = match graph {
4925 None => Some(&self.index),
4926 Some(g) => self.graph_index(g),
4927 };
4928 index
4929 .zip(self.resolve_query_pattern(s, p, o))
4930 .into_iter()
4931 .flat_map(|(ix, pattern)| ix.scan_iter(pattern))
4932 .filter_map(move |(s, p, o)| {
4933 Some((
4934 self.dict.subject_term(s)?,
4935 self.dict.predicate_term(p)?,
4936 self.dict.object_term(o)?,
4937 ))
4938 })
4939 }
4940
4941 pub fn query_batch(
4960 &self,
4961 graph: Option<&str>,
4962 s: Option<&str>,
4963 p: Option<&str>,
4964 o: Option<&str>,
4965 cursor: u64,
4966 max_quads: usize,
4967 ) -> (Vec<TermTriple>, u64, bool) {
4968 let index = match graph {
4969 None => &self.index,
4970 Some(g) => match self.graph_index(g) {
4973 Some(i) => i,
4974 None => return (Vec::new(), cursor, true),
4975 },
4976 };
4977 let Some(pattern) = self.resolve_query_pattern(s, p, o) else {
4980 return (Vec::new(), cursor, true);
4981 };
4982 let (ids, next, done) = index.scan_batch(pattern, cursor, max_quads);
4983 if !ids.is_empty() {
4987 let mut nodes = Vec::with_capacity(ids.len() * 2);
4988 let mut preds = Vec::with_capacity(ids.len());
4989 for &(s, p, o) in &ids {
4990 nodes.push(self.dict.subject_node(s));
4991 nodes.push(self.dict.object_node(o));
4992 preds.push(p);
4993 }
4994 self.dict.prefetch_terms(&nodes, &preds);
4995 }
4996 let triples = ids
4997 .into_iter()
4998 .filter_map(|(s, p, o)| {
4999 Some((
5000 self.dict.subject_term(s)?,
5001 self.dict.predicate_term(p)?,
5002 self.dict.object_term(o)?,
5003 ))
5004 })
5005 .collect();
5006 (triples, next, done)
5007 }
5008
5009 pub fn dump_batch(
5035 &self,
5036 graph: Option<&str>,
5037 cursor: u32,
5038 max_quads: usize,
5039 ) -> (Vec<TermTriple>, u32, bool) {
5040 let index = match graph {
5041 None => self.default_index(),
5042 Some(g) => match self.graph_index(g) {
5045 Some(i) => i,
5046 None => return (Vec::new(), cursor, true),
5047 },
5048 };
5049 let spo = IndexPermutation::Spo.section_index();
5053 let Some((first, last)) = index.leading_bounds(spo) else {
5054 return (Vec::new(), cursor, true); };
5056
5057 let mut sid = cursor.max(first);
5058 let mut probes = max_quads.saturating_mul(4).max(1 << 16);
5059 let mut ids: Vec<(u32, u32, u32)> = Vec::new();
5060 let mut exhausted = false;
5061 while sid <= last && probes > 0 {
5062 probes -= 1;
5063 let hits = index.match_pattern((Some(sid), None, None));
5064 if hits.is_empty() {
5065 match index.next_leading(IndexPermutation::Spo.section_index(), sid) {
5075 Some(next) if next > sid => {
5076 sid = next;
5077 continue;
5078 }
5079 None if !index.load_incomplete() => {
5080 exhausted = true;
5081 break;
5082 }
5083 _ => {}
5084 }
5085 match index.next_tile_start(spo, sid) {
5086 None => {
5087 exhausted = true;
5088 break;
5089 }
5090 Some(next) if next > sid => {
5091 sid = next;
5092 continue;
5093 }
5094 Some(_) => {}
5095 }
5096 } else {
5097 ids.extend(hits);
5098 }
5099 if sid == u32::MAX {
5100 exhausted = true;
5101 break;
5102 }
5103 sid += 1;
5104 if ids.len() >= max_quads {
5105 break;
5106 }
5107 }
5108 let done = exhausted || sid > last;
5109
5110 let dict = self.dictionary();
5117 if !ids.is_empty() {
5118 let mut nodes = Vec::with_capacity(ids.len() * 2);
5119 let mut preds = Vec::with_capacity(ids.len());
5120 for &(s, p, o) in &ids {
5121 nodes.push(dict.subject_node(s));
5122 nodes.push(dict.object_node(o));
5123 preds.push(p);
5124 }
5125 dict.prefetch_terms(&nodes, &preds);
5126 }
5127 let triples = ids
5128 .into_iter()
5129 .filter_map(|(s, p, o)| {
5130 Some((
5131 dict.subject_term(s)?,
5132 dict.predicate_term(p)?,
5133 dict.object_term(o)?,
5134 ))
5135 })
5136 .collect();
5137 (triples, sid, done)
5138 }
5139
5140 pub fn named_graph_count(&self) -> usize {
5143 self.named_graphs.count()
5144 }
5145
5146 pub fn named_graph_quad_count(&self, i: usize) -> Option<u64> {
5151 match &self.named_graphs {
5152 NamedGraphsSlot::Quad(q) => q.quad_count_at(i),
5153 _ => None,
5154 }
5155 }
5156
5157 pub fn named_graph_transient(&self, i: usize) -> Option<GraphIndex> {
5166 match &self.named_graphs {
5167 NamedGraphsSlot::Quad(q) => q.transient_view(i, TRANSIENT_GRAPH_QUADS),
5168 _ => None,
5169 }
5170 }
5171
5172 pub(crate) fn named_graphs_with_subjects(
5179 &self,
5180 subjects: &std::collections::BTreeSet<u32>,
5181 ) -> Option<Vec<usize>> {
5182 match &self.named_graphs {
5183 NamedGraphsSlot::Quad(q) => q.graphs_with_subjects(subjects),
5184 _ => None,
5185 }
5186 }
5187
5188 pub fn named_quad_count(&self) -> Option<u64> {
5193 match &self.named_graphs {
5194 NamedGraphsSlot::Quad(q) => Some(q.quad_count()),
5195 _ => None,
5196 }
5197 }
5198
5199 pub(crate) fn index_triples(&self, index: &GraphIndex) -> u64 {
5205 index.size_hint().unwrap_or(self.header().quad_count)
5206 }
5207
5208 pub fn named_graph_name_at(&self, i: usize) -> Option<&str> {
5211 self.named_graphs.name_at(&self.dict, i, false)
5212 }
5213
5214 pub fn named_graph_at(&self, i: usize) -> Option<(&str, &GraphIndex)> {
5218 self.named_graphs.graph_at(&self.dict, i, false)
5219 }
5220
5221 pub(crate) fn named_graph_name_owned_demand(
5229 &self,
5230 i: usize,
5231 exhaustive: bool,
5232 ) -> Option<String> {
5233 self.named_graphs.name_owned(&self.dict, i, exhaustive)
5234 }
5235
5236 pub(crate) fn named_graph_ordinal(&self, iri: &str) -> Option<usize> {
5240 match &self.named_graphs {
5241 NamedGraphsSlot::Quad(q) => q.ordinal_of_iri(&self.dict, iri),
5242 _ => None,
5243 }
5244 }
5245
5246 pub(crate) fn named_graph_ordinal_of_id(&self, g: u32) -> Option<usize> {
5249 match &self.named_graphs {
5250 NamedGraphsSlot::Quad(q) => q.ordinal_of_id(g),
5251 _ => None,
5252 }
5253 }
5254
5255 pub(crate) fn named_quad_scan(
5260 &self,
5261 pat: (Option<u32>, Option<u32>, Option<u32>),
5262 ) -> Option<crate::quad::QuadScan> {
5263 match &self.named_graphs {
5264 NamedGraphsSlot::Quad(q) => q.scan(pat),
5265 _ => None,
5266 }
5267 }
5268
5269 pub(crate) fn quad_named(&self) -> Option<&crate::quad::QuadNamed> {
5271 match &self.named_graphs {
5272 NamedGraphsSlot::Quad(q) => Some(q),
5273 _ => None,
5274 }
5275 }
5276
5277 pub(crate) fn named_graph_at_demand(
5280 &self,
5281 i: usize,
5282 exhaustive: bool,
5283 ) -> Option<(&str, &GraphIndex)> {
5284 self.named_graphs.graph_at(&self.dict, i, exhaustive)
5285 }
5286
5287 pub fn graph_names(&self) -> Vec<&str> {
5292 (0..self.named_graphs.count())
5293 .filter_map(|i| self.named_graphs.name_at(&self.dict, i, false))
5294 .collect()
5295 }
5296
5297 pub fn graph_index(&self, iri: &str) -> Option<&GraphIndex> {
5299 self.named_graphs.find(&self.dict, iri)
5300 }
5301
5302 pub fn match_ids(
5305 &self,
5306 pattern: (Option<u32>, Option<u32>, Option<u32>),
5307 ) -> Vec<(u32, u32, u32)> {
5308 self.index.match_pattern(pattern)
5309 }
5310
5311 pub fn predicate_pairs(&self, predicate: &str) -> Vec<(u32, u32)> {
5314 let pid = match self.dict.predicate_id(predicate) {
5315 Some(p) => p,
5316 None => return Vec::new(),
5317 };
5318 self.index
5319 .match_pattern((None, Some(pid), None))
5320 .into_iter()
5321 .map(|(s, _p, o)| (self.dict.subject_node(s), self.dict.object_node(o)))
5322 .collect()
5323 }
5324
5325 pub fn open_ranged<R: RangeReader>(reader: &R) -> Result<Self, FileError> {
5329 let head = reader.read_at(0, (HEADER_LEN as u64).min(reader.len()))?;
5330 if crate::v06::open::is_v06(&head) {
5331 let mut all = head;
5334 let at = all.len() as u64;
5335 if reader.len() > at {
5336 all.extend_from_slice(&reader.read_at(at, reader.len() - at)?);
5337 }
5338 return Self::open(&all);
5339 }
5340 let header = Header::from_bytes(&head)?;
5341
5342 let dict_bytes = reader.read_at(header.dictionary_offset, header.dictionary_len)?;
5343 let dict = decode_dictionary_container(&dict_bytes, header.dict_codec)?;
5344
5345 check_named_layout(&header)?;
5346 let index_bytes = reader.read_at(header.root_dir_offset, header.root_dir_len)?;
5347 let (index, _) = decode_root_index_container(&index_bytes, &header)?;
5348 let index_section_ranges = decode_index_section_ranges(
5349 &index_bytes,
5350 header.root_dir_offset,
5351 header.perms,
5352 header.index_container_sections(),
5353 )?;
5354
5355 let pyramid = PyramidSlot::Resident(if header.pyramid_meta_len > 0 {
5356 let mb = reader.read_at(header.pyramid_meta_offset, header.pyramid_meta_len)?;
5357 Some(
5358 PyramidMeta::decode(&mb)
5359 .map_err(|_| FileError::Container("malformed pyramid meta"))?,
5360 )
5361 } else {
5362 None
5363 });
5364
5365 let (ti_off, ti_len) = header.text_index_payload();
5368 let text_index_bytes = if ti_len > 0 {
5369 Some(reader.read_at(ti_off, ti_len)?)
5370 } else {
5371 None
5372 };
5373 let text_index = resident_text_index_slot(text_index_bytes.as_deref(), header.block_codec)?;
5374 let labels = SectionSlot::Resident(header.label_index_section().and_then(|s| {
5377 let b = reader.read_at(s.offset, s.length).ok()?;
5378 crate::label_index::LabelIndex::from_section(&b, header.block_codec).ok()
5379 }));
5380 let schema = SectionSlot::Resident(read_schema_with_header(reader, &header));
5381
5382 let named_graphs = NamedGraphsSlot::resident(
5383 &header,
5384 |off, len| Ok(reader.read_at(off, len)?),
5385 || {
5386 let nb = reader.read_at(header.named_graphs_offset, header.named_graphs_len)?;
5387 decode_named_graphs(&nb, header.block_codec, header.perms)
5388 },
5389 )?;
5390
5391 let tile_ranges =
5395 tile_file_ranges(&index_bytes, header.root_dir_offset, &index_section_ranges);
5396 Ok(Self {
5397 header,
5398 dict,
5399 index,
5400 index_section_ranges,
5401 tile_ranges,
5402 pyramid,
5403 text_index,
5404 labels,
5405 schema,
5406 named_graphs,
5407 metadata: Vec::new(),
5408 service_client: None,
5409 service_error: std::sync::Mutex::new(None),
5410 spill_threshold: std::sync::atomic::AtomicU64::new(u64::MAX),
5411 v06: None,
5412 })
5413 }
5414
5415 fn open_v06(
5421 reader: std::sync::Arc<dyn RangeReader + Send + Sync>,
5422 first: &[u8],
5423 budget: bool,
5424 ) -> Result<Self, FileError> {
5425 let f = std::sync::Arc::new(crate::v06::open::V06File::open(reader.clone(), first)?);
5426 let header = crate::v06::logical_header(&f.h);
5427 let rc = reader.concurrency();
5428 let dict = f.dictionary([true; 4])?;
5429 let index = f.index(rc)?;
5430 let (pyramid, text_index, labels, schema) = v06_slots(&f);
5431 let named_graphs = match f.quad(rc) {
5432 Some(q) => NamedGraphsSlot::Quad(q?),
5433 None => NamedGraphsSlot::Resident(Vec::new()),
5434 };
5435 let rete = Self {
5436 header,
5437 dict,
5438 index,
5439 index_section_ranges: [ByteRange::default(); NUM_PERMS],
5440 tile_ranges: Default::default(),
5441 pyramid,
5442 text_index,
5443 labels,
5444 schema,
5445 named_graphs,
5446 metadata: Vec::new(),
5447 service_client: None,
5448 service_error: std::sync::Mutex::new(None),
5449 spill_threshold: std::sync::atomic::AtomicU64::new(u64::MAX),
5450 v06: Some(f),
5451 };
5452 #[cfg(not(target_arch = "wasm32"))]
5453 if budget {
5454 rete.set_memory_budget(match crate::sysmem::default_query_budget_mb() {
5455 0 => None,
5456 mb => Some(mb << 20),
5457 });
5458 }
5459 #[cfg(target_arch = "wasm32")]
5460 let _ = budget;
5461 Ok(rete)
5462 }
5463
5464 pub fn v06(&self) -> Option<&crate::v06::open::V06File> {
5466 self.v06.as_deref()
5467 }
5468
5469 pub fn open_ranged_lazy<R: RangeReader + Send + Sync + 'static>(
5481 reader: R,
5482 ) -> Result<Self, FileError> {
5483 Self::open_ranged_lazy_with(reader, crate::v06::FIRST_READ)
5484 }
5485
5486 pub fn open_ranged_lazy_with<R: RangeReader + Send + Sync + 'static>(
5491 reader: R,
5492 first_read: u64,
5493 ) -> Result<Self, FileError> {
5494 let first_len = first_read.max(HEADER_LEN as u64).min(reader.len());
5497 let first: std::sync::Arc<[u8]> = std::sync::Arc::from(reader.read_at(0, first_len)?);
5498 #[cfg(feature = "v06-parity")]
5499 if !crate::v06::open::is_v06(&first) {
5500 let all = reader.read_at(0, reader.len())?;
5501 if let Some(v6) = parity_image(&all) {
5502 let r: std::sync::Arc<dyn RangeReader + Send + Sync> =
5503 std::sync::Arc::new(crate::reader::BytesReader(std::sync::Arc::from(v6)));
5504 let head = r.read_at(0, crate::v06::FIRST_READ.min(r.len()))?;
5505 return Self::open_v06(r, &head, true);
5506 }
5507 }
5508 let reader = crate::reader::PrefixReader::new(reader, first.clone());
5509 if crate::v06::open::is_v06(&first) {
5510 let r: std::sync::Arc<dyn RangeReader + Send + Sync> = std::sync::Arc::new(reader);
5511 return Self::open_v06(r, &first, true);
5512 }
5513 let head = reader.read_at(0, HEADER_LEN as u64)?;
5514 let header = Header::from_bytes(&head)?;
5515 check_named_layout(&header)?;
5516 let reader = std::sync::Arc::new(reader);
5517 let read_concurrency = reader.concurrency();
5520
5521 let open_dict = || ranged_chunked_dictionary(&reader, &header, [true; 4]);
5525
5526 let reader_dyn: std::sync::Arc<dyn RangeReader + Send + Sync> = reader.clone();
5530 let open_index = || {
5531 open_index_container_lazy(
5532 &reader_dyn,
5533 ByteRange {
5534 offset: header.root_dir_offset,
5535 len: header.root_dir_len,
5536 },
5537 header.block_codec,
5538 header.has_tile_synopsis(),
5539 read_concurrency,
5540 header.perms,
5541 header.index_container_sections(),
5542 )
5543 };
5544
5545 let (dict, index) = open_side_by_side(read_concurrency, open_dict, open_index);
5552 let dict = dict?;
5553 let (index, index_section_ranges, tile_ranges) = index?;
5554
5555 let pyramid = ranged_pyramid_slot(&reader, &header);
5559
5560 let text_index = ranged_text_index_slot(&reader, &header);
5565
5566 let labels = ranged_label_slot(&reader, &header);
5570 let schema = ranged_schema_slot(&reader, &header);
5571
5572 let named_graphs = if let Some(q) = header.quad_index_section() {
5579 NamedGraphsSlot::Quad(crate::quad::QuadNamed::new(
5583 reader_dyn,
5584 ByteRange {
5585 offset: q.offset,
5586 len: q.length,
5587 },
5588 header.block_codec,
5589 header.perms,
5590 read_concurrency,
5591 ))
5592 } else if header.named_graphs_len > 0 {
5593 NamedGraphsSlot::Lazy(LazyNamedGraphs::new(
5594 reader_dyn,
5595 ByteRange {
5596 offset: header.named_graphs_offset,
5597 len: header.named_graphs_len,
5598 },
5599 header.block_codec,
5600 header.has_tile_synopsis(),
5601 read_concurrency,
5602 header.perms,
5603 ))
5604 } else {
5605 NamedGraphsSlot::Resident(Vec::new())
5606 };
5607
5608 let rete = Self {
5609 header,
5610 dict,
5611 index,
5612 index_section_ranges,
5613 tile_ranges,
5614 pyramid,
5615 text_index,
5616 labels,
5617 schema,
5618 named_graphs,
5619 metadata: Vec::new(),
5620 service_client: None,
5621 service_error: std::sync::Mutex::new(None),
5622 spill_threshold: std::sync::atomic::AtomicU64::new(u64::MAX),
5623 v06: None,
5624 };
5625 #[cfg(not(target_arch = "wasm32"))]
5637 rete.set_memory_budget(match crate::sysmem::default_query_budget_mb() {
5638 0 => None,
5639 mb => Some(mb << 20),
5640 });
5641 Ok(rete)
5642 }
5643
5644 pub fn index_incomplete(&self) -> bool {
5649 self.index.load_incomplete()
5650 || self.dict.load_incomplete()
5651 || self.named_graphs.load_incomplete()
5652 }
5653
5654 pub fn reset_load_failures(&self) {
5662 self.index.reset_load_failure();
5663 self.dict.reset_load_failure();
5664 self.named_graphs.reset_load_failures();
5665 }
5666
5667 pub fn set_memory_budget(&self, budget: Option<u64>) -> MemoryBudget {
5698 let total = budget.unwrap_or(u64::MAX);
5699 self.set_spill_threshold(budget.map(spill_threshold_for));
5700 let mut split = split_memory_budget(total);
5701 let fixed = if total == u64::MAX {
5702 0
5703 } else {
5704 self.fixed_overhead().total()
5705 };
5706 if split.dict_cache != u64::MAX {
5707 split.dict_cache = split
5708 .dict_cache
5709 .saturating_sub(fixed)
5710 .max(MIN_DICT_CACHE_CAP);
5711 }
5712 self.dict.set_cache_cap(split.dict_cache);
5713 self.index.set_cache_cap(split.tile_cache);
5714 match &self.named_graphs {
5719 NamedGraphsSlot::Lazy(lazy) => lazy.set_tile_cap(split.tile_cache),
5720 NamedGraphsSlot::Quad(q) => q.set_tile_cap(split.tile_cache),
5723 NamedGraphsSlot::Resident(_) => {}
5724 }
5725 if std::env::var("RETE_OPEN_DEBUG").is_ok() {
5726 eprintln!(
5727 "[memory-budget] total={} dict_cache={} tile_cache={} block_cache={} fixed={:.1}MiB",
5728 if total == u64::MAX {
5729 "unlimited".to_string()
5730 } else {
5731 format!("{}MiB", total >> 20)
5732 },
5733 fmt_cap(split.dict_cache),
5734 fmt_cap(split.tile_cache),
5735 fmt_cap(split.block_cache),
5736 fixed as f64 / (1u64 << 20) as f64,
5737 );
5738 }
5739 split
5740 }
5741
5742 pub fn spill_threshold(&self) -> u64 {
5749 self.spill_threshold
5750 .load(std::sync::atomic::Ordering::Relaxed)
5751 }
5752
5753 pub fn set_spill_threshold(&self, bytes: Option<u64>) {
5757 self.spill_threshold.store(
5758 bytes.unwrap_or(u64::MAX),
5759 std::sync::atomic::Ordering::Relaxed,
5760 );
5761 }
5762
5763 pub fn dict_cache_stats(&self) -> crate::chunk_cache::CacheStats {
5767 self.dict.cache_stats()
5768 }
5769
5770 pub fn fixed_overhead(&self) -> FixedOverhead {
5774 FixedOverhead {
5775 dict_directory: self.dict.directory_bytes(),
5776 index_directory: self.index.directory_bytes(),
5777 named_graphs: self.named_graphs.directory_bytes(),
5778 }
5779 }
5780
5781 pub fn index_cache_stats(&self) -> crate::chunk_cache::CacheStats {
5783 self.index.cache_stats()
5784 }
5785
5786 pub fn dict_cache_cap(&self) -> u64 {
5788 self.dict.cache_cap()
5789 }
5790
5791 pub fn release_named_graph(&mut self, iri: &str) {
5804 match &mut self.named_graphs {
5805 NamedGraphsSlot::Lazy(lazy) => lazy.release(iri),
5806 NamedGraphsSlot::Quad(q) => q.release(&self.dict, iri),
5807 NamedGraphsSlot::Resident(_) => {}
5808 }
5809 }
5810
5811 fn resolve_query_pattern(
5812 &self,
5813 s: Option<&str>,
5814 p: Option<&str>,
5815 o: Option<&str>,
5816 ) -> Option<Pattern> {
5817 let sid = match s {
5818 Some(t) => match self.dict.subject_id(t) {
5819 Some(id) => Some(id),
5820 None => return None,
5821 },
5822 None => None,
5823 };
5824 let pid = match p {
5825 Some(t) => match self.dict.predicate_id(t) {
5826 Some(id) => Some(id),
5827 None => return None,
5828 },
5829 None => None,
5830 };
5831 let oid = match o {
5832 Some(t) => match self.dict.object_id(t) {
5833 Some(id) => Some(id),
5834 None => return None,
5835 },
5836 None => None,
5837 };
5838 Some((sid, pid, oid))
5839 }
5840
5841 pub fn query_with_provenance(
5845 &self,
5846 s: Option<&str>,
5847 p: Option<&str>,
5848 o: Option<&str>,
5849 ) -> Vec<TripleProvenance> {
5850 let pattern = match self.resolve_query_pattern(s, p, o) {
5851 Some(pattern) => pattern,
5852 None => return Vec::new(),
5853 };
5854
5855 let index_permutation = GraphIndex::best_permutation_in(self.header.perms, pattern);
5856 let si = index_permutation.section_index();
5857 let (dictionary_range, index_range, index_section_range, pyramid_range) = match &self.v06 {
5858 Some(f) => {
5859 use crate::v06::kind;
5860 let sec = |k| f.section(k).unwrap_or_default();
5861 let perm = f
5862 .root
5863 .unit(crate::v06::tag::INDEX)
5864 .and_then(|u| crate::v06::decode_index_root(u).ok())
5865 .and_then(|v| v.into_iter().find(|p| p.si == si))
5866 .map(|p| ByteRange {
5867 offset: sec(kind::INDEX_DATA).offset + p.data_off,
5868 len: p.data_len,
5869 })
5870 .unwrap_or_default();
5871 (
5872 sec(kind::DICT_DATA),
5873 sec(kind::INDEX_DATA),
5874 perm,
5875 f.section(kind::PYRAMID),
5876 )
5877 }
5878 None => (
5879 ByteRange {
5880 offset: self.header.dictionary_offset,
5881 len: self.header.dictionary_len,
5882 },
5883 ByteRange {
5884 offset: self.header.root_dir_offset,
5885 len: self.header.root_dir_len,
5886 },
5887 self.index_section_ranges[si],
5888 (self.header.pyramid_meta_len > 0).then_some(ByteRange {
5889 offset: self.header.pyramid_meta_offset,
5890 len: self.header.pyramid_meta_len,
5891 }),
5892 ),
5893 };
5894
5895 let tiles = &self.tile_ranges[si];
5896 let v06_tiles = self.v06.is_some().then(|| self.index.tile_sections()[si]);
5897 self.index
5898 .match_pattern(pattern)
5899 .into_iter()
5900 .filter_map(|(s, p, o)| {
5901 let terms = (
5902 self.dict.subject_term(s)?,
5903 self.dict.predicate_term(p)?,
5904 self.dict.object_term(o)?,
5905 );
5906 let a = index_permutation.forward((s, p, o)).0;
5909 let (tile, tile_range) = if let Some(tl) = v06_tiles {
5910 let (ti, tj) = self.index.tile_span(si, Some(a));
5911 match (ti < tj && ti < tl.len()).then(|| tl.range(ti)).flatten() {
5912 Some((offset, len)) => (
5913 Some(format!("{}/{ti}", index_permutation.name())),
5914 Some(ByteRange { offset, len }),
5915 ),
5916 None => (None, None),
5917 }
5918 } else {
5919 let ti = tiles.partition_point(|&(_, max_a, _)| max_a < a);
5920 match tiles.get(ti) {
5921 Some(&(min_a, _, range)) if min_a <= a => (
5922 Some(format!("{}/{ti}", index_permutation.name())),
5923 Some(range),
5924 ),
5925 _ => (None, None),
5926 }
5927 };
5928 Some(TripleProvenance {
5929 terms,
5930 ids: (s, p, o),
5931 graph: None,
5932 matched_pattern: pattern,
5933 index_permutation,
5934 dictionary_range,
5935 index_range,
5936 index_section_range,
5937 pyramid_range,
5938 tile,
5939 tile_range,
5940 })
5941 })
5942 .collect()
5943 }
5944
5945 pub fn query(&self, s: Option<&str>, p: Option<&str>, o: Option<&str>) -> Vec<TermTriple> {
5949 self.query_with_provenance(s, p, o)
5950 .into_iter()
5951 .map(|m| m.terms)
5952 .collect()
5953 }
5954
5955 pub fn query_in_graph(
5963 &self,
5964 graph: Option<&str>,
5965 s: Option<&str>,
5966 p: Option<&str>,
5967 o: Option<&str>,
5968 ) -> Vec<TermTriple> {
5969 let pattern = match self.resolve_query_pattern(s, p, o) {
5970 Some(pattern) => pattern,
5971 None => return Vec::new(),
5972 };
5973 let index = match graph {
5974 None => &self.index,
5975 Some(g) => match self.graph_index(g) {
5976 Some(i) => i,
5977 None => return Vec::new(),
5978 },
5979 };
5980 self.resolve_matches(index.match_pattern(pattern))
5981 }
5982
5983 fn resolve_matches(&self, ids: Vec<Triple>) -> Vec<TermTriple> {
5986 if !ids.is_empty() {
5994 let mut nodes = Vec::with_capacity(ids.len() * 2);
5995 let mut preds = Vec::with_capacity(ids.len());
5996 for &(s, p, o) in &ids {
5997 nodes.push(self.dict.subject_node(s));
5998 nodes.push(self.dict.object_node(o));
5999 preds.push(p);
6000 }
6001 self.dict.prefetch_terms(&nodes, &preds);
6002 }
6003 ids.into_iter()
6004 .filter_map(|(s, p, o)| {
6005 Some((
6006 self.dict.subject_term(s)?,
6007 self.dict.predicate_term(p)?,
6008 self.dict.object_term(o)?,
6009 ))
6010 })
6011 .collect()
6012 }
6013
6014 pub fn query_quads(
6019 &self,
6020 s: Option<&str>,
6021 p: Option<&str>,
6022 o: Option<&str>,
6023 ) -> Vec<(TermTriple, Option<String>)> {
6024 let mut out: Vec<(TermTriple, Option<String>)> = self
6025 .query_in_graph(None, s, p, o)
6026 .into_iter()
6027 .map(|t| (t, None))
6028 .collect();
6029 let Some(pattern) = self.resolve_query_pattern(s, p, o) else {
6030 return out;
6031 };
6032 for i in 0..self.named_graphs.count() {
6033 let Some(iri) = self.named_graphs.name_at(&self.dict, i, true) else {
6036 continue;
6037 };
6038 let owned = self.named_graph_transient(i);
6041 let index = match &owned {
6042 Some(view) => view,
6043 None => match self.named_graphs.graph_at(&self.dict, i, true) {
6044 Some((_, g)) => g,
6045 None => continue,
6046 },
6047 };
6048 for triple in self.resolve_matches(index.match_pattern(pattern)) {
6049 out.push((triple, Some(iri.to_string())));
6050 }
6051 }
6052 out
6053 }
6054
6055 pub fn query_ranged<R: RangeReader>(
6062 reader: &R,
6063 s: Option<&str>,
6064 p: Option<&str>,
6065 o: Option<&str>,
6066 ) -> Result<Vec<TermTriple>, FileError> {
6067 let head = reader.read_at(0, (HEADER_LEN as u64).min(reader.len()))?;
6068 if crate::v06::open::is_v06(&head) {
6069 return Ok(v06_query_ranged(reader, head, s, p, o, true)?.unwrap_or_default());
6070 }
6071 let routed = match route_pattern(reader, head, s, p, o)? {
6072 Some(routed) => routed,
6073 None => return Ok(Vec::new()),
6074 };
6075 let matches = fetch_routed_matches(reader, &routed)?;
6076 Ok(matches
6077 .into_iter()
6078 .filter_map(|(s, p, o)| {
6079 Some((
6080 routed.dict.subject_term(s)?,
6081 routed.dict.predicate_term(p)?,
6082 routed.dict.object_term(o)?,
6083 ))
6084 })
6085 .collect())
6086 }
6087
6088 pub fn route_pattern_ranged<R: RangeReader>(
6092 reader: &R,
6093 s: Option<&str>,
6094 p: Option<&str>,
6095 o: Option<&str>,
6096 ) -> Result<bool, FileError> {
6097 let head = reader.read_at(0, (HEADER_LEN as u64).min(reader.len()))?;
6098 if crate::v06::open::is_v06(&head) {
6099 return Ok(v06_query_ranged(reader, head, s, p, o, false)?.is_some());
6100 }
6101 Ok(route_pattern(reader, head, s, p, o)?.is_some())
6102 }
6103}
6104
6105fn v06_query_ranged<R: RangeReader>(
6111 reader: &R,
6112 head: Vec<u8>,
6113 s: Option<&str>,
6114 p: Option<&str>,
6115 o: Option<&str>,
6116 fetch: bool,
6117) -> Result<Option<Vec<TermTriple>>, FileError> {
6118 use crate::v06::{kind, open::SparseReader, Header06, Root06, HEADER_LEN};
6119 let len = reader.len();
6120 let h = Header06::from_bytes(&head)?;
6121 let root_end = (HEADER_LEN as u64 + h.root_len as u64).min(len);
6122 let root_bytes = if root_end <= head.len() as u64 {
6123 head[HEADER_LEN..root_end as usize].to_vec()
6124 } else {
6125 reader.read_at(HEADER_LEN as u64, root_end - HEADER_LEN as u64)?
6126 };
6127 let root = Root06::decode(&root_bytes, h.internal_codec)?;
6128 let dict = root.section(kind::DICT_DATA).and_then(|d| d.abs(&h).ok());
6129 let end = dict
6132 .map_or(h.data_offset, |d| d.offset + d.len)
6133 .max(crate::header::HEADER_LEN as u64)
6134 .min(len);
6135 let mut held = head;
6136 if end > held.len() as u64 {
6137 let at = held.len() as u64;
6138 held.extend_from_slice(&reader.read_at(at, end - at)?);
6139 }
6140 let sparse = SparseReader::fetch(reader, held, &[])?;
6141 let rete = Rete::open_ranged_lazy_with(sparse, 0)?;
6142 let Some(pattern) = resolve_query_pattern(rete.dictionary(), s, p, o) else {
6143 return Ok(None);
6144 };
6145 if !fetch {
6146 return Ok(Some(Vec::new()));
6147 }
6148 let perm = GraphIndex::best_permutation_in(h.perms(), pattern);
6149 let si = perm.section_index();
6150 let index = rete.default_index();
6151 let [pa, _, _] = perm.order_pattern(pattern);
6152 let mut out = Vec::new();
6155 for (start, stop) in index.routed_spans(si, pa) {
6156 let ranges: Vec<(u64, u64)> = (start..stop)
6157 .filter_map(|i| index.tile_range(si, i))
6158 .collect();
6159 if let (Some(&(lo, _)), Some(&(last, last_len))) = (ranges.first(), ranges.last()) {
6160 let body = reader.read_at(lo, last + last_len - lo)?;
6161 for &(off, l) in &ranges {
6162 let at = (off - lo) as usize;
6163 let tile = decompress(h.block_codec, &body[at..at + l as usize])?;
6164 out.extend(GraphIndex::match_serialized_block(&tile, perm, pattern));
6165 }
6166 }
6167 }
6168 out.sort_unstable();
6169 let d = rete.dictionary();
6170 Ok(Some(
6171 out.into_iter()
6172 .filter_map(|(s, p, o)| {
6173 Some((d.subject_term(s)?, d.predicate_term(p)?, d.object_term(o)?))
6174 })
6175 .collect(),
6176 ))
6177}
6178
6179struct RoutedPattern {
6182 dict: Dictionary,
6183 pattern: Pattern,
6184 permutation: IndexPermutation,
6185 header: Header,
6186 section: ByteRange,
6188}
6189
6190fn route_pattern<R: RangeReader>(
6193 reader: &R,
6194 head: Vec<u8>,
6195 s: Option<&str>,
6196 p: Option<&str>,
6197 o: Option<&str>,
6198) -> Result<Option<RoutedPattern>, FileError> {
6199 let header = Header::from_bytes(&head)?;
6200
6201 let dict_bytes = reader.read_at(header.dictionary_offset, header.dictionary_len)?;
6202 let dict = decode_dictionary_container(&dict_bytes, header.dict_codec)?;
6203
6204 let Some(pattern) = resolve_query_pattern(&dict, s, p, o) else {
6205 return Ok(None);
6206 };
6207 let permutation = GraphIndex::best_permutation_in(header.perms, pattern);
6208 let section = locate_container_section_ranged(
6209 reader,
6210 header.root_dir_offset,
6211 header.root_dir_len,
6212 header
6213 .perms
6214 .position(permutation)
6215 .ok_or(FileError::Container("routed to an absent permutation"))?,
6216 header.index_container_sections() as u64,
6217 )?;
6218 Ok(Some(RoutedPattern {
6219 dict,
6220 pattern,
6221 permutation,
6222 header,
6223 section,
6224 }))
6225}
6226
6227fn fetch_routed_matches<R: RangeReader>(
6232 reader: &R,
6233 routed: &RoutedPattern,
6234) -> Result<Vec<Triple>, FileError> {
6235 let dir = read_tile_directory_ranged(reader, routed.section)?;
6236 let [pa, _, _] = routed.permutation.order_pattern(routed.pattern);
6237 let codec = routed.header.block_codec;
6238 let mut out = Vec::new();
6239 match pa {
6240 Some(a) => {
6243 for e in dir.iter().filter(|e| e.min_a <= a && a <= e.max_a) {
6244 let len = e.end - e.start;
6245 let bytes = reader.read_at(checked_end(routed.section.offset, e.start)?, len)?;
6246 if bytes.len() as u64 != len {
6247 return Err(FileError::Container("short tile read"));
6248 }
6249 let tile = decompress(codec, &bytes)?;
6250 out.extend(GraphIndex::match_serialized_block(
6251 &tile,
6252 routed.permutation,
6253 routed.pattern,
6254 ));
6255 }
6256 }
6257 None => {
6260 if let (Some(first), Some(last)) = (dir.first(), dir.last()) {
6261 let base = first.start;
6262 let body =
6263 reader.read_at(checked_end(routed.section.offset, base)?, last.end - base)?;
6264 for e in &dir {
6265 let stored = checked_slice(&body, e.start - base, e.end - e.start)
6267 .ok_or(FileError::Container("short tile read"))?;
6268 let tile = decompress(codec, stored)?;
6269 out.extend(GraphIndex::match_serialized_block(
6270 &tile,
6271 routed.permutation,
6272 routed.pattern,
6273 ));
6274 }
6275 }
6276 }
6277 }
6278 out.sort_unstable();
6279 Ok(out)
6280}
6281
6282fn resolve_query_pattern(
6283 dict: &Dictionary,
6284 s: Option<&str>,
6285 p: Option<&str>,
6286 o: Option<&str>,
6287) -> Option<Pattern> {
6288 let sid = match s {
6289 Some(t) => Some(dict.subject_id(t)?),
6290 None => None,
6291 };
6292 let pid = match p {
6293 Some(t) => Some(dict.predicate_id(t)?),
6294 None => None,
6295 };
6296 let oid = match o {
6297 Some(t) => Some(dict.object_id(t)?),
6298 None => None,
6299 };
6300 Some((sid, pid, oid))
6301}
6302
6303fn ranged_chunked_dictionary<R: RangeReader + Send + Sync + 'static>(
6318 reader: &std::sync::Arc<R>,
6319 header: &Header,
6320 want: [bool; 4],
6321) -> Result<Dictionary, FileError> {
6322 let cache = crate::chunk_cache::ChunkCache::unlimited_arc();
6325 let mut dict_sections: Vec<crate::dict::ChunkedSection> = Vec::with_capacity(4);
6326 let mut section_ranges: [std::sync::Arc<Vec<ByteRange>>; 4] = Default::default();
6327 for si in 0..4 {
6328 if !want[si] {
6329 dict_sections.push(crate::dict::ChunkedSection::from_parts(
6330 crate::dict::SectionMeta {
6331 term_count: 0,
6332 restart_interval: 1,
6333 restart_offsets: Vec::new(),
6334 },
6335 Vec::new(),
6336 None,
6337 cache.clone(),
6338 si as u8,
6339 ));
6340 continue;
6341 }
6342 let section = locate_container_section_ranged(
6343 reader.as_ref(),
6344 header.dictionary_offset,
6345 header.dictionary_len,
6346 si,
6347 4,
6348 )?;
6349 let (meta, entries) = read_dict_dir_ranged(reader.as_ref(), section)?;
6350 let ranges: std::sync::Arc<Vec<ByteRange>> = std::sync::Arc::new(
6353 entries
6354 .iter()
6355 .map(|e| ByteRange {
6356 offset: section.offset + e.start,
6357 len: (e.end - e.start),
6358 })
6359 .collect(),
6360 );
6361 section_ranges[si] = ranges.clone();
6362 let chunks: Vec<crate::dict::SectionChunk> = entries
6363 .into_iter()
6364 .map(|e| crate::dict::SectionChunk::new(e.first_run, e.key, e.body_start))
6365 .collect();
6366 let chunk_reader = reader.clone();
6367 let codec = header.dict_codec;
6368 let loader_ranges = ranges.clone();
6369 let loader: crate::dict::ChunkLoader = Box::new(move |ci| {
6370 let range = loader_ranges.get(ci)?;
6371 let bytes = chunk_reader.read_at(range.offset, range.len).ok()?;
6372 decompress(codec, &bytes).ok()
6373 });
6374 let bulk_reader = reader.clone();
6377 let bulk: crate::dict::ChunkBulkLoader = Box::new(move |cis| {
6378 let want: Option<Vec<ByteRange>> =
6379 cis.iter().map(|&ci| ranges.get(ci).copied()).collect();
6380 let blobs = read_coalesced(bulk_reader.as_ref(), &want?, DICT_COALESCE_GAP)?;
6381 blobs.iter().map(|b| decompress(codec, b).ok()).collect()
6382 });
6383 dict_sections.push(
6384 crate::dict::ChunkedSection::from_parts(
6385 meta,
6386 chunks,
6387 Some(loader),
6388 cache.clone(),
6389 si as u8,
6390 )
6391 .with_bulk_loader(bulk),
6392 );
6393 }
6394 let dict_arr: [crate::dict::ChunkedSection; 4] = dict_sections
6395 .try_into()
6396 .map_err(|_| FileError::Container("expected 4 dictionary sections"))?;
6397 let multi_reader = reader.clone();
6401 let codec = header.dict_codec;
6402 let multi: crate::dict::MultiChunkBulkLoader = Box::new(move |pairs| {
6403 let want: Option<Vec<ByteRange>> = pairs
6404 .iter()
6405 .map(|&(si, ci)| section_ranges.get(si as usize)?.get(ci).copied())
6406 .collect();
6407 let blobs = read_coalesced(multi_reader.as_ref(), &want?, DICT_COALESCE_GAP)?;
6408 blobs.iter().map(|b| decompress(codec, b).ok()).collect()
6409 });
6410 Ok(Dictionary::from_chunked_sections(dict_arr).with_multi_bulk_loader(multi))
6411}
6412
6413#[cfg(not(target_arch = "wasm32"))]
6418fn open_side_by_side<A, B: Send>(
6419 concurrency: usize,
6420 a: impl FnOnce() -> A,
6421 b: impl FnOnce() -> B + Send,
6422) -> (A, B) {
6423 if concurrency <= 1 {
6424 return (a(), b());
6425 }
6426 std::thread::scope(|scope| {
6427 let hb = scope.spawn(b);
6428 let ra = a();
6429 let rb = hb
6430 .join()
6431 .unwrap_or_else(|panic| std::panic::resume_unwind(panic));
6432 (ra, rb)
6433 })
6434}
6435
6436#[cfg(target_arch = "wasm32")]
6438fn open_side_by_side<A, B>(
6439 _concurrency: usize,
6440 a: impl FnOnce() -> A,
6441 b: impl FnOnce() -> B,
6442) -> (A, B) {
6443 (a(), b())
6444}
6445
6446#[cfg(feature = "v06-parity")]
6449fn parity_image(bytes: &[u8]) -> Option<Vec<u8>> {
6450 if crate::v06::open::is_v06(bytes) || bytes.len() < HEADER_LEN {
6451 return None;
6452 }
6453 crate::v06::write::convert_image(bytes, crate::v06::write::WriteOpts::default()).ok()
6454}
6455
6456fn v06_layout(f: &crate::v06::open::V06File) -> Vec<LayoutSegment> {
6459 let h = &f.h;
6460 let seg = |kind: &'static str, label: String, offset: u64, len: u64| LayoutSegment {
6461 kind,
6462 label,
6463 offset,
6464 len,
6465 };
6466 let mut out = vec![
6467 seg(
6468 "header",
6469 format!("header (fixed {} bytes)", crate::v06::HEADER_LEN),
6470 0,
6471 crate::v06::HEADER_LEN as u64,
6472 ),
6473 seg(
6474 "directory",
6475 "root block (section table, directory roots)".into(),
6476 h.root_offset(),
6477 h.root_len as u64,
6478 ),
6479 ];
6480 let c = h.card_range();
6481 if c.len > 0 {
6482 out.push(seg(
6483 "metadata",
6484 "metadata (dataset card, zstd)".into(),
6485 c.offset,
6486 c.len,
6487 ));
6488 }
6489 let b = h.build_range();
6490 if b.len > 0 {
6491 out.push(seg("build-info", "build record".into(), b.offset, b.len));
6492 }
6493 for s in &f.root.sections {
6494 let Ok(a) = s.abs(h) else { continue };
6495 let kind: &'static str = match s.kind {
6496 crate::v06::kind::SCHEMA => "schema",
6497 crate::v06::kind::DICT_DATA => "dictionary",
6498 crate::v06::kind::INDEX_DATA => "tile",
6499 crate::v06::kind::QUAD_DATA => "named-graphs",
6500 crate::v06::kind::LABEL_DATA => "label-index",
6501 crate::v06::kind::TEXT_DATA => "text-index",
6502 crate::v06::kind::PYRAMID => "pyramid",
6503 _ => "directory",
6504 };
6505 out.push(seg(
6506 kind,
6507 crate::v06::kind::name(s.kind).to_string(),
6508 a.offset,
6509 a.len,
6510 ));
6511 }
6512 out.sort_by_key(|s| s.offset);
6513 out
6514}
6515
6516#[allow(clippy::type_complexity)]
6519fn v06_slots(
6520 f: &std::sync::Arc<crate::v06::open::V06File>,
6521) -> (
6522 PyramidSlot,
6523 TextIndexSlot,
6524 SectionSlot<crate::label_index::LabelIndex>,
6525 SectionSlot<crate::schema_section::SchemaMeta>,
6526) {
6527 use crate::v06::{P_LABELS, P_PYRAMID, P_SCHEMA, P_TEXT};
6528 let pyramid = if f.h.has(P_PYRAMID) {
6529 let a = f.clone();
6530 PyramidSlot::Lazy {
6531 loader: Box::new(move || PyramidMeta::decode(&a.pyramid_bytes()?).ok()),
6532 cell: std::sync::OnceLock::new(),
6533 }
6534 } else {
6535 PyramidSlot::Resident(None)
6536 };
6537 let text_index = if f.h.has(P_TEXT) {
6538 let (a, b) = (f.clone(), f.clone());
6539 TextIndexSlot::Lazy {
6540 loader: Box::new(move || a.text_index()?.ok()),
6541 cell: std::sync::OnceLock::new(),
6542 token_table: Box::new(move || b.token_table_bytes()),
6543 token_table_cell: std::sync::OnceLock::new(),
6544 }
6545 } else {
6546 TextIndexSlot::Resident {
6547 index: None,
6548 token_table_len: None,
6549 }
6550 };
6551 let labels = if f.h.has(P_LABELS) {
6552 let a = f.clone();
6553 SectionSlot::Lazy {
6554 loader: Box::new(move || a.label_index()?.ok()),
6555 cell: std::sync::OnceLock::new(),
6556 }
6557 } else {
6558 SectionSlot::Resident(None)
6559 };
6560 let schema = if f.h.has(P_SCHEMA) {
6561 let a = f.clone();
6562 SectionSlot::Lazy {
6563 loader: Box::new(move || a.schema()),
6564 cell: std::sync::OnceLock::new(),
6565 }
6566 } else {
6567 SectionSlot::Resident(None)
6568 };
6569 (pyramid, text_index, labels, schema)
6570}
6571
6572fn ranged_pyramid_slot<R: RangeReader + Send + Sync + 'static>(
6576 reader: &std::sync::Arc<R>,
6577 header: &Header,
6578) -> PyramidSlot {
6579 if header.pyramid_meta_len == 0 {
6580 return PyramidSlot::Resident(None);
6581 }
6582 let pyr_reader = reader.clone();
6583 let pyr_off = header.pyramid_meta_offset;
6584 let pyr_len = header.pyramid_meta_len;
6585 PyramidSlot::Lazy {
6586 loader: Box::new(move || {
6587 let mb = pyr_reader.read_at(pyr_off, pyr_len).ok()?;
6588 PyramidMeta::decode(&mb).ok()
6589 }),
6590 cell: std::sync::OnceLock::new(),
6591 }
6592}
6593
6594fn ranged_text_index_slot<R: RangeReader + Send + Sync + 'static>(
6599 reader: &std::sync::Arc<R>,
6600 header: &Header,
6601) -> TextIndexSlot {
6602 let (ti_off, ti_len) = header.text_index_payload();
6603 if ti_len == 0 {
6604 return TextIndexSlot::Resident {
6605 index: None,
6606 token_table_len: None,
6607 };
6608 }
6609 let ti_reader = reader.clone();
6610 let probe_reader = reader.clone();
6611 let codec = header.block_codec;
6612 TextIndexSlot::Lazy {
6613 loader: Box::new(move || {
6614 let prefix_len = read_token_table_len(&*ti_reader, ti_off, ti_len)?;
6618 let prefix = ti_reader.read_at(ti_off, prefix_len).ok()?;
6619 let postings_base = crate::text_index::TextIndex::postings_base(&prefix)? as u64;
6620 let postings_abs = ti_off + postings_base;
6621 let pr = ti_reader.clone();
6622 let posting_loader =
6623 Box::new(move |off: u64, len: u64| pr.read_at(postings_abs + off, len).ok());
6624 crate::text_index::TextIndex::from_token_table(&prefix, codec, posting_loader).ok()
6625 }),
6626 cell: std::sync::OnceLock::new(),
6627 token_table: Box::new(move || read_token_table_len(&*probe_reader, ti_off, ti_len)),
6630 token_table_cell: std::sync::OnceLock::new(),
6631 }
6632}
6633
6634fn resolve_label_hits(
6641 dict: &Dictionary,
6642 hits: Vec<&crate::meta::LabelEntry>,
6643) -> Vec<(String, String)> {
6644 let ids: Vec<u32> = hits.iter().map(|e| e.subject).collect();
6645 dict.prefetch_subject_terms(&ids);
6646 hits.iter()
6647 .zip(dict.subject_terms(&ids))
6648 .filter_map(|(e, iri)| Some((e.label.clone(), iri?)))
6649 .collect()
6650}
6651
6652fn text_search_in(
6655 ti: Option<&crate::text_index::TextIndex>,
6656 dict: &Dictionary,
6657 words: &[&str],
6658 prefix: Option<&str>,
6659 limit: usize,
6660) -> Vec<String> {
6661 let Some(ti) = ti else {
6662 return Vec::new();
6663 };
6664 let mut acc: Option<Vec<u32>> = None;
6668 if let Some(p) = prefix {
6669 acc = Some(ti.prefix(&p.to_lowercase()));
6670 }
6671 for w in words {
6672 for tok in crate::text_index::tokenize(w) {
6673 let posting = ti.lookup(&tok);
6674 acc = Some(match acc {
6675 Some(a) => intersect_sorted(&a, &posting),
6676 None => posting,
6677 });
6678 if acc.as_ref().is_some_and(|a| a.is_empty()) {
6679 return Vec::new();
6680 }
6681 }
6682 }
6683 let ids = acc.unwrap_or_default();
6684 let mut out = Vec::with_capacity(if limit > 0 {
6685 limit.min(ids.len())
6686 } else {
6687 ids.len()
6688 });
6689 let page = if limit > 0 {
6693 limit.min(ids.len())
6694 } else {
6695 ids.len()
6696 };
6697 dict.prefetch_subject_terms(&ids[..page]);
6698 for id in ids {
6699 if let Some(iri) = dict.subject_term(id) {
6700 out.push(iri);
6701 if limit > 0 && out.len() >= limit {
6702 break;
6703 }
6704 }
6705 }
6706 out
6707}
6708
6709pub struct SearchView {
6732 header: Header,
6733 dict: SectionSlot<Dictionary>,
6734 pyramid: PyramidSlot,
6735 text_index: TextIndexSlot,
6736 labels: SectionSlot<crate::label_index::LabelIndex>,
6737}
6738
6739impl SearchView {
6740 pub fn open_ranged<R: RangeReader + Send + Sync + 'static>(
6745 reader: R,
6746 ) -> Result<Self, FileError> {
6747 Self::open_ranged_with(reader, crate::v06::FIRST_READ)
6748 }
6749
6750 pub fn open_ranged_with<R: RangeReader + Send + Sync + 'static>(
6753 reader: R,
6754 first_read: u64,
6755 ) -> Result<Self, FileError> {
6756 let first_len = first_read.max(HEADER_LEN as u64).min(reader.len());
6757 let first: std::sync::Arc<[u8]> = std::sync::Arc::from(reader.read_at(0, first_len)?);
6758 let reader = crate::reader::PrefixReader::new(reader, first.clone());
6759 if crate::v06::open::is_v06(&first) {
6760 let r: std::sync::Arc<dyn RangeReader + Send + Sync> = std::sync::Arc::new(reader);
6761 let f = std::sync::Arc::new(crate::v06::open::V06File::open(r, &first)?);
6762 let header = crate::v06::logical_header(&f.h);
6763 let (pyramid, text_index, labels, _) = v06_slots(&f);
6764 let want = [true, true, false, false];
6765 let dict = if f.h.has(crate::v06::P_LABELS) {
6766 let a = f.clone();
6767 SectionSlot::Lazy {
6768 loader: Box::new(move || a.dictionary(want).ok()),
6769 cell: std::sync::OnceLock::new(),
6770 }
6771 } else {
6772 SectionSlot::Resident(Some(f.dictionary(want)?))
6773 };
6774 return Ok(Self {
6775 header,
6776 dict,
6777 pyramid,
6778 text_index,
6779 labels,
6780 });
6781 }
6782 let head = reader.read_at(0, HEADER_LEN as u64)?;
6783 let header = Header::from_bytes(&head)?;
6784 let reader = std::sync::Arc::new(reader);
6785 let dict = if header.label_index_section().is_some() {
6789 let (r, h) = (reader.clone(), header.clone());
6790 SectionSlot::Lazy {
6791 loader: Box::new(move || {
6792 ranged_chunked_dictionary(&r, &h, [true, true, false, false]).ok()
6793 }),
6794 cell: std::sync::OnceLock::new(),
6795 }
6796 } else {
6797 SectionSlot::Resident(Some(ranged_chunked_dictionary(
6798 &reader,
6799 &header,
6800 [true, true, false, false],
6801 )?))
6802 };
6803 let pyramid = ranged_pyramid_slot(&reader, &header);
6804 let text_index = ranged_text_index_slot(&reader, &header);
6805 let labels = ranged_label_slot(&reader, &header);
6806 Ok(Self {
6807 header,
6808 dict,
6809 pyramid,
6810 text_index,
6811 labels,
6812 })
6813 }
6814
6815 pub fn has_labels(&self) -> bool {
6819 self.header.label_index_section().is_some() || self.header.pyramid_meta_len > 0
6820 }
6821
6822 pub fn has_label_index(&self) -> bool {
6824 self.header.label_index_section().is_some()
6825 }
6826
6827 pub fn header(&self) -> &Header {
6829 &self.header
6830 }
6831
6832 pub fn has_text_index(&self) -> bool {
6834 self.header.text_index_len > 0
6835 }
6836
6837 pub fn has_pyramid(&self) -> bool {
6840 self.header.pyramid_meta_len > 0
6841 }
6842
6843 pub fn text_search(&self, words: &[&str], prefix: Option<&str>, limit: usize) -> Vec<String> {
6846 let Some(dict) = self.dict.get() else {
6847 return Vec::new();
6848 };
6849 text_search_in(self.text_index.index(), dict, words, prefix, limit)
6850 }
6851
6852 pub fn text_index_token_table_len(&self) -> Option<u64> {
6856 self.text_index.token_table_len()
6857 }
6858
6859 pub fn prefix_search(&self, prefix: &str, limit: usize) -> Vec<(String, String)> {
6863 if let Some(li) = self.labels.get() {
6864 return li.prefix_search(prefix, limit);
6865 }
6866 let pyr = match &self.pyramid {
6867 PyramidSlot::Resident(p) => p.as_ref(),
6868 PyramidSlot::Lazy { loader, cell } => cell.get_or_init(loader).as_ref(),
6869 };
6870 let (Some(pyr), Some(dict)) = (pyr, self.dict.get()) else {
6871 return Vec::new();
6872 };
6873 resolve_label_hits(dict, pyr.prefix_search(prefix, limit))
6874 }
6875}
6876
6877#[must_use]
6882pub struct SummaryView {
6883 pub round: u32,
6884 pub summary: Vec<SuperEdge>,
6885 pub class_hierarchy: Vec<ClassNode>,
6887 pub level_rollups: Vec<LevelRollup>,
6889 pub level_links: Vec<LevelLinks>,
6891 pub descriptors: Vec<CommunityDescriptor>,
6893 pub subclass_cycles: Vec<Vec<String>>,
6895 pub disjoint_pairs: Vec<(String, String)>,
6897 pub equivalent_pairs: Vec<(String, String)>,
6899 dict: Dictionary,
6900}
6901
6902impl SummaryView {
6903 pub fn open_ranged<R: RangeReader>(reader: &R) -> Result<Option<Self>, FileError> {
6905 let head = reader.read_at(0, (HEADER_LEN as u64).min(reader.len()))?;
6906 let header = Header::from_bytes(&head)?;
6907 if header.pyramid_meta_len == 0 {
6908 return Ok(None);
6909 }
6910 if crate::v06::reads(header.version) {
6911 return Self::open_ranged_v06(reader, &header, head).map(Some);
6912 }
6913
6914 let dict_bytes = reader.read_at(header.dictionary_offset, header.dictionary_len)?;
6915 let dict = decode_dictionary_container(&dict_bytes, header.dict_codec)?;
6916
6917 let mb = reader.read_at(header.pyramid_meta_offset, header.pyramid_meta_len)?;
6918 let mut meta =
6919 PyramidMeta::decode(&mb).map_err(|_| FileError::Container("malformed pyramid meta"))?;
6920 if let Some(s) = read_schema_with_header(reader, &header) {
6923 meta.class_hierarchy = s.class_hierarchy;
6924 meta.level_rollups = s.level_rollups;
6925 meta.level_links = s.level_links;
6926 meta.subclass_cycles = s.subclass_cycles;
6927 meta.disjoint_pairs = s.disjoint_pairs;
6928 meta.equivalent_pairs = s.equivalent_pairs;
6929 }
6930
6931 Ok(Some(SummaryView {
6932 round: meta.round,
6933 summary: meta.summary,
6934 class_hierarchy: meta.class_hierarchy,
6935 level_rollups: meta.level_rollups,
6936 level_links: meta.level_links,
6937 descriptors: meta.descriptors,
6938 subclass_cycles: meta.subclass_cycles,
6939 disjoint_pairs: meta.disjoint_pairs,
6940 equivalent_pairs: meta.equivalent_pairs,
6941 dict,
6942 }))
6943 }
6944
6945 fn open_ranged_v06<R: RangeReader>(
6949 reader: &R,
6950 header: &Header,
6951 head: Vec<u8>,
6952 ) -> Result<Self, FileError> {
6953 use crate::v06::{kind, open};
6954 let mut first = head;
6958 let want_first = crate::v06::FIRST_READ.min(reader.len());
6959 if want_first > first.len() as u64 {
6960 let at = first.len() as u64;
6961 first.extend_from_slice(&reader.read_at(at, want_first - at)?);
6962 }
6963 let pre = open::Prefixed {
6964 first: &first,
6965 r: reader,
6966 };
6967 let (h, root) = open::read_front(&pre)?;
6968 let want: Vec<ByteRange> = [
6969 kind::PYRAMID,
6970 kind::SCHEMA,
6971 kind::DICT_LEAVES,
6972 kind::DICT_DATA,
6973 ]
6974 .iter()
6975 .filter_map(|&k| root.section(k).and_then(|s| s.abs(&h).ok()))
6976 .collect();
6977 let sparse = open::SparseReader::fetch(&pre, first.clone(), &want)?;
6978 let mb = open::read_section(&sparse, &h, &root, kind::PYRAMID)?
6979 .ok_or(FileError::Container("0x06 file has no pyramid"))?;
6980 let mut meta =
6981 PyramidMeta::decode(&mb).map_err(|_| FileError::Container("malformed pyramid meta"))?;
6982 if let Some(s) = read_schema_with_header(&sparse, header) {
6983 meta.class_hierarchy = s.class_hierarchy;
6984 meta.level_rollups = s.level_rollups;
6985 meta.level_links = s.level_links;
6986 meta.subclass_cycles = s.subclass_cycles;
6987 meta.disjoint_pairs = s.disjoint_pairs;
6988 meta.equivalent_pairs = s.equivalent_pairs;
6989 }
6990 let f = open::V06File::open(std::sync::Arc::new(sparse), &first)?;
6991 let dict = f.dictionary([true; 4])?;
6992 Ok(SummaryView {
6993 round: meta.round,
6994 summary: meta.summary,
6995 class_hierarchy: meta.class_hierarchy,
6996 level_rollups: meta.level_rollups,
6997 level_links: meta.level_links,
6998 descriptors: meta.descriptors,
6999 subclass_cycles: meta.subclass_cycles,
7000 disjoint_pairs: meta.disjoint_pairs,
7001 equivalent_pairs: meta.equivalent_pairs,
7002 dict,
7003 })
7004 }
7005
7006 pub fn open_schema_ranged<R: RangeReader>(reader: &R) -> Result<Option<Self>, FileError> {
7014 let head = reader.read_at(0, HEADER_LEN as u64)?;
7015 let header = Header::from_bytes(&head)?;
7016 let Some(s) = read_schema_with_header(reader, &header) else {
7017 return Ok(None);
7018 };
7019 let dict = crate::DictionaryBuilder::new().build();
7020 Ok(Some(SummaryView {
7021 round: 0,
7022 summary: Vec::new(),
7023 class_hierarchy: s.class_hierarchy,
7024 level_rollups: s.level_rollups,
7025 level_links: s.level_links,
7026 descriptors: Vec::new(),
7027 subclass_cycles: s.subclass_cycles,
7028 disjoint_pairs: s.disjoint_pairs,
7029 equivalent_pairs: s.equivalent_pairs,
7030 dict,
7031 }))
7032 }
7033
7034 pub fn level_count(&self) -> usize {
7036 self.level_rollups.len()
7037 }
7038
7039 pub fn level_rollup(&self, k: usize) -> Option<&LevelRollup> {
7042 self.level_rollups.get(k)
7043 }
7044
7045 pub fn predicate_term(&self, id: u32) -> Option<String> {
7047 self.dict.predicate_term(id)
7048 }
7049
7050 pub fn predicate_total(&self, predicate: &str) -> u32 {
7053 match self.dict.predicate_id(predicate) {
7054 Some(pid) => self
7055 .summary
7056 .iter()
7057 .filter(|e| e.predicate == pid)
7058 .map(|e| e.count)
7059 .sum(),
7060 None => 0,
7061 }
7062 }
7063
7064 pub fn predicate_totals(&self) -> Vec<(String, u32)> {
7066 let mut by_pred: std::collections::BTreeMap<u32, u32> = std::collections::BTreeMap::new();
7067 for e in &self.summary {
7068 *by_pred.entry(e.predicate).or_default() += e.count;
7069 }
7070 let mut out: Vec<(String, u32)> = by_pred
7071 .into_iter()
7072 .filter_map(|(pid, c)| self.dict.predicate_term(pid).map(|t| (t, c)))
7073 .collect();
7074 out.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
7075 out
7076 }
7077
7078 pub fn community_count(&self) -> usize {
7080 let mut comms = std::collections::BTreeSet::new();
7081 for e in &self.summary {
7082 comms.insert(e.s_comm);
7083 comms.insert(e.o_comm);
7084 }
7085 comms.len()
7086 }
7087
7088 pub fn tbox_coherence(&self) -> Vec<crate::reason::Inconsistency> {
7103 schema_coherence(
7104 &self.class_hierarchy,
7105 &self.subclass_cycles,
7106 &self.disjoint_pairs,
7107 &self.equivalent_pairs,
7108 )
7109 }
7110
7111 pub fn tbox_is_coherent(&self) -> bool {
7114 self.tbox_coherence().is_empty()
7115 }
7116}
7117
7118pub fn schema_coherence(
7124 class_hierarchy: &[ClassNode],
7125 subclass_cycles: &[Vec<String>],
7126 disjoint_pairs: &[(String, String)],
7127 equivalent_pairs: &[(String, String)],
7128) -> Vec<crate::reason::Inconsistency> {
7129 use crate::reason::Inconsistency;
7130 use std::collections::{BTreeMap, BTreeSet, VecDeque};
7131 const MAX_REACH: usize = 100_000;
7132
7133 let mut out: Vec<Inconsistency> = Vec::new();
7134
7135 for cyc in subclass_cycles {
7136 let detail = if cyc.len() == 1 {
7137 format!("{} is rdfs:subClassOf itself (a cycle)", cyc[0])
7138 } else {
7139 format!(
7140 "classes {{{}}} are mutually rdfs:subClassOf (a cycle)",
7141 cyc.join(", ")
7142 )
7143 };
7144 out.push(Inconsistency {
7145 kind: "subclass-cycle",
7146 detail,
7147 });
7148 }
7149
7150 if !disjoint_pairs.is_empty() {
7151 let mut adj: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
7153 for n in class_hierarchy {
7154 let e = adj.entry(n.class.as_str()).or_default();
7155 for p in &n.parents {
7156 e.push(p.as_str());
7157 }
7158 }
7159 for (a, b) in equivalent_pairs {
7160 adj.entry(a.as_str()).or_default().push(b.as_str());
7161 adj.entry(b.as_str()).or_default().push(a.as_str());
7162 }
7163
7164 let mut focuses: BTreeSet<&str> =
7166 class_hierarchy.iter().map(|n| n.class.as_str()).collect();
7167 for (a, b) in disjoint_pairs.iter().chain(equivalent_pairs) {
7168 focuses.insert(a.as_str());
7169 focuses.insert(b.as_str());
7170 }
7171
7172 let mut seen: BTreeSet<&str> = BTreeSet::new();
7173 for &c in &focuses {
7174 let mut reach: BTreeSet<&str> = BTreeSet::new();
7176 let mut q: VecDeque<&str> = VecDeque::new();
7177 reach.insert(c);
7178 q.push_back(c);
7179 while let Some(x) = q.pop_front() {
7180 if reach.len() > MAX_REACH {
7181 break;
7182 }
7183 if let Some(ns) = adj.get(x) {
7184 for &p in ns {
7185 if reach.insert(p) {
7186 q.push_back(p);
7187 }
7188 }
7189 }
7190 }
7191 for (x, y) in disjoint_pairs {
7192 if reach.contains(x.as_str()) && reach.contains(y.as_str()) && seen.insert(c) {
7193 out.push(Inconsistency {
7194 kind: "unsatisfiable-class",
7195 detail: format!(
7196 "{c} is a subclass of both {x} and {y}, which are \
7197 owl:disjointWith — no individual can be a {c}"
7198 ),
7199 });
7200 break;
7201 }
7202 }
7203 }
7204 }
7205
7206 out.sort_by(|a, b| (a.kind, &a.detail).cmp(&(b.kind, &b.detail)));
7207 out
7208}
7209
7210pub fn read_schema_coherence_ranged<R: RangeReader>(
7218 reader: &R,
7219) -> Result<Option<Vec<crate::reason::Inconsistency>>, FileError> {
7220 let head = reader.read_at(0, HEADER_LEN as u64)?;
7221 let header = Header::from_bytes(&head)?;
7222 if let Some(s) = read_schema_with_header(reader, &header) {
7224 return Ok(Some(schema_coherence(
7225 &s.class_hierarchy,
7226 &s.subclass_cycles,
7227 &s.disjoint_pairs,
7228 &s.equivalent_pairs,
7229 )));
7230 }
7231 if header.pyramid_meta_len == 0 {
7232 return Ok(None);
7233 }
7234 if header.schema_meta_len > 0 && (header.schema_meta_len as u64) <= header.pyramid_meta_len {
7238 let off =
7239 header.pyramid_meta_offset + header.pyramid_meta_len - header.schema_meta_len as u64;
7240 let block = reader.read_at(off, header.schema_meta_len as u64)?;
7241 let (hierarchy, cycles, disjoint, equivalent) = crate::meta::decode_schema_block(&block)
7242 .map_err(|_| FileError::Container("malformed schema block"))?;
7243 return Ok(Some(schema_coherence(
7244 &hierarchy,
7245 &cycles,
7246 &disjoint,
7247 &equivalent,
7248 )));
7249 }
7250 let mb = if crate::v06::reads(header.version) {
7252 crate::v06::open::read_pyramid(reader)?.unwrap_or_default()
7253 } else {
7254 reader.read_at(header.pyramid_meta_offset, header.pyramid_meta_len)?
7255 };
7256 let meta =
7257 PyramidMeta::decode(&mb).map_err(|_| FileError::Container("malformed pyramid meta"))?;
7258 Ok(Some(schema_coherence(
7259 &meta.class_hierarchy,
7260 &meta.subclass_cycles,
7261 &meta.disjoint_pairs,
7262 &meta.equivalent_pairs,
7263 )))
7264}
7265
7266#[allow(clippy::type_complexity)]
7274pub fn read_schema_summary_ranged<R: RangeReader>(
7275 reader: &R,
7276) -> Result<Option<(Vec<(String, u64)>, Vec<(String, String, String, u64)>)>, FileError> {
7277 let head = reader.read_at(0, HEADER_LEN as u64)?;
7278 let header = Header::from_bytes(&head)?;
7279 let meta = if let Some(s) = read_schema_with_header(reader, &header) {
7281 PyramidMeta::new(0, Vec::new(), &[]).with_schema(
7282 Vec::new(),
7283 s.level_rollups,
7284 s.level_links,
7285 Vec::new(),
7286 Vec::new(),
7287 Vec::new(),
7288 Vec::new(),
7289 )
7290 } else {
7291 if header.pyramid_meta_len == 0 {
7292 return Ok(None);
7293 }
7294 if header.schema_meta_len > 0 && (header.schema_meta_len as u64) <= header.pyramid_meta_len
7295 {
7296 let off = header.pyramid_meta_offset + header.pyramid_meta_len
7297 - header.schema_meta_len as u64;
7298 let block = reader.read_at(off, header.schema_meta_len as u64)?;
7299 let summary = crate::meta::decode_schema_block_summary(&block)
7300 .map_err(|_| FileError::Container("malformed schema block"))?;
7301 return Ok(Some(summary));
7302 }
7303 let mb = if crate::v06::reads(header.version) {
7305 crate::v06::open::read_pyramid(reader)?.unwrap_or_default()
7306 } else {
7307 reader.read_at(header.pyramid_meta_offset, header.pyramid_meta_len)?
7308 };
7309 PyramidMeta::decode(&mb).map_err(|_| FileError::Container("malformed pyramid meta"))?
7310 };
7311 if meta.level_rollups.is_empty() && meta.level_links.is_empty() {
7312 return Ok(None);
7313 }
7314 let classes = meta
7315 .level_rollups
7316 .iter()
7317 .max_by_key(|r| r.depth)
7318 .map(|r| r.classes.clone())
7319 .unwrap_or_default();
7320 let relations = meta
7321 .level_links
7322 .iter()
7323 .max_by_key(|l| l.depth)
7324 .map(|l| {
7325 l.links
7326 .iter()
7327 .map(|c| {
7328 (
7329 c.s_class.clone(),
7330 c.predicate.clone(),
7331 c.o_class.clone(),
7332 c.count,
7333 )
7334 })
7335 .collect()
7336 })
7337 .unwrap_or_default();
7338 Ok(Some((classes, relations)))
7339}
7340
7341#[cfg(test)]
7346pub(crate) fn dict_chunk_keys_for_test(image: &[u8]) -> Vec<Vec<Vec<u8>>> {
7347 if crate::v06::open::is_v06(image) {
7348 use crate::v06::{decode_chunk_leaf, decode_dict_root, kind, open, tag};
7350 let r = crate::reader::SliceReader::new(image);
7351 let (h, root) = open::read_front(&r).unwrap();
7352 let roots = decode_dict_root(root.unit(tag::DICT).unwrap()).unwrap();
7353 let leaves = open::read_section(&r, &h, &root, kind::DICT_LEAVES)
7354 .unwrap()
7355 .unwrap();
7356 return roots
7357 .iter()
7358 .map(|s| {
7359 s.leaves
7360 .iter()
7361 .flat_map(|(l, _, _, _)| {
7362 let stored = &leaves[l.off as usize..(l.off + l.len) as usize];
7363 let raw = decompress(h.internal_codec, stored).unwrap();
7364 decode_chunk_leaf(&raw, l.n).unwrap()
7365 })
7366 .map(|c| c.key)
7367 .collect()
7368 })
7369 .collect();
7370 }
7371 let header = Header::from_bytes(&image[..HEADER_LEN]).unwrap();
7372 let s = header.dictionary_offset as usize;
7373 let e = s + header.dictionary_len as usize;
7374 decode_container(&image[s..e], CODEC_NONE)
7375 .unwrap()
7376 .iter()
7377 .map(|payload| {
7378 let (_meta, entries) = parse_chunked_dict_dir(payload, payload.len() as u64).unwrap();
7379 entries.into_iter().map(|c| c.key).collect()
7380 })
7381 .collect()
7382}
7383
7384#[cfg(test)]
7385mod tests {
7386 use super::*;
7387 use super::{
7388 write_dataset_v05 as write_dataset,
7389 write_dataset_with_metadata_v05 as write_dataset_with_metadata,
7390 write_file_v05 as write_file,
7391 };
7392 use crate::dictionary::DictionaryBuilder;
7393 use crate::index::GraphIndexBuilder;
7394
7395 #[cfg(not(feature = "compression"))]
7398 #[test]
7399 fn ruzstd_decodes_a_zstd_frame() {
7400 let data: Vec<u8> = (0..50_000u32)
7401 .flat_map(|i| (i % 251).to_le_bytes())
7402 .collect();
7403 let frame = ruzstd::encoding::compress_to_vec(
7404 &data[..],
7405 ruzstd::encoding::CompressionLevel::Fastest,
7406 );
7407 assert!(frame.len() < data.len());
7408 assert_eq!(decompress(CODEC_ZSTD, &frame).unwrap(), data);
7409 }
7410
7411 #[cfg(feature = "compression")]
7416 #[test]
7417 fn decompression_is_bounded() {
7418 let data: Vec<u8> = (0..100_000u32).map(|i| (i % 251) as u8).collect();
7419 let sized = zstd::bulk::compress(&data, 3).unwrap();
7420 assert_eq!(zstd_frame_content_size(&sized), Some(100_000));
7421 assert_eq!(block_raw_len(CODEC_ZSTD, &sized, 1 << 20).unwrap(), 100_000);
7422 assert_eq!(
7423 decompress_bounded(CODEC_ZSTD, &sized, 100_000).unwrap(),
7424 data
7425 );
7426 assert!(decompress_bounded(CODEC_ZSTD, &sized, 99_999).is_err());
7427 let stream = zstd::encode_all(&data[..], 3).unwrap();
7429 assert_eq!(zstd_frame_content_size(&stream), None);
7430 assert_eq!(
7431 block_raw_len(CODEC_ZSTD, &stream, 1 << 20).unwrap(),
7432 100_000
7433 );
7434 assert_eq!(
7435 decompress_bounded(CODEC_ZSTD, &stream, 100_000).unwrap(),
7436 data
7437 );
7438 assert!(decompress_bounded(CODEC_ZSTD, &stream, 50_000).is_err());
7439 let mut liar = sized.clone();
7441 let fhd = liar[4];
7442 let fcs_at = 5 + usize::from(fhd & 0x20 == 0);
7443 liar[fcs_at] = liar[fcs_at].wrapping_sub(1);
7444 assert!(decompress_bounded(CODEC_ZSTD, &liar, 200_000).is_err());
7445 assert!(decompress_bounded(CODEC_NONE, &data, 99_999).is_err());
7447 assert_eq!(
7448 decompress_bounded(CODEC_NONE, &data, 100_000).unwrap(),
7449 data
7450 );
7451 assert_eq!(zstd_frame_content_size(b"RETE"), None);
7452 }
7453
7454 #[test]
7460 fn three_permutation_file_round_trips_every_open_path() {
7461 use crate::index::PermSet;
7462 use crate::reader::SliceReader;
7463
7464 let build = |perms: PermSet| {
7465 let mut db = crate::DictionaryBuilder::new();
7466 let mut triples = Vec::new();
7467 for i in 0..60u32 {
7468 let (s, p, o) = (
7469 format!("<http://ex/s{}>", i % 11),
7470 format!("<http://ex/p{}>", i % 3),
7471 format!("<http://ex/o{}>", i % 7),
7472 );
7473 db.observe(&s, &p, &o);
7474 triples.push((s, p, o));
7475 }
7476 let dict = db.build();
7477 let ids: Vec<(u32, u32, u32)> = triples
7478 .iter()
7479 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
7480 .collect();
7481 let def = GraphIndexBuilder::from_triples(ids.clone())
7482 .with_tile_budget(96)
7483 .with_perms(perms)
7484 .build();
7485 let named = GraphIndexBuilder::from_triples(ids)
7486 .with_tile_budget(96)
7487 .with_perms(perms)
7488 .build();
7489 write_dataset(
7490 &dict,
7491 &def,
7492 &[("<http://ex/g>".to_string(), named)],
7493 true,
7494 &[],
7495 0,
7496 )
7497 };
7498
7499 let six = build(PermSet::ALL);
7500 let three = build(PermSet::CORE);
7501 assert!(three.len() < six.len());
7502 assert_eq!(Header::from_bytes(&three).unwrap().perms, PermSet::CORE);
7503 assert_eq!(Header::from_bytes(&six).unwrap().perms, PermSet::ALL);
7504
7505 let shapes: Vec<(Option<&str>, Option<&str>, Option<&str>)> = vec![
7506 (None, None, None),
7507 (Some("<http://ex/s3>"), None, None),
7508 (None, Some("<http://ex/p1>"), None),
7509 (None, None, Some("<http://ex/o5>")),
7510 (Some("<http://ex/s3>"), Some("<http://ex/p1>"), None),
7511 (Some("<http://ex/s3>"), None, Some("<http://ex/o5>")),
7512 (None, Some("<http://ex/p1>"), Some("<http://ex/o5>")),
7513 (
7514 Some("<http://ex/s3>"),
7515 Some("<http://ex/p1>"),
7516 Some("<http://ex/o5>"),
7517 ),
7518 ];
7519
7520 for (image, tag) in [(&six, "six"), (&three, "three")] {
7521 let resident = Rete::open(image).unwrap();
7522 let leaked: &'static [u8] = Box::leak(image.clone().into_boxed_slice());
7523 let ranged = Rete::open_ranged(&SliceReader::new(leaked)).unwrap();
7524 let lazy =
7525 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64).unwrap();
7526 for (s, p, o) in &shapes {
7527 let want: Vec<_> = {
7528 let mut v = Rete::open(&six).unwrap().query(*s, *p, *o);
7529 v.sort();
7530 v
7531 };
7532 for (got, path) in [
7533 (resident.query(*s, *p, *o), "resident"),
7534 (ranged.query(*s, *p, *o), "ranged"),
7535 (lazy.query(*s, *p, *o), "lazy"),
7536 ] {
7537 let mut got = got;
7538 got.sort();
7539 assert_eq!(got, want, "{tag}/{path} disagreed on {:?}", (s, p, o));
7540 }
7541 let mut g = resident.query_in_graph(Some("<http://ex/g>"), *s, *p, *o);
7543 g.sort();
7544 assert_eq!(g, want, "{tag}/named disagreed on {:?}", (s, p, o));
7545 }
7546 }
7547
7548 let leaked: &'static [u8] = Box::leak(three.clone().into_boxed_slice());
7552 let reader = SliceReader::new(leaked);
7553 let routed = Rete::query_ranged(&reader, None, None, Some("<http://ex/o5>")).unwrap();
7554 let mut want = Rete::open(&six)
7555 .unwrap()
7556 .query(None, None, Some("<http://ex/o5>"));
7557 want.sort();
7558 let mut got = routed;
7559 got.sort();
7560 assert_eq!(got, want, "routed single-pattern read on a lean file");
7561 }
7562
7563 #[test]
7564 fn read_coalesced_merges_within_gap_and_splits_beyond() {
7565 use crate::reader::{CountingReader, SliceReader};
7566 let bytes = vec![0u8; 4096];
7567 let ranges = [
7569 ByteRange { offset: 0, len: 16 },
7570 ByteRange {
7571 offset: 48,
7572 len: 16,
7573 },
7574 ByteRange {
7575 offset: 1088,
7576 len: 16,
7577 },
7578 ];
7579 let r = CountingReader::new(SliceReader::new(&bytes));
7581 let out = read_coalesced(&r, &ranges, 16).unwrap();
7582 assert_eq!(out.len(), 3);
7583 assert_eq!(r.requests(), 3);
7584 let r = CountingReader::new(SliceReader::new(&bytes));
7586 read_coalesced(&r, &ranges, 64).unwrap();
7587 assert_eq!(r.requests(), 2);
7588 let r = CountingReader::new(SliceReader::new(&bytes));
7590 read_coalesced(&r, &ranges, 4096).unwrap();
7591 assert_eq!(r.requests(), 1);
7592 }
7593
7594 fn build_image() -> Vec<u8> {
7595 let triples = [
7596 ("Alice", "knows", "Bob"),
7597 ("Bob", "knows", "Carol"),
7598 ("Alice", "age", "30"),
7599 ];
7600 let mut db = DictionaryBuilder::new();
7601 for (s, p, o) in triples {
7602 db.observe(s, p, o);
7603 }
7604 let dict = db.build();
7605
7606 let mut ib = GraphIndexBuilder::new();
7607 for (s, p, o) in triples {
7608 ib.push(dict.encode(s, p, o).unwrap());
7609 }
7610 let index = ib.build();
7611
7612 let (meta, levels) = build_pyramid_meta(&dict, &triples_ids(&dict), DEFAULT_TILE_BUDGET);
7613 write_file(&dict, &index, false, &meta, levels)
7614 }
7615
7616 fn triples_ids(dict: &Dictionary) -> Vec<(u32, u32, u32)> {
7617 [
7618 ("Alice", "knows", "Bob"),
7619 ("Bob", "knows", "Carol"),
7620 ("Alice", "age", "30"),
7621 ]
7622 .iter()
7623 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
7624 .collect()
7625 }
7626
7627 #[test]
7628 fn file_round_trips_header_and_counts() {
7629 let bytes = build_image();
7630 let rete = Rete::open(&bytes).unwrap();
7631 assert_eq!(rete.header().quad_count, 3);
7632 assert!(rete.header().term_count >= 5);
7633 let expected_codec = writer_codec();
7634 assert_eq!(rete.header().dict_codec, expected_codec);
7635 assert_eq!(rete.header().block_codec, expected_codec);
7636 assert_eq!(&bytes[bytes.len() - 4..], &MAGIC); }
7638
7639 #[test]
7644 fn multi_tile_file_round_trips_and_routes() {
7645 let triples: Vec<(String, String, String)> = (0..200)
7646 .map(|i| {
7647 (
7648 format!("<http://ex/s/{i}>"),
7649 format!("<http://ex/p/{}>", i % 5),
7650 format!("<http://ex/o/{}>", i % 23),
7651 )
7652 })
7653 .collect();
7654 let mut db = DictionaryBuilder::new();
7655 for (s, p, o) in &triples {
7656 db.observe(s, p, o);
7657 }
7658 let dict = db.build();
7659 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
7660 for (s, p, o) in &triples {
7661 ib.push(dict.encode(s, p, o).unwrap());
7662 }
7663 let index = ib.build();
7664 assert!(
7665 index.tile_sections()[0].len() > 3,
7666 "tiny budget must force many tiles"
7667 );
7668 let bytes = write_file(&dict, &index, false, &[], 0);
7669
7670 let rete = Rete::open(&bytes).unwrap();
7671 assert_eq!(rete.header().version, crate::header::LEGACY_FORMAT_VERSION);
7672 assert_eq!(rete.query(None, None, None).len(), 200);
7673 assert_eq!(rete.query(Some("<http://ex/s/7>"), None, None).len(), 1);
7674 assert_eq!(
7675 rete.query(None, Some("<http://ex/p/3>"), None).len(),
7676 40,
7677 "predicate extent spans tiles"
7678 );
7679 assert_eq!(
7680 rete.query(None, None, Some("<http://ex/o/22>")).len(),
7681 8 );
7683
7684 use crate::reader::SliceReader;
7686 let reader = SliceReader::new(&bytes);
7687 let routed = Rete::query_ranged(&reader, Some("<http://ex/s/7>"), None, None).unwrap();
7688 assert_eq!(routed.len(), 1);
7689 let routed = Rete::query_ranged(&reader, None, Some("<http://ex/p/3>"), None).unwrap();
7690 assert_eq!(routed.len(), 40);
7691 let routed = Rete::query_ranged(&reader, None, None, Some("<http://ex/o/22>")).unwrap();
7692 assert_eq!(routed.len(), 8);
7693 }
7694
7695 #[test]
7704 fn tile_directory_offsets_survive_past_4gib() {
7705 let mut dir = Vec::new();
7706 write_uvarint(&mut dir, 2); write_uvarint(&mut dir, 5); write_uvarint(&mut dir, 0); write_uvarint(&mut dir, 3 << 30); write_uvarint(&mut dir, 1); write_uvarint(&mut dir, 0);
7712 write_uvarint(&mut dir, 2 << 30); let total = dir.len() as u64 + (3u64 << 30) + (2u64 << 30) + 64;
7714 let entries = parse_tile_directory(&dir, total).unwrap();
7715 assert_eq!(entries.len(), 2);
7716 assert_eq!(entries[1].start, dir.len() as u64 + (3u64 << 30));
7717 assert!(
7718 entries[1].end > u32::MAX as u64,
7719 "tail tile sits past 4 GiB"
7720 );
7721 assert!(parse_tile_directory(&dir, 1 << 20).is_err());
7723 }
7724
7725 #[test]
7726 fn tile_synopsis_trailer_round_trips() {
7727 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
7728 for i in 0..200u32 {
7729 ib.push((i, i % 7, i % 13));
7730 }
7731 let index = ib.build();
7732 let tile_count = index.tile_sections()[0].len();
7733 assert!(tile_count > 3, "tiny budget forces many tiles");
7734
7735 let payload = encode_tiled_section(&index, 0, CODEC_NONE);
7736 let dir = parse_tile_directory(&payload, payload.len() as u64).unwrap();
7737 assert_eq!(dir.len(), tile_count);
7738 let trailer_start = dir.iter().map(|e| e.end).max().unwrap();
7740 assert!(
7741 trailer_start < payload.len() as u64,
7742 "a trailer follows the tiles"
7743 );
7744 for e in &dir {
7745 assert!(
7746 e.end <= payload.len() as u64,
7747 "tiles still located within the payload"
7748 );
7749 }
7750 let syn = parse_tile_synopsis(&payload, trailer_start as usize, dir.len()).unwrap();
7751 for (e, (min_b, max_b, min_c, max_c)) in dir.iter().zip(syn) {
7752 let block = decompress(CODEC_NONE, &payload[e.start as usize..e.end as usize]).unwrap();
7753 let z = *crate::triples::TripleBlock::parse(&block).unwrap().zone();
7754 assert_eq!(
7755 (min_b, max_b, min_c, max_c),
7756 (z.min_b, z.max_b, z.min_c, z.max_c),
7757 "synopsis equals the tile's own zone"
7758 );
7759 }
7760 }
7761
7762 #[test]
7766 fn tile_synopsis_lazy_matches_reference_every_shape() {
7767 use crate::reader::{CountingReader, SliceReader};
7768 let triples: Vec<(String, String, String)> = (0..200u32)
7769 .map(|i| {
7770 (
7771 format!("<http://ex/s/{i:04}>"),
7772 format!("<http://ex/p/{}>", i % 7),
7773 format!("<http://ex/o/{:04}>", i % 13),
7774 )
7775 })
7776 .collect();
7777 let mut db = DictionaryBuilder::new();
7778 for (s, p, o) in &triples {
7779 db.observe(s, p, o);
7780 }
7781 let dict = db.build();
7782 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
7783 for (s, p, o) in &triples {
7784 ib.push(dict.encode(s, p, o).unwrap());
7785 }
7786 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
7787
7788 let eager = Rete::open(&bytes).unwrap();
7789 assert!(
7790 eager.header().has_tile_synopsis(),
7791 "new files set the synopsis flag"
7792 );
7793
7794 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
7797 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
7798 let lazy = Rete::open_ranged_lazy_with(reader, HEADER_LEN as u64).unwrap();
7799
7800 let brute = |s: Option<&str>, p: Option<&str>, o: Option<&str>| {
7801 let mut v: Vec<(String, String, String)> = triples
7802 .iter()
7803 .filter(|(a, b, c)| {
7804 s.is_none_or(|x| x == a) && p.is_none_or(|x| x == b) && o.is_none_or(|x| x == c)
7805 })
7806 .cloned()
7807 .collect();
7808 v.sort();
7809 v
7810 };
7811 let sv = [
7813 None,
7814 Some("<http://ex/s/0007>"),
7815 Some("<http://ex/s/0130>"),
7816 Some("<http://ex/s/9999>"),
7817 ];
7818 let pv = [
7819 None,
7820 Some("<http://ex/p/3>"),
7821 Some("<http://ex/p/6>"),
7822 Some("<http://ex/p/999>"),
7823 ];
7824 let ov = [
7825 None,
7826 Some("<http://ex/o/0000>"),
7827 Some("<http://ex/o/0012>"),
7828 Some("<http://ex/o/9999>"),
7829 ];
7830 for &s in &sv {
7831 for &p in &pv {
7832 for &o in &ov {
7833 let mut e = eager.query(s, p, o);
7834 e.sort();
7835 let mut l = lazy.query(s, p, o);
7836 l.sort();
7837 let r = brute(s, p, o);
7838 assert_eq!(e, r, "eager {s:?} {p:?} {o:?}");
7839 assert_eq!(l, r, "lazy {s:?} {p:?} {o:?} — synopsis over-pruned");
7840 }
7841 }
7842 }
7843 assert!(!lazy.index_incomplete(), "no lazy fetch failed");
7844 }
7845
7846 #[test]
7850 fn polyglot_offset_reads_lazily() {
7851 use crate::reader::{
7852 detect_polyglot_base, CountingReader, OffsetReader, SliceReader, POLYGLOT_DIGITS,
7853 POLYGLOT_MARKER,
7854 };
7855
7856 let image = build_image();
7860 let mut shell = Vec::new();
7861 shell.extend_from_slice(b"<!DOCTYPE html><html><head><!--");
7862 shell.extend_from_slice(POLYGLOT_MARKER);
7863 let digits_at = shell.len();
7864 shell.extend_from_slice(&[b'0'; POLYGLOT_DIGITS]); shell.extend_from_slice(b"--></head><body>a web page</body></html>\n");
7866 shell.resize(50_000, b' '); let base = shell.len() as u64;
7868 let digits = format!("{base:0width$}", width = POLYGLOT_DIGITS);
7869 shell[digits_at..digits_at + POLYGLOT_DIGITS].copy_from_slice(digits.as_bytes());
7870
7871 let mut poly = shell;
7872 poly.extend_from_slice(&image);
7873
7874 assert_ne!(
7876 &poly[0..4],
7877 b"RETE",
7878 "polyglot must not start with the magic"
7879 );
7880 let detected = detect_polyglot_base(&poly[..crate::header::HEADER_LEN]).unwrap();
7882 assert_eq!(detected, base);
7883
7884 let leaked: &'static [u8] = Box::leak(poly.into_boxed_slice());
7886 let counting = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
7887 let lazy = Rete::open_ranged_lazy_with(
7888 OffsetReader::new(counting.clone(), detected),
7889 HEADER_LEN as u64,
7890 )
7891 .unwrap();
7892
7893 let plain = Rete::open(&image).unwrap();
7895 let mut want = plain.query(None, None, None);
7896 want.sort();
7897 let mut got = lazy.query(None, None, None);
7898 got.sort();
7899 assert_eq!(
7900 got, want,
7901 "polyglot lazy query differs from the plain .rete"
7902 );
7903 assert!(!got.is_empty(), "expected some triples");
7904 assert!(!lazy.index_incomplete(), "a lazy fetch failed");
7905
7906 let read = counting.bytes_read();
7909 eprintln!(
7910 "polyglot lazy read: HTML shell {base} B + .rete image {} B; \
7911 the query touched only {read} B (never the shell).",
7912 image.len()
7913 );
7914 assert!(
7915 read < base,
7916 "read {read} bytes; the HTML shell alone is {base} — the reader \
7917 touched the prefix instead of only the embedded .rete"
7918 );
7919 }
7920
7921 #[cfg(test)]
7924 fn build_text_indexed(triples: &[(String, String, String)]) -> Vec<u8> {
7925 let mut db = DictionaryBuilder::new();
7926 for (s, p, o) in triples {
7927 db.observe(s, p, o);
7928 }
7929 let dict = db.build();
7930 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
7931 let mut id_triples: Vec<(u32, u32, u32)> = Vec::with_capacity(triples.len());
7932 for (s, p, o) in triples {
7933 let t = dict.encode(s, p, o).unwrap();
7934 ib.push(t);
7935 id_triples.push(t);
7936 }
7937 let index = ib.build();
7938 let text_index = compute_text_index(&dict, &id_triples);
7939 assert!(
7940 !text_index.is_empty(),
7941 "literals should produce a text index"
7942 );
7943 write_dataset_with_metadata(&dict, &index, &[], false, &[], 0, &[], &text_index)
7944 }
7945
7946 #[test]
7950 fn text_index_eager_matches_brute_force() {
7951 let triples: Vec<(String, String, String)> = vec![
7952 (
7953 "<http://ex/s0>",
7954 "<http://ex/label>",
7955 "\"alpha glucose phosphate\"",
7956 ),
7957 ("<http://ex/s1>", "<http://ex/label>", "\"beta Glucose\""),
7958 ("<http://ex/s2>", "<http://ex/label>", "\"gamma fructose\""),
7959 (
7960 "<http://ex/s3>",
7961 "<http://ex/note>",
7962 "\"einstein relativity\"",
7963 ),
7964 (
7965 "<http://ex/s4>",
7966 "<http://ex/ref>",
7967 "<http://ex/not-a-literal>",
7968 ),
7969 ]
7970 .into_iter()
7971 .map(|(s, p, o)| (s.to_string(), p.to_string(), o.to_string()))
7972 .collect();
7973 let bytes = build_text_indexed(&triples);
7974 let rete = Rete::open(&bytes).unwrap();
7975 assert!(rete.has_text_index());
7976
7977 let brute = |words: &[&str]| -> Vec<String> {
7979 let mut v: Vec<String> = triples
7980 .iter()
7981 .filter(|(_, _, o)| {
7982 crate::terms::is_literal(o)
7983 && words.iter().all(|w| {
7984 let wl = w.to_lowercase();
7985 crate::terms::literal_lexical(o)
7986 .unwrap()
7987 .split(|c: char| !c.is_alphanumeric())
7988 .any(|t| t.to_lowercase() == wl)
7989 })
7990 })
7991 .map(|(s, _, _)| s.clone())
7992 .collect();
7993 v.sort();
7994 v.dedup();
7995 v
7996 };
7997
7998 let mut got = rete.text_search(&["glucose"], None, 0);
7999 got.sort();
8000 assert_eq!(got, brute(&["glucose"]), "case-insensitive single word");
8001
8002 let mut got = rete.text_search(&["glucose", "phosphate"], None, 0);
8004 got.sort();
8005 assert_eq!(got, brute(&["glucose", "phosphate"]));
8006
8007 assert!(rete.text_search(&["zzznope"], None, 0).is_empty());
8009
8010 let got = rete.text_search(&[], Some("ein"), 0);
8012 assert_eq!(got, vec!["<http://ex/s3>".to_string()]);
8013
8014 let mut db = DictionaryBuilder::new();
8016 for (s, p, o) in &triples {
8017 db.observe(s, p, o);
8018 }
8019 let dict = db.build();
8020 let mut ib = GraphIndexBuilder::new();
8021 for (s, p, o) in &triples {
8022 ib.push(dict.encode(s, p, o).unwrap());
8023 }
8024 let plain = write_dataset(&dict, &ib.build(), &[], false, &[], 0);
8025 let plain_rete = Rete::open(&plain).unwrap();
8026 assert!(!plain_rete.has_text_index());
8027 assert!(plain_rete.text_search(&["glucose"], None, 0).is_empty());
8028 }
8029
8030 #[test]
8034 fn text_index_lazy_faults_only_queried_postings() {
8035 use crate::reader::{CountingReader, SliceReader};
8036 let mut triples: Vec<(String, String, String)> = (0..300u32)
8039 .map(|i| {
8040 (
8041 format!("<http://ex/s/{i:04}>"),
8042 "<http://ex/label>".to_string(),
8043 format!("\"common word number {i}\""),
8044 )
8045 })
8046 .collect();
8047 for i in [3u32, 77, 250] {
8048 triples.push((
8049 format!("<http://ex/s/{i:04}>"),
8050 "<http://ex/tag>".to_string(),
8051 "\"raretoken\"".to_string(),
8052 ));
8053 }
8054 let bytes = build_text_indexed(&triples);
8055 let eager = Rete::open(&bytes).unwrap();
8056 let mut want = eager.text_search(&["raretoken"], None, 0);
8057 want.sort();
8058 assert_eq!(want.len(), 3);
8059
8060 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
8061 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
8062 let lazy = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
8063 let before = reader.bytes_read();
8066 let mut got = lazy.text_search(&["raretoken"], None, 0);
8067 got.sort();
8068 assert_eq!(got, want, "lazy search matches eager");
8069 let pulled = reader.bytes_read() - before;
8070 let ti_len = eager.header().text_index_len;
8073 assert!(
8074 pulled < ti_len,
8075 "search pulled {pulled} B but the section is {ti_len} B — faulted too much"
8076 );
8077 assert!(!lazy.index_incomplete());
8078 }
8079
8080 #[test]
8085 fn search_view_matches_full_open_for_far_fewer_bytes() {
8086 use crate::reader::{CountingReader, SliceReader};
8087 let filler = "lorem ipsum dolor sit amet consectetur adipiscing elit ".repeat(20);
8090 let mut triples: Vec<(String, String, String)> = (0..300u32)
8091 .map(|i| {
8092 (
8093 format!("<http://ex/s/{i:04}>"),
8094 "<http://ex/abstract>".to_string(),
8095 format!("\"{filler} number {i}\""),
8096 )
8097 })
8098 .collect();
8099 for i in [3u32, 77, 250] {
8100 triples.push((
8101 format!("<http://ex/s/{i:04}>"),
8102 "<http://ex/tag>".to_string(),
8103 "\"raretoken\"".to_string(),
8104 ));
8105 }
8106 let bytes = build_text_indexed(&triples);
8107 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
8108
8109 let full_reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
8110 let full = Rete::open_ranged_lazy_with(full_reader.clone(), HEADER_LEN as u64).unwrap();
8111 let mut want = full.text_search(&["raretoken"], None, 0);
8112 want.sort();
8113 assert_eq!(want.len(), 3);
8114
8115 let search_reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
8116 let view = SearchView::open_ranged_with(search_reader.clone(), HEADER_LEN as u64).unwrap();
8117 assert!(view.has_text_index());
8118 let mut got = view.text_search(&["raretoken"], None, 0);
8119 got.sort();
8120 assert_eq!(got, want, "search view matches the full open");
8121 assert!(
8122 search_reader.bytes_read() < full_reader.bytes_read(),
8123 "search read {} B, full open read {} B — the narrow open bought nothing",
8124 search_reader.bytes_read(),
8125 full_reader.bytes_read()
8126 );
8127
8128 let mut prefix_hits = view.prefix_search("", 5);
8131 prefix_hits.sort();
8132 assert!(!prefix_hits.is_empty() || !view.has_pyramid());
8133 }
8134
8135 #[test]
8145 fn dict_chunk_directory_probe_costs_about_one_directory() {
8146 use crate::reader::{CountingReader, SliceReader};
8147 let head = "x".repeat(3000);
8161 let triples: Vec<(String, String, String)> = (0..2000u32)
8162 .map(|i| {
8163 let tail = char::from(b'a' + (i % 26) as u8).to_string().repeat(1000);
8164 (
8165 format!("<http://ex/s/{i:04}>"),
8166 "<http://ex/abstract>".to_string(),
8167 format!("\"{head}{i:04}{tail}\""),
8168 )
8169 })
8170 .collect();
8171 let mut db = DictionaryBuilder::new();
8172 for (s, p, o) in &triples {
8173 db.observe(s, p, o);
8174 }
8175 let dict = db.build();
8176 let mut ib = GraphIndexBuilder::new();
8177 for (s, p, o) in &triples {
8178 ib.push(dict.encode(s, p, o).unwrap());
8179 }
8180 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
8181
8182 let reader = CountingReader::new(SliceReader::new(&bytes));
8183 let header = Header::from_bytes(&reader.read_at(0, HEADER_LEN as u64).unwrap()).unwrap();
8184 let section = locate_container_section_ranged(
8186 &reader,
8187 header.dictionary_offset,
8188 header.dictionary_len,
8189 2,
8190 4,
8191 )
8192 .unwrap();
8193
8194 let before = reader.bytes_read();
8195 let (_meta, entries) = read_dict_dir_ranged(&reader, section).unwrap();
8196 let spent = reader.bytes_read() - before;
8197
8198 let dir_end = entries[0].start;
8200 let head = reader.read_at(section.offset, 64).unwrap();
8201 let (header_len, n0) = read_uvarint(&head).unwrap();
8202 let dir_start = n0 as u64 + header_len;
8203 let dir_len = dir_end - dir_start;
8204 let dir_total = section.len - dir_start;
8205 assert!(
8206 dir_start + dir_len > 8192,
8207 "directory fits the header prefix ({dir_len} B) — the probe never runs"
8208 );
8209
8210 let mut old = 0u64;
8212 let mut p = 4096u64.min(dir_total).max(1);
8213 loop {
8214 let got = p.min(dir_total);
8215 old += got;
8216 if got >= dir_len || p >= dir_total {
8217 break;
8218 }
8219 p = p.saturating_mul(2).min(dir_total);
8220 }
8221 assert!(
8222 spent <= dir_len * 2,
8223 "probe read {spent} B for a {dir_len} B directory — past the append-only bound"
8224 );
8225 assert!(
8226 spent < old,
8227 "probe read {spent} B; the re-reading loop it replaced spent {old} B"
8228 );
8229 }
8230
8231 fn verbatim_keyed_twin(payload: &[u8], codec: u8) -> Vec<u8> {
8241 let (_meta, entries) = parse_chunked_dict_dir(payload, payload.len() as u64).unwrap();
8242 let (header_len, n0) = read_uvarint(payload).unwrap();
8243 let mut out = Vec::new();
8244 write_uvarint(&mut out, header_len);
8245 out.extend_from_slice(&payload[n0..n0 + header_len as usize]);
8246 write_uvarint(&mut out, entries.len() as u64);
8247 let mut prev_run = 0usize;
8248 for e in &entries {
8249 let body = decompress(codec, &payload[e.start as usize..e.end as usize]).unwrap();
8250 let first = crate::dict::run_first_term(&body, 0).unwrap();
8251 write_uvarint(&mut out, (e.first_run - prev_run) as u64);
8252 write_uvarint(&mut out, first.len() as u64);
8253 out.extend_from_slice(&first);
8254 write_uvarint(&mut out, e.end - e.start);
8255 prev_run = e.first_run;
8256 }
8257 for e in &entries {
8258 out.extend_from_slice(&payload[e.start as usize..e.end as usize]);
8259 }
8260 out
8261 }
8262
8263 fn chunk_bounds_of(payload: &[u8], codec: u8) -> Vec<(Vec<u8>, Vec<u8>)> {
8265 let (_meta, entries) = parse_chunked_dict_dir(payload, payload.len() as u64).unwrap();
8266 entries
8267 .iter()
8268 .map(|e| {
8269 let body = decompress(codec, &payload[e.start as usize..e.end as usize]).unwrap();
8270 (
8271 crate::dict::run_first_term(&body, 0).unwrap(),
8272 crate::dict::run_last_term(&body, 0, body.len()).unwrap(),
8273 )
8274 })
8275 .collect()
8276 }
8277
8278 fn adversarial_terms() -> Vec<String> {
8284 let mut terms: Vec<String> = Vec::new();
8285 for i in 0..6_000 {
8286 terms.push(format!("<http://example.org/work/{i:06}>"));
8287 }
8288 let shared = "X".repeat(900);
8289 for i in 0..4_000 {
8290 terms.push(format!("\"{shared}-{i:05}-tail\""));
8291 }
8292 let deep = "Y".repeat(3_000); for i in 0..120 {
8294 terms.push(format!("\"{deep}{i:03}\""));
8295 }
8296 for i in 0..6 {
8297 terms.push(format!("\"BIG-{i:02}-{}\"", "Z".repeat(90_000)));
8299 }
8300 for i in 0..800 {
8301 terms.push(format!(
8302 "\"h\u{e9}llo-{}-\u{1F600}{i:04}\"",
8303 "\u{e9}".repeat(40)
8304 ));
8305 }
8306 for i in 0..2_000 {
8307 terms.push(format!("\"{i:05}-{}\"", "T".repeat(1_800)));
8308 }
8309 terms.sort();
8310 terms.dedup();
8311 terms
8312 }
8313
8314 fn chunked_section_of(terms: &[String]) -> Vec<u8> {
8315 let mut b = crate::dict::DictSectionBuilder::new().with_restart_interval(16);
8316 for t in terms {
8317 b.push(t.clone());
8318 }
8319 b.build()
8320 }
8321
8322 #[test]
8332 fn chunk_directory_keys_are_separators_not_terms() {
8333 let terms = adversarial_terms();
8334 let raw = chunked_section_of(&terms);
8335 let payload = encode_chunked_dict_section(&raw, CODEC_NONE);
8336 let (_meta, entries) = parse_chunked_dict_dir(&payload, payload.len() as u64).unwrap();
8337 let bounds = chunk_bounds_of(&payload, CODEC_NONE);
8338 assert!(
8339 entries.len() > 20,
8340 "need a many-chunk section, got {}",
8341 entries.len()
8342 );
8343
8344 assert!(entries[0].key.is_empty(), "chunk 0 needs no separator");
8345 let mut key_bytes = 0usize;
8346 let mut term_bytes = 0usize;
8347 let mut differ = 0usize;
8348 for (i, e) in entries.iter().enumerate() {
8349 key_bytes += e.key.len();
8350 term_bytes += bounds[i].0.len();
8351 if e.key != bounds[i].0 {
8352 differ += 1;
8353 }
8354 assert!(
8355 e.key <= bounds[i].0,
8356 "chunk {i}: key must be <= its own first term"
8357 );
8358 if i > 0 {
8359 assert!(
8360 e.key.as_slice() > bounds[i - 1].1.as_slice(),
8361 "chunk {i}: key must be > the previous chunk's last term"
8362 );
8363 assert!(
8364 e.key > entries[i - 1].key,
8365 "chunk {i}: keys must ascend for partition_point"
8366 );
8367 assert_eq!(
8369 e.key,
8370 crate::dict::shortest_separator(&bounds[i - 1].1, &bounds[i].0),
8371 "chunk {i}: key is not the SHORTEST separator"
8372 );
8373 }
8374 }
8375 assert!(
8376 differ > 0,
8377 "every key equalled its first term — the writer stores terms again"
8378 );
8379 assert!(
8380 key_bytes * 4 < term_bytes,
8381 "separators bought almost nothing: {key_bytes} B vs {term_bytes} B of first terms"
8382 );
8383 eprintln!(
8384 "chunks={} first-term keys={term_bytes} B separator keys={key_bytes} B ({:.1}x)",
8385 entries.len(),
8386 term_bytes as f64 / key_bytes.max(1) as f64
8387 );
8388 }
8389
8390 #[test]
8401 fn separator_keys_route_identically_to_verbatim_first_terms() {
8402 let terms = adversarial_terms();
8403 let raw = chunked_section_of(&terms);
8404 let sep_payload = encode_chunked_dict_section(&raw, CODEC_NONE);
8405 let ver_payload = verbatim_keyed_twin(&sep_payload, CODEC_NONE);
8406
8407 let (_ms, es) = parse_chunked_dict_dir(&sep_payload, sep_payload.len() as u64).unwrap();
8409 let (_mv, ev) = parse_chunked_dict_dir(&ver_payload, ver_payload.len() as u64).unwrap();
8410 assert_eq!(es.len(), ev.len());
8411 for (a, b) in es.iter().zip(ev.iter()) {
8412 assert_eq!(a.first_run, b.first_run);
8413 assert_eq!(
8414 &sep_payload[a.start as usize..a.end as usize],
8415 &ver_payload[b.start as usize..b.end as usize],
8416 "chunk bodies must be identical"
8417 );
8418 }
8419 assert!(
8420 sep_payload.len() < ver_payload.len(),
8421 "separator payload is not smaller"
8422 );
8423
8424 let sec_s = decode_chunked_dict_section(
8425 &sep_payload,
8426 CODEC_NONE,
8427 crate::chunk_cache::ChunkCache::unlimited_arc(),
8428 0,
8429 )
8430 .unwrap();
8431 let sec_v = decode_chunked_dict_section(
8432 &ver_payload,
8433 CODEC_NONE,
8434 crate::chunk_cache::ChunkCache::unlimited_arc(),
8435 0,
8436 )
8437 .unwrap();
8438
8439 for (i, t) in terms.iter().enumerate() {
8441 let want = Some(i as u32 + 1);
8442 assert_eq!(sec_v.id(t), want, "verbatim id() lost a term");
8443 assert_eq!(sec_s.id(t), want, "separator id() lost a term");
8444 }
8445 for i in 0..terms.len() as u32 {
8447 assert_eq!(sec_s.term(i + 1), sec_v.term(i + 1));
8448 assert_eq!(
8449 sec_s.term(i + 1).as_deref(),
8450 Some(terms[i as usize].as_str())
8451 );
8452 }
8453 let bounds = chunk_bounds_of(&sep_payload, CODEC_NONE);
8455 let mut probes: Vec<String> = Vec::new();
8456 let push = |bytes: &[u8], probes: &mut Vec<String>| {
8457 if let Ok(s) = std::str::from_utf8(bytes) {
8458 probes.push(s.to_string());
8459 }
8460 };
8461 for (first, last) in &bounds {
8462 for base in [first, last] {
8463 push(base, &mut probes); let mut after = base.clone();
8465 after.push(0x01); push(&after, &mut probes);
8467 let mut far = base.clone();
8468 far.push(b'~');
8469 push(&far, &mut probes);
8470 if !base.is_empty() {
8471 push(&base[..base.len() - 1], &mut probes); let mut down = base.clone();
8473 *down.last_mut().unwrap() = down.last().unwrap().wrapping_sub(1);
8474 push(&down, &mut probes);
8475 let mut up = base.clone();
8476 *up.last_mut().unwrap() = up.last().unwrap().wrapping_add(1);
8477 push(&up, &mut probes);
8478 }
8479 }
8480 }
8481 for e in &es {
8483 push(&e.key, &mut probes);
8484 let mut plus = e.key.clone();
8485 plus.push(0);
8486 push(&plus, &mut probes);
8487 }
8488 probes.push(String::new()); probes.push("\u{1}".to_string()); probes.push("\u{10FFFF}\u{10FFFF}".to_string()); probes.push(terms.first().unwrap().clone());
8492 probes.push(terms.last().unwrap().clone());
8493
8494 let mut hits = 0usize;
8495 for p in &probes {
8496 let (a, b) = (sec_v.id(p), sec_s.id(p));
8497 assert_eq!(
8498 a,
8499 b,
8500 "probe diverged: {:?}",
8501 p.get(..p.len().min(48)).unwrap_or(p.as_str())
8502 );
8503 hits += usize::from(a.is_some());
8504 }
8505 assert!(
8506 probes.len() > 500 && hits > 50,
8507 "probe set is too thin: {} probes, {hits} of them present",
8508 probes.len()
8509 );
8510 eprintln!(
8511 "{} boundary probes, {hits} present, all identical",
8512 probes.len()
8513 );
8514 }
8515
8516 mod separator_props {
8522 use super::*;
8523 use proptest::prelude::*;
8524
8525 fn term_set() -> impl Strategy<Value = Vec<String>> {
8532 prop::collection::vec(("[a-c]{1,6}", 0u8..3, 300usize..1200), 60..250).prop_map(
8533 |specs| {
8534 let mut terms: Vec<String> = specs
8535 .into_iter()
8536 .enumerate()
8537 .map(|(i, (core, kind, pad))| {
8538 let block = "z".repeat(pad);
8539 match kind {
8540 0 => format!("<http://ex/{core}/{i:05}>"),
8541 1 => format!("\"{block}{core}{i:05}\""),
8542 _ => format!("\"{core}{i:05}{block}\""),
8543 }
8544 })
8545 .collect();
8546 terms.sort();
8547 terms.dedup();
8548 terms
8549 },
8550 )
8551 }
8552
8553 proptest! {
8554 #[test]
8555 fn prop_separator_keyed_section_answers_like_verbatim(
8556 terms in term_set(),
8557 extra in prop::collection::vec(any::<String>(), 0..8),
8558 ) {
8559 let raw = chunked_section_of(&terms);
8560 let sep = encode_chunked_dict_section(&raw, CODEC_NONE);
8561 let ver = verbatim_keyed_twin(&sep, CODEC_NONE);
8562 prop_assert!(sep.len() <= ver.len());
8563
8564 let (_m, es) = parse_chunked_dict_dir(&sep, sep.len() as u64).unwrap();
8566 let bounds = chunk_bounds_of(&sep, CODEC_NONE);
8567 prop_assert!(es[0].key.is_empty());
8568 for i in 1..es.len() {
8569 prop_assert!(es[i].key.as_slice() > bounds[i - 1].1.as_slice());
8570 prop_assert!(es[i].key <= bounds[i].0);
8571 prop_assert!(es[i].key > es[i - 1].key);
8572 }
8573
8574 let sec_s = decode_chunked_dict_section(
8575 &sep,
8576 CODEC_NONE,
8577 crate::chunk_cache::ChunkCache::unlimited_arc(),
8578 0,
8579 )
8580 .unwrap();
8581 let sec_v = decode_chunked_dict_section(
8582 &ver,
8583 CODEC_NONE,
8584 crate::chunk_cache::ChunkCache::unlimited_arc(),
8585 0,
8586 )
8587 .unwrap();
8588
8589 for (i, t) in terms.iter().enumerate() {
8590 prop_assert_eq!(sec_s.id(t), Some(i as u32 + 1));
8591 prop_assert_eq!(sec_v.id(t), Some(i as u32 + 1));
8592 prop_assert_eq!(sec_s.term(i as u32 + 1), sec_v.term(i as u32 + 1));
8593 }
8594
8595 let mut probes: Vec<String> = extra;
8597 probes.push(String::new());
8598 for (first, last) in &bounds {
8599 for base in [first, last] {
8600 if let Ok(s) = std::str::from_utf8(base) {
8601 probes.push(s.to_string());
8602 probes.push(format!("{s}\u{1}"));
8603 probes.push(s[..s.len() - s.chars().next_back()
8604 .map(char::len_utf8).unwrap_or(0)].to_string());
8605 }
8606 }
8607 }
8608 for e in &es {
8609 if let Ok(s) = std::str::from_utf8(&e.key) {
8610 probes.push(s.to_string());
8611 }
8612 }
8613 for p in &probes {
8614 prop_assert_eq!(sec_s.id(p), sec_v.id(p), "probe diverged: {:?}", p);
8615 }
8616 }
8617 }
8618 }
8619
8620 #[test]
8625 fn text_index_is_tamper_evident_and_verifies() {
8626 let triples: Vec<(String, String, String)> = vec![(
8627 "<http://ex/s0>".to_string(),
8628 "<http://ex/label>".to_string(),
8629 "\"alpha glucose phosphate\"".to_string(),
8630 )];
8631 let bytes = build_text_indexed(&triples);
8632 let header = Rete::open(&bytes).unwrap().header().clone();
8633 assert!(header.text_index_len > 0);
8634 assert!(verify(&bytes).unwrap(), "a text-indexed build must verify");
8635
8636 let mut tampered = bytes.clone();
8637 tampered[header.text_index_offset as usize] ^= 0xff;
8638 assert!(
8639 !verify(&tampered).unwrap(),
8640 "tampering with the text index must break verify()"
8641 );
8642 }
8643
8644 #[test]
8648 fn synopsis_cuts_remote_fetch_bytes() {
8649 use crate::header::FLAG_TILE_SYNOPSIS;
8650 use crate::reader::{CountingReader, SliceReader};
8651
8652 let triples: Vec<(String, String, String)> = (0..400u32)
8656 .map(|i| {
8657 (
8658 format!("<http://ex/s/{i:04}>"),
8659 "<http://ex/p>".to_string(),
8660 format!("<http://ex/o/{i:04}>"),
8661 )
8662 })
8663 .collect();
8664 let mut db = DictionaryBuilder::new();
8665 for (s, p, o) in &triples {
8666 db.observe(s, p, o);
8667 }
8668 let dict = db.build();
8669 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
8670 for (s, p, o) in &triples {
8671 ib.push(dict.encode(s, p, o).unwrap());
8672 }
8673 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
8674
8675 let q = (Some("<http://ex/s/0395>"), None, Some("<http://ex/o/0005>"));
8679 let query_bytes = |image: &[u8]| -> (u64, usize) {
8683 let leaked: &'static [u8] = Box::leak(image.to_vec().into_boxed_slice());
8684 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
8685 let rete = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
8686 let before = reader.bytes_read(); let n = rete.query(q.0, q.1, q.2).len();
8688 assert!(!rete.index_incomplete());
8689 (reader.bytes_read() - before, n)
8690 };
8691
8692 let (on_bytes, on_n) = query_bytes(&bytes);
8693 let mut off = bytes.clone();
8695 off[5] &= !FLAG_TILE_SYNOPSIS;
8696 let (off_bytes, off_n) = query_bytes(&off);
8697
8698 assert_eq!(on_n, 0, "the pair never co-occurs");
8699 assert_eq!(off_n, 0, "same answer without the synopsis");
8700 assert!(
8704 on_bytes < off_bytes,
8705 "synopsis skips the routed tile fetch: {on_bytes} < {off_bytes}"
8706 );
8707 }
8708
8709 #[test]
8715 fn double_bound_object_join_eager_matches_lazy() {
8716 use crate::reader::SliceReader;
8717 let occ = "<http://ex/occ>";
8718 let phys = "<http://ex/physicist>";
8719 let phil = "<http://ex/philosopher>";
8720 let label = "<http://www.w3.org/2000/01/rdf-schema#label>";
8721 let mut triples: Vec<(String, String, String)> = Vec::new();
8723 for i in 0..20u32 {
8724 triples.push((format!("<http://ex/p/{i:02}>"), occ.into(), phys.into()));
8725 if i < 10 {
8726 triples.push((format!("<http://ex/p/{i:02}>"), occ.into(), phil.into()));
8727 }
8728 triples.push((
8729 format!("<http://ex/p/{i:02}>"),
8730 label.into(),
8731 format!("\"Name {i:02}\""),
8732 ));
8733 }
8734 let mut db = DictionaryBuilder::new();
8735 for (s, p, o) in &triples {
8736 db.observe(s, p, o);
8737 }
8738 let dict = db.build();
8739 let mut ib = GraphIndexBuilder::new().with_tile_budget(16);
8740 for (s, p, o) in &triples {
8741 ib.push(dict.encode(s, p, o).unwrap());
8742 }
8743 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
8744
8745 let q = "SELECT ?l WHERE { \
8746 ?p <http://ex/occ> <http://ex/physicist> ; \
8747 <http://ex/occ> <http://ex/philosopher> ; \
8748 <http://www.w3.org/2000/01/rdf-schema#label> ?l }";
8749 let run = |rete: &Rete| -> Vec<String> {
8750 let (_, sols) = crate::eval_sparql(rete, q).unwrap();
8751 let mut v: Vec<String> = sols.iter().filter_map(|b| b.get("l").cloned()).collect();
8752 v.sort();
8753 v
8754 };
8755
8756 let eager_rows = run(&Rete::open(&bytes).unwrap());
8757 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
8758 let lazy = Rete::open_ranged_lazy_with(
8759 std::sync::Arc::new(SliceReader::new(leaked)),
8760 HEADER_LEN as u64,
8761 )
8762 .unwrap();
8763 let lazy_rows = run(&lazy);
8764 assert!(!lazy.index_incomplete());
8765
8766 assert_eq!(eager_rows.len(), 10, "the 10 physicist∩philosopher labels");
8767 assert_eq!(eager_rows, lazy_rows, "eager and lazy must agree exactly");
8768 }
8769
8770 #[test]
8774 fn multi_chunk_dictionary_round_trips() {
8775 let mut db = DictionaryBuilder::new();
8776 let term = |i: u32| format!("<http://example.org/some/long/prefix/entity/{i:06}>");
8777 for i in 0..6000u32 {
8778 db.observe(&term(i), "<http://ex/p>", &term(i + 1));
8779 }
8780 let dict = db.build();
8781 let mut ib = GraphIndexBuilder::new();
8782 for i in 0..6000u32 {
8783 ib.push(
8784 dict.encode(&term(i), "<http://ex/p>", &term(i + 1))
8785 .unwrap(),
8786 );
8787 }
8788 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
8789 let rete = Rete::open(&bytes).unwrap();
8790 let d = rete.dictionary();
8791 assert_eq!(d.term_count(), dict.term_count());
8792 for i in (0..6000).step_by(97).chain([0, 1, 5999, 6000]) {
8793 let t = term(i);
8794 let sid = dict.subject_id(&t);
8795 assert_eq!(d.subject_id(&t), sid, "subject_id({t})");
8796 if let Some(id) = sid {
8797 assert_eq!(d.subject_term(id).as_deref(), Some(t.as_str()));
8798 }
8799 let oid = dict.object_id(&t);
8800 assert_eq!(d.object_id(&t), oid, "object_id({t})");
8801 }
8802 assert_eq!(d.subject_id("<http://example.org/absent>"), None);
8803 assert_eq!(d.predicate_id("<http://ex/p>"), Some(1));
8804 assert_eq!(d.predicate_term(1).as_deref(), Some("<http://ex/p>"));
8805 }
8806
8807 #[test]
8808 #[cfg(feature = "compression")]
8809 fn compression_shrinks_repetitive_data() {
8810 let mut db = DictionaryBuilder::new();
8814 let triples: Vec<(String, String, String)> = (0..500)
8815 .map(|i| {
8816 (
8817 format!("<http://example.org/entity/{i}>"),
8818 "<http://example.org/p/relatedTo>".to_string(),
8819 format!("<http://example.org/entity/{}>", (i + 1) % 500),
8820 )
8821 })
8822 .collect();
8823 for (s, p, o) in &triples {
8824 db.observe(s, p, o);
8825 }
8826 let dict = db.build();
8827 let mut ib = GraphIndexBuilder::new();
8828 for (s, p, o) in &triples {
8829 ib.push(dict.encode(s, p, o).unwrap());
8830 }
8831 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
8832
8833 let raw: usize = triples
8834 .iter()
8835 .map(|(s, p, o)| s.len() + p.len() + o.len())
8836 .sum();
8837 assert!(
8838 bytes.len() < raw / 2,
8839 "expected strong compression: file {} vs raw terms {raw}",
8840 bytes.len()
8841 );
8842
8843 let rete = Rete::open(&bytes).unwrap();
8845 let r = rete.query(Some("<http://example.org/entity/0>"), None, None);
8846 assert_eq!(r.len(), 1);
8847 assert_eq!(r[0].2, "<http://example.org/entity/1>");
8848 }
8849
8850 fn big_file_with_pyramid() -> Vec<u8> {
8851 let triples: Vec<(String, String, String)> = (0..300)
8853 .map(|i| {
8854 (
8855 format!("<http://ex/e{i}>"),
8856 "<http://ex/next>".to_string(),
8857 format!("<http://ex/e{}>", (i + 1) % 300),
8858 )
8859 })
8860 .collect();
8861 let mut db = DictionaryBuilder::new();
8862 for (s, p, o) in &triples {
8863 db.observe(s, p, o);
8864 }
8865 let dict = db.build();
8866 let ids: Vec<_> = triples
8867 .iter()
8868 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
8869 .collect();
8870 let mut ib = GraphIndexBuilder::new();
8871 for &t in &ids {
8872 ib.push(t);
8873 }
8874 let (meta, levels) = build_pyramid_meta(&dict, &ids, DEFAULT_TILE_BUDGET);
8875 write_file(&dict, &ib.build(), false, &meta, levels)
8876 }
8877
8878 #[test]
8879 fn ranged_open_is_minimal_and_correct() {
8880 use crate::reader::{CountingReader, SliceReader};
8881 let bytes = big_file_with_pyramid();
8882
8883 let full = CountingReader::new(SliceReader::new(&bytes));
8884 let rete = Rete::open_ranged(&full).unwrap();
8885 assert!(full.requests() <= 4, "requests = {}", full.requests());
8887 assert_eq!(
8888 rete.query(Some("<http://ex/e0>"), None, None)[0].2,
8889 "<http://ex/e1>"
8890 );
8891
8892 let summ_reader = CountingReader::new(SliceReader::new(&bytes));
8894 let view = SummaryView::open_ranged(&summ_reader).unwrap().unwrap();
8895 assert!(!view.summary.is_empty());
8896 assert!(
8897 summ_reader.bytes_read() < bytes.len() as u64,
8898 "summary read {} of {} bytes",
8899 summ_reader.bytes_read(),
8900 bytes.len()
8901 );
8902 assert!(summ_reader.bytes_read() < full.bytes_read());
8904 }
8905
8906 #[test]
8907 fn content_hash_is_set_and_verifies() {
8908 let bytes = build_image();
8909 let rete = Rete::open(&bytes).unwrap();
8910 assert_ne!(
8911 rete.header().content_hash,
8912 [0u8; 16],
8913 "hash must be populated"
8914 );
8915 assert!(verify(&bytes).unwrap(), "freshly built file verifies");
8916 assert!(
8917 verify_ranged(&crate::reader::SliceReader::new(&bytes)).unwrap(),
8918 "the streaming verify agrees"
8919 );
8920
8921 assert_eq!(
8923 Rete::open(&build_image()).unwrap().header().content_hash,
8924 rete.header().content_hash
8925 );
8926
8927 let mut tampered = bytes.clone();
8929 let last = tampered.len() - 5; tampered[last] ^= 0xff;
8931 assert!(!verify(&tampered).unwrap());
8932 assert!(!verify_ranged(&crate::reader::SliceReader::new(&tampered)).unwrap());
8933 let short = &bytes[..bytes.len() / 2];
8935 assert!(verify_ranged(&crate::reader::SliceReader::new(short)).is_err());
8936 assert!(verify_ranged(&crate::reader::SliceReader::new(&bytes[..10])).is_err());
8937 }
8938
8939 fn build_with_metadata(meta: &[u8]) -> Vec<u8> {
8941 let triples = [
8942 ("Alice", "knows", "Bob"),
8943 ("Bob", "knows", "Carol"),
8944 ("Alice", "age", "30"),
8945 ];
8946 let mut db = DictionaryBuilder::new();
8947 for (s, p, o) in triples {
8948 db.observe(s, p, o);
8949 }
8950 let dict = db.build();
8951 let ids: Vec<_> = triples
8952 .iter()
8953 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
8954 .collect();
8955 let mut ib = GraphIndexBuilder::new();
8956 for &t in &ids {
8957 ib.push(t);
8958 }
8959 let (pmeta, levels) = build_pyramid_meta(&dict, &ids, DEFAULT_TILE_BUDGET);
8960 write_dataset_with_metadata(&dict, &ib.build(), &[], false, &pmeta, levels, meta, &[])
8961 }
8962
8963 #[test]
8964 fn metadata_round_trips_and_shifts_offsets() {
8965 let card = br#"{"title":"My Dataset"}"#;
8966 let bytes = build_with_metadata(card);
8967 let rete = Rete::open(&bytes).unwrap();
8968
8969 assert_eq!(rete.metadata(), Some(card.as_slice()));
8971 let h = rete.header();
8972 assert_eq!(h.metadata_offset, HEADER_LEN as u64);
8973 assert_eq!(h.metadata_len, card.len() as u64);
8974 assert_eq!(h.dictionary_offset, HEADER_LEN as u64 + card.len() as u64);
8976
8977 assert_eq!(
8979 rete.query(Some("Bob"), Some("knows"), Some("Carol")).len(),
8980 1
8981 );
8982 assert!(verify(&bytes).unwrap());
8984 }
8985
8986 #[test]
8987 fn empty_metadata_is_byte_identical_to_plain_writer() {
8988 assert_eq!(
8991 build_with_metadata(&[]),
8992 build_image(),
8993 "empty-metadata output must equal the plain writer byte-for-byte"
8994 );
8995 }
8996
8997 #[test]
9002 fn replace_metadata_matches_a_direct_write() {
9003 let first = br#"{"title":"My Dataset","queries":[1,2,3]}"#;
9004 let bytes = build_with_metadata(first);
9005 for target in [
9006 br#"{"title":"My Dataset","queries":[1,2]}"#.as_slice(), br#"{"title":"My Dataset","queries":[1,2,3,4,5,6,7]}"#.as_slice(), b"".as_slice(), first.as_slice(), ] {
9011 let spliced = replace_metadata(&bytes, target).unwrap();
9012 assert_eq!(
9013 spliced,
9014 build_with_metadata(target),
9015 "splicing {} bytes of metadata must equal a direct write",
9016 target.len()
9017 );
9018 assert!(
9019 verify(&spliced).unwrap(),
9020 "the new hash covers the new card"
9021 );
9022 let rete = Rete::open(&spliced).unwrap();
9023 assert_eq!(
9024 rete.metadata(),
9025 (!target.is_empty()).then_some(target),
9026 "the new payload reads back verbatim"
9027 );
9028 assert_eq!(
9030 rete.query(Some("Bob"), Some("knows"), Some("Carol")).len(),
9031 1
9032 );
9033 }
9034 }
9035
9036 #[test]
9039 fn replace_metadata_keeps_build_info_adjacent() {
9040 let with_info =
9041 attach_build_info(&build_with_metadata(br#"{"a":1}"#), br#"{"builder":"x"}"#).unwrap();
9042 let spliced = replace_metadata(&with_info, br#"{"a":1,"b":2}"#).unwrap();
9043 let h = Header::from_bytes(&spliced).unwrap();
9044 assert_eq!(h.metadata_offset, HEADER_LEN as u64);
9045 assert_eq!(h.build_info_offset, HEADER_LEN as u64 + h.metadata_len);
9046 assert_eq!(
9047 read_build_info(&spliced).unwrap().as_deref(),
9048 Some(br#"{"builder":"x"}"#.as_slice())
9049 );
9050 assert!(verify(&spliced).unwrap());
9051 assert_eq!(
9053 h.content_hash,
9054 Header::from_bytes(&build_with_metadata(br#"{"a":1,"b":2}"#))
9055 .unwrap()
9056 .content_hash
9057 );
9058 }
9059
9060 #[test]
9061 fn metadata_is_tamper_evident() {
9062 let card = br#"{"title":"x"}"#;
9063 let mut bytes = build_with_metadata(card);
9064 assert!(verify(&bytes).unwrap());
9065 bytes[HEADER_LEN + 2] ^= 0xff;
9067 assert!(
9068 !verify(&bytes).unwrap(),
9069 "tampering with the card must break verify()"
9070 );
9071 }
9072
9073 #[test]
9074 fn ranged_opens_do_not_fetch_metadata() {
9075 use crate::reader::{CountingReader, SliceReader};
9076 let card = vec![0xABu8; 512]; let bytes = build_with_metadata(&card);
9078 let total = bytes.len() as u64;
9079
9080 let r = CountingReader::new(SliceReader::new(&bytes));
9082 let rete = Rete::open_ranged(&r).unwrap();
9083 assert!(
9084 rete.metadata().is_none(),
9085 "open_ranged must not load the card"
9086 );
9087 assert!(r.requests() <= 4, "requests = {}", r.requests());
9088 assert!(
9089 r.bytes_read() <= total - card.len() as u64,
9090 "read {} of {} bytes; the {}-byte card must be skipped",
9091 r.bytes_read(),
9092 total,
9093 card.len()
9094 );
9095
9096 let rs = CountingReader::new(SliceReader::new(&bytes));
9098 let view = SummaryView::open_ranged(&rs).unwrap().unwrap();
9099 assert!(!view.summary.is_empty());
9100 assert!(rs.bytes_read() <= total - card.len() as u64);
9101 }
9102
9103 #[test]
9104 fn metadata_ranged_fetches_only_header_and_card() {
9105 use crate::reader::{CountingReader, SliceReader};
9106 let card = vec![0xCDu8; 384];
9109 let bytes = build_with_metadata(&card);
9110
9111 let r = CountingReader::new(SliceReader::new(&bytes));
9112 let got = read_metadata_ranged(&r).unwrap().unwrap();
9113 assert_eq!(got, card, "the card reads back verbatim");
9114 assert_eq!(r.requests(), 2, "exactly header + metadata ranges");
9115 assert_eq!(
9116 r.bytes_read(),
9117 HEADER_LEN as u64 + card.len() as u64,
9118 "no dictionary/index/pyramid bytes are touched"
9119 );
9120
9121 let plain = build_image();
9123 let rp = CountingReader::new(SliceReader::new(&plain));
9124 assert!(read_metadata_ranged(&rp).unwrap().is_none());
9125 assert_eq!(rp.requests(), 1, "header only for a cardless file");
9126 assert_eq!(rp.bytes_read(), HEADER_LEN as u64);
9127 }
9128
9129 #[test]
9130 fn build_info_attaches_outside_the_hash() {
9131 let card = br#"{"title":"My Dataset"}"#;
9132 let base = build_with_metadata(card);
9133 let base_hash = Header::from_bytes(&base).unwrap().content_hash;
9134
9135 let info = br#"{"built_at":"2026-08-04T00:00:00Z","builder":"rete-cli 0.3.2"}"#;
9136 let with = attach_build_info(&base, info).unwrap();
9137
9138 assert_eq!(read_build_info(&with).unwrap().unwrap(), info);
9140 let h = Header::from_bytes(&with).unwrap();
9141 assert_eq!(h.build_info_offset, HEADER_LEN as u64 + card.len() as u64);
9142 assert_eq!(h.build_info_len, info.len() as u64);
9143 assert_eq!(h.expected_file_len(), Some(with.len() as u64));
9144
9145 assert_eq!(h.content_hash, base_hash);
9149 assert!(verify(&with).unwrap());
9150 let other = attach_build_info(&base, br#"{"built_at":"1999-01-01T00:00:00Z"}"#).unwrap();
9151 assert_eq!(Header::from_bytes(&other).unwrap().content_hash, base_hash);
9152
9153 let rete = Rete::open(&with).unwrap();
9155 assert_eq!(
9156 rete.query(Some("Bob"), Some("knows"), Some("Carol")).len(),
9157 1
9158 );
9159 assert_eq!(rete.metadata(), Some(card.as_slice()));
9160
9161 let replaced = attach_build_info(&with, br#"{"builder":"other"}"#).unwrap();
9164 assert_eq!(
9165 read_build_info(&replaced).unwrap().unwrap(),
9166 br#"{"builder":"other"}"#
9167 );
9168 assert!(verify(&replaced).unwrap());
9169 let stripped = attach_build_info(&replaced, &[]).unwrap();
9170 assert_eq!(stripped, base, "stripping build-info restores the image");
9171 }
9172
9173 #[test]
9174 fn build_info_attaches_on_a_metadata_free_file() {
9175 let base = build_image();
9177 let info = b"{\"builder\":\"x\"}";
9178 let with = attach_build_info(&base, info).unwrap();
9179 let h = Header::from_bytes(&with).unwrap();
9180 assert_eq!(h.build_info_offset, HEADER_LEN as u64);
9181 assert_eq!(h.metadata_len, 0);
9182 assert_eq!(read_build_info(&with).unwrap().unwrap(), info);
9183 assert!(verify(&with).unwrap());
9184 assert_eq!(
9185 h.content_hash,
9186 Header::from_bytes(&base).unwrap().content_hash
9187 );
9188 Rete::open(&with).unwrap();
9189 }
9190
9191 #[test]
9198 fn a_plan_rebuilds_exactly_what_the_in_memory_splice_produces() {
9199 let card = br#"{"title":"My Dataset"}"#;
9200 let base = build_with_metadata(card);
9201 let base_hash = Header::from_bytes(&base).unwrap().content_hash;
9202 for start in [
9203 base.clone(),
9204 attach_build_info(&base, b"{\"a\":1}").unwrap(),
9205 ] {
9206 for info in [
9207 br#"{"builder":"rete-cli 0.3.2","query_costs":{}}"#.as_slice(), b"{}".as_slice(), b"".as_slice(), ] {
9211 let plan = plan_build_info(&start, start.len() as u64, info.len() as u64).unwrap();
9212 let mut streamed = Vec::new();
9213 streamed.extend_from_slice(&plan.header);
9214 streamed.extend_from_slice(&start[HEADER_LEN..plan.insert as usize]);
9215 streamed.extend_from_slice(info);
9216 streamed.extend_from_slice(&start[plan.tail_start as usize..]);
9217 assert_eq!(streamed.len() as u64, plan.new_len);
9218 assert_eq!(
9219 streamed,
9220 attach_build_info(&start, info).unwrap(),
9221 "a {}-byte section streamed must equal the same section spliced",
9222 info.len()
9223 );
9224 assert!(verify(&streamed).unwrap());
9226 let h = Header::from_bytes(&streamed).unwrap();
9227 assert_eq!(h.content_hash, base_hash);
9228 assert_eq!(h.expected_file_len(), Some(plan.new_len));
9229 let rete = Rete::open(&streamed).unwrap();
9230 assert_eq!(rete.metadata(), Some(card.as_slice()));
9231 assert_eq!(
9232 rete.query(Some("Bob"), Some("knows"), Some("Carol")).len(),
9233 1
9234 );
9235 }
9236 }
9237 }
9238
9239 #[test]
9242 fn a_plan_refuses_a_header_that_overruns_the_file() {
9243 let base = build_with_metadata(br#"{"title":"x"}"#);
9244 assert!(plan_build_info(&base, 8, 16).is_err());
9245 assert!(plan_build_info(&base[..HEADER_LEN], base.len() as u64, 16).is_ok());
9246 }
9247
9248 #[test]
9249 fn card_and_build_info_ranged_is_one_header_plus_one_range() {
9250 use crate::reader::{CountingReader, SliceReader};
9251 let card = vec![0xCDu8; 384];
9252 let info = vec![0xEFu8; 200];
9253 let bytes = attach_build_info(&build_with_metadata(&card), &info).unwrap();
9254
9255 let r = CountingReader::new(SliceReader::new(&bytes));
9258 let (m, b) = read_card_and_build_info_ranged(&r).unwrap();
9259 assert_eq!(m.unwrap(), card);
9260 assert_eq!(b.unwrap(), info);
9261 assert_eq!(r.requests(), 2, "header + one coalesced range");
9262 assert_eq!(
9263 r.bytes_read(),
9264 HEADER_LEN as u64 + card.len() as u64 + info.len() as u64
9265 );
9266
9267 let plain = build_with_metadata(&card);
9269 let rp = CountingReader::new(SliceReader::new(&plain));
9270 let (m, b) = read_card_and_build_info_ranged(&rp).unwrap();
9271 assert_eq!(m.unwrap(), card);
9272 assert!(b.is_none());
9273 assert_eq!(rp.requests(), 2);
9274 assert_eq!(
9279 r.requests(),
9280 rp.requests(),
9281 "build info must not cost an extra request",
9282 );
9283
9284 let none = build_image();
9286 let rn = CountingReader::new(SliceReader::new(&none));
9287 let (m, b) = read_card_and_build_info_ranged(&rn).unwrap();
9288 assert!(m.is_none() && b.is_none());
9289 assert_eq!(rn.requests(), 1);
9290 }
9291
9292 #[test]
9293 fn schema_summary_groups_by_type() {
9294 let rt = RDF_TYPE;
9295 let bytes = build_from(&[
9296 ("Alice", rt, "Person"),
9297 ("Bob", rt, "Person"),
9298 ("NYC", rt, "City"),
9299 ("Alice", "knows", "Bob"),
9300 ("Alice", "livesIn", "NYC"),
9301 ("Alice", "name", "\"Alice\""),
9302 ]);
9303 let rete = Rete::open(&bytes).unwrap();
9304 let summary = schema_summary(&rete);
9305 assert!(summary.contains(&("Person".into(), "knows".into(), "Person".into(), 1)));
9307 assert!(summary.contains(&("Person".into(), "livesIn".into(), "City".into(), 1)));
9308 assert!(summary.contains(&("Person".into(), "name".into(), "(literal)".into(), 1)));
9309 assert!(!summary.iter().any(|(_, p, _, _)| p == RDF_TYPE));
9311
9312 let classes = schema_classes(&rete);
9314 assert_eq!(
9315 classes,
9316 vec![("Person".into(), 2u32), ("City".into(), 1u32)]
9317 );
9318 }
9319
9320 fn build_from(triples: &[(&str, &str, &str)]) -> Vec<u8> {
9321 let mut db = DictionaryBuilder::new();
9322 for (s, p, o) in triples {
9323 db.observe(s, p, o);
9324 }
9325 let dict = db.build();
9326 let mut ib = GraphIndexBuilder::new();
9327 for (s, p, o) in triples {
9328 ib.push(dict.encode(s, p, o).unwrap());
9329 }
9330 write_file(&dict, &ib.build(), false, &[], 0)
9331 }
9332
9333 fn build_with_pyramid(triples: &[(&str, &str, &str)]) -> Vec<u8> {
9335 let mut db = DictionaryBuilder::new();
9336 for (s, p, o) in triples {
9337 db.observe(s, p, o);
9338 }
9339 let dict = db.build();
9340 let encoded: Vec<_> = triples
9341 .iter()
9342 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
9343 .collect();
9344 let mut ib = GraphIndexBuilder::new();
9345 for t in &encoded {
9346 ib.push(*t);
9347 }
9348 let (meta, levels) = build_pyramid_meta(&dict, &encoded, DEFAULT_TILE_BUDGET);
9349 write_dataset(&dict, &ib.build(), &[], false, &meta, levels)
9350 }
9351
9352 #[test]
9353 fn tbox_coherence_flags_unsatisfiable_class_index_free() {
9354 use crate::reader::{CountingReader, SliceReader};
9355 let rt = RDF_TYPE;
9356 let sub = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
9357 let disj = "<http://www.w3.org/2002/07/owl#disjointWith>";
9358 let bytes = build_with_pyramid(&[
9361 ("<http://ex/C>", sub, "<http://ex/D>"),
9362 ("<http://ex/C>", sub, "<http://ex/E>"),
9363 ("<http://ex/D>", disj, "<http://ex/E>"),
9364 ("<http://ex/x>", rt, "<http://ex/C>"),
9365 ]);
9366
9367 let r = CountingReader::new(SliceReader::new(&bytes));
9368 let view = SummaryView::open_ranged(&r).unwrap().unwrap();
9369 let points = view.tbox_coherence();
9370 assert!(
9371 points
9372 .iter()
9373 .any(|i| i.kind == "unsatisfiable-class" && i.detail.contains("http://ex/C>")),
9374 "expected C unsatisfiable from the schema alone, got {points:?}"
9375 );
9376
9377 let header = Header::from_bytes(&bytes[..HEADER_LEN]).unwrap();
9380 assert!(
9381 r.bytes_read() <= bytes.len() as u64 - header.root_dir_len,
9382 "tbox_coherence must not read the triple index"
9383 );
9384 }
9385
9386 #[test]
9387 fn schema_coherence_reads_only_the_schema_block() {
9388 use crate::reader::{CountingReader, SliceReader};
9389 let rt = RDF_TYPE;
9390 let sub = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
9391 let disj = "<http://www.w3.org/2002/07/owl#disjointWith>";
9392 let mut triples: Vec<(String, String, String)> = vec![
9396 ("<http://ex/C>".into(), sub.into(), "<http://ex/D>".into()),
9397 ("<http://ex/C>".into(), sub.into(), "<http://ex/E>".into()),
9398 ("<http://ex/D>".into(), disj.into(), "<http://ex/E>".into()),
9399 ];
9400 for i in 0..500 {
9401 let s = format!("<http://ex/x{i}>");
9402 triples.push((s.clone(), rt.into(), "<http://ex/C>".into()));
9403 triples.push((
9404 s,
9405 "<http://ex/label>".into(),
9406 format!("\"unique label {i}\""),
9407 ));
9408 }
9409 let trefs: Vec<(&str, &str, &str)> = triples
9410 .iter()
9411 .map(|(s, p, o)| (s.as_str(), p.as_str(), o.as_str()))
9412 .collect();
9413 let bytes = build_with_pyramid(&trefs);
9414
9415 let header = Header::from_bytes(&bytes[..HEADER_LEN]).unwrap();
9416 assert!(
9417 header.schema_meta_len > 0,
9418 "the writer recorded a schema-block length"
9419 );
9420 assert!(
9421 (header.schema_meta_len as u64) < header.pyramid_meta_len,
9422 "schema block ({}) should be far smaller than the whole pyramid-meta ({})",
9423 header.schema_meta_len,
9424 header.pyramid_meta_len
9425 );
9426
9427 let r = CountingReader::new(SliceReader::new(&bytes));
9428 let points = read_schema_coherence_ranged(&r).unwrap().unwrap();
9429 assert!(points.iter().any(|i| i.kind == "unsatisfiable-class"));
9430 assert!(
9432 r.bytes_read() <= HEADER_LEN as u64 + header.schema_meta_len as u64,
9433 "read {} bytes; expected <= header + schema block ({})",
9434 r.bytes_read(),
9435 HEADER_LEN as u64 + header.schema_meta_len as u64
9436 );
9437 }
9438
9439 #[test]
9440 fn tbox_coherence_clean_schema_is_coherent() {
9441 use crate::reader::SliceReader;
9442 let rt = RDF_TYPE;
9443 let sub = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
9444 let bytes = build_with_pyramid(&[
9445 ("<http://ex/Dog>", sub, "<http://ex/Animal>"),
9446 ("<http://ex/x>", rt, "<http://ex/Dog>"),
9447 ]);
9448 let view = SummaryView::open_ranged(&SliceReader::new(&bytes))
9449 .unwrap()
9450 .unwrap();
9451 assert!(view.tbox_is_coherent(), "a plain hierarchy is coherent");
9452 }
9453
9454 #[test]
9462 fn readers_before_the_quad_index_refuse_its_files() {
9463 for perms in [PermSet::ALL, PermSet::CORE] {
9464 let quads: Vec<crate::ingest::RawQuad> = (0..50)
9465 .map(|i| {
9466 (
9467 format!("<http://ex/s{i}>"),
9468 "<http://ex/p>".to_string(),
9469 format!("\"{i}\""),
9470 Some(format!("<http://ex/g{}>", i % 7)),
9471 )
9472 })
9473 .collect();
9474 let (bytes, _) = crate::ingest::assemble_dataset_with_layout(
9475 quads,
9476 false,
9477 false,
9478 None,
9479 crate::PyramidAlgo::Louvain,
9480 perms,
9481 crate::ingest::GraphLayout::Quad,
9482 |_, _| Vec::<u8>::new(),
9483 );
9484 let h = Header::from_bytes(&bytes).unwrap();
9485 assert!(h.has_quad_index());
9486 let root =
9487 &bytes[h.root_dir_offset as usize..(h.root_dir_offset + h.root_dir_len) as usize];
9488 assert!(decode_index_container(root, h.block_codec, h.perms).is_err());
9490 assert!(
9491 container_section_payload_ranges(root, h.root_dir_offset, h.perms.len()).is_err()
9492 );
9493 assert_ne!(decode_container(root, CODEC_NONE).unwrap().len(), NUM_PERMS);
9495 assert_ne!(
9496 decode_container(root, CODEC_NONE).unwrap().len(),
9497 h.perms.len()
9498 );
9499 let r = crate::reader::SliceReader::new(&bytes);
9501 for expect in [h.perms.len(), NUM_PERMS] {
9502 assert!(locate_container_section_ranged(
9503 &r,
9504 h.root_dir_offset,
9505 h.root_dir_len,
9506 0,
9507 expect as u64
9508 )
9509 .is_err());
9510 }
9511 assert_eq!(hash_of_sections(&h, &bytes).unwrap(), h.content_hash);
9513 let rete = Rete::open(&bytes).unwrap();
9515 assert_eq!(rete.named_graph_count(), 7);
9516 assert_eq!(rete.dump(Some("<http://ex/g3>")).len(), 7);
9517 }
9518 }
9519
9520 #[test]
9521 fn named_graphs_round_trip() {
9522 let all = [
9524 ("Alice", "knows", "Bob"), ("Bob", "age", "30"), ];
9527 let mut db = DictionaryBuilder::new();
9528 for (s, p, o) in all {
9529 db.observe(s, p, o);
9530 }
9531 let dict = db.build();
9532
9533 let mut def = GraphIndexBuilder::new();
9534 def.push(dict.encode("Alice", "knows", "Bob").unwrap());
9535 let mut g1 = GraphIndexBuilder::new();
9536 g1.push(dict.encode("Bob", "age", "30").unwrap());
9537
9538 let named = vec![("http://ex/g1".to_string(), g1.build())];
9539 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
9540
9541 assert!(verify(&bytes).unwrap());
9542 let rete = Rete::open(&bytes).unwrap();
9543 assert_eq!(rete.graph_names(), vec!["http://ex/g1"]);
9544 let gi = rete.graph_index("http://ex/g1").unwrap();
9546 assert_eq!(gi.triple_count(), 1);
9547 assert!(rete.graph_index("http://ex/missing").is_none());
9548
9549 assert_eq!(rete.header().quad_count, 2);
9552
9553 assert_eq!(rete.query(Some("Alice"), None, None).len(), 1);
9555
9556 assert_eq!(
9558 rete.dump(None),
9559 vec![("Alice".into(), "knows".into(), "Bob".into())]
9560 );
9561 assert_eq!(
9562 rete.dump(Some("http://ex/g1")),
9563 vec![("Bob".into(), "age".into(), "30".into())]
9564 );
9565 }
9566
9567 #[test]
9573 fn named_graph_container_opens_tile_lazily_like_the_root() {
9574 let mut db = DictionaryBuilder::new();
9575 let node = |n: u32| format!("<http://ex/n{n}>");
9576 let p = "<http://ex/p>".to_string();
9577 db.observe(&node(0), &p, &node(1));
9578 for i in 0..500u32 {
9579 db.observe(&node(1000 + i), &p, &node(2000 + i));
9580 }
9581 let dict = db.build();
9582 let mut def = GraphIndexBuilder::new();
9583 def.push(dict.encode(&node(0), &p, &node(1)).unwrap());
9584 let mut g = GraphIndexBuilder::new().with_tile_budget(256); for i in 0..500u32 {
9586 g.push(dict.encode(&node(1000 + i), &p, &node(2000 + i)).unwrap());
9587 }
9588 let named = vec![("<http://ex/g>".to_string(), g.build())];
9589 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
9590 let rete = Rete::open(&bytes).unwrap();
9591 let header = rete.header();
9592
9593 let soff = header.named_graphs_offset as usize;
9596 let send = soff + header.named_graphs_len as usize;
9597 let sec = &bytes[soff..send];
9598 let (n, mut pos) = read_uvarint(sec).unwrap();
9599 assert_eq!(n, 1);
9600 let (ilen, u1) = read_uvarint(&sec[pos..]).unwrap();
9601 pos += u1 + ilen as usize;
9602 let (clen, u2) = read_uvarint(&sec[pos..]).unwrap();
9603 pos += u2;
9604 let container = ByteRange {
9605 offset: (soff + pos) as u64,
9606 len: clen,
9607 };
9608
9609 use crate::reader::SliceReader;
9610 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
9611 let reader: std::sync::Arc<dyn RangeReader + Send + Sync> =
9612 std::sync::Arc::new(SliceReader::new(leaked));
9613 let (lazy_idx, _, _) = open_index_container_lazy(
9614 &reader,
9615 container,
9616 header.block_codec,
9617 header.has_tile_synopsis(),
9618 1,
9619 header.perms,
9620 header.perms.len(),
9621 )
9622 .unwrap();
9623 let mut want = rete
9624 .graph_index("<http://ex/g>")
9625 .unwrap()
9626 .match_pattern((None, None, None));
9627 let mut got = lazy_idx.match_pattern((None, None, None));
9628 want.sort_unstable();
9629 got.sort_unstable();
9630 assert_eq!(got.len(), 500);
9631 assert_eq!(got, want);
9632 assert!(!lazy_idx.load_incomplete());
9633 }
9634
9635 #[test]
9641 fn dump_iter_matches_dump_and_stops_early() {
9642 use crate::reader::{CountingReader, SliceReader};
9643
9644 let triples: Vec<(String, String, String)> = (0..2000u32)
9646 .map(|i| {
9647 (
9648 format!("<http://ex/s/{i:04}>"),
9649 "<http://ex/p>".to_string(),
9650 format!("<http://ex/o/{i:04}>"),
9651 )
9652 })
9653 .collect();
9654 let mut db = DictionaryBuilder::new();
9655 for (s, p, o) in &triples {
9656 db.observe(s, p, o);
9657 }
9658 let dict = db.build();
9659 let mut ib = GraphIndexBuilder::new().with_tile_budget(256);
9660 for (s, p, o) in &triples {
9661 ib.push(dict.encode(s, p, o).unwrap());
9662 }
9663 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
9664
9665 let rete = Rete::open(&bytes).unwrap();
9667 assert_eq!(rete.dump_iter(None).collect::<Vec<_>>(), rete.dump(None));
9668 assert_eq!(rete.dump_iter(Some("http://ex/nope")).count(), 0);
9670
9671 let read_bytes = |take: usize| -> u64 {
9673 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
9674 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
9675 let rete = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
9676 let before = reader.bytes_read();
9677 let n = rete.dump_iter(None).take(take).count();
9678 assert_eq!(n, take.min(triples.len()));
9679 assert!(!rete.index_incomplete());
9680 reader.bytes_read() - before
9681 };
9682 let first_only = read_bytes(1);
9683 let everything = read_bytes(triples.len());
9684 assert!(
9686 first_only < everything,
9687 "dump_iter is not lazy: one triple read {first_only} B, a full scan {everything} B"
9688 );
9689 #[cfg(feature = "compression")]
9696 assert!(
9697 first_only * 2 < everything,
9698 "dump_iter is not lazy: one triple read {first_only} B of the {everything} B a full scan reads"
9699 );
9700
9701 let fresh = Rete::open(&bytes).unwrap();
9706 let drain = |max_quads: usize| {
9711 let (mut out, mut cursor, mut calls) = (Vec::new(), 0u32, 0);
9712 loop {
9713 let (batch, next, done) = fresh.dump_batch(None, cursor, max_quads);
9714 out.extend(batch);
9715 cursor = next;
9716 calls += 1;
9717 assert!(calls < 10_000, "cursor failed to advance");
9718 if done {
9719 break out;
9720 }
9721 }
9722 };
9723 let eager = fresh.dump(None);
9724 for max in [1usize, 7, 128, 100_000] {
9725 assert_eq!(drain(max), eager, "batch size {max} changed the dump");
9726 }
9727 let (t, _, done) = fresh.dump_batch(Some("http://ex/nope"), 0, 16);
9730 assert!(t.is_empty() && done);
9731 }
9732
9733 #[test]
9741 fn query_batch_matches_query_in_graph_and_stops_early() {
9742 use crate::reader::{CountingReader, SliceReader};
9743
9744 let triples: Vec<(String, String, String)> = (0..2000u32)
9747 .map(|i| {
9748 (
9749 format!("<http://ex/s/{:04}>", i / 2),
9750 format!("<http://ex/p/{}>", i % 2),
9751 format!("<http://ex/o/{i:04}>"),
9752 )
9753 })
9754 .collect();
9755 let mut db = DictionaryBuilder::new();
9756 for (s, p, o) in &triples {
9757 db.observe(s, p, o);
9758 }
9759 let dict = db.build();
9760 let mut ib = GraphIndexBuilder::new().with_tile_budget(256);
9761 for (s, p, o) in &triples {
9762 ib.push(dict.encode(s, p, o).unwrap());
9763 }
9764 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
9765 let rete = Rete::open(&bytes).unwrap();
9766
9767 let drain = |s: Option<&str>, p: Option<&str>, o: Option<&str>, max: usize| {
9768 let (mut out, mut cursor, mut calls) = (Vec::new(), 0u64, 0);
9769 loop {
9770 let (batch, next, done) = rete.query_batch(None, s, p, o, cursor, max);
9771 assert!(!batch.is_empty() || done, "empty non-final batch");
9774 out.extend(batch);
9775 cursor = next;
9776 calls += 1;
9777 assert!(calls < 20_000, "cursor failed to advance");
9778 if done {
9779 break out;
9780 }
9781 }
9782 };
9783 let shapes: [(Option<&str>, Option<&str>, Option<&str>); 6] = [
9784 (None, None, None),
9785 (Some("<http://ex/s/0007>"), None, None),
9786 (None, Some("<http://ex/p/1>"), None),
9787 (None, None, Some("<http://ex/o/0042>")),
9788 (Some("<http://ex/s/0007>"), Some("<http://ex/p/0>"), None),
9789 (
9790 Some("<http://ex/s/0007>"),
9791 Some("<http://ex/p/0>"),
9792 Some("<http://ex/o/0014>"),
9793 ),
9794 ];
9795 for (s, p, o) in shapes {
9796 let eager = rete.query_in_graph(None, s, p, o);
9797 assert!(
9798 !eager.is_empty(),
9799 "fixture shape {s:?} {p:?} {o:?} matches nothing"
9800 );
9801 assert_eq!(
9803 rete.query_iter(None, s, p, o).collect::<Vec<_>>(),
9804 eager,
9805 "query_iter disagrees for {s:?} {p:?} {o:?}"
9806 );
9807 for max in [1usize, 3, 64, 100_000] {
9808 let mut got = drain(s, p, o, max);
9809 let mut want = eager.clone();
9810 got.sort();
9813 want.sort();
9814 assert_eq!(got, want, "batch size {max} changed {s:?} {p:?} {o:?}");
9815 }
9816 if s.is_none() && p.is_none() && o.is_none() {
9818 assert_eq!(drain(s, p, o, 7), eager, "unbound batching reordered rows");
9819 }
9820 }
9821
9822 let (t, _, done) = rete.query_batch(None, Some("<http://ex/nope>"), None, None, 0, 16);
9825 assert!(t.is_empty() && done);
9826 let (t, _, done) = rete.query_batch(Some("http://ex/nope"), None, None, None, 0, 16);
9827 assert!(t.is_empty() && done);
9828 assert_eq!(
9829 rete.query_iter(None, Some("<http://ex/nope>"), None, None)
9830 .count(),
9831 0
9832 );
9833
9834 let read_bytes = |take: usize| -> u64 {
9837 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
9838 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
9839 let rete = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
9840 let before = reader.bytes_read();
9841 let (mut n, mut cursor) = (0usize, 0u64);
9842 loop {
9843 let (batch, next, done) = rete.query_batch(None, None, None, None, cursor, 1);
9844 n += batch.len();
9845 cursor = next;
9846 if done || n >= take {
9847 break;
9848 }
9849 }
9850 assert!(n >= take.min(triples.len()));
9851 assert!(!rete.index_incomplete());
9852 reader.bytes_read() - before
9853 };
9854 let first_only = read_bytes(1);
9855 let everything = read_bytes(triples.len());
9856 assert!(
9857 first_only < everything,
9858 "query_batch is not lazy: one row read {first_only} B, a full scan {everything} B"
9859 );
9860 #[cfg(feature = "compression")]
9861 assert!(
9862 first_only * 2 < everything,
9863 "query_batch is not lazy: one row read {first_only} B of the {everything} B a full scan reads"
9864 );
9865 }
9866
9867 #[test]
9870 fn query_batch_is_graph_scoped() {
9871 let mut db = DictionaryBuilder::new();
9872 for (s, p, o) in [
9873 ("Alice", "knows", "Bob"),
9874 ("Alice", "knows", "Carol"),
9875 ("Alice", "knows", "Dave"),
9876 ("Erin", "knows", "Frank"),
9877 ("Alice", "knows", "Zoe"),
9878 ] {
9879 db.observe(s, p, o);
9880 }
9881 let dict = db.build();
9882 let mut def = GraphIndexBuilder::new();
9883 def.push(dict.encode("Alice", "knows", "Bob").unwrap());
9884 def.push(dict.encode("Alice", "knows", "Carol").unwrap());
9885 let mut g1 = GraphIndexBuilder::new();
9886 g1.push(dict.encode("Alice", "knows", "Dave").unwrap());
9887 g1.push(dict.encode("Erin", "knows", "Frank").unwrap());
9888 let mut g2 = GraphIndexBuilder::new();
9889 g2.push(dict.encode("Alice", "knows", "Zoe").unwrap());
9890 let named = vec![
9891 ("http://ex/g1".to_string(), g1.build()),
9892 ("http://ex/g2".to_string(), g2.build()),
9893 ];
9894 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
9895 let rete = Rete::open(&bytes).unwrap();
9896 for graph in [None, Some("http://ex/g1"), Some("http://ex/g2")] {
9897 let eager = rete.query_in_graph(graph, None, None, None);
9898 let (mut out, mut cursor) = (Vec::new(), 0u64);
9899 loop {
9900 let (batch, next, done) = rete.query_batch(graph, None, None, None, cursor, 1);
9901 out.extend(batch);
9902 cursor = next;
9903 if done {
9904 break;
9905 }
9906 }
9907 assert_eq!(out, eager, "graph {graph:?} batched differently");
9908 }
9909 }
9910
9911 #[test]
9912 fn query_in_graph_is_graph_scoped() {
9913 let mut db = DictionaryBuilder::new();
9916 for (s, p, o) in [
9917 ("Alice", "knows", "Bob"),
9918 ("Alice", "knows", "Carol"),
9919 ("Alice", "knows", "Dave"),
9920 ] {
9921 db.observe(s, p, o);
9922 }
9923 let dict = db.build();
9924
9925 let mut def = GraphIndexBuilder::new();
9926 def.push(dict.encode("Alice", "knows", "Bob").unwrap());
9927 def.push(dict.encode("Alice", "knows", "Carol").unwrap());
9928 let mut g1 = GraphIndexBuilder::new();
9929 g1.push(dict.encode("Alice", "knows", "Dave").unwrap());
9930
9931 let named = vec![("http://ex/g1".to_string(), g1.build())];
9932 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
9933 let rete = Rete::open(&bytes).unwrap();
9934
9935 let mut def_objs: Vec<String> = rete
9937 .query_in_graph(None, Some("Alice"), Some("knows"), None)
9938 .into_iter()
9939 .map(|(_, _, o)| o)
9940 .collect();
9941 def_objs.sort();
9942 assert_eq!(def_objs, vec!["Bob".to_string(), "Carol".to_string()]);
9943
9944 assert_eq!(
9946 rete.query_in_graph(Some("http://ex/g1"), Some("Alice"), None, None),
9947 vec![("Alice".into(), "knows".into(), "Dave".into())]
9948 );
9949
9950 assert_eq!(rete.query_in_graph(None, None, None, None).len(), 2);
9952 assert_eq!(
9953 rete.query_in_graph(Some("http://ex/g1"), None, None, None)
9954 .len(),
9955 1
9956 );
9957
9958 assert!(rete
9960 .query_in_graph(Some("http://ex/missing"), None, None, None)
9961 .is_empty());
9962 }
9963
9964 #[test]
9977 fn bounded_query_in_graph_does_not_fault_the_whole_dictionary() {
9978 use crate::reader::{CountingReader, SliceReader};
9979
9980 let payload = |i: u32| -> String {
9986 let mut s = String::with_capacity(800);
9987 let mut x = i as u64 ^ 0x9e37_79b9_7f4a_7c15;
9988 while s.len() < 800 {
9989 x = x
9990 .wrapping_mul(6364136223846793005)
9991 .wrapping_add(1442695040888963407);
9992 s.push_str(&format!("{:016x}", x ^ (x >> 29)));
9993 }
9994 s
9995 };
9996 let quads: Vec<(String, String, String, bool)> = (0..2000u32)
10003 .map(|i| {
10004 let named = i % 2 == 0;
10005 let ns = if named { 'a' } else { 'b' };
10006 (
10007 format!("<http://ex/{ns}/s/{i:04}>"),
10008 "<http://ex/abstract>".to_string(),
10009 format!("\"{ns}{} number {i}\"", payload(i)),
10010 named,
10011 )
10012 })
10013 .collect();
10014 let mut db = DictionaryBuilder::new();
10015 for (s, p, o, _) in &quads {
10016 db.observe(s, p, o);
10017 }
10018 let dict = db.build();
10019 let mut def = GraphIndexBuilder::new().with_tile_budget(256);
10020 let mut g1 = GraphIndexBuilder::new().with_tile_budget(256);
10021 for (s, p, o, named) in &quads {
10022 let t = dict.encode(s, p, o).unwrap();
10023 if *named {
10024 g1.push(t);
10025 } else {
10026 def.push(t);
10027 }
10028 }
10029 let named = vec![("http://ex/g1".to_string(), g1.build())];
10030 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
10031
10032 let eager = Rete::open(&bytes).unwrap();
10033 let dict_len = eager.header().dictionary_len;
10034
10035 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
10038 let probe = |f: &dyn Fn(&Rete) -> Vec<TermTriple>| -> (Vec<TermTriple>, u64) {
10039 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
10040 let lazy = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
10041 let before = reader.bytes_read();
10042 let out = f(&lazy);
10043 assert!(!lazy.index_incomplete(), "a chunk fetch failed");
10044 (out, reader.bytes_read() - before)
10045 };
10046
10047 let want = eager.query_in_graph(
10049 Some("http://ex/g1"),
10050 Some("<http://ex/a/s/0100>"),
10051 None,
10052 None,
10053 );
10054 assert_eq!(want.len(), 1, "fixture: expected exactly one match");
10055 let (got, pulled) = probe(&|r| {
10056 r.query_in_graph(
10057 Some("http://ex/g1"),
10058 Some("<http://ex/a/s/0100>"),
10059 None,
10060 None,
10061 )
10062 });
10063 assert_eq!(got, want, "lazy query_in_graph disagrees with eager");
10064 assert!(
10065 pulled * 4 < dict_len,
10066 "a 1-row query_in_graph faulted {pulled} B of a {dict_len} B dictionary — \
10067 it is prefetching the whole thing again"
10068 );
10069
10070 let (empty, q_pulled) =
10078 probe(&|r| r.query_in_graph(Some("http://ex/nope"), None, None, None));
10079 assert!(empty.is_empty());
10080 let (_, d_pulled) = probe(&|r| {
10081 let mut n = 0usize;
10082 r.dump_each(Some("http://ex/nope"), |_, _, _| n += 1);
10083 assert_eq!(n, 0, "an absent graph yielded triples");
10084 Vec::new()
10085 });
10086 assert_eq!(
10087 q_pulled, d_pulled,
10088 "query_in_graph and dump_each disagree on what an absent graph costs"
10089 );
10090 assert!(
10091 q_pulled * 4 < dict_len,
10092 "an absent graph faulted {q_pulled} B of a {dict_len} B dictionary"
10093 );
10094
10095 let want: Vec<TermTriple> = eager.dump(Some("http://ex/g1"));
10098 assert_eq!(want.len(), 1000);
10099 let (got, pulled) = probe(&|r| {
10100 let mut out = Vec::new();
10101 r.dump_each(Some("http://ex/g1"), |s, p, o| {
10102 out.push((s.to_string(), p.to_string(), o.to_string()))
10103 });
10104 out
10105 });
10106 assert_eq!(got, want, "lazy dump_each disagrees with eager dump");
10107 assert!(
10108 pulled * 3 < dict_len * 2,
10109 "dumping half the graph faulted {pulled} B of a {dict_len} B dictionary — \
10110 the other graph's chunks are being pulled in too"
10111 );
10112 }
10113
10114 #[cfg(test)]
10119 fn build_multichunk_image() -> Vec<u8> {
10120 use crate::index::PermSet;
10121 let mut db = DictionaryBuilder::new();
10122 let mut triples: Vec<(String, String, String)> = (0..4000u32)
10123 .map(|i| {
10124 (
10125 format!("<http://ex/s/{i:07}>"),
10126 format!("<http://ex/p/{}>", i % 8),
10127 format!("\"object literal number {i:07} with padding text to widen the term\""),
10128 )
10129 })
10130 .collect();
10131 triples.push((
10132 "<http://ex/s/big>".to_string(),
10133 "<http://ex/p/big>".to_string(),
10134 format!("\"{}\"", "Z".repeat(8000)),
10135 ));
10136 for (s, p, o) in &triples {
10137 db.observe(s, p, o);
10138 }
10139 let dict = db.build();
10140 let mut idx = GraphIndexBuilder::new()
10141 .with_tile_budget(64)
10142 .with_perms(PermSet::ALL);
10143 for (s, p, o) in &triples {
10144 idx.push(dict.encode(s, p, o).unwrap());
10145 }
10146 write_dataset(&dict, &idx.build(), &[], true, &[], 0)
10147 }
10148
10149 #[test]
10158 fn tiny_dict_cache_evicts_yet_dump_is_byte_identical() {
10159 use crate::reader::SliceReader;
10160 let leaked: &'static [u8] = Box::leak(build_multichunk_image().into_boxed_slice());
10161 let dump = |cap: u64| -> (
10162 Vec<(String, String, String)>,
10163 crate::chunk_cache::CacheStats,
10164 ) {
10165 let rete =
10166 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64).unwrap();
10167 rete.dict.set_cache_cap(cap);
10168 let mut out = Vec::new();
10169 rete.dump_filtered_each(None, None, None, None, |s, p, o| {
10170 out.push((s.to_string(), p.to_string(), o.to_string()))
10171 });
10172 assert!(
10173 !rete.index_incomplete(),
10174 "no lazy fault should fail at cap {cap}"
10175 );
10176 let stats = rete.dict_cache_stats();
10177 (out, stats)
10178 };
10179
10180 let (unlimited, us) = dump(u64::MAX);
10181 assert_eq!(unlimited.len(), 4001, "every triple dumped");
10182 assert_eq!(us.evictions, 0, "unlimited cap evicts nothing");
10183
10184 let (tiny, ts) = dump(128 * 1024);
10187 assert_eq!(tiny, unlimited, "128 KiB-cap dump differs from unlimited");
10188 assert!(ts.evictions > 0, "a tiny cap must evict (stats {ts:?})");
10189
10190 let (starved, ss) = dump(1);
10192 assert_eq!(starved, unlimited, "1-byte-cap dump differs from unlimited");
10193 assert!(
10194 ss.evictions > 0,
10195 "1-byte cap evicts every insert (stats {ss:?})"
10196 );
10197 }
10198
10199 #[test]
10210 fn memory_budget_charges_the_fixed_directories() {
10211 use crate::reader::SliceReader;
10212 let leaked: &'static [u8] = Box::leak(build_multichunk_image().into_boxed_slice());
10213 let rete =
10214 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64).unwrap();
10215
10216 let fixed = rete.fixed_overhead();
10217 assert!(
10220 fixed.dict_directory > 0 && fixed.index_directory > 0,
10221 "{fixed:?}"
10222 );
10223 assert_eq!(fixed.named_graphs, 0, "no named graphs in this file");
10224 assert_eq!(
10225 fixed.total(),
10226 fixed.dict_directory + fixed.index_directory + fixed.named_graphs
10227 );
10228
10229 let total: u64 = 512 << 20;
10232 let applied = rete.set_memory_budget(Some(total));
10233 let plain = split_memory_budget(total);
10234 assert_eq!(applied.dict_cache, plain.dict_cache - fixed.total());
10235 assert_eq!(rete.dict_cache_cap(), applied.dict_cache);
10236 assert_eq!(applied.tile_cache, plain.tile_cache);
10237 assert_eq!(applied.block_cache, plain.block_cache);
10238 assert!(
10239 applied.dict_cache + applied.tile_cache + applied.block_cache + fixed.total() <= total,
10240 "caps + fixed directories exceed the budget: {applied:?} + {fixed:?} > {total}"
10241 );
10242
10243 let applied = rete.set_memory_budget(Some(1 << 20));
10245 assert_eq!(applied.dict_cache, MIN_DICT_CACHE_CAP);
10246
10247 let applied = rete.set_memory_budget(None);
10249 assert_eq!(applied.dict_cache, u64::MAX);
10250 assert_eq!(rete.dict_cache_cap(), u64::MAX);
10251
10252 let rete =
10255 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64).unwrap();
10256 rete.dict.set_cache_cap(128 * 1024);
10257 let mut rows = 0usize;
10258 rete.dump_filtered_each(None, None, None, None, |_, _, _| rows += 1);
10259 assert_eq!(rows, 4001);
10260 let s = rete.dict_cache_stats();
10261 assert!(s.evictions > 0, "the cap must bind: {s:?}");
10262 assert!(
10265 s.entries <= 1 || s.resident_bytes <= 128 * 1024,
10266 "dictionary cache over its cap after the dump: {s:?}"
10267 );
10268 }
10269
10270 #[test]
10275 fn releasing_a_named_graph_drops_and_reopens_its_index() {
10276 use crate::index::PermSet;
10277 use crate::reader::SliceReader;
10278 let mut db = DictionaryBuilder::new();
10279 let all: Vec<(String, String, String)> = (0..40u32)
10280 .map(|i| {
10281 (
10282 format!("<http://ex/s{}>", i % 7),
10283 format!("<http://ex/p{}>", i % 3),
10284 format!("<http://ex/o{}>", i % 5),
10285 )
10286 })
10287 .collect();
10288 for (s, p, o) in &all {
10289 db.observe(s, p, o);
10290 }
10291 let dict = db.build();
10292 let mk = |take: fn(u32) -> bool| {
10293 let mut g = GraphIndexBuilder::new()
10294 .with_tile_budget(16)
10295 .with_perms(PermSet::ALL);
10296 for (i, (s, p, o)) in all.iter().enumerate() {
10297 if take(i as u32) {
10298 g.push(dict.encode(s, p, o).unwrap());
10299 }
10300 }
10301 g.build()
10302 };
10303 let def = mk(|_| true);
10304 let g1 = mk(|i| i % 2 == 0);
10305 let g2 = mk(|i| i % 3 == 0);
10306 let image = write_dataset(
10307 &dict,
10308 &def,
10309 &[
10310 ("<http://ex/g1>".to_string(), g1),
10311 ("<http://ex/g2>".to_string(), g2),
10312 ],
10313 true,
10314 &[],
10315 0,
10316 );
10317 let leaked: &'static [u8] = Box::leak(image.into_boxed_slice());
10318 let mut rete =
10319 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64).unwrap();
10320
10321 let opened = |r: &Rete| -> usize {
10322 match &r.named_graphs {
10323 NamedGraphsSlot::Lazy(l) => {
10324 let mut n = 0;
10325 l.for_each_opened(|_| n += 1);
10326 n
10327 }
10328 _ => 0,
10329 }
10330 };
10331
10332 assert_eq!(opened(&rete), 0, "nothing opened before first touch");
10333 assert!(rete.graph_index("<http://ex/g1>").is_some());
10335 assert_eq!(opened(&rete), 1, "g1 opened");
10336 rete.release_named_graph("<http://ex/g1>");
10338 assert_eq!(opened(&rete), 0, "g1 released");
10339 rete.release_named_graph("<http://ex/absent>");
10341 rete.release_named_graph("<http://ex/g1>");
10342 assert_eq!(opened(&rete), 0);
10343 assert!(rete.graph_index("<http://ex/g1>").is_some());
10345 assert_eq!(opened(&rete), 1, "g1 re-opened after release");
10346 }
10347
10348 #[test]
10366 fn filtered_dump_is_exactly_the_unfiltered_dump_filtered() {
10367 use crate::index::PermSet;
10368 use crate::reader::SliceReader;
10369
10370 let terms = |i: u32| {
10371 (
10372 format!("<http://ex/s{}>", i % 11),
10373 format!("<http://ex/p{}>", i % 3),
10374 if i.is_multiple_of(4) {
10378 format!("\"lit {}\"@en", i % 5)
10379 } else {
10380 format!("<http://ex/o{}>", i % 7)
10381 },
10382 )
10383 };
10384 let build = |perms: PermSet| {
10385 let mut db = DictionaryBuilder::new();
10386 let all: Vec<_> = (0..90u32).map(terms).collect();
10387 for (s, p, o) in &all {
10388 db.observe(s, p, o);
10389 }
10390 let dict = db.build();
10391 let mut def = GraphIndexBuilder::new()
10392 .with_tile_budget(16)
10393 .with_perms(perms);
10394 let mut g1 = GraphIndexBuilder::new()
10395 .with_tile_budget(16)
10396 .with_perms(perms);
10397 for (i, (s, p, o)) in all.iter().enumerate() {
10398 let t = dict.encode(s, p, o).unwrap();
10399 if i % 2 == 0 {
10403 g1.push(t);
10404 }
10405 def.push(t);
10406 }
10407 write_dataset(
10408 &dict,
10409 &def.build(),
10410 &[("<http://ex/g1>".to_string(), g1.build())],
10411 true,
10412 &[],
10413 0,
10414 )
10415 };
10416
10417 let shapes: Vec<(Option<&str>, Option<&str>, Option<&str>)> = vec![
10418 (None, None, None),
10419 (Some("<http://ex/s3>"), None, None),
10420 (None, Some("<http://ex/p1>"), None),
10421 (None, None, Some("<http://ex/o5>")),
10422 (None, None, Some("\"lit 0\"@en")),
10423 (Some("<http://ex/s3>"), Some("<http://ex/p0>"), None),
10424 (Some("<http://ex/s4>"), None, Some("<http://ex/o4>")),
10425 (None, Some("<http://ex/p1>"), Some("<http://ex/o5>")),
10426 (
10427 Some("<http://ex/s3>"),
10428 Some("<http://ex/p0>"),
10429 Some("<http://ex/o3>"),
10430 ),
10431 (Some("<http://ex/nope>"), None, None),
10435 (None, Some("<http://ex/nope>"), None),
10436 (None, None, Some("<http://ex/nope>")),
10437 ];
10438
10439 let mut any_pruned = false;
10440 for perms in [PermSet::ALL, PermSet::CORE] {
10441 let image = build(perms);
10442 let leaked: &'static [u8] = Box::leak(image.clone().into_boxed_slice());
10443 let opens: Vec<(&str, Rete)> = vec![
10444 ("resident", Rete::open(&image).unwrap()),
10445 (
10446 "ranged",
10447 Rete::open_ranged(&SliceReader::new(leaked)).unwrap(),
10448 ),
10449 (
10450 "lazy",
10451 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64)
10452 .unwrap(),
10453 ),
10454 ];
10455 for graph in [None, Some("<http://ex/g1>"), Some("<http://ex/absent>")] {
10456 let full: Vec<TermTriple> = {
10458 let mut v = Vec::new();
10459 Rete::open(&image).unwrap().dump_each(graph, |s, p, o| {
10460 v.push((s.to_string(), p.to_string(), o.to_string()))
10461 });
10462 v.sort();
10463 v
10464 };
10465 for &(s, p, o) in &shapes {
10466 let mut want = full.clone();
10467 want.retain(|(ts, tp, to)| {
10468 s.is_none_or(|x| x == ts)
10469 && p.is_none_or(|x| x == tp)
10470 && o.is_none_or(|x| x == to)
10471 });
10472 for (path, rete) in &opens {
10473 let mut got = Vec::new();
10474 rete.dump_filtered_each(graph, s, p, o, |s, p, o| {
10475 got.push((s.to_string(), p.to_string(), o.to_string()))
10476 });
10477 got.sort();
10478 assert_eq!(
10479 got,
10480 want,
10481 "{path}/{perms:?} graph={graph:?} pattern={:?} — filtered dump \
10482 is not the unfiltered dump filtered",
10483 (s, p, o)
10484 );
10485 assert!(!rete.index_incomplete(), "{path}: a fetch failed");
10486 }
10487 let plan = opens[2].1.dump_plan(graph, s, p, o);
10491 if graph == Some("<http://ex/absent>")
10492 || [s, p, o].contains(&Some("<http://ex/nope>"))
10493 {
10494 assert!(
10495 plan.scan.is_none(),
10496 "an unmatchable dump still planned a scan: {:?}",
10497 (graph, s, p, o)
10498 );
10499 } else {
10500 let scan = plan.scan.expect("a matchable dump plans a scan");
10501 assert!(
10502 PermSet::CORE.contains(scan.permutation),
10503 "a dump routed to {:?}, outside PermSet::CORE — a \
10504 --permutations 3 file has no such section",
10505 scan.permutation
10506 );
10507 assert!(scan.tiles_admitted <= scan.tiles_routed);
10508 assert!(scan.tiles_routed <= scan.tiles_total);
10509 assert!(scan.tile_bytes <= scan.section_bytes);
10510 if scan.tiles_admitted < scan.tiles_total {
10511 any_pruned = true;
10512 }
10513 }
10514 }
10515 }
10516 }
10517 assert!(
10518 any_pruned,
10519 "no shape pruned a single tile — the fixture is too small to be \
10520 measuring anything"
10521 );
10522 }
10523
10524 #[test]
10534 fn a_predicate_scoped_dump_fetches_less_than_the_graph() {
10535 use crate::reader::{CountingReader, SliceReader};
10536
10537 let mut db = DictionaryBuilder::new();
10543 let mut all = Vec::new();
10544 for s in 0..200u32 {
10545 for p in 0..20u32 {
10546 let t = (
10547 format!("<http://ex/s/{s:04}>"),
10548 format!("<http://ex/p/{p:02}>"),
10549 format!("\"object {s:04}/{p:02}\""),
10550 );
10551 db.observe(&t.0, &t.1, &t.2);
10552 all.push(t);
10553 }
10554 }
10555 let dict = db.build();
10556 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
10557 for (s, p, o) in &all {
10558 ib.push(dict.encode(s, p, o).unwrap());
10559 }
10560 let image = write_dataset(&dict, &ib.build(), &[], false, &[], 0);
10561 let leaked: &'static [u8] = Box::leak(image.clone().into_boxed_slice());
10562
10563 let probe = |s: Option<&str>, p: Option<&str>, o: Option<&str>| -> (usize, u64) {
10565 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
10566 let lazy = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
10567 let before = reader.bytes_read();
10568 let mut n = 0usize;
10569 lazy.dump_filtered_each(None, s, p, o, |_, _, _| n += 1);
10570 assert!(!lazy.index_incomplete());
10571 (n, reader.bytes_read() - before)
10572 };
10573
10574 let (full_rows, full_bytes) = probe(None, None, None);
10575 let (pred_rows, pred_bytes) = probe(None, Some("<http://ex/p/07>"), None);
10576 let (subj_rows, subj_bytes) = probe(Some("<http://ex/s/0021>"), None, None);
10577 assert_eq!(full_rows, 4000);
10578 assert_eq!(pred_rows, 200, "one predicate covers every subject once");
10579 assert_eq!(subj_rows, 20);
10580 assert!(
10582 pred_bytes < full_bytes && subj_bytes < full_bytes,
10583 "a slice fetched {pred_bytes} / {subj_bytes} B where the whole graph fetched \
10584 {full_bytes} B — the scan is not being pruned at all"
10585 );
10586 #[cfg(feature = "compression")]
10597 assert!(
10598 pred_bytes * 4 < full_bytes && subj_bytes * 4 < full_bytes,
10599 "a 1-in-20 predicate slice fetched {pred_bytes} B and one subject \
10600 {subj_bytes} B where the whole graph fetched {full_bytes} B"
10601 );
10602
10603 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
10605 let lazy = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
10606 let before = reader.bytes_read();
10607 let plan = lazy
10608 .dump_plan(None, None, Some("<http://ex/p/07>"), None)
10609 .scan
10610 .expect("a known predicate plans a scan");
10611 assert!(
10612 reader.bytes_read() - before < 64 * 1024,
10613 "planning fetched {} B — it is supposed to read directories, not tiles",
10614 reader.bytes_read() - before
10615 );
10616 assert!(plan.tiles_admitted < plan.tiles_total);
10617 assert!(
10623 plan.tile_bytes * 5 < plan.section_bytes,
10624 "one predicate of twenty planned {} B of a {} B section",
10625 plan.tile_bytes,
10626 plan.section_bytes
10627 );
10628 }
10629
10630 #[test]
10631 fn query_quads_tags_every_graph() {
10632 let mut db = DictionaryBuilder::new();
10633 for (s, p, o) in [("Alice", "knows", "Bob"), ("Alice", "knows", "Dave")] {
10634 db.observe(s, p, o);
10635 }
10636 let dict = db.build();
10637 let mut def = GraphIndexBuilder::new();
10638 def.push(dict.encode("Alice", "knows", "Bob").unwrap());
10639 let mut g1 = GraphIndexBuilder::new();
10640 g1.push(dict.encode("Alice", "knows", "Dave").unwrap());
10641 let named = vec![("http://ex/g1".to_string(), g1.build())];
10642 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
10643 let rete = Rete::open(&bytes).unwrap();
10644
10645 let quads = rete.query_quads(Some("Alice"), Some("knows"), None);
10647 assert_eq!(quads.len(), 2);
10648 assert_eq!(
10649 quads[0],
10650 (("Alice".into(), "knows".into(), "Bob".into()), None)
10651 );
10652 assert_eq!(
10653 quads[1],
10654 (
10655 ("Alice".into(), "knows".into(), "Dave".into()),
10656 Some("http://ex/g1".to_string())
10657 )
10658 );
10659
10660 assert!(rete.query_quads(Some("Nobody"), None, None).is_empty());
10662 }
10663
10664 #[test]
10665 fn pyramid_meta_round_trips_in_file() {
10666 let rete = Rete::open(&build_image()).unwrap();
10667 let pyr = rete.pyramid().expect("file has a pyramid");
10668 let total: u32 = pyr.summary.iter().map(|e| e.count).sum();
10670 assert_eq!(total, 3);
10671 assert!(!pyr.summary.is_empty());
10672 assert!(pyr.tiles.is_empty());
10673 }
10674
10675 #[test]
10676 fn schema_pyramid_round_trips_through_file_index_free() {
10677 use crate::reader::{CountingReader, SliceReader};
10678 let sub = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
10679 let q = |s: &str, p: &str, o: &str| {
10680 (s.to_string(), p.to_string(), o.to_string(), None::<String>)
10681 };
10682 let quads = vec![
10684 q("<a>", RDF_TYPE, "<Astronomer>"),
10685 q("<b>", RDF_TYPE, "<Astronomer>"),
10686 q("<c>", RDF_TYPE, "<Person>"),
10687 q("<Astronomer>", sub, "<Scientist>"),
10688 q("<Scientist>", sub, "<Person>"),
10689 q("<Person>", sub, "<Agent>"),
10690 q("<a>", "<knows>", "<b>"),
10691 q("<b>", "<knows>", "<c>"),
10692 ];
10693 let (bytes, _) =
10694 crate::ingest::assemble_dataset_with_opts(quads, true, false, None, |_, _| Vec::new());
10695
10696 let rete = Rete::open(&bytes).unwrap();
10698 let pyr = rete.pyramid().expect("pyramid present");
10699 assert!(!pyr.level_rollups.is_empty(), "schema pyramid shipped");
10700 assert!(pyr
10701 .class_hierarchy
10702 .iter()
10703 .any(|n| n.class == "<Agent>" && n.depth == 0));
10704
10705 let r = CountingReader::new(SliceReader::new(&bytes));
10707 let view = SummaryView::open_ranged(&r).unwrap().unwrap();
10708 assert!(view.level_count() >= 2, "multi-level pyramid");
10709 let coarse = view.level_rollup(0).unwrap();
10710 assert!(
10711 coarse.classes.iter().any(|(c, _)| c == "<Agent>"),
10712 "coarsest level rolls up to the root Agent"
10713 );
10714 let h = Header::from_bytes(&bytes).unwrap();
10715 assert!(
10716 r.bytes_read() <= bytes.len() as u64 - h.root_dir_len,
10717 "summary read {} bytes; the {}-byte index section must be skipped",
10718 r.bytes_read(),
10719 h.root_dir_len
10720 );
10721 }
10722
10723 #[test]
10724 fn predicate_totals_from_summary_only() {
10725 use crate::reader::SliceReader;
10726 let bytes = build_image();
10728 let reader = SliceReader::new(&bytes);
10729 let view = SummaryView::open_ranged(&reader).unwrap().unwrap();
10730 assert_eq!(view.predicate_total("knows"), 2);
10731 assert_eq!(view.predicate_total("age"), 1);
10732 assert_eq!(view.predicate_total("missing"), 0);
10733 let totals = view.predicate_totals();
10734 assert_eq!(totals[0], ("knows".to_string(), 2)); }
10736
10737 #[test]
10738 fn query_patterns_resolve_to_terms() {
10739 let rete = Rete::open(&build_image()).unwrap();
10740
10741 assert_eq!(rete.query(None, None, None).len(), 3);
10743
10744 let mut alice = rete.query(Some("Alice"), None, None);
10746 alice.sort();
10747 assert_eq!(
10748 alice,
10749 vec![
10750 ("Alice".into(), "age".into(), "30".into()),
10751 ("Alice".into(), "knows".into(), "Bob".into()),
10752 ]
10753 );
10754
10755 assert_eq!(rete.query(None, Some("knows"), None).len(), 2);
10757
10758 assert_eq!(
10760 rete.query(Some("Bob"), Some("knows"), Some("Carol")),
10761 vec![("Bob".into(), "knows".into(), "Carol".into())]
10762 );
10763 assert!(rete.query(Some("Nobody"), None, None).is_empty());
10764 assert!(rete.query(None, Some("likes"), None).is_empty());
10765 }
10766
10767 #[test]
10768 fn query_provenance_reports_terms_ids_sections_and_index_choice() {
10769 let bytes = build_image();
10770 let rete = Rete::open(&bytes).unwrap();
10771
10772 let mut matches = rete.query_with_provenance(None, Some("knows"), None);
10773 matches.sort_by(|a, b| a.terms.cmp(&b.terms));
10774
10775 assert_eq!(matches.len(), 2);
10776 assert_eq!(
10777 matches[0].terms,
10778 ("Alice".into(), "knows".into(), "Bob".into())
10779 );
10780 assert_eq!(
10781 matches[0].ids,
10782 rete.dictionary().encode("Alice", "knows", "Bob").unwrap()
10783 );
10784 assert_eq!(matches[0].graph.as_deref(), None);
10785 assert_eq!(
10786 matches[0].matched_pattern,
10787 (None, Some(matches[0].ids.1), None)
10788 );
10789 assert_eq!(
10790 matches[0].index_permutation,
10791 crate::index::IndexPermutation::Pos
10792 );
10793
10794 let h = rete.header();
10795 assert_eq!(matches[0].dictionary_range.offset, h.dictionary_offset);
10796 assert_eq!(matches[0].dictionary_range.len, h.dictionary_len);
10797 assert_eq!(matches[0].index_range.offset, h.root_dir_offset);
10798 assert_eq!(matches[0].index_range.len, h.root_dir_len);
10799 assert!(
10800 matches[0].index_section_range.offset > h.root_dir_offset,
10801 "POS is section 1, so its payload starts after the container header and SPO payload"
10802 );
10803 assert!(matches[0].index_section_range.len > 0);
10804 assert!(matches[0].index_section_range.end() <= matches[0].index_range.end());
10805 assert!(matches[0].index_section_range.len < matches[0].index_range.len);
10806 assert_eq!(
10807 matches[0].pyramid_range.as_ref().map(|r| (r.offset, r.len)),
10808 Some((h.pyramid_meta_offset, h.pyramid_meta_len))
10809 );
10810 let tile_range = matches[0].tile_range.expect("tiled file reports a tile");
10813 assert!(matches[0]
10814 .tile
10815 .as_deref()
10816 .unwrap()
10817 .starts_with(matches[0].index_permutation.name()));
10818 assert!(matches[0].index_section_range.offset <= tile_range.offset);
10819 assert!(tile_range.end() <= matches[0].index_section_range.end());
10820 }
10821
10822 fn build_labeled(n: usize) -> Vec<u8> {
10826 const LABEL: &str = "<http://www.w3.org/2000/01/rdf-schema#label>";
10827 const WORDS: &[&str] = &[
10828 "alanine",
10829 "benzene",
10830 "glucose",
10831 "dextrose",
10832 "ethanol",
10833 "formate",
10834 "heptane",
10835 "isoleucine",
10836 ];
10837 let triples: Vec<(String, String, String)> = (0..n)
10838 .flat_map(|i| {
10839 let s = format!("<http://ex/e{i}>");
10840 let w = WORDS[i % WORDS.len()];
10841 [
10842 (s.clone(), LABEL.to_string(), format!("\"{w}-{i:06}\"")),
10843 (
10844 s,
10845 "<http://ex/p>".to_string(),
10846 format!("<http://ex/c{}>", i % 64),
10847 ),
10848 ]
10849 })
10850 .collect();
10851 let mut db = DictionaryBuilder::new();
10852 for (s, p, o) in &triples {
10853 db.observe(s, p, o);
10854 }
10855 let dict = db.build();
10856 let ids: Vec<(u32, u32, u32)> = triples
10857 .iter()
10858 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
10859 .collect();
10860 let mut ib = GraphIndexBuilder::new();
10861 for &t in &ids {
10862 ib.push(t);
10863 }
10864 let (meta, levels) = build_pyramid_meta(&dict, &ids, DEFAULT_TILE_BUDGET);
10865 write_file(&dict, &ib.build(), false, &meta, levels)
10866 }
10867
10868 #[test]
10869 fn prefix_search_matches_a_filter_scan() {
10870 let bytes = build_labeled(800);
10873 let rete = Rete::open(&bytes).unwrap();
10874 let idx_subjects: std::collections::BTreeSet<String> = rete
10875 .prefix_search("glucose", 10_000)
10876 .into_iter()
10877 .map(|(_label, subject)| subject)
10878 .collect();
10879 let q = "SELECT ?s WHERE { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?l \
10881 FILTER(STRSTARTS(LCASE(?l), \"glucose\")) }";
10882 let crate::QueryOutput::Select(_, rows) = crate::eval_query(&rete, q).unwrap() else {
10883 panic!("expected SELECT");
10884 };
10885 let scan_subjects: std::collections::BTreeSet<String> =
10886 rows.iter().map(|r| r.get("s").cloned().unwrap()).collect();
10887 assert_eq!(idx_subjects, scan_subjects, "index agrees with the scan");
10888 assert_eq!(
10889 idx_subjects.len(),
10890 100,
10891 "800/8 words = 100 glucose-* labels"
10892 );
10893 }
10894
10895 #[test]
10899 fn legacy_label_hits_resolve_in_one_batched_read() {
10900 use std::sync::{Arc, Mutex};
10901 type CallLog = Arc<Mutex<Vec<Vec<(u64, u64)>>>>;
10902 #[derive(Clone)]
10903 struct Calls(Arc<Vec<u8>>, CallLog);
10904 impl crate::RangeReader for Calls {
10905 fn len(&self) -> u64 {
10906 self.0.len() as u64
10907 }
10908 fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
10909 self.1.lock().unwrap().push(vec![(offset, len)]);
10910 crate::SliceReader::new(&self.0).read_at(offset, len)
10911 }
10912 fn read_many(&self, ranges: &[(u64, u64)]) -> std::io::Result<Vec<Vec<u8>>> {
10913 self.1.lock().unwrap().push(ranges.to_vec());
10914 let r = crate::SliceReader::new(&self.0);
10915 ranges.iter().map(|&(o, l)| r.read_at(o, l)).collect()
10916 }
10917 }
10918 let bytes = build_labeled(20_000);
10919 let h = Header::from_bytes(&bytes).unwrap();
10920 let (d0, dl) = (h.dictionary_offset, h.dictionary_len);
10921 let want = Rete::open(&bytes).unwrap().prefix_search("glucose", 1000);
10922 assert_eq!(want.len(), 1000);
10923 for search_view in [false, true] {
10924 let calls = Calls(Arc::new(bytes.clone()), Arc::new(Mutex::new(Vec::new())));
10925 let got = if search_view {
10926 let view = SearchView::open_ranged_with(calls.clone(), HEADER_LEN as u64).unwrap();
10927 calls.1.lock().unwrap().clear();
10928 view.prefix_search("glucose", 1000)
10929 } else {
10930 let rete = Rete::open_ranged_lazy_with(calls.clone(), HEADER_LEN as u64).unwrap();
10931 calls.1.lock().unwrap().clear();
10932 rete.prefix_search("glucose", 1000)
10933 };
10934 assert_eq!(got, want, "search view = {search_view}");
10935 let dict_reads = calls
10936 .1
10937 .lock()
10938 .unwrap()
10939 .iter()
10940 .filter(|c| c.iter().any(|&(o, l)| o < d0 + dl && d0 < o + l))
10941 .count();
10942 assert_eq!(dict_reads, 1, "search view = {search_view}");
10943 }
10944 }
10945
10946 #[test]
10950 #[ignore]
10951 fn bench_prefix_search_vs_filter_scan() {
10952 use std::time::Instant;
10953 let n = 6000; let bytes = build_labeled(n);
10955 let rete = Rete::open(&bytes).unwrap();
10956 let q = "SELECT ?s WHERE { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?l \
10957 FILTER(STRSTARTS(LCASE(?l), \"glucose\")) }";
10958 let reps = 200;
10959 let idx_n = rete.prefix_search("glucose", 100_000).len();
10960 let t = Instant::now();
10961 for _ in 0..reps {
10962 std::hint::black_box(rete.prefix_search("glucose", 100_000));
10963 }
10964 let idx_ms = t.elapsed().as_secs_f64() * 1000.0 / reps as f64;
10965 let t = Instant::now();
10966 for _ in 0..reps {
10967 let _ = std::hint::black_box(crate::eval_query(&rete, q).unwrap());
10968 }
10969 let scan_ms = t.elapsed().as_secs_f64() * 1000.0 / reps as f64;
10970 println!(
10971 "label prefix search over {n} labeled subjects ({idx_n} matches): \
10972 index {idx_ms:.4} ms vs FILTER scan {scan_ms:.3} ms ({:.0}× faster)",
10973 scan_ms / idx_ms
10974 );
10975 }
10976
10977 #[test]
10981 #[ignore]
10982 fn bench_text_search_vs_contains_scan() {
10983 use std::time::Instant;
10984 const LABEL: &str = "<http://www.w3.org/2000/01/rdf-schema#label>";
10985 const WORDS: &[&str] = &[
10986 "alanine",
10987 "benzene",
10988 "glucose",
10989 "dextrose",
10990 "ethanol",
10991 "formate",
10992 "heptane",
10993 "isoleucine",
10994 ];
10995 let n = 6000;
10996 let triples: Vec<(String, String, String)> = (0..n)
10997 .map(|i| {
10998 (
10999 format!("<http://ex/e{i}>"),
11000 LABEL.to_string(),
11001 format!("\"{} sample number {i:06}\"", WORDS[i % WORDS.len()]),
11002 )
11003 })
11004 .collect();
11005 let mut db = DictionaryBuilder::new();
11006 for (s, p, o) in &triples {
11007 db.observe(s, p, o);
11008 }
11009 let dict = db.build();
11010 let ids: Vec<(u32, u32, u32)> = triples
11011 .iter()
11012 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
11013 .collect();
11014 let mut ib = GraphIndexBuilder::new();
11015 for &t in &ids {
11016 ib.push(t);
11017 }
11018 let ti = compute_text_index(&dict, &ids);
11019 let bytes = write_dataset_with_metadata(&dict, &ib.build(), &[], false, &[], 0, &[], &ti);
11020 let rete = Rete::open(&bytes).unwrap();
11021
11022 let q = "SELECT ?s WHERE { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?l \
11023 FILTER(CONTAINS(LCASE(?l), \"glucose\")) }";
11024 let reps = 200;
11025 let idx_n = rete.text_search(&["glucose"], None, 100_000).len();
11026 let t = Instant::now();
11027 for _ in 0..reps {
11028 std::hint::black_box(rete.text_search(&["glucose"], None, 100_000));
11029 }
11030 let idx_ms = t.elapsed().as_secs_f64() * 1000.0 / reps as f64;
11031 let t = Instant::now();
11032 for _ in 0..reps {
11033 let _ = std::hint::black_box(crate::eval_query(&rete, q).unwrap());
11034 }
11035 let scan_ms = t.elapsed().as_secs_f64() * 1000.0 / reps as f64;
11036 println!(
11037 "text search over {n} literals ({idx_n} matches): \
11038 index {idx_ms:.4} ms vs FILTER(CONTAINS) scan {scan_ms:.3} ms ({:.0}× faster)",
11039 scan_ms / idx_ms
11040 );
11041 }
11042
11043 #[test]
11047 #[ignore = "operational tool, driven by RETE_DEBUG_* env vars"]
11048 fn debug_bound_po_routing() {
11049 struct FR(std::fs::File);
11050 impl crate::RangeReader for FR {
11051 fn len(&self) -> u64 {
11052 self.0.metadata().map(|m| m.len()).unwrap_or(0)
11053 }
11054 fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
11055 use std::os::unix::fs::FileExt;
11056 let mut buf = vec![0u8; len as usize];
11057 self.0.read_exact_at(&mut buf, offset)?;
11058 Ok(buf)
11059 }
11060 }
11061 let path = std::env::var("RETE_DEBUG_FILE").expect("RETE_DEBUG_FILE");
11062 let p_iri = std::env::var("RETE_DEBUG_P").expect("RETE_DEBUG_P");
11063 let o_iri = std::env::var("RETE_DEBUG_O").expect("RETE_DEBUG_O");
11064 let rete = Rete::open_ranged_lazy_with(
11065 std::sync::Arc::new(FR(std::fs::File::open(&path).unwrap())),
11066 HEADER_LEN as u64,
11067 )
11068 .unwrap();
11069 let pid = rete.dict.predicate_id(&p_iri).expect("p resolves");
11070 let oid = rete.dict.object_id(&o_iri).expect("o resolves");
11071 eprintln!("pid={pid} oid={oid}");
11072 let pattern = (None, Some(pid), Some(oid));
11073 let perm = GraphIndex::best_permutation(pattern);
11074 eprintln!("best_permutation = {}", perm.name());
11075 let si = perm.section_index();
11076 let tiles = &rete.index.sections[si];
11077 eprintln!("section {} tiles = {}", perm.name(), tiles.len());
11078 let [pa, pb, pc] = perm.order_pattern(pattern);
11079 eprintln!("permuted pattern pa={pa:?} pb={pb:?} pc={pc:?}");
11080 let (start, end) = rete.index.tile_span(si, pa);
11081 eprintln!("tile_span = [{start}, {end}) -> {} tiles", end - start);
11082 let mut admitted = 0usize;
11083 for (ti, t) in tiles.iter().enumerate().take(end).skip(start) {
11084 if t.syn_admits(pb, pc) {
11085 admitted += 1;
11086 if admitted <= 10 {
11087 let (lo, hi) = t.leading_range();
11088 eprintln!(" admit tile {ti}: a=[{lo},{hi}] syn={:?}", t.syn);
11089 }
11090 }
11091 }
11092 eprintln!("admitted {admitted} tile(s) by synopsis");
11093 let n = rete.index.scan_iter(pattern).count();
11094 eprintln!("scan_iter matches = {n}");
11095 let hi_res = rete.query(None, Some(&p_iri), Some(&o_iri));
11096 eprintln!("high-level query matches = {}", hi_res.len());
11097 }
11098
11099 #[test]
11107 fn layout_header_label_matches_its_span() {
11108 let mut db = DictionaryBuilder::new();
11109 let mut triples = Vec::new();
11110 for i in 0..24u32 {
11111 let (s, p, o) = (
11112 format!("<http://ex/s{}>", i % 5),
11113 format!("<http://ex/p{}>", i % 3),
11114 format!("<http://ex/o{i}>"),
11115 );
11116 db.observe(&s, &p, &o);
11117 triples.push((s, p, o));
11118 }
11119 let dict = db.build();
11120 let ids: Vec<(u32, u32, u32)> = triples
11121 .iter()
11122 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
11123 .collect();
11124 let index = GraphIndexBuilder::from_triples(ids).build();
11125 let image = write_dataset_with_metadata(
11126 &dict,
11127 &index,
11128 &[],
11129 false,
11130 &[],
11131 0,
11132 br#"{"name":"layout-label-fixture"}"#,
11133 &[],
11134 );
11135 let rete = Rete::open(&image).unwrap();
11136
11137 let layout = rete.file_layout();
11138 let header = layout
11139 .iter()
11140 .find(|s| s.kind == "header")
11141 .expect("every layout starts with a header segment");
11142
11143 assert_eq!(
11144 header.offset, 0,
11145 "the header is the first thing in the file"
11146 );
11147 assert_eq!(
11148 header.len, HEADER_LEN as u64,
11149 "the header segment must span exactly HEADER_LEN"
11150 );
11151
11152 let digits: String = header
11155 .label
11156 .chars()
11157 .skip_while(|c| !c.is_ascii_digit())
11158 .take_while(|c| c.is_ascii_digit())
11159 .collect();
11160 assert!(
11161 !digits.is_empty(),
11162 "header label {:?} states no size at all",
11163 header.label
11164 );
11165 assert_eq!(
11166 digits.parse::<u64>().unwrap(),
11167 header.len,
11168 "header label {:?} disagrees with the {}-byte span it describes",
11169 header.label,
11170 header.len
11171 );
11172
11173 assert!(
11176 layout.windows(2).all(|w| w[0].offset <= w[1].offset),
11177 "file_layout must return segments sorted by offset"
11178 );
11179 }
11180}