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
2611#[allow(clippy::type_complexity)]
2621pub fn read_card_and_build_info_ranged<R: RangeReader>(
2622 reader: &R,
2623) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>), FileError> {
2624 read_card_and_build_info_with_header(reader).map(|(_, m, b)| (m, b))
2625}
2626
2627#[allow(clippy::type_complexity)]
2638pub fn read_card_and_build_info_with_header<R: RangeReader>(
2639 reader: &R,
2640) -> Result<(Header, Option<Vec<u8>>, Option<Vec<u8>>), FileError> {
2641 let head = reader.read_at(0, HEADER_LEN as u64)?;
2642 let header = Header::from_bytes(&head)?;
2643 if header.version == crate::v06::VERSION {
2644 let h = crate::v06::Header06::from_bytes(&head)?;
2645 let (card, build) = crate::v06::open::read_card_build(reader, &h)?;
2646 return Ok((header, card, build));
2647 }
2648 let meta = (header.metadata_offset, header.metadata_len);
2649 let build = (header.build_info_offset, header.build_info_len);
2650 if meta.1 > 0 && build.1 > 0 && build.0 == meta.0 + meta.1 {
2651 let both = reader.read_at(meta.0, meta.1 + build.1)?;
2653 let (m, b) = usize::try_from(meta.1)
2654 .ok()
2655 .and_then(|mid| both.split_at_checked(mid))
2656 .ok_or(FileError::Container("short card read"))?;
2657 return Ok((header, Some(m.to_vec()), Some(b.to_vec())));
2658 }
2659 let fetch = |off: u64, len: u64| -> Result<Option<Vec<u8>>, FileError> {
2660 if len == 0 {
2661 return Ok(None);
2662 }
2663 Ok(Some(reader.read_at(off, len)?))
2664 };
2665 Ok((header, fetch(meta.0, meta.1)?, fetch(build.0, build.1)?))
2666}
2667
2668pub fn read_build_info(bytes: &[u8]) -> Result<Option<Vec<u8>>, FileError> {
2673 if crate::v06::open::is_v06(bytes) {
2674 let h = crate::v06::Header06::from_bytes(bytes)?;
2675 let r = crate::reader::SliceReader::new(bytes);
2676 return Ok(crate::v06::open::read_card_build(&r, &h)?.1);
2677 }
2678 let header = Header::from_bytes(bytes)?;
2679 if header.build_info_len == 0 {
2680 return Ok(None);
2681 }
2682 let section = checked_slice(bytes, header.build_info_offset, header.build_info_len)
2683 .ok_or(FileError::Container("build-info section overruns buffer"))?;
2684 Ok(Some(section.to_vec()))
2685}
2686
2687#[derive(Debug, Clone, PartialEq, Eq)]
2696pub struct BuildInfoPlan {
2697 pub header: [u8; HEADER_LEN],
2699 pub insert: u64,
2702 pub tail_start: u64,
2706 pub new_len: u64,
2708}
2709
2710pub fn plan_build_info(
2732 head: &[u8],
2733 file_len: u64,
2734 info_len: u64,
2735) -> Result<BuildInfoPlan, FileError> {
2736 let mut header = Header::from_bytes(head)?;
2737 let insert = if header.metadata_len > 0 {
2742 header
2743 .metadata_offset
2744 .checked_add(header.metadata_len)
2745 .filter(|&end| header.metadata_offset >= HEADER_LEN as u64 && end <= file_len)
2746 .ok_or(FileError::Container(
2747 "the metadata section lies outside the file",
2748 ))?
2749 } else {
2750 HEADER_LEN as u64
2751 };
2752 let old_len = header.build_info_len;
2753 if old_len > 0 && header.build_info_offset != insert {
2754 return Err(FileError::Container(
2755 "existing build-info section is not adjacent to the metadata",
2756 ));
2757 }
2758 let tail_start = insert.saturating_add(old_len);
2759 if tail_start > file_len || insert > file_len {
2760 return Err(FileError::Container("build-info splice out of bounds"));
2761 }
2762
2763 let shift = |off: &mut u64, len: u64| {
2765 if len > 0 && *off >= tail_start {
2766 *off = *off - old_len + info_len;
2767 }
2768 };
2769 shift(&mut header.dictionary_offset, header.dictionary_len);
2770 shift(&mut header.root_dir_offset, header.root_dir_len);
2771 shift(&mut header.pyramid_meta_offset, header.pyramid_meta_len);
2772 shift(&mut header.named_graphs_offset, header.named_graphs_len);
2773 shift(&mut header.text_index_offset, header.text_index_len);
2774 for s in &mut header.extra_sections {
2775 if s.length > 0 && s.offset >= tail_start {
2776 s.offset = s.offset - old_len + info_len;
2777 }
2778 }
2779 if info_len == 0 {
2780 header.build_info_offset = 0;
2781 header.build_info_len = 0;
2782 } else {
2783 header.build_info_offset = insert;
2784 header.build_info_len = info_len;
2785 }
2786
2787 Ok(BuildInfoPlan {
2788 header: header.to_bytes(),
2789 insert,
2790 tail_start,
2791 new_len: file_len - old_len + info_len,
2792 })
2793}
2794
2795pub fn attach_build_info(image: &[u8], info: &[u8]) -> Result<Vec<u8>, FileError> {
2801 if crate::v06::open::is_v06(image) {
2802 let h = crate::v06::Header06::from_bytes(image)?;
2804 let (card, _) =
2805 crate::v06::open::read_card_build(&crate::reader::SliceReader::new(image), &h)?;
2806 return crate::v06::write::replace_card(
2807 image,
2808 card.as_deref(),
2809 (!info.is_empty()).then_some(info),
2810 );
2811 }
2812 let plan = plan_build_info(image, image.len() as u64, info.len() as u64)?;
2813 let mut out = Vec::with_capacity(plan.new_len as usize);
2814 out.extend_from_slice(&plan.header);
2815 out.extend_from_slice(&image[HEADER_LEN..plan.insert as usize]);
2816 out.extend_from_slice(info);
2817 out.extend_from_slice(&image[plan.tail_start as usize..]);
2818 debug_assert_eq!(out.len() as u64, plan.new_len);
2819 Ok(out)
2820}
2821
2822pub fn replace_metadata(image: &[u8], metadata: &[u8]) -> Result<Vec<u8>, FileError> {
2842 if crate::v06::open::is_v06(image) {
2843 let h = crate::v06::Header06::from_bytes(image)?;
2845 let (_, build) =
2846 crate::v06::open::read_card_build(&crate::reader::SliceReader::new(image), &h)?;
2847 return crate::v06::write::replace_card(
2848 image,
2849 (!metadata.is_empty()).then_some(metadata),
2850 build.as_deref(),
2851 );
2852 }
2853 let mut header = Header::from_bytes(image)?;
2854 let insert = HEADER_LEN as u64;
2857 if header.metadata_len > 0 && header.metadata_offset != insert {
2858 return Err(FileError::Container(
2859 "metadata section does not sit immediately after the header",
2860 ));
2861 }
2862 let old_len = header.metadata_len;
2863 let tail_start = (insert + old_len) as usize;
2864 if tail_start > image.len() {
2865 return Err(FileError::Container("metadata splice out of bounds"));
2866 }
2867 let new_len = metadata.len() as u64;
2868
2869 let shift = |off: &mut u64, len: u64| {
2870 if len > 0 && *off >= insert + old_len {
2871 *off = *off - old_len + new_len;
2872 }
2873 };
2874 shift(&mut header.dictionary_offset, header.dictionary_len);
2875 shift(&mut header.root_dir_offset, header.root_dir_len);
2876 shift(&mut header.pyramid_meta_offset, header.pyramid_meta_len);
2877 shift(&mut header.named_graphs_offset, header.named_graphs_len);
2878 shift(&mut header.text_index_offset, header.text_index_len);
2879 shift(&mut header.build_info_offset, header.build_info_len);
2880 for s in &mut header.extra_sections {
2881 if s.length > 0 && s.offset >= insert + old_len {
2882 s.offset = s.offset - old_len + new_len;
2883 }
2884 }
2885 header.metadata_offset = insert;
2886 header.metadata_len = new_len;
2887
2888 let mut out = Vec::with_capacity(image.len() - old_len as usize + metadata.len());
2889 out.extend_from_slice(&header.to_bytes());
2890 out.extend_from_slice(metadata);
2891 out.extend_from_slice(&image[tail_start..]);
2892 header.content_hash = hash_of_sections(&header, &out)?;
2896 out[..HEADER_LEN].copy_from_slice(&header.to_bytes());
2897 Ok(out)
2898}
2899
2900fn hash_of_sections(header: &Header, bytes: &[u8]) -> Result<[u8; 16], FileError> {
2906 let slice = |off: u64, len: u64| -> Result<&[u8], FileError> {
2907 checked_slice(bytes, off, len).ok_or(FileError::Container("section overruns buffer"))
2916 };
2917 let parts = content_hash_parts(header)
2918 .into_iter()
2919 .map(|(off, len)| slice(off, len))
2920 .collect::<Result<Vec<&[u8]>, FileError>>()?;
2921 Ok(content_hash(&parts))
2922}
2923
2924pub fn content_hash_parts(header: &Header) -> Vec<(u64, u64)> {
2937 let mut parts: Vec<(u64, u64)> = Vec::with_capacity(6);
2938 if header.metadata_len > 0 {
2939 parts.push((header.metadata_offset, header.metadata_len));
2940 }
2941 parts.push((header.dictionary_offset, header.dictionary_len));
2942 parts.push((header.root_dir_offset, header.root_dir_len));
2943 if header.pyramid_meta_len > 0 {
2946 parts.push((header.pyramid_meta_offset, header.pyramid_meta_len));
2947 }
2948 if header.text_index_len > 0 && !header.text_index_partial {
2950 parts.push((header.text_index_offset, header.text_index_len));
2951 }
2952 if header.named_graphs_len > 0 {
2953 parts.push((header.named_graphs_offset, header.named_graphs_len));
2954 }
2955 parts
2956}
2957
2958pub fn verify_ranged_v06(
2961 reader: &dyn crate::reader::RangeReader,
2962 head: &[u8],
2963 only: Option<u8>,
2964) -> Result<Vec<String>, FileError> {
2965 const SLICE: u64 = 8 << 20;
2966 let h = crate::v06::Header06::from_bytes(head)?;
2967 if h.file_len != reader.len() {
2968 return Ok(vec!["file length".to_string()]);
2969 }
2970 let mut bad = Vec::new();
2971 let root_bytes = reader.read_at(crate::v06::HEADER_LEN as u64, h.root_len as u64)?;
2972 if crate::v06::digest16(&root_bytes) != h.root_digest {
2973 bad.push("root".to_string());
2974 return Ok(bad);
2975 }
2976 let root = crate::v06::Root06::decode(&root_bytes, h.internal_codec)?;
2977 if crate::v06::content_hash(&h) != h.content_hash {
2978 bad.push("content hash".to_string());
2979 }
2980 let card = h.card_range();
2981 if only.is_none() && card.len > 0 {
2982 let stored = reader.read_at(card.offset, card.len)?;
2983 if crate::v06::digest16(&stored) != h.card_digest {
2984 bad.push("card".to_string());
2985 }
2986 }
2987 for s in &root.sections {
2988 if only.is_some_and(|k| k != s.kind) {
2989 continue;
2990 }
2991 let a = match s.abs(&h) {
2992 Ok(a) if a.offset + a.len <= h.file_len => a,
2993 _ => {
2994 bad.push(crate::v06::kind::name(s.kind).to_string());
2995 continue;
2996 }
2997 };
2998 let mut hs = blake3::Hasher::new();
2999 let mut at = a.offset;
3000 while at < a.offset + a.len {
3001 let n = (a.offset + a.len - at).min(SLICE);
3002 hs.update(&reader.read_at(at, n)?);
3003 at += n;
3004 }
3005 if hs.finalize().as_bytes()[..16] != s.digest {
3006 bad.push(crate::v06::kind::name(s.kind).to_string());
3007 }
3008 }
3009 if only.is_none() {
3010 let n = crate::v06::FOOTER.len() as u64;
3011 if reader.read_at(h.file_len - n, n)? != crate::v06::FOOTER {
3012 bad.push("footer".to_string());
3013 }
3014 }
3015 Ok(bad)
3016}
3017
3018pub fn verify(bytes: &[u8]) -> Result<bool, FileError> {
3026 if crate::v06::open::is_v06(bytes) {
3027 let r: std::sync::Arc<dyn RangeReader + Send + Sync> =
3028 std::sync::Arc::new(crate::reader::BytesReader(std::sync::Arc::from(bytes)));
3029 return crate::v06::open::V06File::open(r, bytes)?.verify(None);
3030 }
3031 let header = Header::from_bytes(bytes)?;
3032 if hash_of_sections(&header, bytes)? != header.content_hash {
3033 return Ok(false);
3034 }
3035 if header.has_quad_index() || header.quad_index_section().is_some() {
3038 check_named_layout(&header)?;
3039 let slice = |off: u64, len: u64| -> Result<&[u8], FileError> {
3040 checked_slice(bytes, off, len).ok_or(FileError::Container("section overruns buffer"))
3041 };
3042 let root = slice(header.root_dir_offset, header.root_dir_len)?;
3043 let ranges = container_section_payload_ranges(
3044 root,
3045 header.root_dir_offset,
3046 header.index_container_sections(),
3047 )?;
3048 let seal = ranges
3049 .last()
3050 .ok_or(FileError::Container("missing quad-index seal"))?;
3051 let want = crate::quad::parse_seal(slice(seal.offset, seal.len)?)?;
3052 let q = header
3053 .quad_index_section()
3054 .ok_or(FileError::Container("missing quad-index section"))?;
3055 if crate::quad::digest(slice(q.offset, q.length)?) != want {
3056 return Ok(false);
3057 }
3058 }
3059 for s in self_digested_sections(&header) {
3060 let section = checked_slice(bytes, s.offset, s.length)
3061 .ok_or(FileError::Container("section overruns buffer"))?;
3062 if !crate::label_index::digest_ok(section) {
3063 return Ok(false);
3064 }
3065 }
3066 Ok(true)
3067}
3068
3069fn self_digested_sections(header: &Header) -> Vec<Section> {
3073 [
3074 header.label_index_section(),
3075 header.schema_section(),
3076 header
3077 .section(crate::header::SectionKind::TextIndexPartial)
3078 .filter(|s| s.length > 0),
3079 ]
3080 .into_iter()
3081 .flatten()
3082 .collect()
3083}
3084
3085pub fn append_sections(
3093 image: &[u8],
3094 sections: &[(SectionKind, &[u8])],
3095) -> Result<Vec<u8>, FileError> {
3096 let lens: Vec<(SectionKind, u64)> =
3097 sections.iter().map(|(k, b)| (*k, b.len() as u64)).collect();
3098 let (header, body_end) = plan_append(image, image.len() as u64, &lens)?;
3099 let extra: usize = sections.iter().map(|(_, b)| b.len()).sum();
3100 let mut out = Vec::with_capacity(image.len() + extra);
3101 out.extend_from_slice(&header.to_bytes());
3102 out.extend_from_slice(&image[HEADER_LEN..body_end as usize]);
3103 for (_, b) in sections {
3104 out.extend_from_slice(b);
3105 }
3106 out.extend_from_slice(&MAGIC);
3107 Ok(out)
3108}
3109
3110fn plan_append(
3112 head: &[u8],
3113 file_len: u64,
3114 sections: &[(SectionKind, u64)],
3115) -> Result<(Header, u64), FileError> {
3116 let mut header = Header::from_bytes(head)?;
3117 if header.expected_file_len() != Some(file_len) {
3118 return Err(FileError::Container(
3119 "cannot append sections: the file length does not match its header",
3120 ));
3121 }
3122 let body_end = file_len - MAGIC.len() as u64;
3123 let mut at = body_end;
3124 for &(kind, len) in sections {
3125 if !matches!(kind, SectionKind::LabelIndex | SectionKind::Schema) {
3126 return Err(FileError::Container(
3127 "only LABEL_INDEX and SCHEMA sections can be appended",
3128 ));
3129 }
3130 if len == 0 {
3131 continue;
3132 }
3133 if header.section(kind).is_some_and(|s| s.length > 0) {
3134 return Err(FileError::Container(
3135 "the file already carries that section",
3136 ));
3137 }
3138 header = header.with_section(kind, at, len);
3139 at += len;
3140 }
3141 Ok((header, body_end))
3142}
3143
3144#[cfg(not(target_arch = "wasm32"))]
3149pub(crate) fn open_dictionary_lazy<R: RangeReader + Send + Sync + 'static>(
3150 reader: R,
3151) -> Result<Dictionary, FileError> {
3152 let head = reader.read_at(0, HEADER_LEN as u64)?;
3153 let header = Header::from_bytes(&head)?;
3154 ranged_chunked_dictionary(&std::sync::Arc::new(reader), &header, [true; 4])
3155}
3156
3157pub fn verify_ranged(reader: &dyn crate::reader::RangeReader) -> Result<bool, FileError> {
3163 const SLICE: u64 = 8 << 20;
3166 let len = reader.len();
3167 if len < HEADER_LEN as u64 {
3168 return Err(FileError::Container("file shorter than its header"));
3169 }
3170 let head = reader.read_at(0, HEADER_LEN as u64)?;
3171 if crate::v06::open::is_v06(&head) {
3172 return verify_ranged_v06(reader, &head, None).map(|bad| bad.is_empty());
3173 }
3174 let header = Header::from_bytes(&head)?;
3175 let mut h = blake3::Hasher::new();
3176 for (off, n) in content_hash_parts(&header) {
3177 if off.checked_add(n).is_none_or(|end| end > len) {
3180 return Err(FileError::Container("section overruns buffer"));
3181 }
3182 let mut at = off;
3183 while at < off + n {
3184 let take = (off + n - at).min(SLICE);
3185 h.update(&reader.read_at(at, take)?);
3186 at += take;
3187 }
3188 }
3189 let mut out = [0u8; 16];
3190 out.copy_from_slice(&h.finalize().as_bytes()[..16]);
3191 if out != header.content_hash {
3192 return Ok(false);
3193 }
3194 if header.has_quad_index() || header.quad_index_section().is_some() {
3197 check_named_layout(&header)?;
3198 let sections = header.index_container_sections();
3199 let seal = locate_container_section_ranged(
3200 reader,
3201 header.root_dir_offset,
3202 header.root_dir_len,
3203 sections - 1,
3204 sections as u64,
3205 )?;
3206 let want = crate::quad::parse_seal(&reader.read_at(seal.offset, seal.len)?)?;
3207 let q = header
3208 .quad_index_section()
3209 .ok_or(FileError::Container("missing quad-index section"))?;
3210 if q.offset.checked_add(q.length).is_none_or(|end| end > len) {
3211 return Err(FileError::Container("section overruns buffer"));
3212 }
3213 let mut h = blake3::Hasher::new();
3214 let mut at = q.offset;
3215 while at < q.offset + q.length {
3216 let take = (q.offset + q.length - at).min(SLICE);
3217 h.update(&reader.read_at(at, take)?);
3218 at += take;
3219 }
3220 let mut got = [0u8; 16];
3221 got.copy_from_slice(&h.finalize().as_bytes()[..16]);
3222 if got != want {
3223 return Ok(false);
3224 }
3225 }
3226 for s in self_digested_sections(&header) {
3228 if s.length < 16 || s.offset.checked_add(s.length).is_none_or(|end| end > len) {
3229 return Err(FileError::Container("section overruns buffer"));
3230 }
3231 let want = reader.read_at(s.offset, 16)?;
3232 let mut h = blake3::Hasher::new();
3233 let mut at = s.offset + 16;
3234 while at < s.offset + s.length {
3235 let take = (s.offset + s.length - at).min(SLICE);
3236 h.update(&reader.read_at(at, take)?);
3237 at += take;
3238 }
3239 if h.finalize().as_bytes()[..16] != want[..] {
3240 return Ok(false);
3241 }
3242 }
3243 Ok(true)
3244}
3245
3246type PyramidLoader = Box<dyn Fn() -> Option<PyramidMeta> + Send + Sync>;
3248
3249enum PyramidSlot {
3255 Resident(Option<PyramidMeta>),
3256 Lazy {
3257 loader: PyramidLoader,
3258 cell: std::sync::OnceLock<Option<PyramidMeta>>,
3259 },
3260}
3261
3262pub(crate) enum SectionSlot<T> {
3267 Resident(Option<T>),
3268 Lazy {
3269 loader: Box<dyn Fn() -> Option<T> + Send + Sync>,
3270 cell: std::sync::OnceLock<Option<T>>,
3271 },
3272}
3273
3274impl<T> SectionSlot<T> {
3275 pub(crate) fn get(&self) -> Option<&T> {
3277 match self {
3278 SectionSlot::Resident(v) => v.as_ref(),
3279 SectionSlot::Lazy { loader, cell } => cell.get_or_init(loader).as_ref(),
3280 }
3281 }
3282
3283 pub(crate) fn get_if_loaded(&self) -> Option<&T> {
3285 match self {
3286 SectionSlot::Resident(v) => v.as_ref(),
3287 SectionSlot::Lazy { cell, .. } => cell.get().and_then(|o| o.as_ref()),
3288 }
3289 }
3290}
3291
3292fn resident_label_slot<'a>(
3294 header: &Header,
3295 region: &dyn Fn(u64, u64) -> Result<&'a [u8], FileError>,
3296) -> SectionSlot<crate::label_index::LabelIndex> {
3297 SectionSlot::Resident(header.label_index_section().and_then(|s| {
3298 let bytes = region(s.offset, s.length).ok()?;
3299 crate::label_index::LabelIndex::from_section(bytes, header.block_codec).ok()
3300 }))
3301}
3302
3303fn resident_schema_slot<'a>(
3305 header: &Header,
3306 region: &dyn Fn(u64, u64) -> Result<&'a [u8], FileError>,
3307) -> SectionSlot<crate::schema_section::SchemaMeta> {
3308 SectionSlot::Resident(header.schema_section().and_then(|s| {
3309 crate::schema_section::SchemaMeta::decode(region(s.offset, s.length).ok()?).ok()
3310 }))
3311}
3312
3313fn ranged_label_slot<R: RangeReader + Send + Sync + 'static>(
3317 reader: &std::sync::Arc<R>,
3318 header: &Header,
3319) -> SectionSlot<crate::label_index::LabelIndex> {
3320 let Some(s) = header.label_index_section() else {
3321 return SectionSlot::Resident(None);
3322 };
3323 let r = reader.clone();
3324 let codec = header.block_codec;
3325 SectionSlot::Lazy {
3326 loader: Box::new(move || {
3327 let head = r
3328 .read_at(s.offset, crate::label_index::HEAD_READ.min(s.length))
3329 .ok()?;
3330 let rr = r.clone();
3331 let loader = Box::new(move |off: u64, len: u64| rr.read_at(s.offset + off, len).ok());
3332 crate::label_index::LabelIndex::from_head(&head, s.length, codec, loader).ok()
3333 }),
3334 cell: std::sync::OnceLock::new(),
3335 }
3336}
3337
3338fn ranged_schema_slot<R: RangeReader + Send + Sync + 'static>(
3340 reader: &std::sync::Arc<R>,
3341 header: &Header,
3342) -> SectionSlot<crate::schema_section::SchemaMeta> {
3343 let Some(s) = header.schema_section() else {
3344 return SectionSlot::Resident(None);
3345 };
3346 let r = reader.clone();
3347 SectionSlot::Lazy {
3348 loader: Box::new(move || {
3349 let bytes = r.read_at(s.offset, s.length).ok()?;
3350 crate::schema_section::SchemaMeta::decode(&bytes).ok()
3351 }),
3352 cell: std::sync::OnceLock::new(),
3353 }
3354}
3355
3356pub fn read_schema_ranged<R: RangeReader + ?Sized>(
3360 reader: &R,
3361) -> Result<Option<crate::schema_section::SchemaMeta>, FileError> {
3362 let head = reader.read_at(0, HEADER_LEN as u64)?;
3363 let header = Header::from_bytes(&head)?;
3364 Ok(read_schema_with_header(reader, &header))
3365}
3366
3367fn read_schema_with_header<R: RangeReader + ?Sized>(
3368 reader: &R,
3369 header: &Header,
3370) -> Option<crate::schema_section::SchemaMeta> {
3371 if header.version == crate::v06::VERSION {
3372 let b = crate::v06::open::read_schema_bytes(reader).ok()??;
3373 return crate::schema_section::SchemaMeta::decode(&b).ok();
3374 }
3375 let s = header.schema_section()?;
3376 let bytes = reader.read_at(s.offset, s.length).ok()?;
3377 crate::schema_section::SchemaMeta::decode(&bytes).ok()
3378}
3379
3380type TextIndexLoader = Box<dyn Fn() -> Option<crate::text_index::TextIndex> + Send + Sync>;
3383
3384type TokenTableProbe = Box<dyn Fn() -> Option<u64> + Send + Sync>;
3387
3388enum TextIndexSlot {
3398 Resident {
3399 index: Option<crate::text_index::TextIndex>,
3400 token_table_len: Option<u64>,
3403 },
3404 Lazy {
3405 loader: TextIndexLoader,
3406 cell: std::sync::OnceLock<Option<crate::text_index::TextIndex>>,
3407 token_table: TokenTableProbe,
3409 token_table_cell: std::sync::OnceLock<Option<u64>>,
3410 },
3411}
3412
3413impl TextIndexSlot {
3414 fn index(&self) -> Option<&crate::text_index::TextIndex> {
3416 match self {
3417 TextIndexSlot::Resident { index, .. } => index.as_ref(),
3418 TextIndexSlot::Lazy { loader, cell, .. } => cell.get_or_init(loader).as_ref(),
3419 }
3420 }
3421
3422 fn token_table_len(&self) -> Option<u64> {
3425 match self {
3426 TextIndexSlot::Resident {
3427 token_table_len, ..
3428 } => *token_table_len,
3429 TextIndexSlot::Lazy {
3430 token_table,
3431 token_table_cell,
3432 ..
3433 } => *token_table_cell.get_or_init(token_table),
3434 }
3435 }
3436}
3437
3438fn resident_text_index_slot(section: Option<&[u8]>, codec: u8) -> Result<TextIndexSlot, FileError> {
3441 let Some(section) = section else {
3442 return Ok(TextIndexSlot::Resident {
3443 index: None,
3444 token_table_len: None,
3445 });
3446 };
3447 Ok(TextIndexSlot::Resident {
3448 index: Some(
3449 crate::text_index::TextIndex::from_section(section, codec)
3450 .map_err(|_| FileError::Container("malformed text index"))?,
3451 ),
3452 token_table_len: crate::text_index::TextIndex::postings_base(section).map(|b| b as u64),
3453 })
3454}
3455
3456pub fn read_text_index_token_table_len_ranged<R: RangeReader + ?Sized>(
3469 reader: &R,
3470 header: &Header,
3471) -> Option<u64> {
3472 if header.version == crate::v06::VERSION {
3473 return crate::v06::open::read_token_table_bytes(reader);
3474 }
3475 let (ti_off, ti_len) = header.text_index_payload();
3476 if ti_len == 0 {
3477 return None;
3478 }
3479 read_token_table_len(reader, ti_off, ti_len)
3480}
3481
3482fn read_token_table_len<R: RangeReader + ?Sized>(reader: &R, off: u64, len: u64) -> Option<u64> {
3486 let head = reader.read_at(off, 10u64.min(len)).ok()?;
3487 let (ttlen, n) = crate::varint::read_uvarint(&head)?;
3488 Some((n as u64 + ttlen).min(len))
3489}
3490
3491const NAMED_GRAPH_RESIDENT_MAX: u64 = 1 << 20; pub const TRANSIENT_GRAPH_QUADS: u64 = 1024;
3503
3504const NAMED_SLAB: usize = 1024;
3509
3510const NAMED_WALK_CHUNK: u64 = 64 * 1024;
3514
3515const NAMED_WALK_CHUNK_MAX: u64 = 8 * 1024 * 1024;
3528
3529#[derive(Default)]
3531struct NamedEntry {
3532 meta: std::sync::OnceLock<(String, ByteRange)>,
3535 index: std::sync::OnceLock<Box<GraphIndex>>,
3538}
3539
3540#[derive(Default)]
3544struct NamedWalk {
3545 next: usize,
3547 pos: u64,
3551 buf: Vec<u8>,
3558 buf_off: u64,
3559 chunk: u64,
3566 big_seen: bool,
3573}
3574
3575struct LazyNamedGraphs {
3589 reader: std::sync::Arc<dyn RangeReader + Send + Sync>,
3590 section: ByteRange,
3592 codec: u8,
3593 has_synopsis: bool,
3594 read_concurrency: usize,
3595 perms: PermSet,
3598 #[allow(clippy::type_complexity)]
3602 dir: std::sync::OnceLock<(usize, Box<[std::sync::OnceLock<Box<[NamedEntry]>>]>)>,
3603 walk: std::sync::Mutex<NamedWalk>,
3604 failed: std::sync::atomic::AtomicBool,
3605 tile_cap: std::sync::atomic::AtomicU64,
3611}
3612
3613impl LazyNamedGraphs {
3614 fn new(
3615 reader: std::sync::Arc<dyn RangeReader + Send + Sync>,
3616 section: ByteRange,
3617 codec: u8,
3618 has_synopsis: bool,
3619 read_concurrency: usize,
3620 perms: PermSet,
3621 ) -> Self {
3622 LazyNamedGraphs {
3623 reader,
3624 section,
3625 codec,
3626 has_synopsis,
3627 read_concurrency,
3628 perms,
3629 dir: std::sync::OnceLock::new(),
3630 walk: std::sync::Mutex::new(NamedWalk::default()),
3631 failed: std::sync::atomic::AtomicBool::new(false),
3632 tile_cap: std::sync::atomic::AtomicU64::new(u64::MAX),
3633 }
3634 }
3635
3636 fn set_tile_cap(&self, cap: u64) {
3640 self.tile_cap
3641 .store(cap, std::sync::atomic::Ordering::Relaxed);
3642 self.for_each_opened(|g| {
3643 if g.is_lazy() {
3644 g.set_cache_cap(cap);
3645 }
3646 });
3647 }
3648
3649 fn fail(&self) {
3651 self.failed
3652 .store(true, std::sync::atomic::Ordering::Relaxed);
3653 }
3654
3655 #[allow(clippy::type_complexity)]
3657 fn directory(&self) -> Option<&(usize, Box<[std::sync::OnceLock<Box<[NamedEntry]>>]>)> {
3658 if let Some(d) = self.dir.get() {
3659 return Some(d);
3660 }
3661 let end = self.section.offset.checked_add(self.section.len)?;
3662 let (n, used) = match read_uvarint_at(&self.reader, self.section.offset, end) {
3663 Ok(v) => v,
3664 Err(_) => {
3665 self.fail();
3666 return None;
3667 }
3668 };
3669 if n > self.section.len / 2 {
3672 self.fail();
3673 return None;
3674 }
3675 let Ok(n) = usize::try_from(n) else {
3676 self.fail();
3677 return None;
3678 };
3679 let slabs = n.div_ceil(NAMED_SLAB);
3680 let table: Box<[std::sync::OnceLock<Box<[NamedEntry]>>]> =
3681 (0..slabs).map(|_| std::sync::OnceLock::new()).collect();
3682 let _ = self.dir.set((n, table));
3683 {
3684 let mut w = self.walk.lock().unwrap();
3687 if w.pos == 0 {
3688 w.pos = self.section.offset + used;
3689 }
3690 }
3691 self.dir.get()
3692 }
3693
3694 fn count(&self) -> usize {
3695 self.directory().map(|(n, _)| *n).unwrap_or(0)
3696 }
3697
3698 fn entry(&self, i: usize) -> Option<&NamedEntry> {
3700 let (n, table) = self.directory()?;
3701 if i >= *n {
3702 return None;
3703 }
3704 let slab = table[i / NAMED_SLAB].get_or_init(|| {
3705 let len = NAMED_SLAB.min(n - (i / NAMED_SLAB) * NAMED_SLAB);
3706 (0..len).map(|_| NamedEntry::default()).collect()
3707 });
3708 slab.get(i % NAMED_SLAB)
3709 }
3710
3711 fn next_read_len(w: &mut NamedWalk, pos: u64, end: u64, need: u64) -> u64 {
3719 let cur = w.chunk.max(NAMED_WALK_CHUNK);
3720 w.chunk = (cur * 2).min(NAMED_WALK_CHUNK_MAX);
3721 cur.max(need).min(end - pos)
3722 }
3723
3724 fn ensure_meta(&self, upto: usize, exhaustive: bool) -> Option<()> {
3739 let target = self.entry(upto)?;
3740 if target.meta.get().is_some() {
3741 return Some(());
3742 }
3743 let end = self.section.offset.checked_add(self.section.len)?;
3744 let mut w = self.walk.lock().unwrap();
3745 if exhaustive && !w.big_seen {
3746 w.chunk = NAMED_WALK_CHUNK_MAX;
3747 }
3748 while w.next <= upto {
3749 let pos = w.pos;
3750 if pos >= end {
3751 self.fail();
3753 return None;
3754 }
3755 let have =
3758 |b: &[u8], off: u64, need: u64| pos >= off && pos + need <= off + b.len() as u64;
3759 if !have(&w.buf, w.buf_off, 20.min(end - pos)) {
3760 let len = Self::next_read_len(&mut w, pos, end, 20.min(end - pos));
3761 w.buf = match self.reader.read_at(pos, len) {
3762 Ok(b) => b,
3763 Err(_) => {
3764 self.fail();
3765 return None;
3766 }
3767 };
3768 w.buf_off = pos;
3769 }
3770 let rel = (pos - w.buf_off) as usize;
3773 let Some((ilen, u1)) = w.buf.get(rel..).and_then(read_uvarint) else {
3774 self.fail();
3775 return None;
3776 };
3777 let Some(iri_end) = (u1 as u64)
3778 .checked_add(ilen)
3779 .and_then(|n| pos.checked_add(n))
3780 .filter(|&e| e <= end)
3781 else {
3782 self.fail(); return None;
3784 };
3785 let header_need = (iri_end - pos).saturating_add(10);
3787 if !have(&w.buf, w.buf_off, header_need.min(end - pos)) {
3788 let len = Self::next_read_len(&mut w, pos, end, header_need);
3789 w.buf = match self.reader.read_at(pos, len) {
3790 Ok(b) => b,
3791 Err(_) => {
3792 self.fail();
3793 return None;
3794 }
3795 };
3796 w.buf_off = pos;
3797 }
3798 let rel = (pos - w.buf_off) as usize;
3799 let istart = rel + u1;
3800 let Some(iend) = usize::try_from(ilen)
3801 .ok()
3802 .and_then(|l| istart.checked_add(l))
3803 .filter(|&e| e <= w.buf.len())
3804 else {
3805 self.fail(); return None;
3807 };
3808 let iri = String::from_utf8_lossy(&w.buf[istart..iend]).into_owned();
3809 let Some((clen, u2)) = read_uvarint(&w.buf[iend..]) else {
3810 self.fail();
3811 return None;
3812 };
3813 let cend = match iri_end
3814 .checked_add(u2 as u64)
3815 .and_then(|cstart| cstart.checked_add(clen))
3816 {
3817 Some(e) if e <= end => e,
3818 _ => {
3819 self.fail(); return None;
3821 }
3822 };
3823 if clen > NAMED_GRAPH_RESIDENT_MAX {
3824 w.big_seen = true;
3829 w.chunk = NAMED_WALK_CHUNK;
3830 }
3831 let range = ByteRange {
3832 offset: cend - clen,
3833 len: clen,
3834 };
3835 if let Some(e) = self.entry(w.next) {
3836 let _ = e.meta.set((iri, range));
3837 }
3838 w.pos = cend;
3839 w.next += 1;
3840 }
3841 Some(())
3842 }
3843
3844 fn name_at(&self, i: usize, exhaustive: bool) -> Option<&str> {
3847 self.ensure_meta(i, exhaustive)?;
3848 self.entry(i)?.meta.get().map(|(iri, _)| iri.as_str())
3849 }
3850
3851 fn graph_at(&self, i: usize, exhaustive: bool) -> Option<(&str, &GraphIndex)> {
3854 self.ensure_meta(i, exhaustive)?;
3855 let e = self.entry(i)?;
3856 let (iri, range) = e.meta.get()?;
3857 if e.index.get().is_none() {
3858 let opened = self.open_graph(*range)?;
3859 let _ = e.index.set(Box::new(opened));
3860 }
3861 Some((iri.as_str(), e.index.get()?.as_ref()))
3862 }
3863
3864 fn container_bytes(&self, range: ByteRange) -> Option<Vec<u8>> {
3868 {
3869 let w = self.walk.lock().unwrap();
3870 let buf_end = w.buf_off + w.buf.len() as u64;
3871 if range.offset >= w.buf_off && range.offset + range.len <= buf_end {
3872 let a = (range.offset - w.buf_off) as usize;
3873 return Some(w.buf[a..a + range.len as usize].to_vec());
3874 }
3875 }
3876 match self.reader.read_at(range.offset, range.len) {
3877 Ok(b) if b.len() as u64 == range.len => Some(b),
3879 _ => {
3880 self.fail();
3881 None
3882 }
3883 }
3884 }
3885
3886 fn open_graph(&self, range: ByteRange) -> Option<GraphIndex> {
3891 if range.len <= NAMED_GRAPH_RESIDENT_MAX {
3892 let bytes = self.container_bytes(range)?;
3893 match decode_index_container(&bytes, self.codec, self.perms) {
3894 Ok(g) => {
3895 g.set_size_hint(u64::from(g.triple_count()));
3898 Some(g)
3899 }
3900 Err(_) => {
3901 self.fail();
3902 None
3903 }
3904 }
3905 } else {
3906 match open_index_container_lazy(
3907 &self.reader,
3908 range,
3909 self.codec,
3910 self.has_synopsis,
3911 self.read_concurrency,
3912 self.perms,
3913 self.perms.len(),
3914 ) {
3915 Ok((g, _, _)) => {
3916 let cap = self.tile_cap.load(std::sync::atomic::Ordering::Relaxed);
3920 if cap != u64::MAX {
3921 g.set_cache_cap(cap);
3922 }
3923 Some(g)
3924 }
3925 Err(_) => {
3926 self.fail();
3927 None
3928 }
3929 }
3930 }
3931 }
3932
3933 fn release(&mut self, iri: &str) {
3939 let Some((_, table)) = self.dir.get_mut() else {
3940 return;
3941 };
3942 for slab in table.iter_mut() {
3943 let Some(entries) = slab.get_mut() else {
3944 continue;
3945 };
3946 for e in entries.iter_mut() {
3947 let matches = e
3948 .meta
3949 .get()
3950 .map(|(name, _)| name.as_str() == iri)
3951 .unwrap_or(false);
3952 if matches {
3953 e.index.take();
3954 return;
3955 }
3956 }
3957 }
3958 }
3959
3960 fn for_each_opened(&self, mut f: impl FnMut(&GraphIndex)) {
3962 if let Some((_, table)) = self.dir.get() {
3963 for slab in table.iter().filter_map(|s| s.get()) {
3964 for e in slab.iter() {
3965 if let Some(g) = e.index.get() {
3966 f(g);
3967 }
3968 }
3969 }
3970 }
3971 }
3972}
3973
3974enum NamedGraphsSlot {
3979 Resident(Vec<(String, GraphIndex)>),
3980 Lazy(LazyNamedGraphs),
3981 Quad(crate::quad::QuadNamed),
3984}
3985
3986impl NamedGraphsSlot {
3987 fn directory_bytes(&self) -> u64 {
3991 match self {
3992 NamedGraphsSlot::Resident(v) => v
3993 .iter()
3994 .map(|(iri, g)| iri.capacity() as u64 + g.directory_bytes())
3995 .sum(),
3996 NamedGraphsSlot::Lazy(l) => {
3997 let mut bytes = l.walk.lock().map(|w| w.buf.capacity() as u64).unwrap_or(0);
3998 if let Some((_, table)) = l.dir.get() {
3999 bytes += table.len() as u64
4000 * std::mem::size_of::<std::sync::OnceLock<Box<[NamedEntry]>>>() as u64;
4001 for slab in table.iter().filter_map(|s| s.get()) {
4002 bytes += slab.len() as u64 * std::mem::size_of::<NamedEntry>() as u64;
4003 for e in slab.iter() {
4004 if let Some((iri, _)) = e.meta.get() {
4005 bytes += iri.capacity() as u64;
4006 }
4007 if let Some(g) = e.index.get() {
4008 bytes += g.directory_bytes();
4009 }
4010 }
4011 }
4012 }
4013 bytes
4014 }
4015 NamedGraphsSlot::Quad(q) => q.directory_bytes(),
4016 }
4017 }
4018
4019 fn count(&self) -> usize {
4020 match self {
4021 NamedGraphsSlot::Resident(v) => v.len(),
4022 NamedGraphsSlot::Lazy(l) => l.count(),
4023 NamedGraphsSlot::Quad(q) => q.count(),
4024 }
4025 }
4026
4027 fn name_at<'a>(&'a self, dict: &Dictionary, i: usize, exhaustive: bool) -> Option<&'a str> {
4031 match self {
4032 NamedGraphsSlot::Resident(v) => v.get(i).map(|(iri, _)| iri.as_str()),
4033 NamedGraphsSlot::Lazy(l) => l.name_at(i, exhaustive),
4034 NamedGraphsSlot::Quad(q) => q.name_at(dict, i, exhaustive),
4035 }
4036 }
4037
4038 fn name_owned(&self, dict: &Dictionary, i: usize, exhaustive: bool) -> Option<String> {
4041 match self {
4042 NamedGraphsSlot::Quad(q) => q.name_owned(dict, i, exhaustive),
4043 _ => self.name_at(dict, i, exhaustive).map(str::to_owned),
4044 }
4045 }
4046
4047 fn graph_at<'a>(
4048 &'a self,
4049 dict: &Dictionary,
4050 i: usize,
4051 exhaustive: bool,
4052 ) -> Option<(&'a str, &'a GraphIndex)> {
4053 match self {
4054 NamedGraphsSlot::Resident(v) => v.get(i).map(|(iri, g)| (iri.as_str(), g)),
4055 NamedGraphsSlot::Lazy(l) => l.graph_at(i, exhaustive),
4056 NamedGraphsSlot::Quad(q) => q.graph_at(dict, i, exhaustive),
4057 }
4058 }
4059
4060 fn find<'a>(&'a self, dict: &Dictionary, iri: &str) -> Option<&'a GraphIndex> {
4061 match self {
4062 NamedGraphsSlot::Quad(q) => q.find(dict, iri),
4063 NamedGraphsSlot::Resident(v) => v.iter().find(|(name, _)| name == iri).map(|(_, g)| g),
4064 NamedGraphsSlot::Lazy(l) => {
4065 for i in 0..l.count() {
4070 if l.name_at(i, false)? == iri {
4071 return l.graph_at(i, false).map(|(_, g)| g);
4072 }
4073 }
4074 None
4075 }
4076 }
4077 }
4078
4079 fn load_incomplete(&self) -> bool {
4080 match self {
4081 NamedGraphsSlot::Resident(v) => v.iter().any(|(_, g)| g.load_incomplete()),
4082 NamedGraphsSlot::Lazy(l) => {
4083 if l.failed.load(std::sync::atomic::Ordering::Relaxed) {
4084 return true;
4085 }
4086 let mut bad = false;
4087 l.for_each_opened(|g| bad |= g.load_incomplete());
4088 bad
4089 }
4090 NamedGraphsSlot::Quad(q) => q.load_incomplete(),
4091 }
4092 }
4093
4094 fn reset_load_failures(&self) {
4095 match self {
4096 NamedGraphsSlot::Resident(v) => {
4097 for (_, g) in v {
4098 g.reset_load_failure();
4099 }
4100 }
4101 NamedGraphsSlot::Lazy(l) => {
4102 l.failed.store(false, std::sync::atomic::Ordering::Relaxed);
4103 l.for_each_opened(|g| g.reset_load_failure());
4104 }
4105 NamedGraphsSlot::Quad(q) => q.reset_load_failures(),
4106 }
4107 }
4108
4109 fn resident(
4113 header: &Header,
4114 quad_section: impl FnOnce(u64, u64) -> Result<Vec<u8>, FileError>,
4115 per_graph: impl FnOnce() -> Result<Vec<(String, GraphIndex)>, FileError>,
4116 ) -> Result<Self, FileError> {
4117 check_named_layout(header)?;
4118 if let Some(q) = header.quad_index_section() {
4119 let bytes = quad_section(q.offset, q.length)?;
4120 return Ok(NamedGraphsSlot::Quad(crate::quad::QuadNamed::resident(
4121 bytes,
4122 header.block_codec,
4123 header.perms,
4124 )));
4125 }
4126 Ok(NamedGraphsSlot::Resident(if header.named_graphs_len > 0 {
4127 per_graph()?
4128 } else {
4129 Vec::new()
4130 }))
4131 }
4132}
4133
4134pub struct Rete {
4136 header: Header,
4137 dict: Dictionary,
4138 index: GraphIndex,
4139 index_section_ranges: [ByteRange; NUM_PERMS],
4140 tile_ranges: [Vec<(u32, u32, ByteRange)>; NUM_PERMS],
4144 pyramid: PyramidSlot,
4145 text_index: TextIndexSlot,
4146 labels: SectionSlot<crate::label_index::LabelIndex>,
4148 schema: SectionSlot<crate::schema_section::SchemaMeta>,
4150 named_graphs: NamedGraphsSlot,
4151 metadata: Vec<u8>,
4156 service_client: Option<Box<dyn crate::service::ServiceClient>>,
4161 service_error: std::sync::Mutex<Option<String>>,
4165 spill_threshold: std::sync::atomic::AtomicU64,
4168 v06: Option<std::sync::Arc<crate::v06::open::V06File>>,
4170}
4171
4172impl Rete {
4173 pub fn open(bytes: &[u8]) -> Result<Self, FileError> {
4176 #[cfg(feature = "v06-parity")]
4177 if let Some(v6) = parity_image(bytes) {
4178 return Self::open(&v6);
4179 }
4180 if crate::v06::open::is_v06(bytes) {
4181 let r: std::sync::Arc<dyn RangeReader + Send + Sync> =
4184 std::sync::Arc::new(crate::reader::BytesReader(std::sync::Arc::from(bytes)));
4185 let mut rete = Self::open_v06(r, bytes, false)?;
4186 rete.metadata = rete
4187 .v06
4188 .as_ref()
4189 .and_then(|f| f.card().ok().flatten())
4190 .unwrap_or_default();
4191 return Ok(rete);
4192 }
4193 let header = Header::from_bytes(bytes)?;
4194
4195 let region = |off: u64, len: u64| -> Result<&[u8], FileError> {
4199 checked_slice(bytes, off, len)
4200 .ok_or(FileError::Container("section range out of bounds"))
4201 };
4202
4203 let dict = decode_dictionary_container(
4204 region(header.dictionary_offset, header.dictionary_len)?,
4205 header.dict_codec,
4206 )?;
4207
4208 check_named_layout(&header)?;
4209 let index_bytes = region(header.root_dir_offset, header.root_dir_len)?;
4210 let (index, _) = decode_root_index_container(index_bytes, &header)?;
4211 let index_section_ranges = decode_index_section_ranges(
4212 index_bytes,
4213 header.root_dir_offset,
4214 header.perms,
4215 header.index_container_sections(),
4216 )?;
4217
4218 let pyramid = PyramidSlot::Resident(if header.pyramid_meta_len > 0 {
4219 Some(
4220 PyramidMeta::decode(region(header.pyramid_meta_offset, header.pyramid_meta_len)?)
4221 .map_err(|_| FileError::Container("malformed pyramid meta"))?,
4222 )
4223 } else {
4224 None
4225 });
4226
4227 let (ti_off, ti_len) = header.text_index_payload();
4230 let text_index = resident_text_index_slot(
4231 if ti_len > 0 {
4232 Some(region(ti_off, ti_len)?)
4233 } else {
4234 None
4235 },
4236 header.block_codec,
4237 )?;
4238 let labels = resident_label_slot(&header, ®ion);
4239 let schema = resident_schema_slot(&header, ®ion);
4240
4241 let named_graphs = NamedGraphsSlot::resident(
4242 &header,
4243 |off, len| Ok(region(off, len)?.to_vec()),
4244 || {
4245 decode_named_graphs(
4246 region(header.named_graphs_offset, header.named_graphs_len)?,
4247 header.block_codec,
4248 header.perms,
4249 )
4250 },
4251 )?;
4252
4253 let metadata = if header.metadata_len > 0 {
4254 region(header.metadata_offset, header.metadata_len)?.to_vec()
4255 } else {
4256 Vec::new()
4257 };
4258
4259 let tile_ranges =
4260 tile_file_ranges(index_bytes, header.root_dir_offset, &index_section_ranges);
4261 Ok(Self {
4262 header,
4263 dict,
4264 index,
4265 index_section_ranges,
4266 tile_ranges,
4267 pyramid,
4268 text_index,
4269 labels,
4270 schema,
4271 named_graphs,
4272 metadata,
4273 service_client: None,
4274 service_error: std::sync::Mutex::new(None),
4275 spill_threshold: std::sync::atomic::AtomicU64::new(u64::MAX),
4276 v06: None,
4277 })
4278 }
4279
4280 pub fn set_service_client(&mut self, client: Box<dyn crate::service::ServiceClient>) {
4285 self.service_client = Some(client);
4286 }
4287
4288 pub(crate) fn service_client(&self) -> Option<&dyn crate::service::ServiceClient> {
4289 self.service_client.as_deref()
4290 }
4291
4292 pub(crate) fn record_service_error(&self, msg: &str) {
4294 let mut e = self.service_error.lock().unwrap();
4295 if e.is_none() {
4296 *e = Some(msg.to_string());
4297 }
4298 }
4299
4300 pub(crate) fn take_service_error(&self) -> Option<String> {
4303 self.service_error.lock().unwrap().take()
4304 }
4305
4306 pub fn header(&self) -> &Header {
4307 &self.header
4308 }
4309
4310 pub fn file_layout(&self) -> Vec<LayoutSegment> {
4316 if let Some(f) = &self.v06 {
4317 return v06_layout(f);
4318 }
4319 let h = &self.header;
4320 let seg = |kind: &'static str, label: String, offset: u64, len: u64| LayoutSegment {
4321 kind,
4322 label,
4323 offset,
4324 len,
4325 };
4326 let mut out = vec![seg(
4332 "header",
4333 format!("header (fixed {} bytes)", crate::header::HEADER_LEN),
4334 0,
4335 crate::header::HEADER_LEN as u64,
4336 )];
4337 if h.metadata_len > 0 {
4338 out.push(seg(
4339 "metadata",
4340 "metadata (dataset card)".into(),
4341 h.metadata_offset,
4342 h.metadata_len,
4343 ));
4344 }
4345 out.push(seg(
4346 "dictionary",
4347 "dictionary (4 front-coded term sections)".into(),
4348 h.dictionary_offset,
4349 h.dictionary_len,
4350 ));
4351 for (si, perm) in crate::index::ALL_PERMS.into_iter().enumerate() {
4352 let sec = self.index_section_ranges[si];
4353 if sec.len == 0 {
4354 continue;
4355 }
4356 let first_tile = self.tile_ranges[si]
4357 .first()
4358 .map(|&(_, _, r)| r.offset)
4359 .unwrap_or(sec.offset + sec.len);
4360 if first_tile > sec.offset {
4361 out.push(seg(
4362 "directory",
4363 format!("{} tile directory", perm.name()),
4364 sec.offset,
4365 first_tile - sec.offset,
4366 ));
4367 }
4368 for (ti, &(min_a, max_a, r)) in self.tile_ranges[si].iter().enumerate() {
4369 out.push(seg(
4370 "tile",
4371 format!("{} tile {ti} (leading ids {min_a}..{max_a})", perm.name()),
4372 r.offset,
4373 r.len,
4374 ));
4375 }
4376 }
4377 if h.pyramid_meta_len > 0 {
4378 out.push(seg(
4379 "pyramid",
4380 "pyramid summary (communities + superedges)".into(),
4381 h.pyramid_meta_offset,
4382 h.pyramid_meta_len,
4383 ));
4384 }
4385 if h.named_graphs_len > 0 {
4386 out.push(seg(
4387 "named-graphs",
4388 format!("named graphs ({})", self.named_graphs.count()),
4389 h.named_graphs_offset,
4390 h.named_graphs_len,
4391 ));
4392 }
4393 if let Some(s) = h.label_index_section() {
4394 let label = match self.labels.get_if_loaded() {
4395 Some(li) => format!("label index ({} entries)", li.entry_count()),
4396 None => "label index".to_string(),
4397 };
4398 out.push(seg("label-index", label, s.offset, s.length));
4399 }
4400 if let Some(s) = h.schema_section() {
4401 out.push(seg(
4402 "schema",
4403 "schema (classes, query_stats, shapes)".into(),
4404 s.offset,
4405 s.length,
4406 ));
4407 }
4408 if let Some(q) = h.quad_index_section() {
4409 out.push(seg(
4410 "quad-index",
4411 format!("quad index ({} named graphs)", self.named_graphs.count()),
4412 q.offset,
4413 q.length,
4414 ));
4415 }
4416 out.sort_by_key(|s| s.offset);
4417 out
4418 }
4419
4420 pub fn metadata(&self) -> Option<&[u8]> {
4425 if self.metadata.is_empty() {
4426 None
4427 } else {
4428 Some(&self.metadata)
4429 }
4430 }
4431
4432 pub fn dictionary(&self) -> &Dictionary {
4433 &self.dict
4434 }
4435
4436 pub fn pyramid(&self) -> Option<&PyramidMeta> {
4438 match &self.pyramid {
4439 PyramidSlot::Resident(p) => p.as_ref(),
4440 PyramidSlot::Lazy { loader, cell } => cell.get_or_init(loader).as_ref(),
4442 }
4443 }
4444
4445 pub fn pyramid_if_loaded(&self) -> Option<&PyramidMeta> {
4450 match &self.pyramid {
4451 PyramidSlot::Resident(p) => p.as_ref(),
4452 PyramidSlot::Lazy { cell, .. } => cell.get().and_then(|o| o.as_ref()),
4453 }
4454 }
4455
4456 pub fn schema(&self) -> Option<&crate::schema_section::SchemaMeta> {
4462 self.schema.get()
4463 }
4464
4465 pub fn schema_or_pyramid(
4469 &self,
4470 ) -> Option<std::borrow::Cow<'_, crate::schema_section::SchemaMeta>> {
4471 if let Some(s) = self.schema() {
4472 return Some(std::borrow::Cow::Borrowed(s));
4473 }
4474 self.pyramid()
4475 .map(|p| std::borrow::Cow::Owned(crate::schema_section::SchemaMeta::from_pyramid(p)))
4476 }
4477
4478 pub fn predicate_stats(&self) -> &[crate::meta::PredStat] {
4483 if let Some(s) = self.schema().filter(|s| !s.predicate_stats.is_empty()) {
4484 return &s.predicate_stats;
4485 }
4486 self.pyramid_if_loaded()
4487 .map(|p| p.predicate_stats.as_slice())
4488 .unwrap_or(&[])
4489 }
4490
4491 pub(crate) fn planner_stats(&self, fault: bool) -> &[crate::meta::PredStat] {
4496 let schema = if fault {
4497 self.schema.get()
4498 } else {
4499 self.schema.get_if_loaded()
4500 };
4501 if let Some(s) = schema.filter(|s| !s.predicate_stats.is_empty()) {
4502 return &s.predicate_stats;
4503 }
4504 self.pyramid_if_loaded()
4505 .map(|p| p.predicate_stats.as_slice())
4506 .unwrap_or(&[])
4507 }
4508
4509 pub fn char_sets(&self) -> &[crate::meta::CharSet] {
4512 if let Some(s) = self.schema().filter(|s| !s.char_sets.is_empty()) {
4513 return &s.char_sets;
4514 }
4515 self.pyramid_if_loaded()
4516 .map(|p| p.char_sets.as_slice())
4517 .unwrap_or(&[])
4518 }
4519
4520 pub fn label_index(&self) -> &[crate::meta::LabelEntry] {
4526 self.pyramid_if_loaded()
4527 .map(|p| p.label_index.as_slice())
4528 .unwrap_or(&[])
4529 }
4530
4531 pub fn has_label_index(&self) -> bool {
4533 self.header.label_index_section().is_some()
4534 }
4535
4536 pub fn label_index_section(&self) -> Option<&crate::label_index::LabelIndex> {
4538 self.labels.get()
4539 }
4540
4541 pub fn prefix_search(&self, prefix: &str, limit: usize) -> Vec<(String, String)> {
4548 if let Some(li) = self.labels.get() {
4549 return li.prefix_search(prefix, limit);
4550 }
4551 let Some(pyr) = self.pyramid() else {
4552 return Vec::new();
4553 };
4554 resolve_label_hits(&self.dict, pyr.prefix_search(prefix, limit))
4555 }
4556
4557 pub(crate) fn text_index(&self) -> Option<&crate::text_index::TextIndex> {
4560 self.text_index.index()
4561 }
4562
4563 pub fn has_text_index(&self) -> bool {
4566 self.header.text_index_len > 0
4567 }
4568
4569 pub fn text_index_scope(&self) -> Option<crate::text_index::TextIndexScope> {
4573 self.text_index().map(|ti| ti.scope().clone())
4574 }
4575
4576 pub fn text_index_token_table_len(&self) -> Option<u64> {
4591 self.text_index.token_table_len()
4592 }
4593
4594 pub fn text_search(&self, words: &[&str], prefix: Option<&str>, limit: usize) -> Vec<String> {
4604 text_search_in(self.text_index(), &self.dict, words, prefix, limit)
4605 }
4606
4607 pub fn default_index(&self) -> &GraphIndex {
4609 &self.index
4610 }
4611
4612 pub fn dump(&self, graph: Option<&str>) -> Vec<TermTriple> {
4614 let index = match graph {
4615 None => &self.index,
4616 Some(g) => match self.graph_index(g) {
4617 Some(i) => i,
4618 None => return Vec::new(),
4619 },
4620 };
4621 index
4622 .match_pattern((None, None, None))
4623 .into_iter()
4624 .filter_map(|(s, p, o)| {
4625 Some((
4626 self.dict.subject_term(s)?,
4627 self.dict.predicate_term(p)?,
4628 self.dict.object_term(o)?,
4629 ))
4630 })
4631 .collect()
4632 }
4633
4634 pub fn dump_each<F: FnMut(&str, &str, &str)>(&self, graph: Option<&str>, f: F) {
4650 self.dump_filtered_each(graph, None, None, None, f)
4651 }
4652
4653 pub fn dump_filtered_each<F: FnMut(&str, &str, &str)>(
4724 &self,
4725 graph: Option<&str>,
4726 s: Option<&str>,
4727 p: Option<&str>,
4728 o: Option<&str>,
4729 mut f: F,
4730 ) {
4731 let index = match graph {
4732 None => Some(&self.index),
4733 Some(g) => self.graph_index(g),
4734 };
4735 let Some(index) = index else { return };
4736 let Some(pattern) = self.resolve_query_pattern(s, p, o) else {
4739 return;
4740 };
4741 let dict = &self.dict;
4742 const WINDOW: usize = 4096;
4787 let cap = dict.cache_cap();
4798 let prefetch_window =
4799 cap == u64::MAX || cap >= (WINDOW as u64) * 2 * (DICT_CHUNK_BUDGET as u64);
4800 const PREFETCH_BATCH: usize = 64;
4807 let prefetch_batch = if cap == u64::MAX {
4808 usize::MAX
4809 } else {
4810 PREFETCH_BATCH
4811 };
4812 let mut ids: Vec<(u32, u32, u32)> = Vec::with_capacity(WINDOW);
4813 let mut nodes: Vec<u32> = Vec::with_capacity(WINDOW * 2);
4814 let mut preds: Vec<u32> = Vec::with_capacity(WINDOW);
4815 let mut resolver = crate::dictionary::WindowResolver::default();
4816 let mut flush = |ids: &mut Vec<(u32, u32, u32)>,
4817 resolver: &mut crate::dictionary::WindowResolver,
4818 f: &mut F| {
4819 if ids.is_empty() {
4820 return;
4821 }
4822 if prefetch_window {
4826 nodes.clear();
4827 preds.clear();
4828 for &(s, p, o) in ids.iter() {
4829 nodes.push(dict.subject_node(s));
4830 nodes.push(dict.object_node(o));
4831 preds.push(p);
4832 }
4833 dict.prefetch_terms_batched(&nodes, &preds, prefetch_batch);
4834 }
4835 dict.resolve_window(ids, resolver, |s, p, o| f(s, p, o));
4836 ids.clear();
4837 };
4838 for t in index.scan_iter(pattern) {
4839 ids.push(t);
4840 if ids.len() == WINDOW {
4841 flush(&mut ids, &mut resolver, &mut f);
4842 }
4843 }
4844 flush(&mut ids, &mut resolver, &mut f);
4845 }
4846
4847 pub fn dump_plan(
4855 &self,
4856 graph: Option<&str>,
4857 s: Option<&str>,
4858 p: Option<&str>,
4859 o: Option<&str>,
4860 ) -> DumpPlan {
4861 let index = match graph {
4862 None => Some(&self.index),
4863 Some(g) => self.graph_index(g),
4864 };
4865 let scan = index
4866 .zip(self.resolve_query_pattern(s, p, o))
4867 .map(|(ix, pattern)| ix.scan_plan(pattern));
4868 DumpPlan {
4869 scan,
4870 dictionary_bytes: match &self.v06 {
4871 Some(f) => f.section(crate::v06::kind::DICT_DATA).map_or(0, |r| r.len),
4872 None => self.header.dictionary_len,
4873 },
4874 }
4875 }
4876
4877 pub fn dump_iter(&self, graph: Option<&str>) -> impl Iterator<Item = TermTriple> + '_ {
4895 self.query_iter(graph, None, None, None)
4896 }
4897
4898 pub fn query_iter(
4909 &self,
4910 graph: Option<&str>,
4911 s: Option<&str>,
4912 p: Option<&str>,
4913 o: Option<&str>,
4914 ) -> impl Iterator<Item = TermTriple> + '_ {
4915 let index = match graph {
4916 None => Some(&self.index),
4917 Some(g) => self.graph_index(g),
4918 };
4919 index
4920 .zip(self.resolve_query_pattern(s, p, o))
4921 .into_iter()
4922 .flat_map(|(ix, pattern)| ix.scan_iter(pattern))
4923 .filter_map(move |(s, p, o)| {
4924 Some((
4925 self.dict.subject_term(s)?,
4926 self.dict.predicate_term(p)?,
4927 self.dict.object_term(o)?,
4928 ))
4929 })
4930 }
4931
4932 pub fn query_batch(
4951 &self,
4952 graph: Option<&str>,
4953 s: Option<&str>,
4954 p: Option<&str>,
4955 o: Option<&str>,
4956 cursor: u64,
4957 max_quads: usize,
4958 ) -> (Vec<TermTriple>, u64, bool) {
4959 let index = match graph {
4960 None => &self.index,
4961 Some(g) => match self.graph_index(g) {
4964 Some(i) => i,
4965 None => return (Vec::new(), cursor, true),
4966 },
4967 };
4968 let Some(pattern) = self.resolve_query_pattern(s, p, o) else {
4971 return (Vec::new(), cursor, true);
4972 };
4973 let (ids, next, done) = index.scan_batch(pattern, cursor, max_quads);
4974 if !ids.is_empty() {
4978 let mut nodes = Vec::with_capacity(ids.len() * 2);
4979 let mut preds = Vec::with_capacity(ids.len());
4980 for &(s, p, o) in &ids {
4981 nodes.push(self.dict.subject_node(s));
4982 nodes.push(self.dict.object_node(o));
4983 preds.push(p);
4984 }
4985 self.dict.prefetch_terms(&nodes, &preds);
4986 }
4987 let triples = ids
4988 .into_iter()
4989 .filter_map(|(s, p, o)| {
4990 Some((
4991 self.dict.subject_term(s)?,
4992 self.dict.predicate_term(p)?,
4993 self.dict.object_term(o)?,
4994 ))
4995 })
4996 .collect();
4997 (triples, next, done)
4998 }
4999
5000 pub fn dump_batch(
5026 &self,
5027 graph: Option<&str>,
5028 cursor: u32,
5029 max_quads: usize,
5030 ) -> (Vec<TermTriple>, u32, bool) {
5031 fn next_tile_start(tiles: &crate::index::TileList, sid: u32) -> Option<u32> {
5036 let i = tiles.first_max_ge(sid);
5037 (i < tiles.len()).then(|| tiles[i].leading_range().0.max(sid))
5038 }
5039
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 tiles = index.tile_sections()[IndexPermutation::Spo.section_index()];
5053 let (Some(first), Some(last)) = (
5054 tiles.first().map(|t| t.leading_range().0),
5055 tiles.last().map(|t| t.leading_range().1),
5056 ) else {
5057 return (Vec::new(), cursor, true); };
5059
5060 let mut sid = cursor.max(first);
5061 let mut probes = max_quads.saturating_mul(4).max(1 << 16);
5062 let mut ids: Vec<(u32, u32, u32)> = Vec::new();
5063 let mut exhausted = false;
5064 while sid <= last && probes > 0 {
5065 probes -= 1;
5066 let hits = index.match_pattern((Some(sid), None, None));
5067 if hits.is_empty() {
5068 match index.next_leading(IndexPermutation::Spo.section_index(), sid) {
5078 Some(next) if next > sid => {
5079 sid = next;
5080 continue;
5081 }
5082 None if !index.load_incomplete() => {
5083 exhausted = true;
5084 break;
5085 }
5086 _ => {}
5087 }
5088 match next_tile_start(tiles, sid) {
5089 None => {
5090 exhausted = true;
5091 break;
5092 }
5093 Some(next) if next > sid => {
5094 sid = next;
5095 continue;
5096 }
5097 Some(_) => {}
5098 }
5099 } else {
5100 ids.extend(hits);
5101 }
5102 if sid == u32::MAX {
5103 exhausted = true;
5104 break;
5105 }
5106 sid += 1;
5107 if ids.len() >= max_quads {
5108 break;
5109 }
5110 }
5111 let done = exhausted || sid > last;
5112
5113 let dict = self.dictionary();
5120 if !ids.is_empty() {
5121 let mut nodes = Vec::with_capacity(ids.len() * 2);
5122 let mut preds = Vec::with_capacity(ids.len());
5123 for &(s, p, o) in &ids {
5124 nodes.push(dict.subject_node(s));
5125 nodes.push(dict.object_node(o));
5126 preds.push(p);
5127 }
5128 dict.prefetch_terms(&nodes, &preds);
5129 }
5130 let triples = ids
5131 .into_iter()
5132 .filter_map(|(s, p, o)| {
5133 Some((
5134 dict.subject_term(s)?,
5135 dict.predicate_term(p)?,
5136 dict.object_term(o)?,
5137 ))
5138 })
5139 .collect();
5140 (triples, sid, done)
5141 }
5142
5143 pub fn named_graph_count(&self) -> usize {
5146 self.named_graphs.count()
5147 }
5148
5149 pub fn named_graph_quad_count(&self, i: usize) -> Option<u64> {
5154 match &self.named_graphs {
5155 NamedGraphsSlot::Quad(q) => q.quad_count_at(i),
5156 _ => None,
5157 }
5158 }
5159
5160 pub fn named_graph_transient(&self, i: usize) -> Option<GraphIndex> {
5169 match &self.named_graphs {
5170 NamedGraphsSlot::Quad(q) => q.transient_view(i, TRANSIENT_GRAPH_QUADS),
5171 _ => None,
5172 }
5173 }
5174
5175 pub(crate) fn named_graphs_with_subjects(
5182 &self,
5183 subjects: &std::collections::BTreeSet<u32>,
5184 ) -> Option<Vec<usize>> {
5185 match &self.named_graphs {
5186 NamedGraphsSlot::Quad(q) => q.graphs_with_subjects(subjects),
5187 _ => None,
5188 }
5189 }
5190
5191 pub fn named_quad_count(&self) -> Option<u64> {
5196 match &self.named_graphs {
5197 NamedGraphsSlot::Quad(q) => Some(q.quad_count()),
5198 _ => None,
5199 }
5200 }
5201
5202 pub(crate) fn index_triples(&self, index: &GraphIndex) -> u64 {
5208 index.size_hint().unwrap_or(self.header().quad_count)
5209 }
5210
5211 pub fn named_graph_name_at(&self, i: usize) -> Option<&str> {
5214 self.named_graphs.name_at(&self.dict, i, false)
5215 }
5216
5217 pub fn named_graph_at(&self, i: usize) -> Option<(&str, &GraphIndex)> {
5221 self.named_graphs.graph_at(&self.dict, i, false)
5222 }
5223
5224 pub(crate) fn named_graph_name_owned_demand(
5232 &self,
5233 i: usize,
5234 exhaustive: bool,
5235 ) -> Option<String> {
5236 self.named_graphs.name_owned(&self.dict, i, exhaustive)
5237 }
5238
5239 pub(crate) fn named_graph_ordinal(&self, iri: &str) -> Option<usize> {
5243 match &self.named_graphs {
5244 NamedGraphsSlot::Quad(q) => q.ordinal_of_iri(&self.dict, iri),
5245 _ => None,
5246 }
5247 }
5248
5249 pub(crate) fn named_graph_ordinal_of_id(&self, g: u32) -> Option<usize> {
5252 match &self.named_graphs {
5253 NamedGraphsSlot::Quad(q) => q.ordinal_of_id(g),
5254 _ => None,
5255 }
5256 }
5257
5258 pub(crate) fn named_quad_scan(
5263 &self,
5264 pat: (Option<u32>, Option<u32>, Option<u32>),
5265 ) -> Option<crate::quad::QuadScan> {
5266 match &self.named_graphs {
5267 NamedGraphsSlot::Quad(q) => q.scan(pat),
5268 _ => None,
5269 }
5270 }
5271
5272 pub(crate) fn named_graph_at_demand(
5275 &self,
5276 i: usize,
5277 exhaustive: bool,
5278 ) -> Option<(&str, &GraphIndex)> {
5279 self.named_graphs.graph_at(&self.dict, i, exhaustive)
5280 }
5281
5282 pub fn graph_names(&self) -> Vec<&str> {
5287 (0..self.named_graphs.count())
5288 .filter_map(|i| self.named_graphs.name_at(&self.dict, i, false))
5289 .collect()
5290 }
5291
5292 pub fn graph_index(&self, iri: &str) -> Option<&GraphIndex> {
5294 self.named_graphs.find(&self.dict, iri)
5295 }
5296
5297 pub fn match_ids(
5300 &self,
5301 pattern: (Option<u32>, Option<u32>, Option<u32>),
5302 ) -> Vec<(u32, u32, u32)> {
5303 self.index.match_pattern(pattern)
5304 }
5305
5306 pub fn predicate_pairs(&self, predicate: &str) -> Vec<(u32, u32)> {
5309 let pid = match self.dict.predicate_id(predicate) {
5310 Some(p) => p,
5311 None => return Vec::new(),
5312 };
5313 self.index
5314 .match_pattern((None, Some(pid), None))
5315 .into_iter()
5316 .map(|(s, _p, o)| (self.dict.subject_node(s), self.dict.object_node(o)))
5317 .collect()
5318 }
5319
5320 pub fn open_ranged<R: RangeReader>(reader: &R) -> Result<Self, FileError> {
5324 let head = reader.read_at(0, (HEADER_LEN as u64).min(reader.len()))?;
5325 if crate::v06::open::is_v06(&head) {
5326 let mut all = head;
5329 let at = all.len() as u64;
5330 if reader.len() > at {
5331 all.extend_from_slice(&reader.read_at(at, reader.len() - at)?);
5332 }
5333 return Self::open(&all);
5334 }
5335 let header = Header::from_bytes(&head)?;
5336
5337 let dict_bytes = reader.read_at(header.dictionary_offset, header.dictionary_len)?;
5338 let dict = decode_dictionary_container(&dict_bytes, header.dict_codec)?;
5339
5340 check_named_layout(&header)?;
5341 let index_bytes = reader.read_at(header.root_dir_offset, header.root_dir_len)?;
5342 let (index, _) = decode_root_index_container(&index_bytes, &header)?;
5343 let index_section_ranges = decode_index_section_ranges(
5344 &index_bytes,
5345 header.root_dir_offset,
5346 header.perms,
5347 header.index_container_sections(),
5348 )?;
5349
5350 let pyramid = PyramidSlot::Resident(if header.pyramid_meta_len > 0 {
5351 let mb = reader.read_at(header.pyramid_meta_offset, header.pyramid_meta_len)?;
5352 Some(
5353 PyramidMeta::decode(&mb)
5354 .map_err(|_| FileError::Container("malformed pyramid meta"))?,
5355 )
5356 } else {
5357 None
5358 });
5359
5360 let (ti_off, ti_len) = header.text_index_payload();
5363 let text_index_bytes = if ti_len > 0 {
5364 Some(reader.read_at(ti_off, ti_len)?)
5365 } else {
5366 None
5367 };
5368 let text_index = resident_text_index_slot(text_index_bytes.as_deref(), header.block_codec)?;
5369 let labels = SectionSlot::Resident(header.label_index_section().and_then(|s| {
5372 let b = reader.read_at(s.offset, s.length).ok()?;
5373 crate::label_index::LabelIndex::from_section(&b, header.block_codec).ok()
5374 }));
5375 let schema = SectionSlot::Resident(read_schema_with_header(reader, &header));
5376
5377 let named_graphs = NamedGraphsSlot::resident(
5378 &header,
5379 |off, len| Ok(reader.read_at(off, len)?),
5380 || {
5381 let nb = reader.read_at(header.named_graphs_offset, header.named_graphs_len)?;
5382 decode_named_graphs(&nb, header.block_codec, header.perms)
5383 },
5384 )?;
5385
5386 let tile_ranges =
5390 tile_file_ranges(&index_bytes, header.root_dir_offset, &index_section_ranges);
5391 Ok(Self {
5392 header,
5393 dict,
5394 index,
5395 index_section_ranges,
5396 tile_ranges,
5397 pyramid,
5398 text_index,
5399 labels,
5400 schema,
5401 named_graphs,
5402 metadata: Vec::new(),
5403 service_client: None,
5404 service_error: std::sync::Mutex::new(None),
5405 spill_threshold: std::sync::atomic::AtomicU64::new(u64::MAX),
5406 v06: None,
5407 })
5408 }
5409
5410 fn open_v06(
5416 reader: std::sync::Arc<dyn RangeReader + Send + Sync>,
5417 first: &[u8],
5418 budget: bool,
5419 ) -> Result<Self, FileError> {
5420 let f = std::sync::Arc::new(crate::v06::open::V06File::open(reader.clone(), first)?);
5421 let header = crate::v06::logical_header(&f.h);
5422 let rc = reader.concurrency();
5423 let dict = f.dictionary([true; 4])?;
5424 let index = f.index(rc)?;
5425 let (pyramid, text_index, labels, schema) = v06_slots(&f);
5426 let named_graphs = match f.quad(rc) {
5427 Some(q) => NamedGraphsSlot::Quad(q?),
5428 None => NamedGraphsSlot::Resident(Vec::new()),
5429 };
5430 let rete = Self {
5431 header,
5432 dict,
5433 index,
5434 index_section_ranges: [ByteRange::default(); NUM_PERMS],
5435 tile_ranges: Default::default(),
5436 pyramid,
5437 text_index,
5438 labels,
5439 schema,
5440 named_graphs,
5441 metadata: Vec::new(),
5442 service_client: None,
5443 service_error: std::sync::Mutex::new(None),
5444 spill_threshold: std::sync::atomic::AtomicU64::new(u64::MAX),
5445 v06: Some(f),
5446 };
5447 #[cfg(not(target_arch = "wasm32"))]
5448 if budget {
5449 rete.set_memory_budget(match crate::sysmem::default_query_budget_mb() {
5450 0 => None,
5451 mb => Some(mb << 20),
5452 });
5453 }
5454 #[cfg(target_arch = "wasm32")]
5455 let _ = budget;
5456 Ok(rete)
5457 }
5458
5459 pub fn v06(&self) -> Option<&crate::v06::open::V06File> {
5461 self.v06.as_deref()
5462 }
5463
5464 pub fn open_ranged_lazy<R: RangeReader + Send + Sync + 'static>(
5476 reader: R,
5477 ) -> Result<Self, FileError> {
5478 Self::open_ranged_lazy_with(reader, crate::v06::FIRST_READ)
5479 }
5480
5481 pub fn open_ranged_lazy_with<R: RangeReader + Send + Sync + 'static>(
5486 reader: R,
5487 first_read: u64,
5488 ) -> Result<Self, FileError> {
5489 let first_len = first_read.max(HEADER_LEN as u64).min(reader.len());
5492 let first: std::sync::Arc<[u8]> = std::sync::Arc::from(reader.read_at(0, first_len)?);
5493 #[cfg(feature = "v06-parity")]
5494 if !crate::v06::open::is_v06(&first) {
5495 let all = reader.read_at(0, reader.len())?;
5496 if let Some(v6) = parity_image(&all) {
5497 let r: std::sync::Arc<dyn RangeReader + Send + Sync> =
5498 std::sync::Arc::new(crate::reader::BytesReader(std::sync::Arc::from(v6)));
5499 let head = r.read_at(0, crate::v06::FIRST_READ.min(r.len()))?;
5500 return Self::open_v06(r, &head, true);
5501 }
5502 }
5503 let reader = crate::reader::PrefixReader::new(reader, first.clone());
5504 if crate::v06::open::is_v06(&first) {
5505 let r: std::sync::Arc<dyn RangeReader + Send + Sync> = std::sync::Arc::new(reader);
5506 return Self::open_v06(r, &first, true);
5507 }
5508 let head = reader.read_at(0, HEADER_LEN as u64)?;
5509 let header = Header::from_bytes(&head)?;
5510 check_named_layout(&header)?;
5511 let reader = std::sync::Arc::new(reader);
5512 let read_concurrency = reader.concurrency();
5515
5516 let open_dict = || ranged_chunked_dictionary(&reader, &header, [true; 4]);
5520
5521 let reader_dyn: std::sync::Arc<dyn RangeReader + Send + Sync> = reader.clone();
5525 let open_index = || {
5526 open_index_container_lazy(
5527 &reader_dyn,
5528 ByteRange {
5529 offset: header.root_dir_offset,
5530 len: header.root_dir_len,
5531 },
5532 header.block_codec,
5533 header.has_tile_synopsis(),
5534 read_concurrency,
5535 header.perms,
5536 header.index_container_sections(),
5537 )
5538 };
5539
5540 let (dict, index) = open_side_by_side(read_concurrency, open_dict, open_index);
5547 let dict = dict?;
5548 let (index, index_section_ranges, tile_ranges) = index?;
5549
5550 let pyramid = ranged_pyramid_slot(&reader, &header);
5554
5555 let text_index = ranged_text_index_slot(&reader, &header);
5560
5561 let labels = ranged_label_slot(&reader, &header);
5565 let schema = ranged_schema_slot(&reader, &header);
5566
5567 let named_graphs = if let Some(q) = header.quad_index_section() {
5574 NamedGraphsSlot::Quad(crate::quad::QuadNamed::new(
5578 reader_dyn,
5579 ByteRange {
5580 offset: q.offset,
5581 len: q.length,
5582 },
5583 header.block_codec,
5584 header.perms,
5585 read_concurrency,
5586 ))
5587 } else if header.named_graphs_len > 0 {
5588 NamedGraphsSlot::Lazy(LazyNamedGraphs::new(
5589 reader_dyn,
5590 ByteRange {
5591 offset: header.named_graphs_offset,
5592 len: header.named_graphs_len,
5593 },
5594 header.block_codec,
5595 header.has_tile_synopsis(),
5596 read_concurrency,
5597 header.perms,
5598 ))
5599 } else {
5600 NamedGraphsSlot::Resident(Vec::new())
5601 };
5602
5603 let rete = Self {
5604 header,
5605 dict,
5606 index,
5607 index_section_ranges,
5608 tile_ranges,
5609 pyramid,
5610 text_index,
5611 labels,
5612 schema,
5613 named_graphs,
5614 metadata: Vec::new(),
5615 service_client: None,
5616 service_error: std::sync::Mutex::new(None),
5617 spill_threshold: std::sync::atomic::AtomicU64::new(u64::MAX),
5618 v06: None,
5619 };
5620 #[cfg(not(target_arch = "wasm32"))]
5632 rete.set_memory_budget(match crate::sysmem::default_query_budget_mb() {
5633 0 => None,
5634 mb => Some(mb << 20),
5635 });
5636 Ok(rete)
5637 }
5638
5639 pub fn index_incomplete(&self) -> bool {
5644 self.index.load_incomplete()
5645 || self.dict.load_incomplete()
5646 || self.named_graphs.load_incomplete()
5647 }
5648
5649 pub fn reset_load_failures(&self) {
5657 self.index.reset_load_failure();
5658 self.dict.reset_load_failure();
5659 self.named_graphs.reset_load_failures();
5660 }
5661
5662 pub fn set_memory_budget(&self, budget: Option<u64>) -> MemoryBudget {
5693 let total = budget.unwrap_or(u64::MAX);
5694 self.set_spill_threshold(budget.map(spill_threshold_for));
5695 let mut split = split_memory_budget(total);
5696 let fixed = if total == u64::MAX {
5697 0
5698 } else {
5699 self.fixed_overhead().total()
5700 };
5701 if split.dict_cache != u64::MAX {
5702 split.dict_cache = split
5703 .dict_cache
5704 .saturating_sub(fixed)
5705 .max(MIN_DICT_CACHE_CAP);
5706 }
5707 self.dict.set_cache_cap(split.dict_cache);
5708 self.index.set_cache_cap(split.tile_cache);
5709 match &self.named_graphs {
5714 NamedGraphsSlot::Lazy(lazy) => lazy.set_tile_cap(split.tile_cache),
5715 NamedGraphsSlot::Quad(q) => q.set_tile_cap(split.tile_cache),
5718 NamedGraphsSlot::Resident(_) => {}
5719 }
5720 if std::env::var("RETE_OPEN_DEBUG").is_ok() {
5721 eprintln!(
5722 "[memory-budget] total={} dict_cache={} tile_cache={} block_cache={} fixed={:.1}MiB",
5723 if total == u64::MAX {
5724 "unlimited".to_string()
5725 } else {
5726 format!("{}MiB", total >> 20)
5727 },
5728 fmt_cap(split.dict_cache),
5729 fmt_cap(split.tile_cache),
5730 fmt_cap(split.block_cache),
5731 fixed as f64 / (1u64 << 20) as f64,
5732 );
5733 }
5734 split
5735 }
5736
5737 pub fn spill_threshold(&self) -> u64 {
5744 self.spill_threshold
5745 .load(std::sync::atomic::Ordering::Relaxed)
5746 }
5747
5748 pub fn set_spill_threshold(&self, bytes: Option<u64>) {
5752 self.spill_threshold.store(
5753 bytes.unwrap_or(u64::MAX),
5754 std::sync::atomic::Ordering::Relaxed,
5755 );
5756 }
5757
5758 pub fn dict_cache_stats(&self) -> crate::chunk_cache::CacheStats {
5762 self.dict.cache_stats()
5763 }
5764
5765 pub fn fixed_overhead(&self) -> FixedOverhead {
5769 FixedOverhead {
5770 dict_directory: self.dict.directory_bytes(),
5771 index_directory: self.index.directory_bytes(),
5772 named_graphs: self.named_graphs.directory_bytes(),
5773 }
5774 }
5775
5776 pub fn index_cache_stats(&self) -> crate::chunk_cache::CacheStats {
5778 self.index.cache_stats()
5779 }
5780
5781 pub fn dict_cache_cap(&self) -> u64 {
5783 self.dict.cache_cap()
5784 }
5785
5786 pub fn release_named_graph(&mut self, iri: &str) {
5799 match &mut self.named_graphs {
5800 NamedGraphsSlot::Lazy(lazy) => lazy.release(iri),
5801 NamedGraphsSlot::Quad(q) => q.release(&self.dict, iri),
5802 NamedGraphsSlot::Resident(_) => {}
5803 }
5804 }
5805
5806 fn resolve_query_pattern(
5807 &self,
5808 s: Option<&str>,
5809 p: Option<&str>,
5810 o: Option<&str>,
5811 ) -> Option<Pattern> {
5812 let sid = match s {
5813 Some(t) => match self.dict.subject_id(t) {
5814 Some(id) => Some(id),
5815 None => return None,
5816 },
5817 None => None,
5818 };
5819 let pid = match p {
5820 Some(t) => match self.dict.predicate_id(t) {
5821 Some(id) => Some(id),
5822 None => return None,
5823 },
5824 None => None,
5825 };
5826 let oid = match o {
5827 Some(t) => match self.dict.object_id(t) {
5828 Some(id) => Some(id),
5829 None => return None,
5830 },
5831 None => None,
5832 };
5833 Some((sid, pid, oid))
5834 }
5835
5836 pub fn query_with_provenance(
5840 &self,
5841 s: Option<&str>,
5842 p: Option<&str>,
5843 o: Option<&str>,
5844 ) -> Vec<TripleProvenance> {
5845 let pattern = match self.resolve_query_pattern(s, p, o) {
5846 Some(pattern) => pattern,
5847 None => return Vec::new(),
5848 };
5849
5850 let index_permutation = GraphIndex::best_permutation_in(self.header.perms, pattern);
5851 let si = index_permutation.section_index();
5852 let (dictionary_range, index_range, index_section_range, pyramid_range) = match &self.v06 {
5853 Some(f) => {
5854 use crate::v06::kind;
5855 let sec = |k| f.section(k).unwrap_or_default();
5856 let perm = f
5857 .root
5858 .unit(crate::v06::tag::INDEX)
5859 .and_then(|u| crate::v06::decode_index_root(u).ok())
5860 .and_then(|v| v.into_iter().find(|p| p.si == si))
5861 .map(|p| ByteRange {
5862 offset: sec(kind::INDEX_DATA).offset + p.data_off,
5863 len: p.data_len,
5864 })
5865 .unwrap_or_default();
5866 (
5867 sec(kind::DICT_DATA),
5868 sec(kind::INDEX_DATA),
5869 perm,
5870 f.section(kind::PYRAMID),
5871 )
5872 }
5873 None => (
5874 ByteRange {
5875 offset: self.header.dictionary_offset,
5876 len: self.header.dictionary_len,
5877 },
5878 ByteRange {
5879 offset: self.header.root_dir_offset,
5880 len: self.header.root_dir_len,
5881 },
5882 self.index_section_ranges[si],
5883 (self.header.pyramid_meta_len > 0).then_some(ByteRange {
5884 offset: self.header.pyramid_meta_offset,
5885 len: self.header.pyramid_meta_len,
5886 }),
5887 ),
5888 };
5889
5890 let tiles = &self.tile_ranges[si];
5891 let v06_tiles = self.v06.is_some().then(|| self.index.tile_sections()[si]);
5892 self.index
5893 .match_pattern(pattern)
5894 .into_iter()
5895 .filter_map(|(s, p, o)| {
5896 let terms = (
5897 self.dict.subject_term(s)?,
5898 self.dict.predicate_term(p)?,
5899 self.dict.object_term(o)?,
5900 );
5901 let a = index_permutation.forward((s, p, o)).0;
5904 let (tile, tile_range) = if let Some(tl) = v06_tiles {
5905 let ti = tl.first_max_ge(a);
5906 match (ti < tl.len() && tl[ti].leading_range().0 <= a)
5907 .then(|| tl.range(ti))
5908 .flatten()
5909 {
5910 Some((offset, len)) => (
5911 Some(format!("{}/{ti}", index_permutation.name())),
5912 Some(ByteRange { offset, len }),
5913 ),
5914 None => (None, None),
5915 }
5916 } else {
5917 let ti = tiles.partition_point(|&(_, max_a, _)| max_a < a);
5918 match tiles.get(ti) {
5919 Some(&(min_a, _, range)) if min_a <= a => (
5920 Some(format!("{}/{ti}", index_permutation.name())),
5921 Some(range),
5922 ),
5923 _ => (None, None),
5924 }
5925 };
5926 Some(TripleProvenance {
5927 terms,
5928 ids: (s, p, o),
5929 graph: None,
5930 matched_pattern: pattern,
5931 index_permutation,
5932 dictionary_range,
5933 index_range,
5934 index_section_range,
5935 pyramid_range,
5936 tile,
5937 tile_range,
5938 })
5939 })
5940 .collect()
5941 }
5942
5943 pub fn query(&self, s: Option<&str>, p: Option<&str>, o: Option<&str>) -> Vec<TermTriple> {
5947 self.query_with_provenance(s, p, o)
5948 .into_iter()
5949 .map(|m| m.terms)
5950 .collect()
5951 }
5952
5953 pub fn query_in_graph(
5961 &self,
5962 graph: Option<&str>,
5963 s: Option<&str>,
5964 p: Option<&str>,
5965 o: Option<&str>,
5966 ) -> Vec<TermTriple> {
5967 let pattern = match self.resolve_query_pattern(s, p, o) {
5968 Some(pattern) => pattern,
5969 None => return Vec::new(),
5970 };
5971 let index = match graph {
5972 None => &self.index,
5973 Some(g) => match self.graph_index(g) {
5974 Some(i) => i,
5975 None => return Vec::new(),
5976 },
5977 };
5978 self.resolve_matches(index.match_pattern(pattern))
5979 }
5980
5981 fn resolve_matches(&self, ids: Vec<Triple>) -> Vec<TermTriple> {
5984 if !ids.is_empty() {
5992 let mut nodes = Vec::with_capacity(ids.len() * 2);
5993 let mut preds = Vec::with_capacity(ids.len());
5994 for &(s, p, o) in &ids {
5995 nodes.push(self.dict.subject_node(s));
5996 nodes.push(self.dict.object_node(o));
5997 preds.push(p);
5998 }
5999 self.dict.prefetch_terms(&nodes, &preds);
6000 }
6001 ids.into_iter()
6002 .filter_map(|(s, p, o)| {
6003 Some((
6004 self.dict.subject_term(s)?,
6005 self.dict.predicate_term(p)?,
6006 self.dict.object_term(o)?,
6007 ))
6008 })
6009 .collect()
6010 }
6011
6012 pub fn query_quads(
6017 &self,
6018 s: Option<&str>,
6019 p: Option<&str>,
6020 o: Option<&str>,
6021 ) -> Vec<(TermTriple, Option<String>)> {
6022 let mut out: Vec<(TermTriple, Option<String>)> = self
6023 .query_in_graph(None, s, p, o)
6024 .into_iter()
6025 .map(|t| (t, None))
6026 .collect();
6027 let Some(pattern) = self.resolve_query_pattern(s, p, o) else {
6028 return out;
6029 };
6030 for i in 0..self.named_graphs.count() {
6031 let Some(iri) = self.named_graphs.name_at(&self.dict, i, true) else {
6034 continue;
6035 };
6036 let owned = self.named_graph_transient(i);
6039 let index = match &owned {
6040 Some(view) => view,
6041 None => match self.named_graphs.graph_at(&self.dict, i, true) {
6042 Some((_, g)) => g,
6043 None => continue,
6044 },
6045 };
6046 for triple in self.resolve_matches(index.match_pattern(pattern)) {
6047 out.push((triple, Some(iri.to_string())));
6048 }
6049 }
6050 out
6051 }
6052
6053 pub fn query_ranged<R: RangeReader>(
6060 reader: &R,
6061 s: Option<&str>,
6062 p: Option<&str>,
6063 o: Option<&str>,
6064 ) -> Result<Vec<TermTriple>, FileError> {
6065 let head = reader.read_at(0, (HEADER_LEN as u64).min(reader.len()))?;
6066 if crate::v06::open::is_v06(&head) {
6067 return Ok(v06_query_ranged(reader, head, s, p, o, true)?.unwrap_or_default());
6068 }
6069 let routed = match route_pattern(reader, head, s, p, o)? {
6070 Some(routed) => routed,
6071 None => return Ok(Vec::new()),
6072 };
6073 let matches = fetch_routed_matches(reader, &routed)?;
6074 Ok(matches
6075 .into_iter()
6076 .filter_map(|(s, p, o)| {
6077 Some((
6078 routed.dict.subject_term(s)?,
6079 routed.dict.predicate_term(p)?,
6080 routed.dict.object_term(o)?,
6081 ))
6082 })
6083 .collect())
6084 }
6085
6086 pub fn route_pattern_ranged<R: RangeReader>(
6090 reader: &R,
6091 s: Option<&str>,
6092 p: Option<&str>,
6093 o: Option<&str>,
6094 ) -> Result<bool, FileError> {
6095 let head = reader.read_at(0, (HEADER_LEN as u64).min(reader.len()))?;
6096 if crate::v06::open::is_v06(&head) {
6097 return Ok(v06_query_ranged(reader, head, s, p, o, false)?.is_some());
6098 }
6099 Ok(route_pattern(reader, head, s, p, o)?.is_some())
6100 }
6101}
6102
6103fn v06_query_ranged<R: RangeReader>(
6109 reader: &R,
6110 head: Vec<u8>,
6111 s: Option<&str>,
6112 p: Option<&str>,
6113 o: Option<&str>,
6114 fetch: bool,
6115) -> Result<Option<Vec<TermTriple>>, FileError> {
6116 use crate::v06::{kind, open::SparseReader, Header06, Root06, HEADER_LEN};
6117 let len = reader.len();
6118 let h = Header06::from_bytes(&head)?;
6119 let root_end = (HEADER_LEN as u64 + h.root_len as u64).min(len);
6120 let root_bytes = if root_end <= head.len() as u64 {
6121 head[HEADER_LEN..root_end as usize].to_vec()
6122 } else {
6123 reader.read_at(HEADER_LEN as u64, root_end - HEADER_LEN as u64)?
6124 };
6125 let root = Root06::decode(&root_bytes, h.internal_codec)?;
6126 let dict = root.section(kind::DICT_DATA).and_then(|d| d.abs(&h).ok());
6127 let end = dict
6130 .map_or(h.data_offset, |d| d.offset + d.len)
6131 .max(crate::header::HEADER_LEN as u64)
6132 .min(len);
6133 let mut held = head;
6134 if end > held.len() as u64 {
6135 let at = held.len() as u64;
6136 held.extend_from_slice(&reader.read_at(at, end - at)?);
6137 }
6138 let sparse = SparseReader::fetch(reader, held, &[])?;
6139 let rete = Rete::open_ranged_lazy_with(sparse, 0)?;
6140 let Some(pattern) = resolve_query_pattern(rete.dictionary(), s, p, o) else {
6141 return Ok(None);
6142 };
6143 if !fetch {
6144 return Ok(Some(Vec::new()));
6145 }
6146 let perm = GraphIndex::best_permutation_in(h.perms(), pattern);
6147 let si = perm.section_index();
6148 let index = rete.default_index();
6149 let list = index.tile_sections()[si];
6150 let n = list.len();
6151 let [pa, _, _] = perm.order_pattern(pattern);
6152 let (start, stop) = match pa {
6153 Some(a) => {
6154 let start = list.first_max_ge(a);
6155 let mut stop = start;
6156 while stop < n {
6157 list.ensure_span(stop, stop + 1);
6158 if list[stop].leading_range().0 > a {
6159 break;
6160 }
6161 stop += 1;
6162 }
6163 (start, stop)
6164 }
6165 None => {
6166 list.ensure_span(0, n);
6167 (0, n)
6168 }
6169 };
6170 let ranges: Vec<(u64, u64)> = (start..stop)
6171 .filter_map(|i| index.tile_range(si, i))
6172 .collect();
6173 let mut out = Vec::new();
6174 if let (Some(&(lo, _)), Some(&(last, last_len))) = (ranges.first(), ranges.last()) {
6175 let body = reader.read_at(lo, last + last_len - lo)?;
6177 for &(off, l) in &ranges {
6178 let at = (off - lo) as usize;
6179 let tile = decompress(h.block_codec, &body[at..at + l as usize])?;
6180 out.extend(GraphIndex::match_serialized_block(&tile, perm, pattern));
6181 }
6182 }
6183 out.sort_unstable();
6184 let d = rete.dictionary();
6185 Ok(Some(
6186 out.into_iter()
6187 .filter_map(|(s, p, o)| {
6188 Some((d.subject_term(s)?, d.predicate_term(p)?, d.object_term(o)?))
6189 })
6190 .collect(),
6191 ))
6192}
6193
6194struct RoutedPattern {
6197 dict: Dictionary,
6198 pattern: Pattern,
6199 permutation: IndexPermutation,
6200 header: Header,
6201 section: ByteRange,
6203}
6204
6205fn route_pattern<R: RangeReader>(
6208 reader: &R,
6209 head: Vec<u8>,
6210 s: Option<&str>,
6211 p: Option<&str>,
6212 o: Option<&str>,
6213) -> Result<Option<RoutedPattern>, FileError> {
6214 let header = Header::from_bytes(&head)?;
6215
6216 let dict_bytes = reader.read_at(header.dictionary_offset, header.dictionary_len)?;
6217 let dict = decode_dictionary_container(&dict_bytes, header.dict_codec)?;
6218
6219 let Some(pattern) = resolve_query_pattern(&dict, s, p, o) else {
6220 return Ok(None);
6221 };
6222 let permutation = GraphIndex::best_permutation_in(header.perms, pattern);
6223 let section = locate_container_section_ranged(
6224 reader,
6225 header.root_dir_offset,
6226 header.root_dir_len,
6227 header
6228 .perms
6229 .position(permutation)
6230 .ok_or(FileError::Container("routed to an absent permutation"))?,
6231 header.index_container_sections() as u64,
6232 )?;
6233 Ok(Some(RoutedPattern {
6234 dict,
6235 pattern,
6236 permutation,
6237 header,
6238 section,
6239 }))
6240}
6241
6242fn fetch_routed_matches<R: RangeReader>(
6247 reader: &R,
6248 routed: &RoutedPattern,
6249) -> Result<Vec<Triple>, FileError> {
6250 let dir = read_tile_directory_ranged(reader, routed.section)?;
6251 let [pa, _, _] = routed.permutation.order_pattern(routed.pattern);
6252 let codec = routed.header.block_codec;
6253 let mut out = Vec::new();
6254 match pa {
6255 Some(a) => {
6258 for e in dir.iter().filter(|e| e.min_a <= a && a <= e.max_a) {
6259 let len = e.end - e.start;
6260 let bytes = reader.read_at(checked_end(routed.section.offset, e.start)?, len)?;
6261 if bytes.len() as u64 != len {
6262 return Err(FileError::Container("short tile read"));
6263 }
6264 let tile = decompress(codec, &bytes)?;
6265 out.extend(GraphIndex::match_serialized_block(
6266 &tile,
6267 routed.permutation,
6268 routed.pattern,
6269 ));
6270 }
6271 }
6272 None => {
6275 if let (Some(first), Some(last)) = (dir.first(), dir.last()) {
6276 let base = first.start;
6277 let body =
6278 reader.read_at(checked_end(routed.section.offset, base)?, last.end - base)?;
6279 for e in &dir {
6280 let stored = checked_slice(&body, e.start - base, e.end - e.start)
6282 .ok_or(FileError::Container("short tile read"))?;
6283 let tile = decompress(codec, stored)?;
6284 out.extend(GraphIndex::match_serialized_block(
6285 &tile,
6286 routed.permutation,
6287 routed.pattern,
6288 ));
6289 }
6290 }
6291 }
6292 }
6293 out.sort_unstable();
6294 Ok(out)
6295}
6296
6297fn resolve_query_pattern(
6298 dict: &Dictionary,
6299 s: Option<&str>,
6300 p: Option<&str>,
6301 o: Option<&str>,
6302) -> Option<Pattern> {
6303 let sid = match s {
6304 Some(t) => Some(dict.subject_id(t)?),
6305 None => None,
6306 };
6307 let pid = match p {
6308 Some(t) => Some(dict.predicate_id(t)?),
6309 None => None,
6310 };
6311 let oid = match o {
6312 Some(t) => Some(dict.object_id(t)?),
6313 None => None,
6314 };
6315 Some((sid, pid, oid))
6316}
6317
6318fn ranged_chunked_dictionary<R: RangeReader + Send + Sync + 'static>(
6333 reader: &std::sync::Arc<R>,
6334 header: &Header,
6335 want: [bool; 4],
6336) -> Result<Dictionary, FileError> {
6337 let cache = crate::chunk_cache::ChunkCache::unlimited_arc();
6340 let mut dict_sections: Vec<crate::dict::ChunkedSection> = Vec::with_capacity(4);
6341 let mut section_ranges: [std::sync::Arc<Vec<ByteRange>>; 4] = Default::default();
6342 for si in 0..4 {
6343 if !want[si] {
6344 dict_sections.push(crate::dict::ChunkedSection::from_parts(
6345 crate::dict::SectionMeta {
6346 term_count: 0,
6347 restart_interval: 1,
6348 restart_offsets: Vec::new(),
6349 },
6350 Vec::new(),
6351 None,
6352 cache.clone(),
6353 si as u8,
6354 ));
6355 continue;
6356 }
6357 let section = locate_container_section_ranged(
6358 reader.as_ref(),
6359 header.dictionary_offset,
6360 header.dictionary_len,
6361 si,
6362 4,
6363 )?;
6364 let (meta, entries) = read_dict_dir_ranged(reader.as_ref(), section)?;
6365 let ranges: std::sync::Arc<Vec<ByteRange>> = std::sync::Arc::new(
6368 entries
6369 .iter()
6370 .map(|e| ByteRange {
6371 offset: section.offset + e.start,
6372 len: (e.end - e.start),
6373 })
6374 .collect(),
6375 );
6376 section_ranges[si] = ranges.clone();
6377 let chunks: Vec<crate::dict::SectionChunk> = entries
6378 .into_iter()
6379 .map(|e| crate::dict::SectionChunk::new(e.first_run, e.key, e.body_start))
6380 .collect();
6381 let chunk_reader = reader.clone();
6382 let codec = header.dict_codec;
6383 let loader_ranges = ranges.clone();
6384 let loader: crate::dict::ChunkLoader = Box::new(move |ci| {
6385 let range = loader_ranges.get(ci)?;
6386 let bytes = chunk_reader.read_at(range.offset, range.len).ok()?;
6387 decompress(codec, &bytes).ok()
6388 });
6389 let bulk_reader = reader.clone();
6392 let bulk: crate::dict::ChunkBulkLoader = Box::new(move |cis| {
6393 let want: Option<Vec<ByteRange>> =
6394 cis.iter().map(|&ci| ranges.get(ci).copied()).collect();
6395 let blobs = read_coalesced(bulk_reader.as_ref(), &want?, DICT_COALESCE_GAP)?;
6396 blobs.iter().map(|b| decompress(codec, b).ok()).collect()
6397 });
6398 dict_sections.push(
6399 crate::dict::ChunkedSection::from_parts(
6400 meta,
6401 chunks,
6402 Some(loader),
6403 cache.clone(),
6404 si as u8,
6405 )
6406 .with_bulk_loader(bulk),
6407 );
6408 }
6409 let dict_arr: [crate::dict::ChunkedSection; 4] = dict_sections
6410 .try_into()
6411 .map_err(|_| FileError::Container("expected 4 dictionary sections"))?;
6412 let multi_reader = reader.clone();
6416 let codec = header.dict_codec;
6417 let multi: crate::dict::MultiChunkBulkLoader = Box::new(move |pairs| {
6418 let want: Option<Vec<ByteRange>> = pairs
6419 .iter()
6420 .map(|&(si, ci)| section_ranges.get(si as usize)?.get(ci).copied())
6421 .collect();
6422 let blobs = read_coalesced(multi_reader.as_ref(), &want?, DICT_COALESCE_GAP)?;
6423 blobs.iter().map(|b| decompress(codec, b).ok()).collect()
6424 });
6425 Ok(Dictionary::from_chunked_sections(dict_arr).with_multi_bulk_loader(multi))
6426}
6427
6428#[cfg(not(target_arch = "wasm32"))]
6433fn open_side_by_side<A, B: Send>(
6434 concurrency: usize,
6435 a: impl FnOnce() -> A,
6436 b: impl FnOnce() -> B + Send,
6437) -> (A, B) {
6438 if concurrency <= 1 {
6439 return (a(), b());
6440 }
6441 std::thread::scope(|scope| {
6442 let hb = scope.spawn(b);
6443 let ra = a();
6444 let rb = hb
6445 .join()
6446 .unwrap_or_else(|panic| std::panic::resume_unwind(panic));
6447 (ra, rb)
6448 })
6449}
6450
6451#[cfg(target_arch = "wasm32")]
6453fn open_side_by_side<A, B>(
6454 _concurrency: usize,
6455 a: impl FnOnce() -> A,
6456 b: impl FnOnce() -> B,
6457) -> (A, B) {
6458 (a(), b())
6459}
6460
6461#[cfg(feature = "v06-parity")]
6464fn parity_image(bytes: &[u8]) -> Option<Vec<u8>> {
6465 if crate::v06::open::is_v06(bytes) || bytes.len() < HEADER_LEN {
6466 return None;
6467 }
6468 crate::v06::write::convert_image(bytes, crate::v06::write::WriteOpts::default()).ok()
6469}
6470
6471fn v06_layout(f: &crate::v06::open::V06File) -> Vec<LayoutSegment> {
6474 let h = &f.h;
6475 let seg = |kind: &'static str, label: String, offset: u64, len: u64| LayoutSegment {
6476 kind,
6477 label,
6478 offset,
6479 len,
6480 };
6481 let mut out = vec![
6482 seg(
6483 "header",
6484 format!("header (fixed {} bytes)", crate::v06::HEADER_LEN),
6485 0,
6486 crate::v06::HEADER_LEN as u64,
6487 ),
6488 seg(
6489 "directory",
6490 "root block (section table, directory roots)".into(),
6491 h.root_offset(),
6492 h.root_len as u64,
6493 ),
6494 ];
6495 let c = h.card_range();
6496 if c.len > 0 {
6497 out.push(seg(
6498 "metadata",
6499 "metadata (dataset card, zstd)".into(),
6500 c.offset,
6501 c.len,
6502 ));
6503 }
6504 let b = h.build_range();
6505 if b.len > 0 {
6506 out.push(seg("build-info", "build record".into(), b.offset, b.len));
6507 }
6508 for s in &f.root.sections {
6509 let Ok(a) = s.abs(h) else { continue };
6510 let kind: &'static str = match s.kind {
6511 crate::v06::kind::SCHEMA => "schema",
6512 crate::v06::kind::DICT_DATA => "dictionary",
6513 crate::v06::kind::INDEX_DATA => "tile",
6514 crate::v06::kind::QUAD_DATA => "named-graphs",
6515 crate::v06::kind::LABEL_DATA => "label-index",
6516 crate::v06::kind::TEXT_DATA => "text-index",
6517 crate::v06::kind::PYRAMID => "pyramid",
6518 _ => "directory",
6519 };
6520 out.push(seg(
6521 kind,
6522 crate::v06::kind::name(s.kind).to_string(),
6523 a.offset,
6524 a.len,
6525 ));
6526 }
6527 out.sort_by_key(|s| s.offset);
6528 out
6529}
6530
6531#[allow(clippy::type_complexity)]
6534fn v06_slots(
6535 f: &std::sync::Arc<crate::v06::open::V06File>,
6536) -> (
6537 PyramidSlot,
6538 TextIndexSlot,
6539 SectionSlot<crate::label_index::LabelIndex>,
6540 SectionSlot<crate::schema_section::SchemaMeta>,
6541) {
6542 use crate::v06::{P_LABELS, P_PYRAMID, P_SCHEMA, P_TEXT};
6543 let pyramid = if f.h.has(P_PYRAMID) {
6544 let a = f.clone();
6545 PyramidSlot::Lazy {
6546 loader: Box::new(move || PyramidMeta::decode(&a.pyramid_bytes()?).ok()),
6547 cell: std::sync::OnceLock::new(),
6548 }
6549 } else {
6550 PyramidSlot::Resident(None)
6551 };
6552 let text_index = if f.h.has(P_TEXT) {
6553 let (a, b) = (f.clone(), f.clone());
6554 TextIndexSlot::Lazy {
6555 loader: Box::new(move || a.text_index()?.ok()),
6556 cell: std::sync::OnceLock::new(),
6557 token_table: Box::new(move || b.token_table_bytes()),
6558 token_table_cell: std::sync::OnceLock::new(),
6559 }
6560 } else {
6561 TextIndexSlot::Resident {
6562 index: None,
6563 token_table_len: None,
6564 }
6565 };
6566 let labels = if f.h.has(P_LABELS) {
6567 let a = f.clone();
6568 SectionSlot::Lazy {
6569 loader: Box::new(move || a.label_index()?.ok()),
6570 cell: std::sync::OnceLock::new(),
6571 }
6572 } else {
6573 SectionSlot::Resident(None)
6574 };
6575 let schema = if f.h.has(P_SCHEMA) {
6576 let a = f.clone();
6577 SectionSlot::Lazy {
6578 loader: Box::new(move || a.schema()),
6579 cell: std::sync::OnceLock::new(),
6580 }
6581 } else {
6582 SectionSlot::Resident(None)
6583 };
6584 (pyramid, text_index, labels, schema)
6585}
6586
6587fn ranged_pyramid_slot<R: RangeReader + Send + Sync + 'static>(
6591 reader: &std::sync::Arc<R>,
6592 header: &Header,
6593) -> PyramidSlot {
6594 if header.pyramid_meta_len == 0 {
6595 return PyramidSlot::Resident(None);
6596 }
6597 let pyr_reader = reader.clone();
6598 let pyr_off = header.pyramid_meta_offset;
6599 let pyr_len = header.pyramid_meta_len;
6600 PyramidSlot::Lazy {
6601 loader: Box::new(move || {
6602 let mb = pyr_reader.read_at(pyr_off, pyr_len).ok()?;
6603 PyramidMeta::decode(&mb).ok()
6604 }),
6605 cell: std::sync::OnceLock::new(),
6606 }
6607}
6608
6609fn ranged_text_index_slot<R: RangeReader + Send + Sync + 'static>(
6614 reader: &std::sync::Arc<R>,
6615 header: &Header,
6616) -> TextIndexSlot {
6617 let (ti_off, ti_len) = header.text_index_payload();
6618 if ti_len == 0 {
6619 return TextIndexSlot::Resident {
6620 index: None,
6621 token_table_len: None,
6622 };
6623 }
6624 let ti_reader = reader.clone();
6625 let probe_reader = reader.clone();
6626 let codec = header.block_codec;
6627 TextIndexSlot::Lazy {
6628 loader: Box::new(move || {
6629 let prefix_len = read_token_table_len(&*ti_reader, ti_off, ti_len)?;
6633 let prefix = ti_reader.read_at(ti_off, prefix_len).ok()?;
6634 let postings_base = crate::text_index::TextIndex::postings_base(&prefix)? as u64;
6635 let postings_abs = ti_off + postings_base;
6636 let pr = ti_reader.clone();
6637 let posting_loader =
6638 Box::new(move |off: u64, len: u64| pr.read_at(postings_abs + off, len).ok());
6639 crate::text_index::TextIndex::from_token_table(&prefix, codec, posting_loader).ok()
6640 }),
6641 cell: std::sync::OnceLock::new(),
6642 token_table: Box::new(move || read_token_table_len(&*probe_reader, ti_off, ti_len)),
6645 token_table_cell: std::sync::OnceLock::new(),
6646 }
6647}
6648
6649fn resolve_label_hits(
6656 dict: &Dictionary,
6657 hits: Vec<&crate::meta::LabelEntry>,
6658) -> Vec<(String, String)> {
6659 let ids: Vec<u32> = hits.iter().map(|e| e.subject).collect();
6660 dict.prefetch_subject_terms(&ids);
6661 hits.iter()
6662 .zip(dict.subject_terms(&ids))
6663 .filter_map(|(e, iri)| Some((e.label.clone(), iri?)))
6664 .collect()
6665}
6666
6667fn text_search_in(
6670 ti: Option<&crate::text_index::TextIndex>,
6671 dict: &Dictionary,
6672 words: &[&str],
6673 prefix: Option<&str>,
6674 limit: usize,
6675) -> Vec<String> {
6676 let Some(ti) = ti else {
6677 return Vec::new();
6678 };
6679 let mut acc: Option<Vec<u32>> = None;
6683 if let Some(p) = prefix {
6684 acc = Some(ti.prefix(&p.to_lowercase()));
6685 }
6686 for w in words {
6687 for tok in crate::text_index::tokenize(w) {
6688 let posting = ti.lookup(&tok);
6689 acc = Some(match acc {
6690 Some(a) => intersect_sorted(&a, &posting),
6691 None => posting,
6692 });
6693 if acc.as_ref().is_some_and(|a| a.is_empty()) {
6694 return Vec::new();
6695 }
6696 }
6697 }
6698 let ids = acc.unwrap_or_default();
6699 let mut out = Vec::with_capacity(if limit > 0 {
6700 limit.min(ids.len())
6701 } else {
6702 ids.len()
6703 });
6704 let page = if limit > 0 {
6708 limit.min(ids.len())
6709 } else {
6710 ids.len()
6711 };
6712 dict.prefetch_subject_terms(&ids[..page]);
6713 for id in ids {
6714 if let Some(iri) = dict.subject_term(id) {
6715 out.push(iri);
6716 if limit > 0 && out.len() >= limit {
6717 break;
6718 }
6719 }
6720 }
6721 out
6722}
6723
6724pub struct SearchView {
6747 header: Header,
6748 dict: SectionSlot<Dictionary>,
6749 pyramid: PyramidSlot,
6750 text_index: TextIndexSlot,
6751 labels: SectionSlot<crate::label_index::LabelIndex>,
6752}
6753
6754impl SearchView {
6755 pub fn open_ranged<R: RangeReader + Send + Sync + 'static>(
6760 reader: R,
6761 ) -> Result<Self, FileError> {
6762 Self::open_ranged_with(reader, crate::v06::FIRST_READ)
6763 }
6764
6765 pub fn open_ranged_with<R: RangeReader + Send + Sync + 'static>(
6768 reader: R,
6769 first_read: u64,
6770 ) -> Result<Self, FileError> {
6771 let first_len = first_read.max(HEADER_LEN as u64).min(reader.len());
6772 let first: std::sync::Arc<[u8]> = std::sync::Arc::from(reader.read_at(0, first_len)?);
6773 let reader = crate::reader::PrefixReader::new(reader, first.clone());
6774 if crate::v06::open::is_v06(&first) {
6775 let r: std::sync::Arc<dyn RangeReader + Send + Sync> = std::sync::Arc::new(reader);
6776 let f = std::sync::Arc::new(crate::v06::open::V06File::open(r, &first)?);
6777 let header = crate::v06::logical_header(&f.h);
6778 let (pyramid, text_index, labels, _) = v06_slots(&f);
6779 let want = [true, true, false, false];
6780 let dict = if f.h.has(crate::v06::P_LABELS) {
6781 let a = f.clone();
6782 SectionSlot::Lazy {
6783 loader: Box::new(move || a.dictionary(want).ok()),
6784 cell: std::sync::OnceLock::new(),
6785 }
6786 } else {
6787 SectionSlot::Resident(Some(f.dictionary(want)?))
6788 };
6789 return Ok(Self {
6790 header,
6791 dict,
6792 pyramid,
6793 text_index,
6794 labels,
6795 });
6796 }
6797 let head = reader.read_at(0, HEADER_LEN as u64)?;
6798 let header = Header::from_bytes(&head)?;
6799 let reader = std::sync::Arc::new(reader);
6800 let dict = if header.label_index_section().is_some() {
6804 let (r, h) = (reader.clone(), header.clone());
6805 SectionSlot::Lazy {
6806 loader: Box::new(move || {
6807 ranged_chunked_dictionary(&r, &h, [true, true, false, false]).ok()
6808 }),
6809 cell: std::sync::OnceLock::new(),
6810 }
6811 } else {
6812 SectionSlot::Resident(Some(ranged_chunked_dictionary(
6813 &reader,
6814 &header,
6815 [true, true, false, false],
6816 )?))
6817 };
6818 let pyramid = ranged_pyramid_slot(&reader, &header);
6819 let text_index = ranged_text_index_slot(&reader, &header);
6820 let labels = ranged_label_slot(&reader, &header);
6821 Ok(Self {
6822 header,
6823 dict,
6824 pyramid,
6825 text_index,
6826 labels,
6827 })
6828 }
6829
6830 pub fn has_labels(&self) -> bool {
6834 self.header.label_index_section().is_some() || self.header.pyramid_meta_len > 0
6835 }
6836
6837 pub fn has_label_index(&self) -> bool {
6839 self.header.label_index_section().is_some()
6840 }
6841
6842 pub fn header(&self) -> &Header {
6844 &self.header
6845 }
6846
6847 pub fn has_text_index(&self) -> bool {
6849 self.header.text_index_len > 0
6850 }
6851
6852 pub fn has_pyramid(&self) -> bool {
6855 self.header.pyramid_meta_len > 0
6856 }
6857
6858 pub fn text_search(&self, words: &[&str], prefix: Option<&str>, limit: usize) -> Vec<String> {
6861 let Some(dict) = self.dict.get() else {
6862 return Vec::new();
6863 };
6864 text_search_in(self.text_index.index(), dict, words, prefix, limit)
6865 }
6866
6867 pub fn text_index_token_table_len(&self) -> Option<u64> {
6871 self.text_index.token_table_len()
6872 }
6873
6874 pub fn prefix_search(&self, prefix: &str, limit: usize) -> Vec<(String, String)> {
6878 if let Some(li) = self.labels.get() {
6879 return li.prefix_search(prefix, limit);
6880 }
6881 let pyr = match &self.pyramid {
6882 PyramidSlot::Resident(p) => p.as_ref(),
6883 PyramidSlot::Lazy { loader, cell } => cell.get_or_init(loader).as_ref(),
6884 };
6885 let (Some(pyr), Some(dict)) = (pyr, self.dict.get()) else {
6886 return Vec::new();
6887 };
6888 resolve_label_hits(dict, pyr.prefix_search(prefix, limit))
6889 }
6890}
6891
6892#[must_use]
6897pub struct SummaryView {
6898 pub round: u32,
6899 pub summary: Vec<SuperEdge>,
6900 pub class_hierarchy: Vec<ClassNode>,
6902 pub level_rollups: Vec<LevelRollup>,
6904 pub level_links: Vec<LevelLinks>,
6906 pub descriptors: Vec<CommunityDescriptor>,
6908 pub subclass_cycles: Vec<Vec<String>>,
6910 pub disjoint_pairs: Vec<(String, String)>,
6912 pub equivalent_pairs: Vec<(String, String)>,
6914 dict: Dictionary,
6915}
6916
6917impl SummaryView {
6918 pub fn open_ranged<R: RangeReader>(reader: &R) -> Result<Option<Self>, FileError> {
6920 let head = reader.read_at(0, (HEADER_LEN as u64).min(reader.len()))?;
6921 let header = Header::from_bytes(&head)?;
6922 if header.pyramid_meta_len == 0 {
6923 return Ok(None);
6924 }
6925 if header.version == crate::v06::VERSION {
6926 return Self::open_ranged_v06(reader, &header, head).map(Some);
6927 }
6928
6929 let dict_bytes = reader.read_at(header.dictionary_offset, header.dictionary_len)?;
6930 let dict = decode_dictionary_container(&dict_bytes, header.dict_codec)?;
6931
6932 let mb = reader.read_at(header.pyramid_meta_offset, header.pyramid_meta_len)?;
6933 let mut meta =
6934 PyramidMeta::decode(&mb).map_err(|_| FileError::Container("malformed pyramid meta"))?;
6935 if let Some(s) = read_schema_with_header(reader, &header) {
6938 meta.class_hierarchy = s.class_hierarchy;
6939 meta.level_rollups = s.level_rollups;
6940 meta.level_links = s.level_links;
6941 meta.subclass_cycles = s.subclass_cycles;
6942 meta.disjoint_pairs = s.disjoint_pairs;
6943 meta.equivalent_pairs = s.equivalent_pairs;
6944 }
6945
6946 Ok(Some(SummaryView {
6947 round: meta.round,
6948 summary: meta.summary,
6949 class_hierarchy: meta.class_hierarchy,
6950 level_rollups: meta.level_rollups,
6951 level_links: meta.level_links,
6952 descriptors: meta.descriptors,
6953 subclass_cycles: meta.subclass_cycles,
6954 disjoint_pairs: meta.disjoint_pairs,
6955 equivalent_pairs: meta.equivalent_pairs,
6956 dict,
6957 }))
6958 }
6959
6960 fn open_ranged_v06<R: RangeReader>(
6964 reader: &R,
6965 header: &Header,
6966 head: Vec<u8>,
6967 ) -> Result<Self, FileError> {
6968 use crate::v06::{kind, open};
6969 let mut first = head;
6973 let want_first = crate::v06::FIRST_READ.min(reader.len());
6974 if want_first > first.len() as u64 {
6975 let at = first.len() as u64;
6976 first.extend_from_slice(&reader.read_at(at, want_first - at)?);
6977 }
6978 let pre = open::Prefixed {
6979 first: &first,
6980 r: reader,
6981 };
6982 let (h, root) = open::read_front(&pre)?;
6983 let want: Vec<ByteRange> = [
6984 kind::PYRAMID,
6985 kind::SCHEMA,
6986 kind::DICT_LEAVES,
6987 kind::DICT_DATA,
6988 ]
6989 .iter()
6990 .filter_map(|&k| root.section(k).and_then(|s| s.abs(&h).ok()))
6991 .collect();
6992 let sparse = open::SparseReader::fetch(&pre, first.clone(), &want)?;
6993 let mb = open::read_section(&sparse, &h, &root, kind::PYRAMID)?
6994 .ok_or(FileError::Container("0x06 file has no pyramid"))?;
6995 let mut meta =
6996 PyramidMeta::decode(&mb).map_err(|_| FileError::Container("malformed pyramid meta"))?;
6997 if let Some(s) = read_schema_with_header(&sparse, header) {
6998 meta.class_hierarchy = s.class_hierarchy;
6999 meta.level_rollups = s.level_rollups;
7000 meta.level_links = s.level_links;
7001 meta.subclass_cycles = s.subclass_cycles;
7002 meta.disjoint_pairs = s.disjoint_pairs;
7003 meta.equivalent_pairs = s.equivalent_pairs;
7004 }
7005 let f = open::V06File::open(std::sync::Arc::new(sparse), &first)?;
7006 let dict = f.dictionary([true; 4])?;
7007 Ok(SummaryView {
7008 round: meta.round,
7009 summary: meta.summary,
7010 class_hierarchy: meta.class_hierarchy,
7011 level_rollups: meta.level_rollups,
7012 level_links: meta.level_links,
7013 descriptors: meta.descriptors,
7014 subclass_cycles: meta.subclass_cycles,
7015 disjoint_pairs: meta.disjoint_pairs,
7016 equivalent_pairs: meta.equivalent_pairs,
7017 dict,
7018 })
7019 }
7020
7021 pub fn open_schema_ranged<R: RangeReader>(reader: &R) -> Result<Option<Self>, FileError> {
7029 let head = reader.read_at(0, HEADER_LEN as u64)?;
7030 let header = Header::from_bytes(&head)?;
7031 let Some(s) = read_schema_with_header(reader, &header) else {
7032 return Ok(None);
7033 };
7034 let dict = crate::DictionaryBuilder::new().build();
7035 Ok(Some(SummaryView {
7036 round: 0,
7037 summary: Vec::new(),
7038 class_hierarchy: s.class_hierarchy,
7039 level_rollups: s.level_rollups,
7040 level_links: s.level_links,
7041 descriptors: Vec::new(),
7042 subclass_cycles: s.subclass_cycles,
7043 disjoint_pairs: s.disjoint_pairs,
7044 equivalent_pairs: s.equivalent_pairs,
7045 dict,
7046 }))
7047 }
7048
7049 pub fn level_count(&self) -> usize {
7051 self.level_rollups.len()
7052 }
7053
7054 pub fn level_rollup(&self, k: usize) -> Option<&LevelRollup> {
7057 self.level_rollups.get(k)
7058 }
7059
7060 pub fn predicate_term(&self, id: u32) -> Option<String> {
7062 self.dict.predicate_term(id)
7063 }
7064
7065 pub fn predicate_total(&self, predicate: &str) -> u32 {
7068 match self.dict.predicate_id(predicate) {
7069 Some(pid) => self
7070 .summary
7071 .iter()
7072 .filter(|e| e.predicate == pid)
7073 .map(|e| e.count)
7074 .sum(),
7075 None => 0,
7076 }
7077 }
7078
7079 pub fn predicate_totals(&self) -> Vec<(String, u32)> {
7081 let mut by_pred: std::collections::BTreeMap<u32, u32> = std::collections::BTreeMap::new();
7082 for e in &self.summary {
7083 *by_pred.entry(e.predicate).or_default() += e.count;
7084 }
7085 let mut out: Vec<(String, u32)> = by_pred
7086 .into_iter()
7087 .filter_map(|(pid, c)| self.dict.predicate_term(pid).map(|t| (t, c)))
7088 .collect();
7089 out.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
7090 out
7091 }
7092
7093 pub fn community_count(&self) -> usize {
7095 let mut comms = std::collections::BTreeSet::new();
7096 for e in &self.summary {
7097 comms.insert(e.s_comm);
7098 comms.insert(e.o_comm);
7099 }
7100 comms.len()
7101 }
7102
7103 pub fn tbox_coherence(&self) -> Vec<crate::reason::Inconsistency> {
7118 schema_coherence(
7119 &self.class_hierarchy,
7120 &self.subclass_cycles,
7121 &self.disjoint_pairs,
7122 &self.equivalent_pairs,
7123 )
7124 }
7125
7126 pub fn tbox_is_coherent(&self) -> bool {
7129 self.tbox_coherence().is_empty()
7130 }
7131}
7132
7133pub fn schema_coherence(
7139 class_hierarchy: &[ClassNode],
7140 subclass_cycles: &[Vec<String>],
7141 disjoint_pairs: &[(String, String)],
7142 equivalent_pairs: &[(String, String)],
7143) -> Vec<crate::reason::Inconsistency> {
7144 use crate::reason::Inconsistency;
7145 use std::collections::{BTreeMap, BTreeSet, VecDeque};
7146 const MAX_REACH: usize = 100_000;
7147
7148 let mut out: Vec<Inconsistency> = Vec::new();
7149
7150 for cyc in subclass_cycles {
7151 let detail = if cyc.len() == 1 {
7152 format!("{} is rdfs:subClassOf itself (a cycle)", cyc[0])
7153 } else {
7154 format!(
7155 "classes {{{}}} are mutually rdfs:subClassOf (a cycle)",
7156 cyc.join(", ")
7157 )
7158 };
7159 out.push(Inconsistency {
7160 kind: "subclass-cycle",
7161 detail,
7162 });
7163 }
7164
7165 if !disjoint_pairs.is_empty() {
7166 let mut adj: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
7168 for n in class_hierarchy {
7169 let e = adj.entry(n.class.as_str()).or_default();
7170 for p in &n.parents {
7171 e.push(p.as_str());
7172 }
7173 }
7174 for (a, b) in equivalent_pairs {
7175 adj.entry(a.as_str()).or_default().push(b.as_str());
7176 adj.entry(b.as_str()).or_default().push(a.as_str());
7177 }
7178
7179 let mut focuses: BTreeSet<&str> =
7181 class_hierarchy.iter().map(|n| n.class.as_str()).collect();
7182 for (a, b) in disjoint_pairs.iter().chain(equivalent_pairs) {
7183 focuses.insert(a.as_str());
7184 focuses.insert(b.as_str());
7185 }
7186
7187 let mut seen: BTreeSet<&str> = BTreeSet::new();
7188 for &c in &focuses {
7189 let mut reach: BTreeSet<&str> = BTreeSet::new();
7191 let mut q: VecDeque<&str> = VecDeque::new();
7192 reach.insert(c);
7193 q.push_back(c);
7194 while let Some(x) = q.pop_front() {
7195 if reach.len() > MAX_REACH {
7196 break;
7197 }
7198 if let Some(ns) = adj.get(x) {
7199 for &p in ns {
7200 if reach.insert(p) {
7201 q.push_back(p);
7202 }
7203 }
7204 }
7205 }
7206 for (x, y) in disjoint_pairs {
7207 if reach.contains(x.as_str()) && reach.contains(y.as_str()) && seen.insert(c) {
7208 out.push(Inconsistency {
7209 kind: "unsatisfiable-class",
7210 detail: format!(
7211 "{c} is a subclass of both {x} and {y}, which are \
7212 owl:disjointWith — no individual can be a {c}"
7213 ),
7214 });
7215 break;
7216 }
7217 }
7218 }
7219 }
7220
7221 out.sort_by(|a, b| (a.kind, &a.detail).cmp(&(b.kind, &b.detail)));
7222 out
7223}
7224
7225pub fn read_schema_coherence_ranged<R: RangeReader>(
7233 reader: &R,
7234) -> Result<Option<Vec<crate::reason::Inconsistency>>, FileError> {
7235 let head = reader.read_at(0, HEADER_LEN as u64)?;
7236 let header = Header::from_bytes(&head)?;
7237 if let Some(s) = read_schema_with_header(reader, &header) {
7239 return Ok(Some(schema_coherence(
7240 &s.class_hierarchy,
7241 &s.subclass_cycles,
7242 &s.disjoint_pairs,
7243 &s.equivalent_pairs,
7244 )));
7245 }
7246 if header.pyramid_meta_len == 0 {
7247 return Ok(None);
7248 }
7249 if header.schema_meta_len > 0 && (header.schema_meta_len as u64) <= header.pyramid_meta_len {
7253 let off =
7254 header.pyramid_meta_offset + header.pyramid_meta_len - header.schema_meta_len as u64;
7255 let block = reader.read_at(off, header.schema_meta_len as u64)?;
7256 let (hierarchy, cycles, disjoint, equivalent) = crate::meta::decode_schema_block(&block)
7257 .map_err(|_| FileError::Container("malformed schema block"))?;
7258 return Ok(Some(schema_coherence(
7259 &hierarchy,
7260 &cycles,
7261 &disjoint,
7262 &equivalent,
7263 )));
7264 }
7265 let mb = if header.version == crate::v06::VERSION {
7267 crate::v06::open::read_pyramid(reader)?.unwrap_or_default()
7268 } else {
7269 reader.read_at(header.pyramid_meta_offset, header.pyramid_meta_len)?
7270 };
7271 let meta =
7272 PyramidMeta::decode(&mb).map_err(|_| FileError::Container("malformed pyramid meta"))?;
7273 Ok(Some(schema_coherence(
7274 &meta.class_hierarchy,
7275 &meta.subclass_cycles,
7276 &meta.disjoint_pairs,
7277 &meta.equivalent_pairs,
7278 )))
7279}
7280
7281#[allow(clippy::type_complexity)]
7289pub fn read_schema_summary_ranged<R: RangeReader>(
7290 reader: &R,
7291) -> Result<Option<(Vec<(String, u64)>, Vec<(String, String, String, u64)>)>, FileError> {
7292 let head = reader.read_at(0, HEADER_LEN as u64)?;
7293 let header = Header::from_bytes(&head)?;
7294 let meta = if let Some(s) = read_schema_with_header(reader, &header) {
7296 PyramidMeta::new(0, Vec::new(), &[]).with_schema(
7297 Vec::new(),
7298 s.level_rollups,
7299 s.level_links,
7300 Vec::new(),
7301 Vec::new(),
7302 Vec::new(),
7303 Vec::new(),
7304 )
7305 } else {
7306 if header.pyramid_meta_len == 0 {
7307 return Ok(None);
7308 }
7309 if header.schema_meta_len > 0 && (header.schema_meta_len as u64) <= header.pyramid_meta_len
7310 {
7311 let off = header.pyramid_meta_offset + header.pyramid_meta_len
7312 - header.schema_meta_len as u64;
7313 let block = reader.read_at(off, header.schema_meta_len as u64)?;
7314 let summary = crate::meta::decode_schema_block_summary(&block)
7315 .map_err(|_| FileError::Container("malformed schema block"))?;
7316 return Ok(Some(summary));
7317 }
7318 let mb = if header.version == crate::v06::VERSION {
7320 crate::v06::open::read_pyramid(reader)?.unwrap_or_default()
7321 } else {
7322 reader.read_at(header.pyramid_meta_offset, header.pyramid_meta_len)?
7323 };
7324 PyramidMeta::decode(&mb).map_err(|_| FileError::Container("malformed pyramid meta"))?
7325 };
7326 if meta.level_rollups.is_empty() && meta.level_links.is_empty() {
7327 return Ok(None);
7328 }
7329 let classes = meta
7330 .level_rollups
7331 .iter()
7332 .max_by_key(|r| r.depth)
7333 .map(|r| r.classes.clone())
7334 .unwrap_or_default();
7335 let relations = meta
7336 .level_links
7337 .iter()
7338 .max_by_key(|l| l.depth)
7339 .map(|l| {
7340 l.links
7341 .iter()
7342 .map(|c| {
7343 (
7344 c.s_class.clone(),
7345 c.predicate.clone(),
7346 c.o_class.clone(),
7347 c.count,
7348 )
7349 })
7350 .collect()
7351 })
7352 .unwrap_or_default();
7353 Ok(Some((classes, relations)))
7354}
7355
7356#[cfg(test)]
7361pub(crate) fn dict_chunk_keys_for_test(image: &[u8]) -> Vec<Vec<Vec<u8>>> {
7362 if crate::v06::open::is_v06(image) {
7363 use crate::v06::{decode_chunk_leaf, decode_dict_root, kind, open, tag};
7365 let r = crate::reader::SliceReader::new(image);
7366 let (h, root) = open::read_front(&r).unwrap();
7367 let roots = decode_dict_root(root.unit(tag::DICT).unwrap()).unwrap();
7368 let leaves = open::read_section(&r, &h, &root, kind::DICT_LEAVES)
7369 .unwrap()
7370 .unwrap();
7371 return roots
7372 .iter()
7373 .map(|s| {
7374 s.leaves
7375 .iter()
7376 .flat_map(|(l, _, _, _)| {
7377 let stored = &leaves[l.off as usize..(l.off + l.len) as usize];
7378 let raw = decompress(h.internal_codec, stored).unwrap();
7379 decode_chunk_leaf(&raw, l.n).unwrap()
7380 })
7381 .map(|c| c.key)
7382 .collect()
7383 })
7384 .collect();
7385 }
7386 let header = Header::from_bytes(&image[..HEADER_LEN]).unwrap();
7387 let s = header.dictionary_offset as usize;
7388 let e = s + header.dictionary_len as usize;
7389 decode_container(&image[s..e], CODEC_NONE)
7390 .unwrap()
7391 .iter()
7392 .map(|payload| {
7393 let (_meta, entries) = parse_chunked_dict_dir(payload, payload.len() as u64).unwrap();
7394 entries.into_iter().map(|c| c.key).collect()
7395 })
7396 .collect()
7397}
7398
7399#[cfg(test)]
7400mod tests {
7401 use super::*;
7402 use super::{
7403 write_dataset_v05 as write_dataset,
7404 write_dataset_with_metadata_v05 as write_dataset_with_metadata,
7405 write_file_v05 as write_file,
7406 };
7407 use crate::dictionary::DictionaryBuilder;
7408 use crate::index::GraphIndexBuilder;
7409
7410 #[cfg(not(feature = "compression"))]
7413 #[test]
7414 fn ruzstd_decodes_a_zstd_frame() {
7415 let data: Vec<u8> = (0..50_000u32)
7416 .flat_map(|i| (i % 251).to_le_bytes())
7417 .collect();
7418 let frame = ruzstd::encoding::compress_to_vec(
7419 &data[..],
7420 ruzstd::encoding::CompressionLevel::Fastest,
7421 );
7422 assert!(frame.len() < data.len());
7423 assert_eq!(decompress(CODEC_ZSTD, &frame).unwrap(), data);
7424 }
7425
7426 #[cfg(feature = "compression")]
7431 #[test]
7432 fn decompression_is_bounded() {
7433 let data: Vec<u8> = (0..100_000u32).map(|i| (i % 251) as u8).collect();
7434 let sized = zstd::bulk::compress(&data, 3).unwrap();
7435 assert_eq!(zstd_frame_content_size(&sized), Some(100_000));
7436 assert_eq!(block_raw_len(CODEC_ZSTD, &sized, 1 << 20).unwrap(), 100_000);
7437 assert_eq!(
7438 decompress_bounded(CODEC_ZSTD, &sized, 100_000).unwrap(),
7439 data
7440 );
7441 assert!(decompress_bounded(CODEC_ZSTD, &sized, 99_999).is_err());
7442 let stream = zstd::encode_all(&data[..], 3).unwrap();
7444 assert_eq!(zstd_frame_content_size(&stream), None);
7445 assert_eq!(
7446 block_raw_len(CODEC_ZSTD, &stream, 1 << 20).unwrap(),
7447 100_000
7448 );
7449 assert_eq!(
7450 decompress_bounded(CODEC_ZSTD, &stream, 100_000).unwrap(),
7451 data
7452 );
7453 assert!(decompress_bounded(CODEC_ZSTD, &stream, 50_000).is_err());
7454 let mut liar = sized.clone();
7456 let fhd = liar[4];
7457 let fcs_at = 5 + usize::from(fhd & 0x20 == 0);
7458 liar[fcs_at] = liar[fcs_at].wrapping_sub(1);
7459 assert!(decompress_bounded(CODEC_ZSTD, &liar, 200_000).is_err());
7460 assert!(decompress_bounded(CODEC_NONE, &data, 99_999).is_err());
7462 assert_eq!(
7463 decompress_bounded(CODEC_NONE, &data, 100_000).unwrap(),
7464 data
7465 );
7466 assert_eq!(zstd_frame_content_size(b"RETE"), None);
7467 }
7468
7469 #[test]
7475 fn three_permutation_file_round_trips_every_open_path() {
7476 use crate::index::PermSet;
7477 use crate::reader::SliceReader;
7478
7479 let build = |perms: PermSet| {
7480 let mut db = crate::DictionaryBuilder::new();
7481 let mut triples = Vec::new();
7482 for i in 0..60u32 {
7483 let (s, p, o) = (
7484 format!("<http://ex/s{}>", i % 11),
7485 format!("<http://ex/p{}>", i % 3),
7486 format!("<http://ex/o{}>", i % 7),
7487 );
7488 db.observe(&s, &p, &o);
7489 triples.push((s, p, o));
7490 }
7491 let dict = db.build();
7492 let ids: Vec<(u32, u32, u32)> = triples
7493 .iter()
7494 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
7495 .collect();
7496 let def = GraphIndexBuilder::from_triples(ids.clone())
7497 .with_tile_budget(96)
7498 .with_perms(perms)
7499 .build();
7500 let named = GraphIndexBuilder::from_triples(ids)
7501 .with_tile_budget(96)
7502 .with_perms(perms)
7503 .build();
7504 write_dataset(
7505 &dict,
7506 &def,
7507 &[("<http://ex/g>".to_string(), named)],
7508 true,
7509 &[],
7510 0,
7511 )
7512 };
7513
7514 let six = build(PermSet::ALL);
7515 let three = build(PermSet::CORE);
7516 assert!(three.len() < six.len());
7517 assert_eq!(Header::from_bytes(&three).unwrap().perms, PermSet::CORE);
7518 assert_eq!(Header::from_bytes(&six).unwrap().perms, PermSet::ALL);
7519
7520 let shapes: Vec<(Option<&str>, Option<&str>, Option<&str>)> = vec![
7521 (None, None, None),
7522 (Some("<http://ex/s3>"), None, None),
7523 (None, Some("<http://ex/p1>"), None),
7524 (None, None, Some("<http://ex/o5>")),
7525 (Some("<http://ex/s3>"), Some("<http://ex/p1>"), None),
7526 (Some("<http://ex/s3>"), None, Some("<http://ex/o5>")),
7527 (None, Some("<http://ex/p1>"), Some("<http://ex/o5>")),
7528 (
7529 Some("<http://ex/s3>"),
7530 Some("<http://ex/p1>"),
7531 Some("<http://ex/o5>"),
7532 ),
7533 ];
7534
7535 for (image, tag) in [(&six, "six"), (&three, "three")] {
7536 let resident = Rete::open(image).unwrap();
7537 let leaked: &'static [u8] = Box::leak(image.clone().into_boxed_slice());
7538 let ranged = Rete::open_ranged(&SliceReader::new(leaked)).unwrap();
7539 let lazy =
7540 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64).unwrap();
7541 for (s, p, o) in &shapes {
7542 let want: Vec<_> = {
7543 let mut v = Rete::open(&six).unwrap().query(*s, *p, *o);
7544 v.sort();
7545 v
7546 };
7547 for (got, path) in [
7548 (resident.query(*s, *p, *o), "resident"),
7549 (ranged.query(*s, *p, *o), "ranged"),
7550 (lazy.query(*s, *p, *o), "lazy"),
7551 ] {
7552 let mut got = got;
7553 got.sort();
7554 assert_eq!(got, want, "{tag}/{path} disagreed on {:?}", (s, p, o));
7555 }
7556 let mut g = resident.query_in_graph(Some("<http://ex/g>"), *s, *p, *o);
7558 g.sort();
7559 assert_eq!(g, want, "{tag}/named disagreed on {:?}", (s, p, o));
7560 }
7561 }
7562
7563 let leaked: &'static [u8] = Box::leak(three.clone().into_boxed_slice());
7567 let reader = SliceReader::new(leaked);
7568 let routed = Rete::query_ranged(&reader, None, None, Some("<http://ex/o5>")).unwrap();
7569 let mut want = Rete::open(&six)
7570 .unwrap()
7571 .query(None, None, Some("<http://ex/o5>"));
7572 want.sort();
7573 let mut got = routed;
7574 got.sort();
7575 assert_eq!(got, want, "routed single-pattern read on a lean file");
7576 }
7577
7578 #[test]
7579 fn read_coalesced_merges_within_gap_and_splits_beyond() {
7580 use crate::reader::{CountingReader, SliceReader};
7581 let bytes = vec![0u8; 4096];
7582 let ranges = [
7584 ByteRange { offset: 0, len: 16 },
7585 ByteRange {
7586 offset: 48,
7587 len: 16,
7588 },
7589 ByteRange {
7590 offset: 1088,
7591 len: 16,
7592 },
7593 ];
7594 let r = CountingReader::new(SliceReader::new(&bytes));
7596 let out = read_coalesced(&r, &ranges, 16).unwrap();
7597 assert_eq!(out.len(), 3);
7598 assert_eq!(r.requests(), 3);
7599 let r = CountingReader::new(SliceReader::new(&bytes));
7601 read_coalesced(&r, &ranges, 64).unwrap();
7602 assert_eq!(r.requests(), 2);
7603 let r = CountingReader::new(SliceReader::new(&bytes));
7605 read_coalesced(&r, &ranges, 4096).unwrap();
7606 assert_eq!(r.requests(), 1);
7607 }
7608
7609 fn build_image() -> Vec<u8> {
7610 let triples = [
7611 ("Alice", "knows", "Bob"),
7612 ("Bob", "knows", "Carol"),
7613 ("Alice", "age", "30"),
7614 ];
7615 let mut db = DictionaryBuilder::new();
7616 for (s, p, o) in triples {
7617 db.observe(s, p, o);
7618 }
7619 let dict = db.build();
7620
7621 let mut ib = GraphIndexBuilder::new();
7622 for (s, p, o) in triples {
7623 ib.push(dict.encode(s, p, o).unwrap());
7624 }
7625 let index = ib.build();
7626
7627 let (meta, levels) = build_pyramid_meta(&dict, &triples_ids(&dict), DEFAULT_TILE_BUDGET);
7628 write_file(&dict, &index, false, &meta, levels)
7629 }
7630
7631 fn triples_ids(dict: &Dictionary) -> Vec<(u32, u32, u32)> {
7632 [
7633 ("Alice", "knows", "Bob"),
7634 ("Bob", "knows", "Carol"),
7635 ("Alice", "age", "30"),
7636 ]
7637 .iter()
7638 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
7639 .collect()
7640 }
7641
7642 #[test]
7643 fn file_round_trips_header_and_counts() {
7644 let bytes = build_image();
7645 let rete = Rete::open(&bytes).unwrap();
7646 assert_eq!(rete.header().quad_count, 3);
7647 assert!(rete.header().term_count >= 5);
7648 let expected_codec = writer_codec();
7649 assert_eq!(rete.header().dict_codec, expected_codec);
7650 assert_eq!(rete.header().block_codec, expected_codec);
7651 assert_eq!(&bytes[bytes.len() - 4..], &MAGIC); }
7653
7654 #[test]
7659 fn multi_tile_file_round_trips_and_routes() {
7660 let triples: Vec<(String, String, String)> = (0..200)
7661 .map(|i| {
7662 (
7663 format!("<http://ex/s/{i}>"),
7664 format!("<http://ex/p/{}>", i % 5),
7665 format!("<http://ex/o/{}>", i % 23),
7666 )
7667 })
7668 .collect();
7669 let mut db = DictionaryBuilder::new();
7670 for (s, p, o) in &triples {
7671 db.observe(s, p, o);
7672 }
7673 let dict = db.build();
7674 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
7675 for (s, p, o) in &triples {
7676 ib.push(dict.encode(s, p, o).unwrap());
7677 }
7678 let index = ib.build();
7679 assert!(
7680 index.tile_sections()[0].len() > 3,
7681 "tiny budget must force many tiles"
7682 );
7683 let bytes = write_file(&dict, &index, false, &[], 0);
7684
7685 let rete = Rete::open(&bytes).unwrap();
7686 assert_eq!(rete.header().version, crate::header::LEGACY_FORMAT_VERSION);
7687 assert_eq!(rete.query(None, None, None).len(), 200);
7688 assert_eq!(rete.query(Some("<http://ex/s/7>"), None, None).len(), 1);
7689 assert_eq!(
7690 rete.query(None, Some("<http://ex/p/3>"), None).len(),
7691 40,
7692 "predicate extent spans tiles"
7693 );
7694 assert_eq!(
7695 rete.query(None, None, Some("<http://ex/o/22>")).len(),
7696 8 );
7698
7699 use crate::reader::SliceReader;
7701 let reader = SliceReader::new(&bytes);
7702 let routed = Rete::query_ranged(&reader, Some("<http://ex/s/7>"), None, None).unwrap();
7703 assert_eq!(routed.len(), 1);
7704 let routed = Rete::query_ranged(&reader, None, Some("<http://ex/p/3>"), None).unwrap();
7705 assert_eq!(routed.len(), 40);
7706 let routed = Rete::query_ranged(&reader, None, None, Some("<http://ex/o/22>")).unwrap();
7707 assert_eq!(routed.len(), 8);
7708 }
7709
7710 #[test]
7719 fn tile_directory_offsets_survive_past_4gib() {
7720 let mut dir = Vec::new();
7721 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);
7727 write_uvarint(&mut dir, 2 << 30); let total = dir.len() as u64 + (3u64 << 30) + (2u64 << 30) + 64;
7729 let entries = parse_tile_directory(&dir, total).unwrap();
7730 assert_eq!(entries.len(), 2);
7731 assert_eq!(entries[1].start, dir.len() as u64 + (3u64 << 30));
7732 assert!(
7733 entries[1].end > u32::MAX as u64,
7734 "tail tile sits past 4 GiB"
7735 );
7736 assert!(parse_tile_directory(&dir, 1 << 20).is_err());
7738 }
7739
7740 #[test]
7741 fn tile_synopsis_trailer_round_trips() {
7742 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
7743 for i in 0..200u32 {
7744 ib.push((i, i % 7, i % 13));
7745 }
7746 let index = ib.build();
7747 let tile_count = index.tile_sections()[0].len();
7748 assert!(tile_count > 3, "tiny budget forces many tiles");
7749
7750 let payload = encode_tiled_section(&index, 0, CODEC_NONE);
7751 let dir = parse_tile_directory(&payload, payload.len() as u64).unwrap();
7752 assert_eq!(dir.len(), tile_count);
7753 let trailer_start = dir.iter().map(|e| e.end).max().unwrap();
7755 assert!(
7756 trailer_start < payload.len() as u64,
7757 "a trailer follows the tiles"
7758 );
7759 for e in &dir {
7760 assert!(
7761 e.end <= payload.len() as u64,
7762 "tiles still located within the payload"
7763 );
7764 }
7765 let syn = parse_tile_synopsis(&payload, trailer_start as usize, dir.len()).unwrap();
7766 for (e, (min_b, max_b, min_c, max_c)) in dir.iter().zip(syn) {
7767 let block = decompress(CODEC_NONE, &payload[e.start as usize..e.end as usize]).unwrap();
7768 let z = *crate::triples::TripleBlock::parse(&block).unwrap().zone();
7769 assert_eq!(
7770 (min_b, max_b, min_c, max_c),
7771 (z.min_b, z.max_b, z.min_c, z.max_c),
7772 "synopsis equals the tile's own zone"
7773 );
7774 }
7775 }
7776
7777 #[test]
7781 fn tile_synopsis_lazy_matches_reference_every_shape() {
7782 use crate::reader::{CountingReader, SliceReader};
7783 let triples: Vec<(String, String, String)> = (0..200u32)
7784 .map(|i| {
7785 (
7786 format!("<http://ex/s/{i:04}>"),
7787 format!("<http://ex/p/{}>", i % 7),
7788 format!("<http://ex/o/{:04}>", i % 13),
7789 )
7790 })
7791 .collect();
7792 let mut db = DictionaryBuilder::new();
7793 for (s, p, o) in &triples {
7794 db.observe(s, p, o);
7795 }
7796 let dict = db.build();
7797 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
7798 for (s, p, o) in &triples {
7799 ib.push(dict.encode(s, p, o).unwrap());
7800 }
7801 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
7802
7803 let eager = Rete::open(&bytes).unwrap();
7804 assert!(
7805 eager.header().has_tile_synopsis(),
7806 "new files set the synopsis flag"
7807 );
7808
7809 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
7812 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
7813 let lazy = Rete::open_ranged_lazy_with(reader, HEADER_LEN as u64).unwrap();
7814
7815 let brute = |s: Option<&str>, p: Option<&str>, o: Option<&str>| {
7816 let mut v: Vec<(String, String, String)> = triples
7817 .iter()
7818 .filter(|(a, b, c)| {
7819 s.is_none_or(|x| x == a) && p.is_none_or(|x| x == b) && o.is_none_or(|x| x == c)
7820 })
7821 .cloned()
7822 .collect();
7823 v.sort();
7824 v
7825 };
7826 let sv = [
7828 None,
7829 Some("<http://ex/s/0007>"),
7830 Some("<http://ex/s/0130>"),
7831 Some("<http://ex/s/9999>"),
7832 ];
7833 let pv = [
7834 None,
7835 Some("<http://ex/p/3>"),
7836 Some("<http://ex/p/6>"),
7837 Some("<http://ex/p/999>"),
7838 ];
7839 let ov = [
7840 None,
7841 Some("<http://ex/o/0000>"),
7842 Some("<http://ex/o/0012>"),
7843 Some("<http://ex/o/9999>"),
7844 ];
7845 for &s in &sv {
7846 for &p in &pv {
7847 for &o in &ov {
7848 let mut e = eager.query(s, p, o);
7849 e.sort();
7850 let mut l = lazy.query(s, p, o);
7851 l.sort();
7852 let r = brute(s, p, o);
7853 assert_eq!(e, r, "eager {s:?} {p:?} {o:?}");
7854 assert_eq!(l, r, "lazy {s:?} {p:?} {o:?} — synopsis over-pruned");
7855 }
7856 }
7857 }
7858 assert!(!lazy.index_incomplete(), "no lazy fetch failed");
7859 }
7860
7861 #[test]
7865 fn polyglot_offset_reads_lazily() {
7866 use crate::reader::{
7867 detect_polyglot_base, CountingReader, OffsetReader, SliceReader, POLYGLOT_DIGITS,
7868 POLYGLOT_MARKER,
7869 };
7870
7871 let image = build_image();
7875 let mut shell = Vec::new();
7876 shell.extend_from_slice(b"<!DOCTYPE html><html><head><!--");
7877 shell.extend_from_slice(POLYGLOT_MARKER);
7878 let digits_at = shell.len();
7879 shell.extend_from_slice(&[b'0'; POLYGLOT_DIGITS]); shell.extend_from_slice(b"--></head><body>a web page</body></html>\n");
7881 shell.resize(50_000, b' '); let base = shell.len() as u64;
7883 let digits = format!("{base:0width$}", width = POLYGLOT_DIGITS);
7884 shell[digits_at..digits_at + POLYGLOT_DIGITS].copy_from_slice(digits.as_bytes());
7885
7886 let mut poly = shell;
7887 poly.extend_from_slice(&image);
7888
7889 assert_ne!(
7891 &poly[0..4],
7892 b"RETE",
7893 "polyglot must not start with the magic"
7894 );
7895 let detected = detect_polyglot_base(&poly[..crate::header::HEADER_LEN]).unwrap();
7897 assert_eq!(detected, base);
7898
7899 let leaked: &'static [u8] = Box::leak(poly.into_boxed_slice());
7901 let counting = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
7902 let lazy = Rete::open_ranged_lazy_with(
7903 OffsetReader::new(counting.clone(), detected),
7904 HEADER_LEN as u64,
7905 )
7906 .unwrap();
7907
7908 let plain = Rete::open(&image).unwrap();
7910 let mut want = plain.query(None, None, None);
7911 want.sort();
7912 let mut got = lazy.query(None, None, None);
7913 got.sort();
7914 assert_eq!(
7915 got, want,
7916 "polyglot lazy query differs from the plain .rete"
7917 );
7918 assert!(!got.is_empty(), "expected some triples");
7919 assert!(!lazy.index_incomplete(), "a lazy fetch failed");
7920
7921 let read = counting.bytes_read();
7924 eprintln!(
7925 "polyglot lazy read: HTML shell {base} B + .rete image {} B; \
7926 the query touched only {read} B (never the shell).",
7927 image.len()
7928 );
7929 assert!(
7930 read < base,
7931 "read {read} bytes; the HTML shell alone is {base} — the reader \
7932 touched the prefix instead of only the embedded .rete"
7933 );
7934 }
7935
7936 #[cfg(test)]
7939 fn build_text_indexed(triples: &[(String, String, String)]) -> Vec<u8> {
7940 let mut db = DictionaryBuilder::new();
7941 for (s, p, o) in triples {
7942 db.observe(s, p, o);
7943 }
7944 let dict = db.build();
7945 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
7946 let mut id_triples: Vec<(u32, u32, u32)> = Vec::with_capacity(triples.len());
7947 for (s, p, o) in triples {
7948 let t = dict.encode(s, p, o).unwrap();
7949 ib.push(t);
7950 id_triples.push(t);
7951 }
7952 let index = ib.build();
7953 let text_index = compute_text_index(&dict, &id_triples);
7954 assert!(
7955 !text_index.is_empty(),
7956 "literals should produce a text index"
7957 );
7958 write_dataset_with_metadata(&dict, &index, &[], false, &[], 0, &[], &text_index)
7959 }
7960
7961 #[test]
7965 fn text_index_eager_matches_brute_force() {
7966 let triples: Vec<(String, String, String)> = vec![
7967 (
7968 "<http://ex/s0>",
7969 "<http://ex/label>",
7970 "\"alpha glucose phosphate\"",
7971 ),
7972 ("<http://ex/s1>", "<http://ex/label>", "\"beta Glucose\""),
7973 ("<http://ex/s2>", "<http://ex/label>", "\"gamma fructose\""),
7974 (
7975 "<http://ex/s3>",
7976 "<http://ex/note>",
7977 "\"einstein relativity\"",
7978 ),
7979 (
7980 "<http://ex/s4>",
7981 "<http://ex/ref>",
7982 "<http://ex/not-a-literal>",
7983 ),
7984 ]
7985 .into_iter()
7986 .map(|(s, p, o)| (s.to_string(), p.to_string(), o.to_string()))
7987 .collect();
7988 let bytes = build_text_indexed(&triples);
7989 let rete = Rete::open(&bytes).unwrap();
7990 assert!(rete.has_text_index());
7991
7992 let brute = |words: &[&str]| -> Vec<String> {
7994 let mut v: Vec<String> = triples
7995 .iter()
7996 .filter(|(_, _, o)| {
7997 crate::terms::is_literal(o)
7998 && words.iter().all(|w| {
7999 let wl = w.to_lowercase();
8000 crate::terms::literal_lexical(o)
8001 .unwrap()
8002 .split(|c: char| !c.is_alphanumeric())
8003 .any(|t| t.to_lowercase() == wl)
8004 })
8005 })
8006 .map(|(s, _, _)| s.clone())
8007 .collect();
8008 v.sort();
8009 v.dedup();
8010 v
8011 };
8012
8013 let mut got = rete.text_search(&["glucose"], None, 0);
8014 got.sort();
8015 assert_eq!(got, brute(&["glucose"]), "case-insensitive single word");
8016
8017 let mut got = rete.text_search(&["glucose", "phosphate"], None, 0);
8019 got.sort();
8020 assert_eq!(got, brute(&["glucose", "phosphate"]));
8021
8022 assert!(rete.text_search(&["zzznope"], None, 0).is_empty());
8024
8025 let got = rete.text_search(&[], Some("ein"), 0);
8027 assert_eq!(got, vec!["<http://ex/s3>".to_string()]);
8028
8029 let mut db = DictionaryBuilder::new();
8031 for (s, p, o) in &triples {
8032 db.observe(s, p, o);
8033 }
8034 let dict = db.build();
8035 let mut ib = GraphIndexBuilder::new();
8036 for (s, p, o) in &triples {
8037 ib.push(dict.encode(s, p, o).unwrap());
8038 }
8039 let plain = write_dataset(&dict, &ib.build(), &[], false, &[], 0);
8040 let plain_rete = Rete::open(&plain).unwrap();
8041 assert!(!plain_rete.has_text_index());
8042 assert!(plain_rete.text_search(&["glucose"], None, 0).is_empty());
8043 }
8044
8045 #[test]
8049 fn text_index_lazy_faults_only_queried_postings() {
8050 use crate::reader::{CountingReader, SliceReader};
8051 let mut triples: Vec<(String, String, String)> = (0..300u32)
8054 .map(|i| {
8055 (
8056 format!("<http://ex/s/{i:04}>"),
8057 "<http://ex/label>".to_string(),
8058 format!("\"common word number {i}\""),
8059 )
8060 })
8061 .collect();
8062 for i in [3u32, 77, 250] {
8063 triples.push((
8064 format!("<http://ex/s/{i:04}>"),
8065 "<http://ex/tag>".to_string(),
8066 "\"raretoken\"".to_string(),
8067 ));
8068 }
8069 let bytes = build_text_indexed(&triples);
8070 let eager = Rete::open(&bytes).unwrap();
8071 let mut want = eager.text_search(&["raretoken"], None, 0);
8072 want.sort();
8073 assert_eq!(want.len(), 3);
8074
8075 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
8076 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
8077 let lazy = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
8078 let before = reader.bytes_read();
8081 let mut got = lazy.text_search(&["raretoken"], None, 0);
8082 got.sort();
8083 assert_eq!(got, want, "lazy search matches eager");
8084 let pulled = reader.bytes_read() - before;
8085 let ti_len = eager.header().text_index_len;
8088 assert!(
8089 pulled < ti_len,
8090 "search pulled {pulled} B but the section is {ti_len} B — faulted too much"
8091 );
8092 assert!(!lazy.index_incomplete());
8093 }
8094
8095 #[test]
8100 fn search_view_matches_full_open_for_far_fewer_bytes() {
8101 use crate::reader::{CountingReader, SliceReader};
8102 let filler = "lorem ipsum dolor sit amet consectetur adipiscing elit ".repeat(20);
8105 let mut triples: Vec<(String, String, String)> = (0..300u32)
8106 .map(|i| {
8107 (
8108 format!("<http://ex/s/{i:04}>"),
8109 "<http://ex/abstract>".to_string(),
8110 format!("\"{filler} number {i}\""),
8111 )
8112 })
8113 .collect();
8114 for i in [3u32, 77, 250] {
8115 triples.push((
8116 format!("<http://ex/s/{i:04}>"),
8117 "<http://ex/tag>".to_string(),
8118 "\"raretoken\"".to_string(),
8119 ));
8120 }
8121 let bytes = build_text_indexed(&triples);
8122 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
8123
8124 let full_reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
8125 let full = Rete::open_ranged_lazy_with(full_reader.clone(), HEADER_LEN as u64).unwrap();
8126 let mut want = full.text_search(&["raretoken"], None, 0);
8127 want.sort();
8128 assert_eq!(want.len(), 3);
8129
8130 let search_reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
8131 let view = SearchView::open_ranged_with(search_reader.clone(), HEADER_LEN as u64).unwrap();
8132 assert!(view.has_text_index());
8133 let mut got = view.text_search(&["raretoken"], None, 0);
8134 got.sort();
8135 assert_eq!(got, want, "search view matches the full open");
8136 assert!(
8137 search_reader.bytes_read() < full_reader.bytes_read(),
8138 "search read {} B, full open read {} B — the narrow open bought nothing",
8139 search_reader.bytes_read(),
8140 full_reader.bytes_read()
8141 );
8142
8143 let mut prefix_hits = view.prefix_search("", 5);
8146 prefix_hits.sort();
8147 assert!(!prefix_hits.is_empty() || !view.has_pyramid());
8148 }
8149
8150 #[test]
8160 fn dict_chunk_directory_probe_costs_about_one_directory() {
8161 use crate::reader::{CountingReader, SliceReader};
8162 let head = "x".repeat(3000);
8176 let triples: Vec<(String, String, String)> = (0..2000u32)
8177 .map(|i| {
8178 let tail = char::from(b'a' + (i % 26) as u8).to_string().repeat(1000);
8179 (
8180 format!("<http://ex/s/{i:04}>"),
8181 "<http://ex/abstract>".to_string(),
8182 format!("\"{head}{i:04}{tail}\""),
8183 )
8184 })
8185 .collect();
8186 let mut db = DictionaryBuilder::new();
8187 for (s, p, o) in &triples {
8188 db.observe(s, p, o);
8189 }
8190 let dict = db.build();
8191 let mut ib = GraphIndexBuilder::new();
8192 for (s, p, o) in &triples {
8193 ib.push(dict.encode(s, p, o).unwrap());
8194 }
8195 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
8196
8197 let reader = CountingReader::new(SliceReader::new(&bytes));
8198 let header = Header::from_bytes(&reader.read_at(0, HEADER_LEN as u64).unwrap()).unwrap();
8199 let section = locate_container_section_ranged(
8201 &reader,
8202 header.dictionary_offset,
8203 header.dictionary_len,
8204 2,
8205 4,
8206 )
8207 .unwrap();
8208
8209 let before = reader.bytes_read();
8210 let (_meta, entries) = read_dict_dir_ranged(&reader, section).unwrap();
8211 let spent = reader.bytes_read() - before;
8212
8213 let dir_end = entries[0].start;
8215 let head = reader.read_at(section.offset, 64).unwrap();
8216 let (header_len, n0) = read_uvarint(&head).unwrap();
8217 let dir_start = n0 as u64 + header_len;
8218 let dir_len = dir_end - dir_start;
8219 let dir_total = section.len - dir_start;
8220 assert!(
8221 dir_start + dir_len > 8192,
8222 "directory fits the header prefix ({dir_len} B) — the probe never runs"
8223 );
8224
8225 let mut old = 0u64;
8227 let mut p = 4096u64.min(dir_total).max(1);
8228 loop {
8229 let got = p.min(dir_total);
8230 old += got;
8231 if got >= dir_len || p >= dir_total {
8232 break;
8233 }
8234 p = p.saturating_mul(2).min(dir_total);
8235 }
8236 assert!(
8237 spent <= dir_len * 2,
8238 "probe read {spent} B for a {dir_len} B directory — past the append-only bound"
8239 );
8240 assert!(
8241 spent < old,
8242 "probe read {spent} B; the re-reading loop it replaced spent {old} B"
8243 );
8244 }
8245
8246 fn verbatim_keyed_twin(payload: &[u8], codec: u8) -> Vec<u8> {
8256 let (_meta, entries) = parse_chunked_dict_dir(payload, payload.len() as u64).unwrap();
8257 let (header_len, n0) = read_uvarint(payload).unwrap();
8258 let mut out = Vec::new();
8259 write_uvarint(&mut out, header_len);
8260 out.extend_from_slice(&payload[n0..n0 + header_len as usize]);
8261 write_uvarint(&mut out, entries.len() as u64);
8262 let mut prev_run = 0usize;
8263 for e in &entries {
8264 let body = decompress(codec, &payload[e.start as usize..e.end as usize]).unwrap();
8265 let first = crate::dict::run_first_term(&body, 0).unwrap();
8266 write_uvarint(&mut out, (e.first_run - prev_run) as u64);
8267 write_uvarint(&mut out, first.len() as u64);
8268 out.extend_from_slice(&first);
8269 write_uvarint(&mut out, e.end - e.start);
8270 prev_run = e.first_run;
8271 }
8272 for e in &entries {
8273 out.extend_from_slice(&payload[e.start as usize..e.end as usize]);
8274 }
8275 out
8276 }
8277
8278 fn chunk_bounds_of(payload: &[u8], codec: u8) -> Vec<(Vec<u8>, Vec<u8>)> {
8280 let (_meta, entries) = parse_chunked_dict_dir(payload, payload.len() as u64).unwrap();
8281 entries
8282 .iter()
8283 .map(|e| {
8284 let body = decompress(codec, &payload[e.start as usize..e.end as usize]).unwrap();
8285 (
8286 crate::dict::run_first_term(&body, 0).unwrap(),
8287 crate::dict::run_last_term(&body, 0, body.len()).unwrap(),
8288 )
8289 })
8290 .collect()
8291 }
8292
8293 fn adversarial_terms() -> Vec<String> {
8299 let mut terms: Vec<String> = Vec::new();
8300 for i in 0..6_000 {
8301 terms.push(format!("<http://example.org/work/{i:06}>"));
8302 }
8303 let shared = "X".repeat(900);
8304 for i in 0..4_000 {
8305 terms.push(format!("\"{shared}-{i:05}-tail\""));
8306 }
8307 let deep = "Y".repeat(3_000); for i in 0..120 {
8309 terms.push(format!("\"{deep}{i:03}\""));
8310 }
8311 for i in 0..6 {
8312 terms.push(format!("\"BIG-{i:02}-{}\"", "Z".repeat(90_000)));
8314 }
8315 for i in 0..800 {
8316 terms.push(format!(
8317 "\"h\u{e9}llo-{}-\u{1F600}{i:04}\"",
8318 "\u{e9}".repeat(40)
8319 ));
8320 }
8321 for i in 0..2_000 {
8322 terms.push(format!("\"{i:05}-{}\"", "T".repeat(1_800)));
8323 }
8324 terms.sort();
8325 terms.dedup();
8326 terms
8327 }
8328
8329 fn chunked_section_of(terms: &[String]) -> Vec<u8> {
8330 let mut b = crate::dict::DictSectionBuilder::new().with_restart_interval(16);
8331 for t in terms {
8332 b.push(t.clone());
8333 }
8334 b.build()
8335 }
8336
8337 #[test]
8347 fn chunk_directory_keys_are_separators_not_terms() {
8348 let terms = adversarial_terms();
8349 let raw = chunked_section_of(&terms);
8350 let payload = encode_chunked_dict_section(&raw, CODEC_NONE);
8351 let (_meta, entries) = parse_chunked_dict_dir(&payload, payload.len() as u64).unwrap();
8352 let bounds = chunk_bounds_of(&payload, CODEC_NONE);
8353 assert!(
8354 entries.len() > 20,
8355 "need a many-chunk section, got {}",
8356 entries.len()
8357 );
8358
8359 assert!(entries[0].key.is_empty(), "chunk 0 needs no separator");
8360 let mut key_bytes = 0usize;
8361 let mut term_bytes = 0usize;
8362 let mut differ = 0usize;
8363 for (i, e) in entries.iter().enumerate() {
8364 key_bytes += e.key.len();
8365 term_bytes += bounds[i].0.len();
8366 if e.key != bounds[i].0 {
8367 differ += 1;
8368 }
8369 assert!(
8370 e.key <= bounds[i].0,
8371 "chunk {i}: key must be <= its own first term"
8372 );
8373 if i > 0 {
8374 assert!(
8375 e.key.as_slice() > bounds[i - 1].1.as_slice(),
8376 "chunk {i}: key must be > the previous chunk's last term"
8377 );
8378 assert!(
8379 e.key > entries[i - 1].key,
8380 "chunk {i}: keys must ascend for partition_point"
8381 );
8382 assert_eq!(
8384 e.key,
8385 crate::dict::shortest_separator(&bounds[i - 1].1, &bounds[i].0),
8386 "chunk {i}: key is not the SHORTEST separator"
8387 );
8388 }
8389 }
8390 assert!(
8391 differ > 0,
8392 "every key equalled its first term — the writer stores terms again"
8393 );
8394 assert!(
8395 key_bytes * 4 < term_bytes,
8396 "separators bought almost nothing: {key_bytes} B vs {term_bytes} B of first terms"
8397 );
8398 eprintln!(
8399 "chunks={} first-term keys={term_bytes} B separator keys={key_bytes} B ({:.1}x)",
8400 entries.len(),
8401 term_bytes as f64 / key_bytes.max(1) as f64
8402 );
8403 }
8404
8405 #[test]
8416 fn separator_keys_route_identically_to_verbatim_first_terms() {
8417 let terms = adversarial_terms();
8418 let raw = chunked_section_of(&terms);
8419 let sep_payload = encode_chunked_dict_section(&raw, CODEC_NONE);
8420 let ver_payload = verbatim_keyed_twin(&sep_payload, CODEC_NONE);
8421
8422 let (_ms, es) = parse_chunked_dict_dir(&sep_payload, sep_payload.len() as u64).unwrap();
8424 let (_mv, ev) = parse_chunked_dict_dir(&ver_payload, ver_payload.len() as u64).unwrap();
8425 assert_eq!(es.len(), ev.len());
8426 for (a, b) in es.iter().zip(ev.iter()) {
8427 assert_eq!(a.first_run, b.first_run);
8428 assert_eq!(
8429 &sep_payload[a.start as usize..a.end as usize],
8430 &ver_payload[b.start as usize..b.end as usize],
8431 "chunk bodies must be identical"
8432 );
8433 }
8434 assert!(
8435 sep_payload.len() < ver_payload.len(),
8436 "separator payload is not smaller"
8437 );
8438
8439 let sec_s = decode_chunked_dict_section(
8440 &sep_payload,
8441 CODEC_NONE,
8442 crate::chunk_cache::ChunkCache::unlimited_arc(),
8443 0,
8444 )
8445 .unwrap();
8446 let sec_v = decode_chunked_dict_section(
8447 &ver_payload,
8448 CODEC_NONE,
8449 crate::chunk_cache::ChunkCache::unlimited_arc(),
8450 0,
8451 )
8452 .unwrap();
8453
8454 for (i, t) in terms.iter().enumerate() {
8456 let want = Some(i as u32 + 1);
8457 assert_eq!(sec_v.id(t), want, "verbatim id() lost a term");
8458 assert_eq!(sec_s.id(t), want, "separator id() lost a term");
8459 }
8460 for i in 0..terms.len() as u32 {
8462 assert_eq!(sec_s.term(i + 1), sec_v.term(i + 1));
8463 assert_eq!(
8464 sec_s.term(i + 1).as_deref(),
8465 Some(terms[i as usize].as_str())
8466 );
8467 }
8468 let bounds = chunk_bounds_of(&sep_payload, CODEC_NONE);
8470 let mut probes: Vec<String> = Vec::new();
8471 let push = |bytes: &[u8], probes: &mut Vec<String>| {
8472 if let Ok(s) = std::str::from_utf8(bytes) {
8473 probes.push(s.to_string());
8474 }
8475 };
8476 for (first, last) in &bounds {
8477 for base in [first, last] {
8478 push(base, &mut probes); let mut after = base.clone();
8480 after.push(0x01); push(&after, &mut probes);
8482 let mut far = base.clone();
8483 far.push(b'~');
8484 push(&far, &mut probes);
8485 if !base.is_empty() {
8486 push(&base[..base.len() - 1], &mut probes); let mut down = base.clone();
8488 *down.last_mut().unwrap() = down.last().unwrap().wrapping_sub(1);
8489 push(&down, &mut probes);
8490 let mut up = base.clone();
8491 *up.last_mut().unwrap() = up.last().unwrap().wrapping_add(1);
8492 push(&up, &mut probes);
8493 }
8494 }
8495 }
8496 for e in &es {
8498 push(&e.key, &mut probes);
8499 let mut plus = e.key.clone();
8500 plus.push(0);
8501 push(&plus, &mut probes);
8502 }
8503 probes.push(String::new()); probes.push("\u{1}".to_string()); probes.push("\u{10FFFF}\u{10FFFF}".to_string()); probes.push(terms.first().unwrap().clone());
8507 probes.push(terms.last().unwrap().clone());
8508
8509 let mut hits = 0usize;
8510 for p in &probes {
8511 let (a, b) = (sec_v.id(p), sec_s.id(p));
8512 assert_eq!(
8513 a,
8514 b,
8515 "probe diverged: {:?}",
8516 p.get(..p.len().min(48)).unwrap_or(p.as_str())
8517 );
8518 hits += usize::from(a.is_some());
8519 }
8520 assert!(
8521 probes.len() > 500 && hits > 50,
8522 "probe set is too thin: {} probes, {hits} of them present",
8523 probes.len()
8524 );
8525 eprintln!(
8526 "{} boundary probes, {hits} present, all identical",
8527 probes.len()
8528 );
8529 }
8530
8531 mod separator_props {
8537 use super::*;
8538 use proptest::prelude::*;
8539
8540 fn term_set() -> impl Strategy<Value = Vec<String>> {
8547 prop::collection::vec(("[a-c]{1,6}", 0u8..3, 300usize..1200), 60..250).prop_map(
8548 |specs| {
8549 let mut terms: Vec<String> = specs
8550 .into_iter()
8551 .enumerate()
8552 .map(|(i, (core, kind, pad))| {
8553 let block = "z".repeat(pad);
8554 match kind {
8555 0 => format!("<http://ex/{core}/{i:05}>"),
8556 1 => format!("\"{block}{core}{i:05}\""),
8557 _ => format!("\"{core}{i:05}{block}\""),
8558 }
8559 })
8560 .collect();
8561 terms.sort();
8562 terms.dedup();
8563 terms
8564 },
8565 )
8566 }
8567
8568 proptest! {
8569 #[test]
8570 fn prop_separator_keyed_section_answers_like_verbatim(
8571 terms in term_set(),
8572 extra in prop::collection::vec(any::<String>(), 0..8),
8573 ) {
8574 let raw = chunked_section_of(&terms);
8575 let sep = encode_chunked_dict_section(&raw, CODEC_NONE);
8576 let ver = verbatim_keyed_twin(&sep, CODEC_NONE);
8577 prop_assert!(sep.len() <= ver.len());
8578
8579 let (_m, es) = parse_chunked_dict_dir(&sep, sep.len() as u64).unwrap();
8581 let bounds = chunk_bounds_of(&sep, CODEC_NONE);
8582 prop_assert!(es[0].key.is_empty());
8583 for i in 1..es.len() {
8584 prop_assert!(es[i].key.as_slice() > bounds[i - 1].1.as_slice());
8585 prop_assert!(es[i].key <= bounds[i].0);
8586 prop_assert!(es[i].key > es[i - 1].key);
8587 }
8588
8589 let sec_s = decode_chunked_dict_section(
8590 &sep,
8591 CODEC_NONE,
8592 crate::chunk_cache::ChunkCache::unlimited_arc(),
8593 0,
8594 )
8595 .unwrap();
8596 let sec_v = decode_chunked_dict_section(
8597 &ver,
8598 CODEC_NONE,
8599 crate::chunk_cache::ChunkCache::unlimited_arc(),
8600 0,
8601 )
8602 .unwrap();
8603
8604 for (i, t) in terms.iter().enumerate() {
8605 prop_assert_eq!(sec_s.id(t), Some(i as u32 + 1));
8606 prop_assert_eq!(sec_v.id(t), Some(i as u32 + 1));
8607 prop_assert_eq!(sec_s.term(i as u32 + 1), sec_v.term(i as u32 + 1));
8608 }
8609
8610 let mut probes: Vec<String> = extra;
8612 probes.push(String::new());
8613 for (first, last) in &bounds {
8614 for base in [first, last] {
8615 if let Ok(s) = std::str::from_utf8(base) {
8616 probes.push(s.to_string());
8617 probes.push(format!("{s}\u{1}"));
8618 probes.push(s[..s.len() - s.chars().next_back()
8619 .map(char::len_utf8).unwrap_or(0)].to_string());
8620 }
8621 }
8622 }
8623 for e in &es {
8624 if let Ok(s) = std::str::from_utf8(&e.key) {
8625 probes.push(s.to_string());
8626 }
8627 }
8628 for p in &probes {
8629 prop_assert_eq!(sec_s.id(p), sec_v.id(p), "probe diverged: {:?}", p);
8630 }
8631 }
8632 }
8633 }
8634
8635 #[test]
8640 fn text_index_is_tamper_evident_and_verifies() {
8641 let triples: Vec<(String, String, String)> = vec![(
8642 "<http://ex/s0>".to_string(),
8643 "<http://ex/label>".to_string(),
8644 "\"alpha glucose phosphate\"".to_string(),
8645 )];
8646 let bytes = build_text_indexed(&triples);
8647 let header = Rete::open(&bytes).unwrap().header().clone();
8648 assert!(header.text_index_len > 0);
8649 assert!(verify(&bytes).unwrap(), "a text-indexed build must verify");
8650
8651 let mut tampered = bytes.clone();
8652 tampered[header.text_index_offset as usize] ^= 0xff;
8653 assert!(
8654 !verify(&tampered).unwrap(),
8655 "tampering with the text index must break verify()"
8656 );
8657 }
8658
8659 #[test]
8663 fn synopsis_cuts_remote_fetch_bytes() {
8664 use crate::header::FLAG_TILE_SYNOPSIS;
8665 use crate::reader::{CountingReader, SliceReader};
8666
8667 let triples: Vec<(String, String, String)> = (0..400u32)
8671 .map(|i| {
8672 (
8673 format!("<http://ex/s/{i:04}>"),
8674 "<http://ex/p>".to_string(),
8675 format!("<http://ex/o/{i:04}>"),
8676 )
8677 })
8678 .collect();
8679 let mut db = DictionaryBuilder::new();
8680 for (s, p, o) in &triples {
8681 db.observe(s, p, o);
8682 }
8683 let dict = db.build();
8684 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
8685 for (s, p, o) in &triples {
8686 ib.push(dict.encode(s, p, o).unwrap());
8687 }
8688 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
8689
8690 let q = (Some("<http://ex/s/0395>"), None, Some("<http://ex/o/0005>"));
8694 let query_bytes = |image: &[u8]| -> (u64, usize) {
8698 let leaked: &'static [u8] = Box::leak(image.to_vec().into_boxed_slice());
8699 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
8700 let rete = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
8701 let before = reader.bytes_read(); let n = rete.query(q.0, q.1, q.2).len();
8703 assert!(!rete.index_incomplete());
8704 (reader.bytes_read() - before, n)
8705 };
8706
8707 let (on_bytes, on_n) = query_bytes(&bytes);
8708 let mut off = bytes.clone();
8710 off[5] &= !FLAG_TILE_SYNOPSIS;
8711 let (off_bytes, off_n) = query_bytes(&off);
8712
8713 assert_eq!(on_n, 0, "the pair never co-occurs");
8714 assert_eq!(off_n, 0, "same answer without the synopsis");
8715 assert!(
8719 on_bytes < off_bytes,
8720 "synopsis skips the routed tile fetch: {on_bytes} < {off_bytes}"
8721 );
8722 }
8723
8724 #[test]
8730 fn double_bound_object_join_eager_matches_lazy() {
8731 use crate::reader::SliceReader;
8732 let occ = "<http://ex/occ>";
8733 let phys = "<http://ex/physicist>";
8734 let phil = "<http://ex/philosopher>";
8735 let label = "<http://www.w3.org/2000/01/rdf-schema#label>";
8736 let mut triples: Vec<(String, String, String)> = Vec::new();
8738 for i in 0..20u32 {
8739 triples.push((format!("<http://ex/p/{i:02}>"), occ.into(), phys.into()));
8740 if i < 10 {
8741 triples.push((format!("<http://ex/p/{i:02}>"), occ.into(), phil.into()));
8742 }
8743 triples.push((
8744 format!("<http://ex/p/{i:02}>"),
8745 label.into(),
8746 format!("\"Name {i:02}\""),
8747 ));
8748 }
8749 let mut db = DictionaryBuilder::new();
8750 for (s, p, o) in &triples {
8751 db.observe(s, p, o);
8752 }
8753 let dict = db.build();
8754 let mut ib = GraphIndexBuilder::new().with_tile_budget(16);
8755 for (s, p, o) in &triples {
8756 ib.push(dict.encode(s, p, o).unwrap());
8757 }
8758 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
8759
8760 let q = "SELECT ?l WHERE { \
8761 ?p <http://ex/occ> <http://ex/physicist> ; \
8762 <http://ex/occ> <http://ex/philosopher> ; \
8763 <http://www.w3.org/2000/01/rdf-schema#label> ?l }";
8764 let run = |rete: &Rete| -> Vec<String> {
8765 let (_, sols) = crate::eval_sparql(rete, q).unwrap();
8766 let mut v: Vec<String> = sols.iter().filter_map(|b| b.get("l").cloned()).collect();
8767 v.sort();
8768 v
8769 };
8770
8771 let eager_rows = run(&Rete::open(&bytes).unwrap());
8772 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
8773 let lazy = Rete::open_ranged_lazy_with(
8774 std::sync::Arc::new(SliceReader::new(leaked)),
8775 HEADER_LEN as u64,
8776 )
8777 .unwrap();
8778 let lazy_rows = run(&lazy);
8779 assert!(!lazy.index_incomplete());
8780
8781 assert_eq!(eager_rows.len(), 10, "the 10 physicist∩philosopher labels");
8782 assert_eq!(eager_rows, lazy_rows, "eager and lazy must agree exactly");
8783 }
8784
8785 #[test]
8789 fn multi_chunk_dictionary_round_trips() {
8790 let mut db = DictionaryBuilder::new();
8791 let term = |i: u32| format!("<http://example.org/some/long/prefix/entity/{i:06}>");
8792 for i in 0..6000u32 {
8793 db.observe(&term(i), "<http://ex/p>", &term(i + 1));
8794 }
8795 let dict = db.build();
8796 let mut ib = GraphIndexBuilder::new();
8797 for i in 0..6000u32 {
8798 ib.push(
8799 dict.encode(&term(i), "<http://ex/p>", &term(i + 1))
8800 .unwrap(),
8801 );
8802 }
8803 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
8804 let rete = Rete::open(&bytes).unwrap();
8805 let d = rete.dictionary();
8806 assert_eq!(d.term_count(), dict.term_count());
8807 for i in (0..6000).step_by(97).chain([0, 1, 5999, 6000]) {
8808 let t = term(i);
8809 let sid = dict.subject_id(&t);
8810 assert_eq!(d.subject_id(&t), sid, "subject_id({t})");
8811 if let Some(id) = sid {
8812 assert_eq!(d.subject_term(id).as_deref(), Some(t.as_str()));
8813 }
8814 let oid = dict.object_id(&t);
8815 assert_eq!(d.object_id(&t), oid, "object_id({t})");
8816 }
8817 assert_eq!(d.subject_id("<http://example.org/absent>"), None);
8818 assert_eq!(d.predicate_id("<http://ex/p>"), Some(1));
8819 assert_eq!(d.predicate_term(1).as_deref(), Some("<http://ex/p>"));
8820 }
8821
8822 #[test]
8823 #[cfg(feature = "compression")]
8824 fn compression_shrinks_repetitive_data() {
8825 let mut db = DictionaryBuilder::new();
8829 let triples: Vec<(String, String, String)> = (0..500)
8830 .map(|i| {
8831 (
8832 format!("<http://example.org/entity/{i}>"),
8833 "<http://example.org/p/relatedTo>".to_string(),
8834 format!("<http://example.org/entity/{}>", (i + 1) % 500),
8835 )
8836 })
8837 .collect();
8838 for (s, p, o) in &triples {
8839 db.observe(s, p, o);
8840 }
8841 let dict = db.build();
8842 let mut ib = GraphIndexBuilder::new();
8843 for (s, p, o) in &triples {
8844 ib.push(dict.encode(s, p, o).unwrap());
8845 }
8846 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
8847
8848 let raw: usize = triples
8849 .iter()
8850 .map(|(s, p, o)| s.len() + p.len() + o.len())
8851 .sum();
8852 assert!(
8853 bytes.len() < raw / 2,
8854 "expected strong compression: file {} vs raw terms {raw}",
8855 bytes.len()
8856 );
8857
8858 let rete = Rete::open(&bytes).unwrap();
8860 let r = rete.query(Some("<http://example.org/entity/0>"), None, None);
8861 assert_eq!(r.len(), 1);
8862 assert_eq!(r[0].2, "<http://example.org/entity/1>");
8863 }
8864
8865 fn big_file_with_pyramid() -> Vec<u8> {
8866 let triples: Vec<(String, String, String)> = (0..300)
8868 .map(|i| {
8869 (
8870 format!("<http://ex/e{i}>"),
8871 "<http://ex/next>".to_string(),
8872 format!("<http://ex/e{}>", (i + 1) % 300),
8873 )
8874 })
8875 .collect();
8876 let mut db = DictionaryBuilder::new();
8877 for (s, p, o) in &triples {
8878 db.observe(s, p, o);
8879 }
8880 let dict = db.build();
8881 let ids: Vec<_> = triples
8882 .iter()
8883 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
8884 .collect();
8885 let mut ib = GraphIndexBuilder::new();
8886 for &t in &ids {
8887 ib.push(t);
8888 }
8889 let (meta, levels) = build_pyramid_meta(&dict, &ids, DEFAULT_TILE_BUDGET);
8890 write_file(&dict, &ib.build(), false, &meta, levels)
8891 }
8892
8893 #[test]
8894 fn ranged_open_is_minimal_and_correct() {
8895 use crate::reader::{CountingReader, SliceReader};
8896 let bytes = big_file_with_pyramid();
8897
8898 let full = CountingReader::new(SliceReader::new(&bytes));
8899 let rete = Rete::open_ranged(&full).unwrap();
8900 assert!(full.requests() <= 4, "requests = {}", full.requests());
8902 assert_eq!(
8903 rete.query(Some("<http://ex/e0>"), None, None)[0].2,
8904 "<http://ex/e1>"
8905 );
8906
8907 let summ_reader = CountingReader::new(SliceReader::new(&bytes));
8909 let view = SummaryView::open_ranged(&summ_reader).unwrap().unwrap();
8910 assert!(!view.summary.is_empty());
8911 assert!(
8912 summ_reader.bytes_read() < bytes.len() as u64,
8913 "summary read {} of {} bytes",
8914 summ_reader.bytes_read(),
8915 bytes.len()
8916 );
8917 assert!(summ_reader.bytes_read() < full.bytes_read());
8919 }
8920
8921 #[test]
8922 fn content_hash_is_set_and_verifies() {
8923 let bytes = build_image();
8924 let rete = Rete::open(&bytes).unwrap();
8925 assert_ne!(
8926 rete.header().content_hash,
8927 [0u8; 16],
8928 "hash must be populated"
8929 );
8930 assert!(verify(&bytes).unwrap(), "freshly built file verifies");
8931 assert!(
8932 verify_ranged(&crate::reader::SliceReader::new(&bytes)).unwrap(),
8933 "the streaming verify agrees"
8934 );
8935
8936 assert_eq!(
8938 Rete::open(&build_image()).unwrap().header().content_hash,
8939 rete.header().content_hash
8940 );
8941
8942 let mut tampered = bytes.clone();
8944 let last = tampered.len() - 5; tampered[last] ^= 0xff;
8946 assert!(!verify(&tampered).unwrap());
8947 assert!(!verify_ranged(&crate::reader::SliceReader::new(&tampered)).unwrap());
8948 let short = &bytes[..bytes.len() / 2];
8950 assert!(verify_ranged(&crate::reader::SliceReader::new(short)).is_err());
8951 assert!(verify_ranged(&crate::reader::SliceReader::new(&bytes[..10])).is_err());
8952 }
8953
8954 fn build_with_metadata(meta: &[u8]) -> Vec<u8> {
8956 let triples = [
8957 ("Alice", "knows", "Bob"),
8958 ("Bob", "knows", "Carol"),
8959 ("Alice", "age", "30"),
8960 ];
8961 let mut db = DictionaryBuilder::new();
8962 for (s, p, o) in triples {
8963 db.observe(s, p, o);
8964 }
8965 let dict = db.build();
8966 let ids: Vec<_> = triples
8967 .iter()
8968 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
8969 .collect();
8970 let mut ib = GraphIndexBuilder::new();
8971 for &t in &ids {
8972 ib.push(t);
8973 }
8974 let (pmeta, levels) = build_pyramid_meta(&dict, &ids, DEFAULT_TILE_BUDGET);
8975 write_dataset_with_metadata(&dict, &ib.build(), &[], false, &pmeta, levels, meta, &[])
8976 }
8977
8978 #[test]
8979 fn metadata_round_trips_and_shifts_offsets() {
8980 let card = br#"{"title":"My Dataset"}"#;
8981 let bytes = build_with_metadata(card);
8982 let rete = Rete::open(&bytes).unwrap();
8983
8984 assert_eq!(rete.metadata(), Some(card.as_slice()));
8986 let h = rete.header();
8987 assert_eq!(h.metadata_offset, HEADER_LEN as u64);
8988 assert_eq!(h.metadata_len, card.len() as u64);
8989 assert_eq!(h.dictionary_offset, HEADER_LEN as u64 + card.len() as u64);
8991
8992 assert_eq!(
8994 rete.query(Some("Bob"), Some("knows"), Some("Carol")).len(),
8995 1
8996 );
8997 assert!(verify(&bytes).unwrap());
8999 }
9000
9001 #[test]
9002 fn empty_metadata_is_byte_identical_to_plain_writer() {
9003 assert_eq!(
9006 build_with_metadata(&[]),
9007 build_image(),
9008 "empty-metadata output must equal the plain writer byte-for-byte"
9009 );
9010 }
9011
9012 #[test]
9017 fn replace_metadata_matches_a_direct_write() {
9018 let first = br#"{"title":"My Dataset","queries":[1,2,3]}"#;
9019 let bytes = build_with_metadata(first);
9020 for target in [
9021 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(), ] {
9026 let spliced = replace_metadata(&bytes, target).unwrap();
9027 assert_eq!(
9028 spliced,
9029 build_with_metadata(target),
9030 "splicing {} bytes of metadata must equal a direct write",
9031 target.len()
9032 );
9033 assert!(
9034 verify(&spliced).unwrap(),
9035 "the new hash covers the new card"
9036 );
9037 let rete = Rete::open(&spliced).unwrap();
9038 assert_eq!(
9039 rete.metadata(),
9040 (!target.is_empty()).then_some(target),
9041 "the new payload reads back verbatim"
9042 );
9043 assert_eq!(
9045 rete.query(Some("Bob"), Some("knows"), Some("Carol")).len(),
9046 1
9047 );
9048 }
9049 }
9050
9051 #[test]
9054 fn replace_metadata_keeps_build_info_adjacent() {
9055 let with_info =
9056 attach_build_info(&build_with_metadata(br#"{"a":1}"#), br#"{"builder":"x"}"#).unwrap();
9057 let spliced = replace_metadata(&with_info, br#"{"a":1,"b":2}"#).unwrap();
9058 let h = Header::from_bytes(&spliced).unwrap();
9059 assert_eq!(h.metadata_offset, HEADER_LEN as u64);
9060 assert_eq!(h.build_info_offset, HEADER_LEN as u64 + h.metadata_len);
9061 assert_eq!(
9062 read_build_info(&spliced).unwrap().as_deref(),
9063 Some(br#"{"builder":"x"}"#.as_slice())
9064 );
9065 assert!(verify(&spliced).unwrap());
9066 assert_eq!(
9068 h.content_hash,
9069 Header::from_bytes(&build_with_metadata(br#"{"a":1,"b":2}"#))
9070 .unwrap()
9071 .content_hash
9072 );
9073 }
9074
9075 #[test]
9076 fn metadata_is_tamper_evident() {
9077 let card = br#"{"title":"x"}"#;
9078 let mut bytes = build_with_metadata(card);
9079 assert!(verify(&bytes).unwrap());
9080 bytes[HEADER_LEN + 2] ^= 0xff;
9082 assert!(
9083 !verify(&bytes).unwrap(),
9084 "tampering with the card must break verify()"
9085 );
9086 }
9087
9088 #[test]
9089 fn ranged_opens_do_not_fetch_metadata() {
9090 use crate::reader::{CountingReader, SliceReader};
9091 let card = vec![0xABu8; 512]; let bytes = build_with_metadata(&card);
9093 let total = bytes.len() as u64;
9094
9095 let r = CountingReader::new(SliceReader::new(&bytes));
9097 let rete = Rete::open_ranged(&r).unwrap();
9098 assert!(
9099 rete.metadata().is_none(),
9100 "open_ranged must not load the card"
9101 );
9102 assert!(r.requests() <= 4, "requests = {}", r.requests());
9103 assert!(
9104 r.bytes_read() <= total - card.len() as u64,
9105 "read {} of {} bytes; the {}-byte card must be skipped",
9106 r.bytes_read(),
9107 total,
9108 card.len()
9109 );
9110
9111 let rs = CountingReader::new(SliceReader::new(&bytes));
9113 let view = SummaryView::open_ranged(&rs).unwrap().unwrap();
9114 assert!(!view.summary.is_empty());
9115 assert!(rs.bytes_read() <= total - card.len() as u64);
9116 }
9117
9118 #[test]
9119 fn metadata_ranged_fetches_only_header_and_card() {
9120 use crate::reader::{CountingReader, SliceReader};
9121 let card = vec![0xCDu8; 384];
9124 let bytes = build_with_metadata(&card);
9125
9126 let r = CountingReader::new(SliceReader::new(&bytes));
9127 let got = read_metadata_ranged(&r).unwrap().unwrap();
9128 assert_eq!(got, card, "the card reads back verbatim");
9129 assert_eq!(r.requests(), 2, "exactly header + metadata ranges");
9130 assert_eq!(
9131 r.bytes_read(),
9132 HEADER_LEN as u64 + card.len() as u64,
9133 "no dictionary/index/pyramid bytes are touched"
9134 );
9135
9136 let plain = build_image();
9138 let rp = CountingReader::new(SliceReader::new(&plain));
9139 assert!(read_metadata_ranged(&rp).unwrap().is_none());
9140 assert_eq!(rp.requests(), 1, "header only for a cardless file");
9141 assert_eq!(rp.bytes_read(), HEADER_LEN as u64);
9142 }
9143
9144 #[test]
9145 fn build_info_attaches_outside_the_hash() {
9146 let card = br#"{"title":"My Dataset"}"#;
9147 let base = build_with_metadata(card);
9148 let base_hash = Header::from_bytes(&base).unwrap().content_hash;
9149
9150 let info = br#"{"built_at":"2026-08-04T00:00:00Z","builder":"rete-cli 0.3.2"}"#;
9151 let with = attach_build_info(&base, info).unwrap();
9152
9153 assert_eq!(read_build_info(&with).unwrap().unwrap(), info);
9155 let h = Header::from_bytes(&with).unwrap();
9156 assert_eq!(h.build_info_offset, HEADER_LEN as u64 + card.len() as u64);
9157 assert_eq!(h.build_info_len, info.len() as u64);
9158 assert_eq!(h.expected_file_len(), Some(with.len() as u64));
9159
9160 assert_eq!(h.content_hash, base_hash);
9164 assert!(verify(&with).unwrap());
9165 let other = attach_build_info(&base, br#"{"built_at":"1999-01-01T00:00:00Z"}"#).unwrap();
9166 assert_eq!(Header::from_bytes(&other).unwrap().content_hash, base_hash);
9167
9168 let rete = Rete::open(&with).unwrap();
9170 assert_eq!(
9171 rete.query(Some("Bob"), Some("knows"), Some("Carol")).len(),
9172 1
9173 );
9174 assert_eq!(rete.metadata(), Some(card.as_slice()));
9175
9176 let replaced = attach_build_info(&with, br#"{"builder":"other"}"#).unwrap();
9179 assert_eq!(
9180 read_build_info(&replaced).unwrap().unwrap(),
9181 br#"{"builder":"other"}"#
9182 );
9183 assert!(verify(&replaced).unwrap());
9184 let stripped = attach_build_info(&replaced, &[]).unwrap();
9185 assert_eq!(stripped, base, "stripping build-info restores the image");
9186 }
9187
9188 #[test]
9189 fn build_info_attaches_on_a_metadata_free_file() {
9190 let base = build_image();
9192 let info = b"{\"builder\":\"x\"}";
9193 let with = attach_build_info(&base, info).unwrap();
9194 let h = Header::from_bytes(&with).unwrap();
9195 assert_eq!(h.build_info_offset, HEADER_LEN as u64);
9196 assert_eq!(h.metadata_len, 0);
9197 assert_eq!(read_build_info(&with).unwrap().unwrap(), info);
9198 assert!(verify(&with).unwrap());
9199 assert_eq!(
9200 h.content_hash,
9201 Header::from_bytes(&base).unwrap().content_hash
9202 );
9203 Rete::open(&with).unwrap();
9204 }
9205
9206 #[test]
9213 fn a_plan_rebuilds_exactly_what_the_in_memory_splice_produces() {
9214 let card = br#"{"title":"My Dataset"}"#;
9215 let base = build_with_metadata(card);
9216 let base_hash = Header::from_bytes(&base).unwrap().content_hash;
9217 for start in [
9218 base.clone(),
9219 attach_build_info(&base, b"{\"a\":1}").unwrap(),
9220 ] {
9221 for info in [
9222 br#"{"builder":"rete-cli 0.3.2","query_costs":{}}"#.as_slice(), b"{}".as_slice(), b"".as_slice(), ] {
9226 let plan = plan_build_info(&start, start.len() as u64, info.len() as u64).unwrap();
9227 let mut streamed = Vec::new();
9228 streamed.extend_from_slice(&plan.header);
9229 streamed.extend_from_slice(&start[HEADER_LEN..plan.insert as usize]);
9230 streamed.extend_from_slice(info);
9231 streamed.extend_from_slice(&start[plan.tail_start as usize..]);
9232 assert_eq!(streamed.len() as u64, plan.new_len);
9233 assert_eq!(
9234 streamed,
9235 attach_build_info(&start, info).unwrap(),
9236 "a {}-byte section streamed must equal the same section spliced",
9237 info.len()
9238 );
9239 assert!(verify(&streamed).unwrap());
9241 let h = Header::from_bytes(&streamed).unwrap();
9242 assert_eq!(h.content_hash, base_hash);
9243 assert_eq!(h.expected_file_len(), Some(plan.new_len));
9244 let rete = Rete::open(&streamed).unwrap();
9245 assert_eq!(rete.metadata(), Some(card.as_slice()));
9246 assert_eq!(
9247 rete.query(Some("Bob"), Some("knows"), Some("Carol")).len(),
9248 1
9249 );
9250 }
9251 }
9252 }
9253
9254 #[test]
9257 fn a_plan_refuses_a_header_that_overruns_the_file() {
9258 let base = build_with_metadata(br#"{"title":"x"}"#);
9259 assert!(plan_build_info(&base, 8, 16).is_err());
9260 assert!(plan_build_info(&base[..HEADER_LEN], base.len() as u64, 16).is_ok());
9261 }
9262
9263 #[test]
9264 fn card_and_build_info_ranged_is_one_header_plus_one_range() {
9265 use crate::reader::{CountingReader, SliceReader};
9266 let card = vec![0xCDu8; 384];
9267 let info = vec![0xEFu8; 200];
9268 let bytes = attach_build_info(&build_with_metadata(&card), &info).unwrap();
9269
9270 let r = CountingReader::new(SliceReader::new(&bytes));
9273 let (m, b) = read_card_and_build_info_ranged(&r).unwrap();
9274 assert_eq!(m.unwrap(), card);
9275 assert_eq!(b.unwrap(), info);
9276 assert_eq!(r.requests(), 2, "header + one coalesced range");
9277 assert_eq!(
9278 r.bytes_read(),
9279 HEADER_LEN as u64 + card.len() as u64 + info.len() as u64
9280 );
9281
9282 let plain = build_with_metadata(&card);
9284 let rp = CountingReader::new(SliceReader::new(&plain));
9285 let (m, b) = read_card_and_build_info_ranged(&rp).unwrap();
9286 assert_eq!(m.unwrap(), card);
9287 assert!(b.is_none());
9288 assert_eq!(rp.requests(), 2);
9289 assert_eq!(
9294 r.requests(),
9295 rp.requests(),
9296 "build info must not cost an extra request",
9297 );
9298
9299 let none = build_image();
9301 let rn = CountingReader::new(SliceReader::new(&none));
9302 let (m, b) = read_card_and_build_info_ranged(&rn).unwrap();
9303 assert!(m.is_none() && b.is_none());
9304 assert_eq!(rn.requests(), 1);
9305 }
9306
9307 #[test]
9308 fn schema_summary_groups_by_type() {
9309 let rt = RDF_TYPE;
9310 let bytes = build_from(&[
9311 ("Alice", rt, "Person"),
9312 ("Bob", rt, "Person"),
9313 ("NYC", rt, "City"),
9314 ("Alice", "knows", "Bob"),
9315 ("Alice", "livesIn", "NYC"),
9316 ("Alice", "name", "\"Alice\""),
9317 ]);
9318 let rete = Rete::open(&bytes).unwrap();
9319 let summary = schema_summary(&rete);
9320 assert!(summary.contains(&("Person".into(), "knows".into(), "Person".into(), 1)));
9322 assert!(summary.contains(&("Person".into(), "livesIn".into(), "City".into(), 1)));
9323 assert!(summary.contains(&("Person".into(), "name".into(), "(literal)".into(), 1)));
9324 assert!(!summary.iter().any(|(_, p, _, _)| p == RDF_TYPE));
9326
9327 let classes = schema_classes(&rete);
9329 assert_eq!(
9330 classes,
9331 vec![("Person".into(), 2u32), ("City".into(), 1u32)]
9332 );
9333 }
9334
9335 fn build_from(triples: &[(&str, &str, &str)]) -> Vec<u8> {
9336 let mut db = DictionaryBuilder::new();
9337 for (s, p, o) in triples {
9338 db.observe(s, p, o);
9339 }
9340 let dict = db.build();
9341 let mut ib = GraphIndexBuilder::new();
9342 for (s, p, o) in triples {
9343 ib.push(dict.encode(s, p, o).unwrap());
9344 }
9345 write_file(&dict, &ib.build(), false, &[], 0)
9346 }
9347
9348 fn build_with_pyramid(triples: &[(&str, &str, &str)]) -> Vec<u8> {
9350 let mut db = DictionaryBuilder::new();
9351 for (s, p, o) in triples {
9352 db.observe(s, p, o);
9353 }
9354 let dict = db.build();
9355 let encoded: Vec<_> = triples
9356 .iter()
9357 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
9358 .collect();
9359 let mut ib = GraphIndexBuilder::new();
9360 for t in &encoded {
9361 ib.push(*t);
9362 }
9363 let (meta, levels) = build_pyramid_meta(&dict, &encoded, DEFAULT_TILE_BUDGET);
9364 write_dataset(&dict, &ib.build(), &[], false, &meta, levels)
9365 }
9366
9367 #[test]
9368 fn tbox_coherence_flags_unsatisfiable_class_index_free() {
9369 use crate::reader::{CountingReader, SliceReader};
9370 let rt = RDF_TYPE;
9371 let sub = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
9372 let disj = "<http://www.w3.org/2002/07/owl#disjointWith>";
9373 let bytes = build_with_pyramid(&[
9376 ("<http://ex/C>", sub, "<http://ex/D>"),
9377 ("<http://ex/C>", sub, "<http://ex/E>"),
9378 ("<http://ex/D>", disj, "<http://ex/E>"),
9379 ("<http://ex/x>", rt, "<http://ex/C>"),
9380 ]);
9381
9382 let r = CountingReader::new(SliceReader::new(&bytes));
9383 let view = SummaryView::open_ranged(&r).unwrap().unwrap();
9384 let points = view.tbox_coherence();
9385 assert!(
9386 points
9387 .iter()
9388 .any(|i| i.kind == "unsatisfiable-class" && i.detail.contains("http://ex/C>")),
9389 "expected C unsatisfiable from the schema alone, got {points:?}"
9390 );
9391
9392 let header = Header::from_bytes(&bytes[..HEADER_LEN]).unwrap();
9395 assert!(
9396 r.bytes_read() <= bytes.len() as u64 - header.root_dir_len,
9397 "tbox_coherence must not read the triple index"
9398 );
9399 }
9400
9401 #[test]
9402 fn schema_coherence_reads_only_the_schema_block() {
9403 use crate::reader::{CountingReader, SliceReader};
9404 let rt = RDF_TYPE;
9405 let sub = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
9406 let disj = "<http://www.w3.org/2002/07/owl#disjointWith>";
9407 let mut triples: Vec<(String, String, String)> = vec![
9411 ("<http://ex/C>".into(), sub.into(), "<http://ex/D>".into()),
9412 ("<http://ex/C>".into(), sub.into(), "<http://ex/E>".into()),
9413 ("<http://ex/D>".into(), disj.into(), "<http://ex/E>".into()),
9414 ];
9415 for i in 0..500 {
9416 let s = format!("<http://ex/x{i}>");
9417 triples.push((s.clone(), rt.into(), "<http://ex/C>".into()));
9418 triples.push((
9419 s,
9420 "<http://ex/label>".into(),
9421 format!("\"unique label {i}\""),
9422 ));
9423 }
9424 let trefs: Vec<(&str, &str, &str)> = triples
9425 .iter()
9426 .map(|(s, p, o)| (s.as_str(), p.as_str(), o.as_str()))
9427 .collect();
9428 let bytes = build_with_pyramid(&trefs);
9429
9430 let header = Header::from_bytes(&bytes[..HEADER_LEN]).unwrap();
9431 assert!(
9432 header.schema_meta_len > 0,
9433 "the writer recorded a schema-block length"
9434 );
9435 assert!(
9436 (header.schema_meta_len as u64) < header.pyramid_meta_len,
9437 "schema block ({}) should be far smaller than the whole pyramid-meta ({})",
9438 header.schema_meta_len,
9439 header.pyramid_meta_len
9440 );
9441
9442 let r = CountingReader::new(SliceReader::new(&bytes));
9443 let points = read_schema_coherence_ranged(&r).unwrap().unwrap();
9444 assert!(points.iter().any(|i| i.kind == "unsatisfiable-class"));
9445 assert!(
9447 r.bytes_read() <= HEADER_LEN as u64 + header.schema_meta_len as u64,
9448 "read {} bytes; expected <= header + schema block ({})",
9449 r.bytes_read(),
9450 HEADER_LEN as u64 + header.schema_meta_len as u64
9451 );
9452 }
9453
9454 #[test]
9455 fn tbox_coherence_clean_schema_is_coherent() {
9456 use crate::reader::SliceReader;
9457 let rt = RDF_TYPE;
9458 let sub = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
9459 let bytes = build_with_pyramid(&[
9460 ("<http://ex/Dog>", sub, "<http://ex/Animal>"),
9461 ("<http://ex/x>", rt, "<http://ex/Dog>"),
9462 ]);
9463 let view = SummaryView::open_ranged(&SliceReader::new(&bytes))
9464 .unwrap()
9465 .unwrap();
9466 assert!(view.tbox_is_coherent(), "a plain hierarchy is coherent");
9467 }
9468
9469 #[test]
9477 fn readers_before_the_quad_index_refuse_its_files() {
9478 for perms in [PermSet::ALL, PermSet::CORE] {
9479 let quads: Vec<crate::ingest::RawQuad> = (0..50)
9480 .map(|i| {
9481 (
9482 format!("<http://ex/s{i}>"),
9483 "<http://ex/p>".to_string(),
9484 format!("\"{i}\""),
9485 Some(format!("<http://ex/g{}>", i % 7)),
9486 )
9487 })
9488 .collect();
9489 let (bytes, _) = crate::ingest::assemble_dataset_with_layout(
9490 quads,
9491 false,
9492 false,
9493 None,
9494 crate::PyramidAlgo::Louvain,
9495 perms,
9496 crate::ingest::GraphLayout::Quad,
9497 |_, _| Vec::<u8>::new(),
9498 );
9499 let h = Header::from_bytes(&bytes).unwrap();
9500 assert!(h.has_quad_index());
9501 let root =
9502 &bytes[h.root_dir_offset as usize..(h.root_dir_offset + h.root_dir_len) as usize];
9503 assert!(decode_index_container(root, h.block_codec, h.perms).is_err());
9505 assert!(
9506 container_section_payload_ranges(root, h.root_dir_offset, h.perms.len()).is_err()
9507 );
9508 assert_ne!(decode_container(root, CODEC_NONE).unwrap().len(), NUM_PERMS);
9510 assert_ne!(
9511 decode_container(root, CODEC_NONE).unwrap().len(),
9512 h.perms.len()
9513 );
9514 let r = crate::reader::SliceReader::new(&bytes);
9516 for expect in [h.perms.len(), NUM_PERMS] {
9517 assert!(locate_container_section_ranged(
9518 &r,
9519 h.root_dir_offset,
9520 h.root_dir_len,
9521 0,
9522 expect as u64
9523 )
9524 .is_err());
9525 }
9526 assert_eq!(hash_of_sections(&h, &bytes).unwrap(), h.content_hash);
9528 let rete = Rete::open(&bytes).unwrap();
9530 assert_eq!(rete.named_graph_count(), 7);
9531 assert_eq!(rete.dump(Some("<http://ex/g3>")).len(), 7);
9532 }
9533 }
9534
9535 #[test]
9536 fn named_graphs_round_trip() {
9537 let all = [
9539 ("Alice", "knows", "Bob"), ("Bob", "age", "30"), ];
9542 let mut db = DictionaryBuilder::new();
9543 for (s, p, o) in all {
9544 db.observe(s, p, o);
9545 }
9546 let dict = db.build();
9547
9548 let mut def = GraphIndexBuilder::new();
9549 def.push(dict.encode("Alice", "knows", "Bob").unwrap());
9550 let mut g1 = GraphIndexBuilder::new();
9551 g1.push(dict.encode("Bob", "age", "30").unwrap());
9552
9553 let named = vec![("http://ex/g1".to_string(), g1.build())];
9554 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
9555
9556 assert!(verify(&bytes).unwrap());
9557 let rete = Rete::open(&bytes).unwrap();
9558 assert_eq!(rete.graph_names(), vec!["http://ex/g1"]);
9559 let gi = rete.graph_index("http://ex/g1").unwrap();
9561 assert_eq!(gi.triple_count(), 1);
9562 assert!(rete.graph_index("http://ex/missing").is_none());
9563
9564 assert_eq!(rete.header().quad_count, 2);
9567
9568 assert_eq!(rete.query(Some("Alice"), None, None).len(), 1);
9570
9571 assert_eq!(
9573 rete.dump(None),
9574 vec![("Alice".into(), "knows".into(), "Bob".into())]
9575 );
9576 assert_eq!(
9577 rete.dump(Some("http://ex/g1")),
9578 vec![("Bob".into(), "age".into(), "30".into())]
9579 );
9580 }
9581
9582 #[test]
9588 fn named_graph_container_opens_tile_lazily_like_the_root() {
9589 let mut db = DictionaryBuilder::new();
9590 let node = |n: u32| format!("<http://ex/n{n}>");
9591 let p = "<http://ex/p>".to_string();
9592 db.observe(&node(0), &p, &node(1));
9593 for i in 0..500u32 {
9594 db.observe(&node(1000 + i), &p, &node(2000 + i));
9595 }
9596 let dict = db.build();
9597 let mut def = GraphIndexBuilder::new();
9598 def.push(dict.encode(&node(0), &p, &node(1)).unwrap());
9599 let mut g = GraphIndexBuilder::new().with_tile_budget(256); for i in 0..500u32 {
9601 g.push(dict.encode(&node(1000 + i), &p, &node(2000 + i)).unwrap());
9602 }
9603 let named = vec![("<http://ex/g>".to_string(), g.build())];
9604 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
9605 let rete = Rete::open(&bytes).unwrap();
9606 let header = rete.header();
9607
9608 let soff = header.named_graphs_offset as usize;
9611 let send = soff + header.named_graphs_len as usize;
9612 let sec = &bytes[soff..send];
9613 let (n, mut pos) = read_uvarint(sec).unwrap();
9614 assert_eq!(n, 1);
9615 let (ilen, u1) = read_uvarint(&sec[pos..]).unwrap();
9616 pos += u1 + ilen as usize;
9617 let (clen, u2) = read_uvarint(&sec[pos..]).unwrap();
9618 pos += u2;
9619 let container = ByteRange {
9620 offset: (soff + pos) as u64,
9621 len: clen,
9622 };
9623
9624 use crate::reader::SliceReader;
9625 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
9626 let reader: std::sync::Arc<dyn RangeReader + Send + Sync> =
9627 std::sync::Arc::new(SliceReader::new(leaked));
9628 let (lazy_idx, _, _) = open_index_container_lazy(
9629 &reader,
9630 container,
9631 header.block_codec,
9632 header.has_tile_synopsis(),
9633 1,
9634 header.perms,
9635 header.perms.len(),
9636 )
9637 .unwrap();
9638 let mut want = rete
9639 .graph_index("<http://ex/g>")
9640 .unwrap()
9641 .match_pattern((None, None, None));
9642 let mut got = lazy_idx.match_pattern((None, None, None));
9643 want.sort_unstable();
9644 got.sort_unstable();
9645 assert_eq!(got.len(), 500);
9646 assert_eq!(got, want);
9647 assert!(!lazy_idx.load_incomplete());
9648 }
9649
9650 #[test]
9656 fn dump_iter_matches_dump_and_stops_early() {
9657 use crate::reader::{CountingReader, SliceReader};
9658
9659 let triples: Vec<(String, String, String)> = (0..2000u32)
9661 .map(|i| {
9662 (
9663 format!("<http://ex/s/{i:04}>"),
9664 "<http://ex/p>".to_string(),
9665 format!("<http://ex/o/{i:04}>"),
9666 )
9667 })
9668 .collect();
9669 let mut db = DictionaryBuilder::new();
9670 for (s, p, o) in &triples {
9671 db.observe(s, p, o);
9672 }
9673 let dict = db.build();
9674 let mut ib = GraphIndexBuilder::new().with_tile_budget(256);
9675 for (s, p, o) in &triples {
9676 ib.push(dict.encode(s, p, o).unwrap());
9677 }
9678 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
9679
9680 let rete = Rete::open(&bytes).unwrap();
9682 assert_eq!(rete.dump_iter(None).collect::<Vec<_>>(), rete.dump(None));
9683 assert_eq!(rete.dump_iter(Some("http://ex/nope")).count(), 0);
9685
9686 let read_bytes = |take: usize| -> u64 {
9688 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
9689 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
9690 let rete = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
9691 let before = reader.bytes_read();
9692 let n = rete.dump_iter(None).take(take).count();
9693 assert_eq!(n, take.min(triples.len()));
9694 assert!(!rete.index_incomplete());
9695 reader.bytes_read() - before
9696 };
9697 let first_only = read_bytes(1);
9698 let everything = read_bytes(triples.len());
9699 assert!(
9701 first_only < everything,
9702 "dump_iter is not lazy: one triple read {first_only} B, a full scan {everything} B"
9703 );
9704 #[cfg(feature = "compression")]
9711 assert!(
9712 first_only * 2 < everything,
9713 "dump_iter is not lazy: one triple read {first_only} B of the {everything} B a full scan reads"
9714 );
9715
9716 let fresh = Rete::open(&bytes).unwrap();
9721 let drain = |max_quads: usize| {
9726 let (mut out, mut cursor, mut calls) = (Vec::new(), 0u32, 0);
9727 loop {
9728 let (batch, next, done) = fresh.dump_batch(None, cursor, max_quads);
9729 out.extend(batch);
9730 cursor = next;
9731 calls += 1;
9732 assert!(calls < 10_000, "cursor failed to advance");
9733 if done {
9734 break out;
9735 }
9736 }
9737 };
9738 let eager = fresh.dump(None);
9739 for max in [1usize, 7, 128, 100_000] {
9740 assert_eq!(drain(max), eager, "batch size {max} changed the dump");
9741 }
9742 let (t, _, done) = fresh.dump_batch(Some("http://ex/nope"), 0, 16);
9745 assert!(t.is_empty() && done);
9746 }
9747
9748 #[test]
9756 fn query_batch_matches_query_in_graph_and_stops_early() {
9757 use crate::reader::{CountingReader, SliceReader};
9758
9759 let triples: Vec<(String, String, String)> = (0..2000u32)
9762 .map(|i| {
9763 (
9764 format!("<http://ex/s/{:04}>", i / 2),
9765 format!("<http://ex/p/{}>", i % 2),
9766 format!("<http://ex/o/{i:04}>"),
9767 )
9768 })
9769 .collect();
9770 let mut db = DictionaryBuilder::new();
9771 for (s, p, o) in &triples {
9772 db.observe(s, p, o);
9773 }
9774 let dict = db.build();
9775 let mut ib = GraphIndexBuilder::new().with_tile_budget(256);
9776 for (s, p, o) in &triples {
9777 ib.push(dict.encode(s, p, o).unwrap());
9778 }
9779 let bytes = write_file(&dict, &ib.build(), false, &[], 0);
9780 let rete = Rete::open(&bytes).unwrap();
9781
9782 let drain = |s: Option<&str>, p: Option<&str>, o: Option<&str>, max: usize| {
9783 let (mut out, mut cursor, mut calls) = (Vec::new(), 0u64, 0);
9784 loop {
9785 let (batch, next, done) = rete.query_batch(None, s, p, o, cursor, max);
9786 assert!(!batch.is_empty() || done, "empty non-final batch");
9789 out.extend(batch);
9790 cursor = next;
9791 calls += 1;
9792 assert!(calls < 20_000, "cursor failed to advance");
9793 if done {
9794 break out;
9795 }
9796 }
9797 };
9798 let shapes: [(Option<&str>, Option<&str>, Option<&str>); 6] = [
9799 (None, None, None),
9800 (Some("<http://ex/s/0007>"), None, None),
9801 (None, Some("<http://ex/p/1>"), None),
9802 (None, None, Some("<http://ex/o/0042>")),
9803 (Some("<http://ex/s/0007>"), Some("<http://ex/p/0>"), None),
9804 (
9805 Some("<http://ex/s/0007>"),
9806 Some("<http://ex/p/0>"),
9807 Some("<http://ex/o/0014>"),
9808 ),
9809 ];
9810 for (s, p, o) in shapes {
9811 let eager = rete.query_in_graph(None, s, p, o);
9812 assert!(
9813 !eager.is_empty(),
9814 "fixture shape {s:?} {p:?} {o:?} matches nothing"
9815 );
9816 assert_eq!(
9818 rete.query_iter(None, s, p, o).collect::<Vec<_>>(),
9819 eager,
9820 "query_iter disagrees for {s:?} {p:?} {o:?}"
9821 );
9822 for max in [1usize, 3, 64, 100_000] {
9823 let mut got = drain(s, p, o, max);
9824 let mut want = eager.clone();
9825 got.sort();
9828 want.sort();
9829 assert_eq!(got, want, "batch size {max} changed {s:?} {p:?} {o:?}");
9830 }
9831 if s.is_none() && p.is_none() && o.is_none() {
9833 assert_eq!(drain(s, p, o, 7), eager, "unbound batching reordered rows");
9834 }
9835 }
9836
9837 let (t, _, done) = rete.query_batch(None, Some("<http://ex/nope>"), None, None, 0, 16);
9840 assert!(t.is_empty() && done);
9841 let (t, _, done) = rete.query_batch(Some("http://ex/nope"), None, None, None, 0, 16);
9842 assert!(t.is_empty() && done);
9843 assert_eq!(
9844 rete.query_iter(None, Some("<http://ex/nope>"), None, None)
9845 .count(),
9846 0
9847 );
9848
9849 let read_bytes = |take: usize| -> u64 {
9852 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
9853 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
9854 let rete = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
9855 let before = reader.bytes_read();
9856 let (mut n, mut cursor) = (0usize, 0u64);
9857 loop {
9858 let (batch, next, done) = rete.query_batch(None, None, None, None, cursor, 1);
9859 n += batch.len();
9860 cursor = next;
9861 if done || n >= take {
9862 break;
9863 }
9864 }
9865 assert!(n >= take.min(triples.len()));
9866 assert!(!rete.index_incomplete());
9867 reader.bytes_read() - before
9868 };
9869 let first_only = read_bytes(1);
9870 let everything = read_bytes(triples.len());
9871 assert!(
9872 first_only < everything,
9873 "query_batch is not lazy: one row read {first_only} B, a full scan {everything} B"
9874 );
9875 #[cfg(feature = "compression")]
9876 assert!(
9877 first_only * 2 < everything,
9878 "query_batch is not lazy: one row read {first_only} B of the {everything} B a full scan reads"
9879 );
9880 }
9881
9882 #[test]
9885 fn query_batch_is_graph_scoped() {
9886 let mut db = DictionaryBuilder::new();
9887 for (s, p, o) in [
9888 ("Alice", "knows", "Bob"),
9889 ("Alice", "knows", "Carol"),
9890 ("Alice", "knows", "Dave"),
9891 ("Erin", "knows", "Frank"),
9892 ("Alice", "knows", "Zoe"),
9893 ] {
9894 db.observe(s, p, o);
9895 }
9896 let dict = db.build();
9897 let mut def = GraphIndexBuilder::new();
9898 def.push(dict.encode("Alice", "knows", "Bob").unwrap());
9899 def.push(dict.encode("Alice", "knows", "Carol").unwrap());
9900 let mut g1 = GraphIndexBuilder::new();
9901 g1.push(dict.encode("Alice", "knows", "Dave").unwrap());
9902 g1.push(dict.encode("Erin", "knows", "Frank").unwrap());
9903 let mut g2 = GraphIndexBuilder::new();
9904 g2.push(dict.encode("Alice", "knows", "Zoe").unwrap());
9905 let named = vec![
9906 ("http://ex/g1".to_string(), g1.build()),
9907 ("http://ex/g2".to_string(), g2.build()),
9908 ];
9909 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
9910 let rete = Rete::open(&bytes).unwrap();
9911 for graph in [None, Some("http://ex/g1"), Some("http://ex/g2")] {
9912 let eager = rete.query_in_graph(graph, None, None, None);
9913 let (mut out, mut cursor) = (Vec::new(), 0u64);
9914 loop {
9915 let (batch, next, done) = rete.query_batch(graph, None, None, None, cursor, 1);
9916 out.extend(batch);
9917 cursor = next;
9918 if done {
9919 break;
9920 }
9921 }
9922 assert_eq!(out, eager, "graph {graph:?} batched differently");
9923 }
9924 }
9925
9926 #[test]
9927 fn query_in_graph_is_graph_scoped() {
9928 let mut db = DictionaryBuilder::new();
9931 for (s, p, o) in [
9932 ("Alice", "knows", "Bob"),
9933 ("Alice", "knows", "Carol"),
9934 ("Alice", "knows", "Dave"),
9935 ] {
9936 db.observe(s, p, o);
9937 }
9938 let dict = db.build();
9939
9940 let mut def = GraphIndexBuilder::new();
9941 def.push(dict.encode("Alice", "knows", "Bob").unwrap());
9942 def.push(dict.encode("Alice", "knows", "Carol").unwrap());
9943 let mut g1 = GraphIndexBuilder::new();
9944 g1.push(dict.encode("Alice", "knows", "Dave").unwrap());
9945
9946 let named = vec![("http://ex/g1".to_string(), g1.build())];
9947 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
9948 let rete = Rete::open(&bytes).unwrap();
9949
9950 let mut def_objs: Vec<String> = rete
9952 .query_in_graph(None, Some("Alice"), Some("knows"), None)
9953 .into_iter()
9954 .map(|(_, _, o)| o)
9955 .collect();
9956 def_objs.sort();
9957 assert_eq!(def_objs, vec!["Bob".to_string(), "Carol".to_string()]);
9958
9959 assert_eq!(
9961 rete.query_in_graph(Some("http://ex/g1"), Some("Alice"), None, None),
9962 vec![("Alice".into(), "knows".into(), "Dave".into())]
9963 );
9964
9965 assert_eq!(rete.query_in_graph(None, None, None, None).len(), 2);
9967 assert_eq!(
9968 rete.query_in_graph(Some("http://ex/g1"), None, None, None)
9969 .len(),
9970 1
9971 );
9972
9973 assert!(rete
9975 .query_in_graph(Some("http://ex/missing"), None, None, None)
9976 .is_empty());
9977 }
9978
9979 #[test]
9992 fn bounded_query_in_graph_does_not_fault_the_whole_dictionary() {
9993 use crate::reader::{CountingReader, SliceReader};
9994
9995 let payload = |i: u32| -> String {
10001 let mut s = String::with_capacity(800);
10002 let mut x = i as u64 ^ 0x9e37_79b9_7f4a_7c15;
10003 while s.len() < 800 {
10004 x = x
10005 .wrapping_mul(6364136223846793005)
10006 .wrapping_add(1442695040888963407);
10007 s.push_str(&format!("{:016x}", x ^ (x >> 29)));
10008 }
10009 s
10010 };
10011 let quads: Vec<(String, String, String, bool)> = (0..2000u32)
10018 .map(|i| {
10019 let named = i % 2 == 0;
10020 let ns = if named { 'a' } else { 'b' };
10021 (
10022 format!("<http://ex/{ns}/s/{i:04}>"),
10023 "<http://ex/abstract>".to_string(),
10024 format!("\"{ns}{} number {i}\"", payload(i)),
10025 named,
10026 )
10027 })
10028 .collect();
10029 let mut db = DictionaryBuilder::new();
10030 for (s, p, o, _) in &quads {
10031 db.observe(s, p, o);
10032 }
10033 let dict = db.build();
10034 let mut def = GraphIndexBuilder::new().with_tile_budget(256);
10035 let mut g1 = GraphIndexBuilder::new().with_tile_budget(256);
10036 for (s, p, o, named) in &quads {
10037 let t = dict.encode(s, p, o).unwrap();
10038 if *named {
10039 g1.push(t);
10040 } else {
10041 def.push(t);
10042 }
10043 }
10044 let named = vec![("http://ex/g1".to_string(), g1.build())];
10045 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
10046
10047 let eager = Rete::open(&bytes).unwrap();
10048 let dict_len = eager.header().dictionary_len;
10049
10050 let leaked: &'static [u8] = Box::leak(bytes.clone().into_boxed_slice());
10053 let probe = |f: &dyn Fn(&Rete) -> Vec<TermTriple>| -> (Vec<TermTriple>, u64) {
10054 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
10055 let lazy = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
10056 let before = reader.bytes_read();
10057 let out = f(&lazy);
10058 assert!(!lazy.index_incomplete(), "a chunk fetch failed");
10059 (out, reader.bytes_read() - before)
10060 };
10061
10062 let want = eager.query_in_graph(
10064 Some("http://ex/g1"),
10065 Some("<http://ex/a/s/0100>"),
10066 None,
10067 None,
10068 );
10069 assert_eq!(want.len(), 1, "fixture: expected exactly one match");
10070 let (got, pulled) = probe(&|r| {
10071 r.query_in_graph(
10072 Some("http://ex/g1"),
10073 Some("<http://ex/a/s/0100>"),
10074 None,
10075 None,
10076 )
10077 });
10078 assert_eq!(got, want, "lazy query_in_graph disagrees with eager");
10079 assert!(
10080 pulled * 4 < dict_len,
10081 "a 1-row query_in_graph faulted {pulled} B of a {dict_len} B dictionary — \
10082 it is prefetching the whole thing again"
10083 );
10084
10085 let (empty, q_pulled) =
10093 probe(&|r| r.query_in_graph(Some("http://ex/nope"), None, None, None));
10094 assert!(empty.is_empty());
10095 let (_, d_pulled) = probe(&|r| {
10096 let mut n = 0usize;
10097 r.dump_each(Some("http://ex/nope"), |_, _, _| n += 1);
10098 assert_eq!(n, 0, "an absent graph yielded triples");
10099 Vec::new()
10100 });
10101 assert_eq!(
10102 q_pulled, d_pulled,
10103 "query_in_graph and dump_each disagree on what an absent graph costs"
10104 );
10105 assert!(
10106 q_pulled * 4 < dict_len,
10107 "an absent graph faulted {q_pulled} B of a {dict_len} B dictionary"
10108 );
10109
10110 let want: Vec<TermTriple> = eager.dump(Some("http://ex/g1"));
10113 assert_eq!(want.len(), 1000);
10114 let (got, pulled) = probe(&|r| {
10115 let mut out = Vec::new();
10116 r.dump_each(Some("http://ex/g1"), |s, p, o| {
10117 out.push((s.to_string(), p.to_string(), o.to_string()))
10118 });
10119 out
10120 });
10121 assert_eq!(got, want, "lazy dump_each disagrees with eager dump");
10122 assert!(
10123 pulled * 3 < dict_len * 2,
10124 "dumping half the graph faulted {pulled} B of a {dict_len} B dictionary — \
10125 the other graph's chunks are being pulled in too"
10126 );
10127 }
10128
10129 #[cfg(test)]
10134 fn build_multichunk_image() -> Vec<u8> {
10135 use crate::index::PermSet;
10136 let mut db = DictionaryBuilder::new();
10137 let mut triples: Vec<(String, String, String)> = (0..4000u32)
10138 .map(|i| {
10139 (
10140 format!("<http://ex/s/{i:07}>"),
10141 format!("<http://ex/p/{}>", i % 8),
10142 format!("\"object literal number {i:07} with padding text to widen the term\""),
10143 )
10144 })
10145 .collect();
10146 triples.push((
10147 "<http://ex/s/big>".to_string(),
10148 "<http://ex/p/big>".to_string(),
10149 format!("\"{}\"", "Z".repeat(8000)),
10150 ));
10151 for (s, p, o) in &triples {
10152 db.observe(s, p, o);
10153 }
10154 let dict = db.build();
10155 let mut idx = GraphIndexBuilder::new()
10156 .with_tile_budget(64)
10157 .with_perms(PermSet::ALL);
10158 for (s, p, o) in &triples {
10159 idx.push(dict.encode(s, p, o).unwrap());
10160 }
10161 write_dataset(&dict, &idx.build(), &[], true, &[], 0)
10162 }
10163
10164 #[test]
10173 fn tiny_dict_cache_evicts_yet_dump_is_byte_identical() {
10174 use crate::reader::SliceReader;
10175 let leaked: &'static [u8] = Box::leak(build_multichunk_image().into_boxed_slice());
10176 let dump = |cap: u64| -> (
10177 Vec<(String, String, String)>,
10178 crate::chunk_cache::CacheStats,
10179 ) {
10180 let rete =
10181 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64).unwrap();
10182 rete.dict.set_cache_cap(cap);
10183 let mut out = Vec::new();
10184 rete.dump_filtered_each(None, None, None, None, |s, p, o| {
10185 out.push((s.to_string(), p.to_string(), o.to_string()))
10186 });
10187 assert!(
10188 !rete.index_incomplete(),
10189 "no lazy fault should fail at cap {cap}"
10190 );
10191 let stats = rete.dict_cache_stats();
10192 (out, stats)
10193 };
10194
10195 let (unlimited, us) = dump(u64::MAX);
10196 assert_eq!(unlimited.len(), 4001, "every triple dumped");
10197 assert_eq!(us.evictions, 0, "unlimited cap evicts nothing");
10198
10199 let (tiny, ts) = dump(128 * 1024);
10202 assert_eq!(tiny, unlimited, "128 KiB-cap dump differs from unlimited");
10203 assert!(ts.evictions > 0, "a tiny cap must evict (stats {ts:?})");
10204
10205 let (starved, ss) = dump(1);
10207 assert_eq!(starved, unlimited, "1-byte-cap dump differs from unlimited");
10208 assert!(
10209 ss.evictions > 0,
10210 "1-byte cap evicts every insert (stats {ss:?})"
10211 );
10212 }
10213
10214 #[test]
10225 fn memory_budget_charges_the_fixed_directories() {
10226 use crate::reader::SliceReader;
10227 let leaked: &'static [u8] = Box::leak(build_multichunk_image().into_boxed_slice());
10228 let rete =
10229 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64).unwrap();
10230
10231 let fixed = rete.fixed_overhead();
10232 assert!(
10235 fixed.dict_directory > 0 && fixed.index_directory > 0,
10236 "{fixed:?}"
10237 );
10238 assert_eq!(fixed.named_graphs, 0, "no named graphs in this file");
10239 assert_eq!(
10240 fixed.total(),
10241 fixed.dict_directory + fixed.index_directory + fixed.named_graphs
10242 );
10243
10244 let total: u64 = 512 << 20;
10247 let applied = rete.set_memory_budget(Some(total));
10248 let plain = split_memory_budget(total);
10249 assert_eq!(applied.dict_cache, plain.dict_cache - fixed.total());
10250 assert_eq!(rete.dict_cache_cap(), applied.dict_cache);
10251 assert_eq!(applied.tile_cache, plain.tile_cache);
10252 assert_eq!(applied.block_cache, plain.block_cache);
10253 assert!(
10254 applied.dict_cache + applied.tile_cache + applied.block_cache + fixed.total() <= total,
10255 "caps + fixed directories exceed the budget: {applied:?} + {fixed:?} > {total}"
10256 );
10257
10258 let applied = rete.set_memory_budget(Some(1 << 20));
10260 assert_eq!(applied.dict_cache, MIN_DICT_CACHE_CAP);
10261
10262 let applied = rete.set_memory_budget(None);
10264 assert_eq!(applied.dict_cache, u64::MAX);
10265 assert_eq!(rete.dict_cache_cap(), u64::MAX);
10266
10267 let rete =
10270 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64).unwrap();
10271 rete.dict.set_cache_cap(128 * 1024);
10272 let mut rows = 0usize;
10273 rete.dump_filtered_each(None, None, None, None, |_, _, _| rows += 1);
10274 assert_eq!(rows, 4001);
10275 let s = rete.dict_cache_stats();
10276 assert!(s.evictions > 0, "the cap must bind: {s:?}");
10277 assert!(
10280 s.entries <= 1 || s.resident_bytes <= 128 * 1024,
10281 "dictionary cache over its cap after the dump: {s:?}"
10282 );
10283 }
10284
10285 #[test]
10290 fn releasing_a_named_graph_drops_and_reopens_its_index() {
10291 use crate::index::PermSet;
10292 use crate::reader::SliceReader;
10293 let mut db = DictionaryBuilder::new();
10294 let all: Vec<(String, String, String)> = (0..40u32)
10295 .map(|i| {
10296 (
10297 format!("<http://ex/s{}>", i % 7),
10298 format!("<http://ex/p{}>", i % 3),
10299 format!("<http://ex/o{}>", i % 5),
10300 )
10301 })
10302 .collect();
10303 for (s, p, o) in &all {
10304 db.observe(s, p, o);
10305 }
10306 let dict = db.build();
10307 let mk = |take: fn(u32) -> bool| {
10308 let mut g = GraphIndexBuilder::new()
10309 .with_tile_budget(16)
10310 .with_perms(PermSet::ALL);
10311 for (i, (s, p, o)) in all.iter().enumerate() {
10312 if take(i as u32) {
10313 g.push(dict.encode(s, p, o).unwrap());
10314 }
10315 }
10316 g.build()
10317 };
10318 let def = mk(|_| true);
10319 let g1 = mk(|i| i % 2 == 0);
10320 let g2 = mk(|i| i % 3 == 0);
10321 let image = write_dataset(
10322 &dict,
10323 &def,
10324 &[
10325 ("<http://ex/g1>".to_string(), g1),
10326 ("<http://ex/g2>".to_string(), g2),
10327 ],
10328 true,
10329 &[],
10330 0,
10331 );
10332 let leaked: &'static [u8] = Box::leak(image.into_boxed_slice());
10333 let mut rete =
10334 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64).unwrap();
10335
10336 let opened = |r: &Rete| -> usize {
10337 match &r.named_graphs {
10338 NamedGraphsSlot::Lazy(l) => {
10339 let mut n = 0;
10340 l.for_each_opened(|_| n += 1);
10341 n
10342 }
10343 _ => 0,
10344 }
10345 };
10346
10347 assert_eq!(opened(&rete), 0, "nothing opened before first touch");
10348 assert!(rete.graph_index("<http://ex/g1>").is_some());
10350 assert_eq!(opened(&rete), 1, "g1 opened");
10351 rete.release_named_graph("<http://ex/g1>");
10353 assert_eq!(opened(&rete), 0, "g1 released");
10354 rete.release_named_graph("<http://ex/absent>");
10356 rete.release_named_graph("<http://ex/g1>");
10357 assert_eq!(opened(&rete), 0);
10358 assert!(rete.graph_index("<http://ex/g1>").is_some());
10360 assert_eq!(opened(&rete), 1, "g1 re-opened after release");
10361 }
10362
10363 #[test]
10381 fn filtered_dump_is_exactly_the_unfiltered_dump_filtered() {
10382 use crate::index::PermSet;
10383 use crate::reader::SliceReader;
10384
10385 let terms = |i: u32| {
10386 (
10387 format!("<http://ex/s{}>", i % 11),
10388 format!("<http://ex/p{}>", i % 3),
10389 if i.is_multiple_of(4) {
10393 format!("\"lit {}\"@en", i % 5)
10394 } else {
10395 format!("<http://ex/o{}>", i % 7)
10396 },
10397 )
10398 };
10399 let build = |perms: PermSet| {
10400 let mut db = DictionaryBuilder::new();
10401 let all: Vec<_> = (0..90u32).map(terms).collect();
10402 for (s, p, o) in &all {
10403 db.observe(s, p, o);
10404 }
10405 let dict = db.build();
10406 let mut def = GraphIndexBuilder::new()
10407 .with_tile_budget(16)
10408 .with_perms(perms);
10409 let mut g1 = GraphIndexBuilder::new()
10410 .with_tile_budget(16)
10411 .with_perms(perms);
10412 for (i, (s, p, o)) in all.iter().enumerate() {
10413 let t = dict.encode(s, p, o).unwrap();
10414 if i % 2 == 0 {
10418 g1.push(t);
10419 }
10420 def.push(t);
10421 }
10422 write_dataset(
10423 &dict,
10424 &def.build(),
10425 &[("<http://ex/g1>".to_string(), g1.build())],
10426 true,
10427 &[],
10428 0,
10429 )
10430 };
10431
10432 let shapes: Vec<(Option<&str>, Option<&str>, Option<&str>)> = vec![
10433 (None, None, None),
10434 (Some("<http://ex/s3>"), None, None),
10435 (None, Some("<http://ex/p1>"), None),
10436 (None, None, Some("<http://ex/o5>")),
10437 (None, None, Some("\"lit 0\"@en")),
10438 (Some("<http://ex/s3>"), Some("<http://ex/p0>"), None),
10439 (Some("<http://ex/s4>"), None, Some("<http://ex/o4>")),
10440 (None, Some("<http://ex/p1>"), Some("<http://ex/o5>")),
10441 (
10442 Some("<http://ex/s3>"),
10443 Some("<http://ex/p0>"),
10444 Some("<http://ex/o3>"),
10445 ),
10446 (Some("<http://ex/nope>"), None, None),
10450 (None, Some("<http://ex/nope>"), None),
10451 (None, None, Some("<http://ex/nope>")),
10452 ];
10453
10454 let mut any_pruned = false;
10455 for perms in [PermSet::ALL, PermSet::CORE] {
10456 let image = build(perms);
10457 let leaked: &'static [u8] = Box::leak(image.clone().into_boxed_slice());
10458 let opens: Vec<(&str, Rete)> = vec![
10459 ("resident", Rete::open(&image).unwrap()),
10460 (
10461 "ranged",
10462 Rete::open_ranged(&SliceReader::new(leaked)).unwrap(),
10463 ),
10464 (
10465 "lazy",
10466 Rete::open_ranged_lazy_with(SliceReader::new(leaked), HEADER_LEN as u64)
10467 .unwrap(),
10468 ),
10469 ];
10470 for graph in [None, Some("<http://ex/g1>"), Some("<http://ex/absent>")] {
10471 let full: Vec<TermTriple> = {
10473 let mut v = Vec::new();
10474 Rete::open(&image).unwrap().dump_each(graph, |s, p, o| {
10475 v.push((s.to_string(), p.to_string(), o.to_string()))
10476 });
10477 v.sort();
10478 v
10479 };
10480 for &(s, p, o) in &shapes {
10481 let mut want = full.clone();
10482 want.retain(|(ts, tp, to)| {
10483 s.is_none_or(|x| x == ts)
10484 && p.is_none_or(|x| x == tp)
10485 && o.is_none_or(|x| x == to)
10486 });
10487 for (path, rete) in &opens {
10488 let mut got = Vec::new();
10489 rete.dump_filtered_each(graph, s, p, o, |s, p, o| {
10490 got.push((s.to_string(), p.to_string(), o.to_string()))
10491 });
10492 got.sort();
10493 assert_eq!(
10494 got,
10495 want,
10496 "{path}/{perms:?} graph={graph:?} pattern={:?} — filtered dump \
10497 is not the unfiltered dump filtered",
10498 (s, p, o)
10499 );
10500 assert!(!rete.index_incomplete(), "{path}: a fetch failed");
10501 }
10502 let plan = opens[2].1.dump_plan(graph, s, p, o);
10506 if graph == Some("<http://ex/absent>")
10507 || [s, p, o].contains(&Some("<http://ex/nope>"))
10508 {
10509 assert!(
10510 plan.scan.is_none(),
10511 "an unmatchable dump still planned a scan: {:?}",
10512 (graph, s, p, o)
10513 );
10514 } else {
10515 let scan = plan.scan.expect("a matchable dump plans a scan");
10516 assert!(
10517 PermSet::CORE.contains(scan.permutation),
10518 "a dump routed to {:?}, outside PermSet::CORE — a \
10519 --permutations 3 file has no such section",
10520 scan.permutation
10521 );
10522 assert!(scan.tiles_admitted <= scan.tiles_routed);
10523 assert!(scan.tiles_routed <= scan.tiles_total);
10524 assert!(scan.tile_bytes <= scan.section_bytes);
10525 if scan.tiles_admitted < scan.tiles_total {
10526 any_pruned = true;
10527 }
10528 }
10529 }
10530 }
10531 }
10532 assert!(
10533 any_pruned,
10534 "no shape pruned a single tile — the fixture is too small to be \
10535 measuring anything"
10536 );
10537 }
10538
10539 #[test]
10549 fn a_predicate_scoped_dump_fetches_less_than_the_graph() {
10550 use crate::reader::{CountingReader, SliceReader};
10551
10552 let mut db = DictionaryBuilder::new();
10558 let mut all = Vec::new();
10559 for s in 0..200u32 {
10560 for p in 0..20u32 {
10561 let t = (
10562 format!("<http://ex/s/{s:04}>"),
10563 format!("<http://ex/p/{p:02}>"),
10564 format!("\"object {s:04}/{p:02}\""),
10565 );
10566 db.observe(&t.0, &t.1, &t.2);
10567 all.push(t);
10568 }
10569 }
10570 let dict = db.build();
10571 let mut ib = GraphIndexBuilder::new().with_tile_budget(64);
10572 for (s, p, o) in &all {
10573 ib.push(dict.encode(s, p, o).unwrap());
10574 }
10575 let image = write_dataset(&dict, &ib.build(), &[], false, &[], 0);
10576 let leaked: &'static [u8] = Box::leak(image.clone().into_boxed_slice());
10577
10578 let probe = |s: Option<&str>, p: Option<&str>, o: Option<&str>| -> (usize, u64) {
10580 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
10581 let lazy = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
10582 let before = reader.bytes_read();
10583 let mut n = 0usize;
10584 lazy.dump_filtered_each(None, s, p, o, |_, _, _| n += 1);
10585 assert!(!lazy.index_incomplete());
10586 (n, reader.bytes_read() - before)
10587 };
10588
10589 let (full_rows, full_bytes) = probe(None, None, None);
10590 let (pred_rows, pred_bytes) = probe(None, Some("<http://ex/p/07>"), None);
10591 let (subj_rows, subj_bytes) = probe(Some("<http://ex/s/0021>"), None, None);
10592 assert_eq!(full_rows, 4000);
10593 assert_eq!(pred_rows, 200, "one predicate covers every subject once");
10594 assert_eq!(subj_rows, 20);
10595 assert!(
10597 pred_bytes < full_bytes && subj_bytes < full_bytes,
10598 "a slice fetched {pred_bytes} / {subj_bytes} B where the whole graph fetched \
10599 {full_bytes} B — the scan is not being pruned at all"
10600 );
10601 #[cfg(feature = "compression")]
10612 assert!(
10613 pred_bytes * 4 < full_bytes && subj_bytes * 4 < full_bytes,
10614 "a 1-in-20 predicate slice fetched {pred_bytes} B and one subject \
10615 {subj_bytes} B where the whole graph fetched {full_bytes} B"
10616 );
10617
10618 let reader = std::sync::Arc::new(CountingReader::new(SliceReader::new(leaked)));
10620 let lazy = Rete::open_ranged_lazy_with(reader.clone(), HEADER_LEN as u64).unwrap();
10621 let before = reader.bytes_read();
10622 let plan = lazy
10623 .dump_plan(None, None, Some("<http://ex/p/07>"), None)
10624 .scan
10625 .expect("a known predicate plans a scan");
10626 assert!(
10627 reader.bytes_read() - before < 64 * 1024,
10628 "planning fetched {} B — it is supposed to read directories, not tiles",
10629 reader.bytes_read() - before
10630 );
10631 assert!(plan.tiles_admitted < plan.tiles_total);
10632 assert!(
10638 plan.tile_bytes * 5 < plan.section_bytes,
10639 "one predicate of twenty planned {} B of a {} B section",
10640 plan.tile_bytes,
10641 plan.section_bytes
10642 );
10643 }
10644
10645 #[test]
10646 fn query_quads_tags_every_graph() {
10647 let mut db = DictionaryBuilder::new();
10648 for (s, p, o) in [("Alice", "knows", "Bob"), ("Alice", "knows", "Dave")] {
10649 db.observe(s, p, o);
10650 }
10651 let dict = db.build();
10652 let mut def = GraphIndexBuilder::new();
10653 def.push(dict.encode("Alice", "knows", "Bob").unwrap());
10654 let mut g1 = GraphIndexBuilder::new();
10655 g1.push(dict.encode("Alice", "knows", "Dave").unwrap());
10656 let named = vec![("http://ex/g1".to_string(), g1.build())];
10657 let bytes = write_dataset(&dict, &def.build(), &named, true, &[], 0);
10658 let rete = Rete::open(&bytes).unwrap();
10659
10660 let quads = rete.query_quads(Some("Alice"), Some("knows"), None);
10662 assert_eq!(quads.len(), 2);
10663 assert_eq!(
10664 quads[0],
10665 (("Alice".into(), "knows".into(), "Bob".into()), None)
10666 );
10667 assert_eq!(
10668 quads[1],
10669 (
10670 ("Alice".into(), "knows".into(), "Dave".into()),
10671 Some("http://ex/g1".to_string())
10672 )
10673 );
10674
10675 assert!(rete.query_quads(Some("Nobody"), None, None).is_empty());
10677 }
10678
10679 #[test]
10680 fn pyramid_meta_round_trips_in_file() {
10681 let rete = Rete::open(&build_image()).unwrap();
10682 let pyr = rete.pyramid().expect("file has a pyramid");
10683 let total: u32 = pyr.summary.iter().map(|e| e.count).sum();
10685 assert_eq!(total, 3);
10686 assert!(!pyr.summary.is_empty());
10687 assert!(pyr.tiles.is_empty());
10688 }
10689
10690 #[test]
10691 fn schema_pyramid_round_trips_through_file_index_free() {
10692 use crate::reader::{CountingReader, SliceReader};
10693 let sub = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
10694 let q = |s: &str, p: &str, o: &str| {
10695 (s.to_string(), p.to_string(), o.to_string(), None::<String>)
10696 };
10697 let quads = vec![
10699 q("<a>", RDF_TYPE, "<Astronomer>"),
10700 q("<b>", RDF_TYPE, "<Astronomer>"),
10701 q("<c>", RDF_TYPE, "<Person>"),
10702 q("<Astronomer>", sub, "<Scientist>"),
10703 q("<Scientist>", sub, "<Person>"),
10704 q("<Person>", sub, "<Agent>"),
10705 q("<a>", "<knows>", "<b>"),
10706 q("<b>", "<knows>", "<c>"),
10707 ];
10708 let (bytes, _) =
10709 crate::ingest::assemble_dataset_with_opts(quads, true, false, None, |_, _| Vec::new());
10710
10711 let rete = Rete::open(&bytes).unwrap();
10713 let pyr = rete.pyramid().expect("pyramid present");
10714 assert!(!pyr.level_rollups.is_empty(), "schema pyramid shipped");
10715 assert!(pyr
10716 .class_hierarchy
10717 .iter()
10718 .any(|n| n.class == "<Agent>" && n.depth == 0));
10719
10720 let r = CountingReader::new(SliceReader::new(&bytes));
10722 let view = SummaryView::open_ranged(&r).unwrap().unwrap();
10723 assert!(view.level_count() >= 2, "multi-level pyramid");
10724 let coarse = view.level_rollup(0).unwrap();
10725 assert!(
10726 coarse.classes.iter().any(|(c, _)| c == "<Agent>"),
10727 "coarsest level rolls up to the root Agent"
10728 );
10729 let h = Header::from_bytes(&bytes).unwrap();
10730 assert!(
10731 r.bytes_read() <= bytes.len() as u64 - h.root_dir_len,
10732 "summary read {} bytes; the {}-byte index section must be skipped",
10733 r.bytes_read(),
10734 h.root_dir_len
10735 );
10736 }
10737
10738 #[test]
10739 fn predicate_totals_from_summary_only() {
10740 use crate::reader::SliceReader;
10741 let bytes = build_image();
10743 let reader = SliceReader::new(&bytes);
10744 let view = SummaryView::open_ranged(&reader).unwrap().unwrap();
10745 assert_eq!(view.predicate_total("knows"), 2);
10746 assert_eq!(view.predicate_total("age"), 1);
10747 assert_eq!(view.predicate_total("missing"), 0);
10748 let totals = view.predicate_totals();
10749 assert_eq!(totals[0], ("knows".to_string(), 2)); }
10751
10752 #[test]
10753 fn query_patterns_resolve_to_terms() {
10754 let rete = Rete::open(&build_image()).unwrap();
10755
10756 assert_eq!(rete.query(None, None, None).len(), 3);
10758
10759 let mut alice = rete.query(Some("Alice"), None, None);
10761 alice.sort();
10762 assert_eq!(
10763 alice,
10764 vec![
10765 ("Alice".into(), "age".into(), "30".into()),
10766 ("Alice".into(), "knows".into(), "Bob".into()),
10767 ]
10768 );
10769
10770 assert_eq!(rete.query(None, Some("knows"), None).len(), 2);
10772
10773 assert_eq!(
10775 rete.query(Some("Bob"), Some("knows"), Some("Carol")),
10776 vec![("Bob".into(), "knows".into(), "Carol".into())]
10777 );
10778 assert!(rete.query(Some("Nobody"), None, None).is_empty());
10779 assert!(rete.query(None, Some("likes"), None).is_empty());
10780 }
10781
10782 #[test]
10783 fn query_provenance_reports_terms_ids_sections_and_index_choice() {
10784 let bytes = build_image();
10785 let rete = Rete::open(&bytes).unwrap();
10786
10787 let mut matches = rete.query_with_provenance(None, Some("knows"), None);
10788 matches.sort_by(|a, b| a.terms.cmp(&b.terms));
10789
10790 assert_eq!(matches.len(), 2);
10791 assert_eq!(
10792 matches[0].terms,
10793 ("Alice".into(), "knows".into(), "Bob".into())
10794 );
10795 assert_eq!(
10796 matches[0].ids,
10797 rete.dictionary().encode("Alice", "knows", "Bob").unwrap()
10798 );
10799 assert_eq!(matches[0].graph.as_deref(), None);
10800 assert_eq!(
10801 matches[0].matched_pattern,
10802 (None, Some(matches[0].ids.1), None)
10803 );
10804 assert_eq!(
10805 matches[0].index_permutation,
10806 crate::index::IndexPermutation::Pos
10807 );
10808
10809 let h = rete.header();
10810 assert_eq!(matches[0].dictionary_range.offset, h.dictionary_offset);
10811 assert_eq!(matches[0].dictionary_range.len, h.dictionary_len);
10812 assert_eq!(matches[0].index_range.offset, h.root_dir_offset);
10813 assert_eq!(matches[0].index_range.len, h.root_dir_len);
10814 assert!(
10815 matches[0].index_section_range.offset > h.root_dir_offset,
10816 "POS is section 1, so its payload starts after the container header and SPO payload"
10817 );
10818 assert!(matches[0].index_section_range.len > 0);
10819 assert!(matches[0].index_section_range.end() <= matches[0].index_range.end());
10820 assert!(matches[0].index_section_range.len < matches[0].index_range.len);
10821 assert_eq!(
10822 matches[0].pyramid_range.as_ref().map(|r| (r.offset, r.len)),
10823 Some((h.pyramid_meta_offset, h.pyramid_meta_len))
10824 );
10825 let tile_range = matches[0].tile_range.expect("tiled file reports a tile");
10828 assert!(matches[0]
10829 .tile
10830 .as_deref()
10831 .unwrap()
10832 .starts_with(matches[0].index_permutation.name()));
10833 assert!(matches[0].index_section_range.offset <= tile_range.offset);
10834 assert!(tile_range.end() <= matches[0].index_section_range.end());
10835 }
10836
10837 fn build_labeled(n: usize) -> Vec<u8> {
10841 const LABEL: &str = "<http://www.w3.org/2000/01/rdf-schema#label>";
10842 const WORDS: &[&str] = &[
10843 "alanine",
10844 "benzene",
10845 "glucose",
10846 "dextrose",
10847 "ethanol",
10848 "formate",
10849 "heptane",
10850 "isoleucine",
10851 ];
10852 let triples: Vec<(String, String, String)> = (0..n)
10853 .flat_map(|i| {
10854 let s = format!("<http://ex/e{i}>");
10855 let w = WORDS[i % WORDS.len()];
10856 [
10857 (s.clone(), LABEL.to_string(), format!("\"{w}-{i:06}\"")),
10858 (
10859 s,
10860 "<http://ex/p>".to_string(),
10861 format!("<http://ex/c{}>", i % 64),
10862 ),
10863 ]
10864 })
10865 .collect();
10866 let mut db = DictionaryBuilder::new();
10867 for (s, p, o) in &triples {
10868 db.observe(s, p, o);
10869 }
10870 let dict = db.build();
10871 let ids: Vec<(u32, u32, u32)> = triples
10872 .iter()
10873 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
10874 .collect();
10875 let mut ib = GraphIndexBuilder::new();
10876 for &t in &ids {
10877 ib.push(t);
10878 }
10879 let (meta, levels) = build_pyramid_meta(&dict, &ids, DEFAULT_TILE_BUDGET);
10880 write_file(&dict, &ib.build(), false, &meta, levels)
10881 }
10882
10883 #[test]
10884 fn prefix_search_matches_a_filter_scan() {
10885 let bytes = build_labeled(800);
10888 let rete = Rete::open(&bytes).unwrap();
10889 let idx_subjects: std::collections::BTreeSet<String> = rete
10890 .prefix_search("glucose", 10_000)
10891 .into_iter()
10892 .map(|(_label, subject)| subject)
10893 .collect();
10894 let q = "SELECT ?s WHERE { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?l \
10896 FILTER(STRSTARTS(LCASE(?l), \"glucose\")) }";
10897 let crate::QueryOutput::Select(_, rows) = crate::eval_query(&rete, q).unwrap() else {
10898 panic!("expected SELECT");
10899 };
10900 let scan_subjects: std::collections::BTreeSet<String> =
10901 rows.iter().map(|r| r.get("s").cloned().unwrap()).collect();
10902 assert_eq!(idx_subjects, scan_subjects, "index agrees with the scan");
10903 assert_eq!(
10904 idx_subjects.len(),
10905 100,
10906 "800/8 words = 100 glucose-* labels"
10907 );
10908 }
10909
10910 #[test]
10914 fn legacy_label_hits_resolve_in_one_batched_read() {
10915 use std::sync::{Arc, Mutex};
10916 type CallLog = Arc<Mutex<Vec<Vec<(u64, u64)>>>>;
10917 #[derive(Clone)]
10918 struct Calls(Arc<Vec<u8>>, CallLog);
10919 impl crate::RangeReader for Calls {
10920 fn len(&self) -> u64 {
10921 self.0.len() as u64
10922 }
10923 fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
10924 self.1.lock().unwrap().push(vec![(offset, len)]);
10925 crate::SliceReader::new(&self.0).read_at(offset, len)
10926 }
10927 fn read_many(&self, ranges: &[(u64, u64)]) -> std::io::Result<Vec<Vec<u8>>> {
10928 self.1.lock().unwrap().push(ranges.to_vec());
10929 let r = crate::SliceReader::new(&self.0);
10930 ranges.iter().map(|&(o, l)| r.read_at(o, l)).collect()
10931 }
10932 }
10933 let bytes = build_labeled(20_000);
10934 let h = Header::from_bytes(&bytes).unwrap();
10935 let (d0, dl) = (h.dictionary_offset, h.dictionary_len);
10936 let want = Rete::open(&bytes).unwrap().prefix_search("glucose", 1000);
10937 assert_eq!(want.len(), 1000);
10938 for search_view in [false, true] {
10939 let calls = Calls(Arc::new(bytes.clone()), Arc::new(Mutex::new(Vec::new())));
10940 let got = if search_view {
10941 let view = SearchView::open_ranged_with(calls.clone(), HEADER_LEN as u64).unwrap();
10942 calls.1.lock().unwrap().clear();
10943 view.prefix_search("glucose", 1000)
10944 } else {
10945 let rete = Rete::open_ranged_lazy_with(calls.clone(), HEADER_LEN as u64).unwrap();
10946 calls.1.lock().unwrap().clear();
10947 rete.prefix_search("glucose", 1000)
10948 };
10949 assert_eq!(got, want, "search view = {search_view}");
10950 let dict_reads = calls
10951 .1
10952 .lock()
10953 .unwrap()
10954 .iter()
10955 .filter(|c| c.iter().any(|&(o, l)| o < d0 + dl && d0 < o + l))
10956 .count();
10957 assert_eq!(dict_reads, 1, "search view = {search_view}");
10958 }
10959 }
10960
10961 #[test]
10965 #[ignore]
10966 fn bench_prefix_search_vs_filter_scan() {
10967 use std::time::Instant;
10968 let n = 6000; let bytes = build_labeled(n);
10970 let rete = Rete::open(&bytes).unwrap();
10971 let q = "SELECT ?s WHERE { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?l \
10972 FILTER(STRSTARTS(LCASE(?l), \"glucose\")) }";
10973 let reps = 200;
10974 let idx_n = rete.prefix_search("glucose", 100_000).len();
10975 let t = Instant::now();
10976 for _ in 0..reps {
10977 std::hint::black_box(rete.prefix_search("glucose", 100_000));
10978 }
10979 let idx_ms = t.elapsed().as_secs_f64() * 1000.0 / reps as f64;
10980 let t = Instant::now();
10981 for _ in 0..reps {
10982 let _ = std::hint::black_box(crate::eval_query(&rete, q).unwrap());
10983 }
10984 let scan_ms = t.elapsed().as_secs_f64() * 1000.0 / reps as f64;
10985 println!(
10986 "label prefix search over {n} labeled subjects ({idx_n} matches): \
10987 index {idx_ms:.4} ms vs FILTER scan {scan_ms:.3} ms ({:.0}× faster)",
10988 scan_ms / idx_ms
10989 );
10990 }
10991
10992 #[test]
10996 #[ignore]
10997 fn bench_text_search_vs_contains_scan() {
10998 use std::time::Instant;
10999 const LABEL: &str = "<http://www.w3.org/2000/01/rdf-schema#label>";
11000 const WORDS: &[&str] = &[
11001 "alanine",
11002 "benzene",
11003 "glucose",
11004 "dextrose",
11005 "ethanol",
11006 "formate",
11007 "heptane",
11008 "isoleucine",
11009 ];
11010 let n = 6000;
11011 let triples: Vec<(String, String, String)> = (0..n)
11012 .map(|i| {
11013 (
11014 format!("<http://ex/e{i}>"),
11015 LABEL.to_string(),
11016 format!("\"{} sample number {i:06}\"", WORDS[i % WORDS.len()]),
11017 )
11018 })
11019 .collect();
11020 let mut db = DictionaryBuilder::new();
11021 for (s, p, o) in &triples {
11022 db.observe(s, p, o);
11023 }
11024 let dict = db.build();
11025 let ids: Vec<(u32, u32, u32)> = triples
11026 .iter()
11027 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
11028 .collect();
11029 let mut ib = GraphIndexBuilder::new();
11030 for &t in &ids {
11031 ib.push(t);
11032 }
11033 let ti = compute_text_index(&dict, &ids);
11034 let bytes = write_dataset_with_metadata(&dict, &ib.build(), &[], false, &[], 0, &[], &ti);
11035 let rete = Rete::open(&bytes).unwrap();
11036
11037 let q = "SELECT ?s WHERE { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?l \
11038 FILTER(CONTAINS(LCASE(?l), \"glucose\")) }";
11039 let reps = 200;
11040 let idx_n = rete.text_search(&["glucose"], None, 100_000).len();
11041 let t = Instant::now();
11042 for _ in 0..reps {
11043 std::hint::black_box(rete.text_search(&["glucose"], None, 100_000));
11044 }
11045 let idx_ms = t.elapsed().as_secs_f64() * 1000.0 / reps as f64;
11046 let t = Instant::now();
11047 for _ in 0..reps {
11048 let _ = std::hint::black_box(crate::eval_query(&rete, q).unwrap());
11049 }
11050 let scan_ms = t.elapsed().as_secs_f64() * 1000.0 / reps as f64;
11051 println!(
11052 "text search over {n} literals ({idx_n} matches): \
11053 index {idx_ms:.4} ms vs FILTER(CONTAINS) scan {scan_ms:.3} ms ({:.0}× faster)",
11054 scan_ms / idx_ms
11055 );
11056 }
11057
11058 #[test]
11062 #[ignore = "operational tool, driven by RETE_DEBUG_* env vars"]
11063 fn debug_bound_po_routing() {
11064 struct FR(std::fs::File);
11065 impl crate::RangeReader for FR {
11066 fn len(&self) -> u64 {
11067 self.0.metadata().map(|m| m.len()).unwrap_or(0)
11068 }
11069 fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
11070 use std::os::unix::fs::FileExt;
11071 let mut buf = vec![0u8; len as usize];
11072 self.0.read_exact_at(&mut buf, offset)?;
11073 Ok(buf)
11074 }
11075 }
11076 let path = std::env::var("RETE_DEBUG_FILE").expect("RETE_DEBUG_FILE");
11077 let p_iri = std::env::var("RETE_DEBUG_P").expect("RETE_DEBUG_P");
11078 let o_iri = std::env::var("RETE_DEBUG_O").expect("RETE_DEBUG_O");
11079 let rete = Rete::open_ranged_lazy_with(
11080 std::sync::Arc::new(FR(std::fs::File::open(&path).unwrap())),
11081 HEADER_LEN as u64,
11082 )
11083 .unwrap();
11084 let pid = rete.dict.predicate_id(&p_iri).expect("p resolves");
11085 let oid = rete.dict.object_id(&o_iri).expect("o resolves");
11086 eprintln!("pid={pid} oid={oid}");
11087 let pattern = (None, Some(pid), Some(oid));
11088 let perm = GraphIndex::best_permutation(pattern);
11089 eprintln!("best_permutation = {}", perm.name());
11090 let si = perm.section_index();
11091 let tiles = &rete.index.sections[si];
11092 eprintln!("section {} tiles = {}", perm.name(), tiles.len());
11093 let [pa, pb, pc] = perm.order_pattern(pattern);
11094 eprintln!("permuted pattern pa={pa:?} pb={pb:?} pc={pc:?}");
11095 let (start, end) = rete.index.tile_span(si, pa);
11096 eprintln!("tile_span = [{start}, {end}) -> {} tiles", end - start);
11097 let mut admitted = 0usize;
11098 for (ti, t) in tiles.iter().enumerate().take(end).skip(start) {
11099 if t.syn_admits(pb, pc) {
11100 admitted += 1;
11101 if admitted <= 10 {
11102 let (lo, hi) = t.leading_range();
11103 eprintln!(" admit tile {ti}: a=[{lo},{hi}] syn={:?}", t.syn);
11104 }
11105 }
11106 }
11107 eprintln!("admitted {admitted} tile(s) by synopsis");
11108 let n = rete.index.scan_iter(pattern).count();
11109 eprintln!("scan_iter matches = {n}");
11110 let hi_res = rete.query(None, Some(&p_iri), Some(&o_iri));
11111 eprintln!("high-level query matches = {}", hi_res.len());
11112 }
11113
11114 #[test]
11122 fn layout_header_label_matches_its_span() {
11123 let mut db = DictionaryBuilder::new();
11124 let mut triples = Vec::new();
11125 for i in 0..24u32 {
11126 let (s, p, o) = (
11127 format!("<http://ex/s{}>", i % 5),
11128 format!("<http://ex/p{}>", i % 3),
11129 format!("<http://ex/o{i}>"),
11130 );
11131 db.observe(&s, &p, &o);
11132 triples.push((s, p, o));
11133 }
11134 let dict = db.build();
11135 let ids: Vec<(u32, u32, u32)> = triples
11136 .iter()
11137 .map(|(s, p, o)| dict.encode(s, p, o).unwrap())
11138 .collect();
11139 let index = GraphIndexBuilder::from_triples(ids).build();
11140 let image = write_dataset_with_metadata(
11141 &dict,
11142 &index,
11143 &[],
11144 false,
11145 &[],
11146 0,
11147 br#"{"name":"layout-label-fixture"}"#,
11148 &[],
11149 );
11150 let rete = Rete::open(&image).unwrap();
11151
11152 let layout = rete.file_layout();
11153 let header = layout
11154 .iter()
11155 .find(|s| s.kind == "header")
11156 .expect("every layout starts with a header segment");
11157
11158 assert_eq!(
11159 header.offset, 0,
11160 "the header is the first thing in the file"
11161 );
11162 assert_eq!(
11163 header.len, HEADER_LEN as u64,
11164 "the header segment must span exactly HEADER_LEN"
11165 );
11166
11167 let digits: String = header
11170 .label
11171 .chars()
11172 .skip_while(|c| !c.is_ascii_digit())
11173 .take_while(|c| c.is_ascii_digit())
11174 .collect();
11175 assert!(
11176 !digits.is_empty(),
11177 "header label {:?} states no size at all",
11178 header.label
11179 );
11180 assert_eq!(
11181 digits.parse::<u64>().unwrap(),
11182 header.len,
11183 "header label {:?} disagrees with the {}-byte span it describes",
11184 header.label,
11185 header.len
11186 );
11187
11188 assert!(
11191 layout.windows(2).all(|w| w[0].offset <= w[1].offset),
11192 "file_layout must return segments sorted by offset"
11193 );
11194 }
11195}