rete_core/index.rs
1//! Permutation index set (SPO / POS / OSP) over integer triples (SPEC.md §6).
2//!
3//! The three orders together answer every triple-pattern shape: for any subset
4//! of bound `(s, p, o)` components, at least one permutation sorts those bound
5//! components into a leading prefix, turning the lookup into a range scan.
6//!
7//! Each permutation is **tiled** (format v0.2): consecutive runs of whole
8//! a-groups packed to a byte budget ([`INDEX_TILE_BUDGET`]), each tile a
9//! self-contained [`TripleBlock`]. A bound leading id routes to exactly one
10//! tile (binary search over the tile ranges), then jumps to its a-group via
11//! the tile's lazily-built [`GroupDirectory`]; unbound scans chain all tiles
12//! with per-tile zone-map pruning. On disk each tile is compressed
13//! independently, so a ranged reader can fetch just the tiles a query needs.
14//! v0.1 single-block sections are still read (one tile per permutation).
15
16use std::sync::Arc;
17
18use crate::chunk_cache::{CacheEntry, ChunkCache};
19use crate::triples::{GroupDirectory, Triple, TripleBlock, TripleBlockBuilder};
20
21/// A triple pattern: `None` is an unbound variable, `Some(id)` a bound term.
22pub type Pattern = (Option<u32>, Option<u32>, Option<u32>);
23
24/// Default per-tile budget in (uncompressed) encoded bytes. Tiles are the
25/// independently-compressed, independently-fetchable units of a permutation
26/// section: ~64 KiB matches both zstd's sweet spot and one HTTP range read.
27pub const INDEX_TILE_BUDGET: usize = 64 * 1024;
28
29/// Geometric tile-prefetch ramp for an unbound (multi-tile) scan (see
30/// [`GraphIndex::scan_iter`]). The first coalesced batch faults this many
31/// tiles; each subsequent batch doubles up to [`PREFETCH_WINDOW_MAX`]. Small
32/// enough that `LIMIT 1` fetches only a few tiles, large enough that a full
33/// scan still coalesces into a handful of range reads.
34const PREFETCH_WINDOW_START: usize = 4;
35const PREFETCH_WINDOW_MAX: usize = 512;
36
37/// Fetches one tile's (uncompressed) block image on demand: the bridge that
38/// lets a remote `GraphIndex` fault tiles in over a `RangeReader` without this
39/// module knowing about I/O. `None` = the fetch failed; the index records the
40/// failure ([`GraphIndex::load_incomplete`]) and the scan sees an empty tile —
41/// callers running over remote data MUST check the flag after evaluating.
42pub type TileLoader = Box<dyn Fn(usize, usize) -> Option<Vec<u8>> + Send + Sync>;
43
44/// Fetches **many** tiles of one section in one round trip: given the section
45/// and the (ascending) indices of the tiles wanted, returns each tile's
46/// uncompressed block image in the same order. The ranged reader implements
47/// this by coalescing byte-adjacent tile ranges into single range reads, so a
48/// full-section scan costs a handful of requests instead of one per tile.
49/// `None` = the batch failed as a whole; callers fall back to the per-tile
50/// [`TileLoader`] (which records per-tile failures).
51pub type TileBulkLoader = Box<dyn Fn(usize, &[usize]) -> Option<Vec<Vec<u8>>> + Send + Sync>;
52
53/// One tile of a permutation section: a fully self-contained [`TripleBlock`]
54/// over a consecutive run of whole a-groups, plus the leading-id range it
55/// covers (for routing without parsing or fetching) and its lazily-built group
56/// directory (for intra-tile point lookups). The block image itself may be
57/// local (built/decoded eagerly) or faulted in by the index's [`TileLoader`].
58pub struct Tile {
59 min_a: u32,
60 max_a: u32,
61 /// Optional **tile synopsis**: the inclusive min/max of the two non-leading
62 /// columns `(min_b, max_b, min_c, max_c)`, read from the directory trailer of
63 /// a synopsis-carrying file. Lets a scan prune this tile by a bound secondary
64 /// component *before* faulting it (remote reads). `None` = no synopsis (an
65 /// older file, or a locally-built/opened tile) — then nothing is pruned early
66 /// and the in-tile zone map prunes after the tile is in hand, as before.
67 pub(crate) syn: Option<(u32, u32, u32, u32)>,
68 /// Encoded byte length of this tile (compressed on-disk size for a remote
69 /// tile, in-memory image size for a local one; 0 = unknown). Feeds the join
70 /// planner's fatness gates without faulting any data.
71 len: u32,
72 /// Build-time staging only: a locally-built or locally-decoded tile's body
73 /// waits here until [`GraphIndex::from_sections`] moves it into the shared
74 /// [`ChunkCache`] (keyed by `(section, tile)`) and clears it. `None`
75 /// afterward, and for a remote tile whose body faults in through the loader.
76 /// The long-lived retention is the cache, not this field.
77 staged: Option<Vec<u8>>,
78}
79
80impl Tile {
81 fn local(min_a: u32, max_a: u32, bytes: Vec<u8>) -> Self {
82 let len = bytes.len().min(u32::MAX as usize) as u32;
83 Tile {
84 min_a,
85 max_a,
86 syn: None,
87 len,
88 staged: Some(bytes),
89 }
90 }
91
92 fn remote(min_a: u32, max_a: u32, syn: Option<(u32, u32, u32, u32)>) -> Self {
93 Tile {
94 min_a,
95 max_a,
96 syn,
97 len: 0,
98 staged: None,
99 }
100 }
101
102 /// Encoded byte length (see the field doc); falls back to a still-staged
103 /// body's size when the directory didn't provide one.
104 pub(crate) fn encoded_len(&self) -> u64 {
105 if self.len > 0 {
106 self.len as u64
107 } else {
108 self.staged.as_ref().map_or(0, |d| d.len() as u64)
109 }
110 }
111
112 /// Leading-component (permuted `a`) range this tile covers, inclusive.
113 pub fn leading_range(&self) -> (u32, u32) {
114 (self.min_a, self.max_a)
115 }
116
117 /// Could this tile hold a triple with the given bound non-leading components,
118 /// per its synopsis? `true` when there is no synopsis (can't rule it out) or
119 /// the bound `b`/`c` fall inside the recorded ranges. Conservative: a `false`
120 /// is a *proven* miss (the in-tile zone map would reject the same tile), so
121 /// skipping the fetch never drops a result.
122 pub(crate) fn syn_admits(&self, pb: Option<u32>, pc: Option<u32>) -> bool {
123 match self.syn {
124 None => true,
125 Some((min_b, max_b, min_c, max_c)) => {
126 let ok = |v: Option<u32>, lo: u32, hi: u32| v.is_none_or(|x| lo <= x && x <= hi);
127 ok(pb, min_b, max_b) && ok(pc, min_c, max_c)
128 }
129 }
130 }
131}
132
133/// What a routed scan of one pattern will touch, from the tile directories
134/// alone — see [`GraphIndex::scan_plan`].
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub struct ScanPlan {
137 /// The permutation the scan routes to (always inside [`PermSet::CORE`]).
138 pub permutation: IndexPermutation,
139 /// Tiles in that permutation's section — the denominator.
140 pub tiles_total: usize,
141 /// Tiles left after routing on the bound leading component.
142 pub tiles_routed: usize,
143 /// Tiles left after the synopsis prune — what the scan will actually fetch.
144 pub tiles_admitted: usize,
145 /// Encoded (on-disk) bytes of the admitted tiles: the index-side upper
146 /// bound on the scan's range reads.
147 pub tile_bytes: u64,
148 /// Encoded bytes of the whole section — what an unpruned scan would read.
149 pub section_bytes: u64,
150}
151
152/// Which stored permutation to scan. The full **six** orders (a SPARQL engine's
153/// classic set, as in QLever): together they sort the triples on *every* prefix
154/// of `(s, p, o)` columns, so for any bound-component prefix and any free
155/// component there is a permutation that routes on the prefix **and** yields the
156/// stream sorted on that free component — the precondition for a merge join.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum IndexPermutation {
159 Spo,
160 Sop,
161 Pso,
162 Pos,
163 Osp,
164 Ops,
165}
166
167/// The number of permutations the format can address (the width of every
168/// per-permutation array). How many a *given file* stores is its [`PermSet`].
169pub(crate) const NUM_PERMS: usize = 6;
170
171/// The six permutations in section order — the canonical iteration list. The
172/// original three (SPO, POS, OSP) lead, so a default scan's tie-break (and its
173/// provenance) is unchanged from the 3-permutation format; the three added orders
174/// (SOP, PSO, OPS) follow and exist to give a merge join a stream sorted on the
175/// join key.
176pub(crate) const ALL_PERMS: [IndexPermutation; NUM_PERMS] = [
177 IndexPermutation::Spo,
178 IndexPermutation::Pos,
179 IndexPermutation::Osp,
180 IndexPermutation::Sop,
181 IndexPermutation::Pso,
182 IndexPermutation::Ops,
183];
184
185/// **Which** permutations a file stores — a 6-bit set over
186/// [`IndexPermutation::section_index`], recorded in the header so a reader
187/// never has to assume six.
188///
189/// Every legal set is a superset of [`PermSet::CORE`] = {SPO, POS, OSP}. That
190/// is not a convention: those three **tie the longest bound prefix on all eight
191/// triple-pattern shapes**, so [`GraphIndex::best_permutation`] never selects
192/// outside them and a lean file routes every pattern exactly where a full one
193/// does — same tiles, same rows. What the other three (SOP, PSO, OPS) add is a
194/// *sort order*: they let [`GraphIndex::permutation_sorted_on`] hand a
195/// sort-merge join a co-sorted stream for three of the twelve
196/// (bound-set, join-column) shapes it otherwise has to hash-join. Absent, the
197/// merge seed declines and the hash path answers — the cost is a fast path,
198/// never correctness (`bgp::try_merge_join` already returns `Option`).
199///
200/// `CORE` is the smallest legal set, [`PermSet::ALL`] is the default and what
201/// every file written before this existed carries.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
203pub struct PermSet(u8);
204
205impl Default for PermSet {
206 fn default() -> Self {
207 PermSet::ALL
208 }
209}
210
211impl PermSet {
212 /// All six permutations — the default, and what a `0` header byte means.
213 pub const ALL: PermSet = PermSet(0b0011_1111);
214 /// The three routing permutations {SPO, POS, OSP}: every pattern shape
215 /// routes as well as it does with six, no merge-join sort orders.
216 pub const CORE: PermSet = PermSet(0b0000_0111);
217
218 /// Parse a raw mask. `Err` when it is not a superset of [`PermSet::CORE`]
219 /// or addresses a permutation this build has no section index for — a
220 /// pattern would then route to a permutation the file does not carry, which
221 /// is the one failure mode that must never be silent.
222 pub fn from_bits(bits: u8) -> Result<PermSet, &'static str> {
223 if bits & !PermSet::ALL.0 != 0 {
224 return Err("permutation mask addresses more than six permutations");
225 }
226 if bits & PermSet::CORE.0 != PermSet::CORE.0 {
227 return Err("permutation mask must contain SPO, POS and OSP");
228 }
229 Ok(PermSet(bits))
230 }
231
232 /// The raw 6-bit mask.
233 pub fn bits(self) -> u8 {
234 self.0
235 }
236
237 /// Is `perm` stored in this file?
238 pub fn contains(self, perm: IndexPermutation) -> bool {
239 self.0 & (1 << perm.section_index()) != 0
240 }
241
242 /// How many permutation sections the file's index container holds.
243 pub fn len(self) -> usize {
244 self.0.count_ones() as usize
245 }
246
247 /// Never true: every legal set contains [`PermSet::CORE`]. Present because
248 /// a public `len` without it is a clippy error, and the honest answer is
249 /// more useful than an `allow`.
250 pub fn is_empty(self) -> bool {
251 false
252 }
253
254 /// The stored permutations in [`ALL_PERMS`] (= container) order.
255 pub fn iter(self) -> impl Iterator<Item = IndexPermutation> {
256 ALL_PERMS.into_iter().filter(move |p| self.contains(*p))
257 }
258
259 /// `perm`'s position **inside the index container**, which is its rank
260 /// among the stored permutations — not [`IndexPermutation::section_index`],
261 /// which is its slot in the format's fixed six-wide addressing. The two
262 /// coincide only for [`PermSet::ALL`].
263 pub fn position(self, perm: IndexPermutation) -> Option<usize> {
264 self.contains(perm)
265 .then(|| (self.0 & ((1u8 << perm.section_index()) - 1)).count_ones() as usize)
266 }
267
268 /// Names in container order, e.g. `["SPO", "POS", "OSP"]`.
269 pub fn names(self) -> Vec<&'static str> {
270 self.iter().map(|p| p.name()).collect()
271 }
272
273 /// Does this set carry the three merge-join orders?
274 pub fn has_merge_orders(self) -> bool {
275 self == PermSet::ALL
276 }
277}
278
279impl IndexPermutation {
280 /// Stable display name used in CLI diagnostics and provenance records.
281 pub fn name(self) -> &'static str {
282 match self {
283 IndexPermutation::Spo => "SPO",
284 IndexPermutation::Sop => "SOP",
285 IndexPermutation::Pso => "PSO",
286 IndexPermutation::Pos => "POS",
287 IndexPermutation::Osp => "OSP",
288 IndexPermutation::Ops => "OPS",
289 }
290 }
291
292 /// Section number inside the stored permutation container.
293 pub fn section_index(self) -> usize {
294 match self {
295 IndexPermutation::Spo => 0,
296 IndexPermutation::Pos => 1,
297 IndexPermutation::Osp => 2,
298 IndexPermutation::Sop => 3,
299 IndexPermutation::Pso => 4,
300 IndexPermutation::Ops => 5,
301 }
302 }
303
304 /// The canonical `(s, p, o)` roles in this permutation's `(a, b, c)` slots,
305 /// as indices (0=s, 1=p, 2=o). The single source of truth for `forward` /
306 /// `back` / `order_pattern`.
307 pub(crate) const fn roles(self) -> [usize; 3] {
308 match self {
309 IndexPermutation::Spo => [0, 1, 2],
310 IndexPermutation::Sop => [0, 2, 1],
311 IndexPermutation::Pso => [1, 0, 2],
312 IndexPermutation::Pos => [1, 2, 0],
313 IndexPermutation::Osp => [2, 0, 1],
314 IndexPermutation::Ops => [2, 1, 0],
315 }
316 }
317
318 /// Map a canonical `(s, p, o)` triple into this permutation's `(a, b, c)`.
319 pub(crate) fn forward(self, t: Triple) -> Triple {
320 let c = [t.0, t.1, t.2];
321 let r = self.roles();
322 (c[r[0]], c[r[1]], c[r[2]])
323 }
324
325 /// Map a stored `(a, b, c)` back to canonical `(s, p, o)`.
326 fn back(self, abc: Triple) -> Triple {
327 let a = [abc.0, abc.1, abc.2];
328 let r = self.roles();
329 let mut out = [0u32; 3];
330 out[r[0]] = a[0];
331 out[r[1]] = a[1];
332 out[r[2]] = a[2];
333 (out[0], out[1], out[2])
334 }
335
336 /// The pattern's bound components in this permutation's component order.
337 pub(crate) fn order_pattern(self, p: Pattern) -> [Option<u32>; 3] {
338 let c = [p.0, p.1, p.2];
339 let r = self.roles();
340 [c[r[0]], c[r[1]], c[r[2]]]
341 }
342
343 /// Length of the leading run of bound components — higher is more selective.
344 fn leading_bound(self, pat: Pattern) -> usize {
345 self.order_pattern(pat)
346 .iter()
347 .take_while(|c| c.is_some())
348 .count()
349 }
350}
351
352/// Build a [`GraphIndex`] from canonical `(s, p, o)` integer triples.
353pub struct GraphIndexBuilder {
354 triples: Vec<Triple>,
355 tile_budget: usize,
356 perms: PermSet,
357}
358
359impl Default for GraphIndexBuilder {
360 fn default() -> Self {
361 Self {
362 triples: Vec::new(),
363 tile_budget: INDEX_TILE_BUDGET,
364 perms: PermSet::ALL,
365 }
366 }
367}
368
369impl GraphIndexBuilder {
370 pub fn new() -> Self {
371 Self::default()
372 }
373
374 /// Build directly from an owned triple vector — moves it in, avoiding the
375 /// per-triple `push` copy when the caller already has the id-triples in a
376 /// `Vec` (the assembly path, where they double as the pyramid input).
377 pub fn from_triples(triples: Vec<Triple>) -> Self {
378 Self {
379 triples,
380 tile_budget: INDEX_TILE_BUDGET,
381 perms: PermSet::ALL,
382 }
383 }
384
385 /// Override the per-tile byte budget (tests use tiny budgets to force
386 /// multi-tile sections on small data).
387 pub fn with_tile_budget(mut self, bytes: usize) -> Self {
388 self.tile_budget = bytes.max(1);
389 self
390 }
391
392 /// Build only the permutations in `perms` (default [`PermSet::ALL`]).
393 /// Sections outside the set come out empty and are not written to the file.
394 pub fn with_perms(mut self, perms: PermSet) -> Self {
395 self.perms = perms;
396 self
397 }
398
399 pub fn push(&mut self, t: Triple) {
400 self.triples.push(t);
401 }
402
403 /// Build the six permutations **one at a time** (each permutation's internal
404 /// sort still uses every core), so only a single permuted copy of the triples
405 /// is resident at once instead of all six concurrently. Trades the cross-
406 /// permutation parallelism of [`Self::build`] for a much lower peak RAM — the
407 /// large-graph low-memory path. Output is byte-identical to [`Self::build`].
408 pub fn build_seq(self) -> GraphIndex {
409 let triples = &self.triples;
410 let budget = self.tile_budget;
411 let wanted: Vec<IndexPermutation> = self.perms.iter().collect();
412 // Permute (parallel) + sort (parallel inside `build_tiles`) one permutation
413 // at a time, so only a single permuted copy of the triples is resident — but
414 // every core is still busy. Process permutations in batches of two to
415 // overlap one permutation's tile-building with the next one's sort while
416 // keeping the resident permuted copies to two. Byte-identical to `build`.
417 let build_one = |perm: IndexPermutation| -> Vec<Tile> {
418 #[cfg(feature = "parallel")]
419 let permuted: Vec<Triple> = {
420 use rayon::prelude::*;
421 triples.par_iter().map(|&t| perm.forward(t)).collect()
422 };
423 #[cfg(not(feature = "parallel"))]
424 let permuted: Vec<Triple> = triples.iter().map(|&t| perm.forward(t)).collect();
425 build_tiles(permuted, budget)
426 };
427 #[cfg(feature = "parallel")]
428 let built: Vec<Vec<Tile>> = {
429 use rayon::prelude::*;
430 let mut built: Vec<Vec<Tile>> = Vec::with_capacity(wanted.len());
431 for chunk in wanted.chunks(2) {
432 built.extend(
433 chunk
434 .to_vec()
435 .into_par_iter()
436 .map(build_one)
437 .collect::<Vec<_>>(),
438 );
439 }
440 built
441 };
442 #[cfg(not(feature = "parallel"))]
443 let built: Vec<Vec<Tile>> = wanted.iter().copied().map(build_one).collect();
444 GraphIndex::from_sections(scatter(&wanted, built), self.perms)
445 }
446
447 pub fn build(self) -> GraphIndex {
448 let wanted: Vec<IndexPermutation> = self.perms.iter().collect();
449 let triples = &self.triples;
450 let budget = self.tile_budget;
451 // The permutations are independent — permute + sort + tile each.
452 let build_one = move |perm: IndexPermutation| -> Vec<Tile> {
453 let permuted: Vec<Triple> = triples.iter().map(|&t| perm.forward(t)).collect();
454 build_tiles(permuted, budget)
455 };
456 // Build the permutations concurrently when the `parallel` feature is on
457 // (they share no state); the per-permutation sort inside is also
458 // parallel. Output is byte-identical to the serial path.
459 #[cfg(feature = "parallel")]
460 let built: Vec<Vec<Tile>> = {
461 use rayon::iter::{IntoParallelIterator, ParallelIterator};
462 wanted.clone().into_par_iter().map(build_one).collect()
463 };
464 #[cfg(not(feature = "parallel"))]
465 let built: Vec<Vec<Tile>> = wanted.iter().copied().map(build_one).collect();
466 GraphIndex::from_sections(scatter(&wanted, built), self.perms)
467 }
468}
469
470/// Place each built section at its permutation's fixed [`IndexPermutation::section_index`]
471/// slot, leaving unbuilt permutations empty. The array stays six wide however
472/// few permutations a file carries, so every `sections[perm.section_index()]`
473/// in the engine keeps working unchanged.
474fn scatter(wanted: &[IndexPermutation], built: Vec<Vec<Tile>>) -> [Vec<Tile>; NUM_PERMS] {
475 let mut sections: [Vec<Tile>; NUM_PERMS] = Default::default();
476 for (perm, tiles) in wanted.iter().zip(built) {
477 sections[perm.section_index()] = tiles;
478 }
479 sections
480}
481
482/// The encoded varint length of `v` (LEB128).
483fn varint_len(mut v: u64) -> usize {
484 let mut n = 1;
485 while v >= 0x80 {
486 v >>= 7;
487 n += 1;
488 }
489 n
490}
491
492/// Incremental encoded-size accounting for one a-group of a tiled section —
493/// the running-delta chain of [`build_tiles`], streamable triple by triple.
494/// Shared by the in-memory tiler here and the external build's streaming
495/// tiler ([`crate::extbuild`]) so both choose IDENTICAL tile boundaries and
496/// their outputs stay byte-identical.
497pub(crate) struct GroupSizer {
498 /// finalized contributions: the a-delta plus every closed b-run
499 size: usize,
500 num_b: u64,
501 cur_b: u32,
502 /// the open b-run's c count / last c
503 num_c: u64,
504 prev_c: u32,
505 empty: bool,
506}
507
508impl GroupSizer {
509 /// Start a group for leading id `a` whose delta base is `prev_a` (the
510 /// previous group's leading id; `a` again for a mid-group continuation).
511 pub(crate) fn start(a: u32, prev_a: u32) -> Self {
512 GroupSizer {
513 size: varint_len((a - prev_a) as u64),
514 num_b: 0,
515 cur_b: 0,
516 num_c: 0,
517 prev_c: 0,
518 empty: true,
519 }
520 }
521
522 /// Account one `(b, c)` of this group; returns the group's total encoded
523 /// size so far (open count varints included).
524 pub(crate) fn push(&mut self, b: u32, c: u32) -> usize {
525 if self.empty || b != self.cur_b {
526 if self.empty {
527 self.size += varint_len(b as u64); // first b-run: delta from 0
528 } else {
529 self.size += varint_len(self.num_c); // close the previous b-run
530 self.size += varint_len((b - self.cur_b) as u64);
531 }
532 self.cur_b = b;
533 self.num_c = 0;
534 self.prev_c = 0;
535 self.num_b += 1;
536 self.empty = false;
537 }
538 self.size += varint_len((c - self.prev_c) as u64);
539 self.prev_c = c;
540 self.num_c += 1;
541 self.total()
542 }
543
544 /// The group's total encoded size so far.
545 pub(crate) fn total(&self) -> usize {
546 self.size
547 + if self.empty {
548 0
549 } else {
550 varint_len(self.num_c)
551 }
552 + varint_len(self.num_b)
553 }
554}
555
556/// Split sorted, deduped permuted triples into size-targeted tiles: append
557/// whole a-groups until the (estimated, near-exact) encoded size would exceed
558/// `budget`, then flush — and additionally cut WITHIN an a-group whose own
559/// running size exceeds the budget (a mega-group: one predicate or class
560/// carrying a large share of the graph, e.g. a 2B-triple `cites` predicate in
561/// POS). Split slices become consecutive tiles sharing the leading id — a
562/// bound leading id routes to the whole run of covering tiles (see
563/// [`GraphIndex::tile_span`]) — which bounds both builder memory and the
564/// bytes a remote reader faults for one lookup. Boundary accounting lives in
565/// [`GroupSizer`], shared with the external build for byte-identity.
566fn build_tiles(mut triples: Vec<Triple>, budget: usize) -> Vec<Tile> {
567 #[cfg(feature = "parallel")]
568 {
569 use rayon::slice::ParallelSliceMut;
570 triples.par_sort_unstable();
571 }
572 #[cfg(not(feature = "parallel"))]
573 triples.sort_unstable();
574 triples.dedup();
575 if triples.is_empty() {
576 return Vec::new();
577 }
578
579 let make_tile = |run: &[Triple]| -> Tile {
580 let mut b = TripleBlockBuilder::new();
581 for &t in run {
582 b.push(t);
583 }
584 Tile::local(run[0].0, run[run.len() - 1].0, b.build())
585 };
586
587 let mut tiles = Vec::new();
588 let mut tile_start = 0usize;
589 let mut tile_size = 0usize; // completed groups in the current tile
590 let mut prev_a = 0u32;
591 let mut i = 0usize;
592 while i < triples.len() {
593 let a = triples[i].0;
594 let mut slice_start = i; // group start, or the last mid-group cut
595 let mut sizer = GroupSizer::start(a, prev_a);
596 let mut gtotal = 0usize;
597 while i < triples.len() && triples[i].0 == a {
598 gtotal = sizer.push(triples[i].1, triples[i].2);
599 i += 1;
600 if gtotal > budget {
601 // Mega-group cut: everything buffered — completed groups plus
602 // the slice measured so far — becomes one tile; the group
603 // continues in a fresh chain with `a` as its own delta base.
604 tiles.push(make_tile(&triples[tile_start..i]));
605 tile_start = i;
606 tile_size = 0;
607 prev_a = a;
608 slice_start = i;
609 sizer = GroupSizer::start(a, a);
610 gtotal = 0;
611 }
612 }
613 if slice_start == i {
614 continue; // the cut landed exactly on the group's end
615 }
616 if slice_start > tile_start && tile_size + gtotal > budget {
617 tiles.push(make_tile(&triples[tile_start..slice_start]));
618 tile_start = slice_start;
619 tile_size = 0;
620 }
621 tile_size += gtotal;
622 prev_a = a;
623 }
624 if tile_start < triples.len() {
625 tiles.push(make_tile(&triples[tile_start..]));
626 }
627 tiles
628}
629
630/// The six tiled permutation sections, queryable by triple pattern.
631pub struct GraphIndex {
632 /// Tiles per permutation (SPO, SOP, PSO, POS, OSP, OPS — see [`ALL_PERMS`]),
633 /// ascending in their leading-id ranges; consecutive tiles may share a
634 /// leading id when a mega-group was split (see [`build_tiles`]).
635 pub(crate) sections: [Vec<Tile>; NUM_PERMS],
636 /// Which of those six slots this file actually carries. Sections outside
637 /// the set are empty and must never be consulted — an empty section is
638 /// indistinguishable from an empty *graph*, which is why the planner asks
639 /// this rather than the section lengths.
640 perms: PermSet,
641 /// Faults in remote tiles on first scan (`None` for local indexes).
642 loader: Option<TileLoader>,
643 /// Optional batched fetch for multi-tile scans (`None` falls back to
644 /// one [`TileLoader`] call per tile).
645 bulk: Option<TileBulkLoader>,
646 /// Set when the loader failed for some tile: results may be incomplete and
647 /// the caller must surface an error rather than the partial answer.
648 load_failed: std::sync::atomic::AtomicBool,
649 /// The reader's concurrent-range fan-out (1 = strictly sequential) — see
650 /// [`set_read_concurrency`](Self::set_read_concurrency).
651 read_concurrency: usize,
652 /// Decompressed tile bodies live here, keyed by `(section, tile)`, faulted
653 /// in on first scan and evictable. Phase 0 caps it at unlimited, so a
654 /// scanned permutation stays resident exactly as it did in the old per-tile
655 /// `OnceLock`s.
656 cache: Arc<ChunkCache>,
657}
658
659impl GraphIndex {
660 fn from_sections(mut sections: [Vec<Tile>; NUM_PERMS], perms: PermSet) -> Self {
661 // Move every locally-built/decoded tile body into the shared cache and
662 // clear its staging slot, so the descriptors hold routing metadata only.
663 let cache = ChunkCache::unlimited_arc();
664 for (si, tiles) in sections.iter_mut().enumerate() {
665 for (ti, tile) in tiles.iter_mut().enumerate() {
666 if let Some(body) = tile.staged.take() {
667 cache.insert((si as u8, ti as u32), Arc::from(body));
668 }
669 }
670 }
671 GraphIndex {
672 sections,
673 perms,
674 loader: None,
675 bulk: None,
676 load_failed: std::sync::atomic::AtomicBool::new(false),
677 read_concurrency: 1,
678 cache,
679 }
680 }
681
682 /// Rebuild from tiled sections: per permutation, `(min_a, max_a, block
683 /// bytes)` per tile in ascending leading-id order — the v0.2 layout.
684 /// Slots outside `perms` must be empty.
685 pub fn from_tiles(sections: [Vec<(u32, u32, Vec<u8>)>; NUM_PERMS], perms: PermSet) -> Self {
686 let sections = sections.map(|tiles| {
687 tiles
688 .into_iter()
689 .map(|(min_a, max_a, bytes)| Tile::local(min_a, max_a, bytes))
690 .collect()
691 });
692 Self::from_sections(sections, perms)
693 }
694
695 /// The permutations this index carries.
696 pub fn perms(&self) -> PermSet {
697 self.perms
698 }
699
700 /// Set the byte cap of this index's tile cache (bounded-export phase 2).
701 /// `u64::MAX` (the open-time default) is unlimited — a scanned permutation
702 /// stays resident exactly as before. A finite cap evicts least-recently-used
703 /// tiles, so a full scan's tile residency is bounded.
704 ///
705 /// Only safe on an index whose tiles can be **re-faulted** (a remote/ranged
706 /// index with a loader). A locally-built index has no loader — an evicted
707 /// tile could never be reloaded — so the caller must not cap those; the
708 /// bounded-export path caps only the ranged default-graph index and leaves
709 /// resident named-graph indexes unlimited (released per slot instead).
710 pub fn set_cache_cap(&self, cap: u64) {
711 self.cache.set_cap(cap);
712 }
713
714 /// The current tile-cache byte cap (`u64::MAX` = unlimited).
715 pub fn cache_cap(&self) -> u64 {
716 self.cache.cap()
717 }
718
719 /// Does this index fault its tiles through a loader (a remote/ranged open)?
720 /// Only such an index is safe to give a finite tile-cache cap: a locally
721 /// decoded index has no loader, so an evicted tile could never be reloaded.
722 pub fn is_lazy(&self) -> bool {
723 self.loader.is_some()
724 }
725
726 /// A snapshot of the tile cache's observability counters.
727 pub fn cache_stats(&self) -> crate::chunk_cache::CacheStats {
728 self.cache.stats()
729 }
730
731 /// Heap bytes this index holds for as long as it is open, outside its tile
732 /// cache: one descriptor per tile of every permutation the file carries
733 /// (plus a tile's group directory, if a bound-leading lookup built one),
734 /// and — on a ranged open — the two copies of the per-tile byte ranges the
735 /// loaders capture. Grows with the tile count, never with what a scan
736 /// touches.
737 pub fn directory_bytes(&self) -> u64 {
738 let tiles: u64 = self.sections.iter().map(|s| s.len() as u64).sum();
739 let caps: u64 = self
740 .sections
741 .iter()
742 .map(|s| s.capacity() as u64)
743 .sum::<u64>()
744 * std::mem::size_of::<Tile>() as u64;
745 let ranges = if self.loader.is_some() {
746 2 * 24 * tiles
747 } else {
748 0
749 };
750 caps + ranges
751 }
752
753 /// A **remote** index: only the tile directories (leading-id ranges per
754 /// permutation, ascending) are known; tile payloads fault in through
755 /// `loader` on first scan. Check [`load_incomplete`](Self::load_incomplete)
756 /// after evaluating — a failed fetch must become an error, never a
757 /// silently smaller result.
758 #[allow(clippy::type_complexity)]
759 pub fn from_remote_directories(
760 directories: [Vec<(u32, u32, Option<(u32, u32, u32, u32)>)>; NUM_PERMS],
761 perms: PermSet,
762 loader: TileLoader,
763 ) -> Self {
764 let sections = directories.map(|dir| {
765 dir.into_iter()
766 .map(|(min_a, max_a, syn)| Tile::remote(min_a, max_a, syn))
767 .collect()
768 });
769 GraphIndex {
770 sections,
771 perms,
772 loader: Some(loader),
773 bulk: None,
774 load_failed: std::sync::atomic::AtomicBool::new(false),
775 read_concurrency: 1,
776 cache: ChunkCache::unlimited_arc(),
777 }
778 }
779
780 /// Attach a batched tile fetcher (see [`TileBulkLoader`]): multi-tile
781 /// scans prefetch their span through it instead of faulting tile by tile.
782 pub fn with_bulk_loader(mut self, bulk: TileBulkLoader) -> Self {
783 self.bulk = Some(bulk);
784 self
785 }
786
787 /// Record each remote tile's encoded (on-disk) byte length, per section —
788 /// known to the ranged opener from the tile directory. Powers the join
789 /// planner's fatness gates; never triggers a fetch.
790 pub(crate) fn set_tile_lens(&mut self, lens: [Vec<u32>; NUM_PERMS]) {
791 for (section, ls) in self.sections.iter_mut().zip(lens) {
792 for (tile, l) in section.iter_mut().zip(ls) {
793 tile.len = l;
794 }
795 }
796 }
797
798 /// Record the reader's concurrent-range fan-out (see
799 /// [`RangeReader::concurrency`](crate::reader::RangeReader::concurrency)) —
800 /// the join planner widens its remote probe budget when round trips
801 /// overlap instead of serializing.
802 pub(crate) fn set_read_concurrency(&mut self, c: usize) {
803 self.read_concurrency = c.max(1);
804 }
805
806 /// The reader's concurrent-range fan-out (1 = strictly sequential).
807 pub(crate) fn read_concurrency(&self) -> usize {
808 self.read_concurrency
809 }
810
811 /// Did any tile fetch fail since this index was opened — or since the last
812 /// [`reset_load_failure`](Self::reset_load_failure)?
813 pub fn load_incomplete(&self) -> bool {
814 self.load_failed.load(std::sync::atomic::Ordering::Relaxed)
815 }
816
817 /// Forget recorded fetch failures — the start-of-evaluation reset for a
818 /// RESIDENT session, making the incompleteness verdict per-query instead of
819 /// per-open (one transient network blip used to fail every later query on
820 /// the session). Safe because failed tiles are never cached: the next scan
821 /// simply retries them.
822 pub fn reset_load_failure(&self) {
823 self.load_failed
824 .store(false, std::sync::atomic::Ordering::Relaxed);
825 }
826
827 /// True for a remote/lazy index (tiles fault in over a `RangeReader`). The
828 /// join planner uses this to pick read-aware strategies: here a per-row index
829 /// probe is a network round-trip, not a memory lookup, so a left-deep scan +
830 /// hash join often beats probing a moderately-sized prefix.
831 pub fn is_remote(&self) -> bool {
832 self.loader.is_some()
833 }
834
835 /// Batch-fault the unloaded tiles in `[start, end)` of `section` through
836 /// the bulk loader, if one is attached and at least two tiles are missing
837 /// (a single missing tile costs the same either way). A failed batch is
838 /// not an error here: the tiles stay unloaded and the per-tile loader
839 /// retries each one (recording failures) when the scan reaches it.
840 fn prefetch_span(&self, section: usize, start: usize, end: usize) {
841 let missing: Vec<usize> = (start..end)
842 .filter(|&ti| !self.tile_resident(section, ti))
843 .collect();
844 self.bulk_fault(section, &missing);
845 }
846
847 /// Is tile `(section, tile)`'s body currently resident in the cache?
848 fn tile_resident(&self, section: usize, tile: usize) -> bool {
849 self.cache.contains((section as u8, tile as u32))
850 }
851
852 /// Bulk-fault a set of (possibly scattered, ascending) missing tile indices in
853 /// `section` through the bulk loader in one coalesced read, storing each image.
854 /// No-op without a bulk loader or for fewer than two tiles (a single fault
855 /// costs the same via the per-tile loader). A failed batch leaves the tiles
856 /// unloaded for the per-tile loader to retry. Shared by the consecutive-span
857 /// scan prefetch and the scattered batch-probe prefetch.
858 fn bulk_fault(&self, section: usize, tiles: &[usize]) {
859 if tiles.len() < 2 {
860 return;
861 }
862 let Some(bulk) = &self.bulk else { return };
863 if let Some(images) = bulk(section, tiles) {
864 if images.len() == tiles.len() {
865 for (&ti, img) in tiles.iter().zip(images) {
866 self.cache
867 .insert((section as u8, ti as u32), Arc::from(img));
868 }
869 }
870 }
871 }
872
873 /// Batch-fault the tiles a set of upcoming **probe** patterns will route to,
874 /// before they are probed one at a time. Each probe (a bound leading id)
875 /// routes to a single tile; gathered across the batch those tiles are
876 /// scattered, so faulting them together turns N sequential remote round trips
877 /// into a few coalesced parallel reads — the read-amplification win for a
878 /// label-heavy join over a lazy reader. Honors the synopsis prune (never
879 /// fetches a tile a bound secondary proves can't match). No-op for a local
880 /// index or when fewer than two tiles per section need faulting.
881 pub(crate) fn prefetch_probe_tiles(&self, patterns: &[Pattern]) {
882 if self.bulk.is_none() {
883 return;
884 }
885 let mut want: [std::collections::BTreeSet<usize>; NUM_PERMS] = Default::default();
886 for &pat in patterns {
887 let perm = Self::best_permutation(pat);
888 let [pa, pb, pc] = perm.order_pattern(pat);
889 let si = perm.section_index();
890 let (start, end) = self.tile_span(si, pa);
891 for ti in start..end {
892 if self.sections[si][ti].syn_admits(pb, pc) && !self.tile_resident(si, ti) {
893 want[si].insert(ti);
894 }
895 }
896 }
897 for (si, set) in want.iter().enumerate() {
898 let tiles: Vec<usize> = set.iter().copied().collect();
899 self.bulk_fault(si, &tiles);
900 }
901 }
902
903 /// The tile's cache entry, faulting its block image in through the loader if
904 /// remote. Returns an owned [`CacheEntry`] handle (an `Arc`) the caller
905 /// holds for the duration of one parse/scan — valid even if a later eviction
906 /// drops the map slot (the handout invariant).
907 ///
908 /// A FAILED fetch records the failure and caches nothing (returns `None`),
909 /// so a later evaluation retries the tile — a transient network error must
910 /// not permanently poison a long-lived (resident) session. A local tile
911 /// with no body returns an empty entry (constructed empty on purpose).
912 fn tile_entry(&self, section: usize, tile: usize) -> Option<Arc<CacheEntry>> {
913 let key = (section as u8, tile as u32);
914 if let Some(e) = self.cache.get(key) {
915 return Some(e);
916 }
917 match &self.loader {
918 Some(load) => match load(section, tile) {
919 Some(bytes) => Some(self.cache.insert(key, Arc::from(bytes))),
920 None => {
921 self.load_failed
922 .store(true, std::sync::atomic::Ordering::Relaxed);
923 None
924 }
925 },
926 None => Some(self.cache.insert(key, Arc::from(Vec::new()))),
927 }
928 }
929
930 /// Tile `(section, tile)`'s a-group directory, held in its cache entry and
931 /// built from `block` (that entry's parsed body) on first use. Its bytes
932 /// are charged to the tile cache when built, so a capped cache bounds the
933 /// directories too, and they are evicted with their tile.
934 fn tile_dir<'e>(
935 &self,
936 section: usize,
937 tile: usize,
938 entry: &'e Arc<CacheEntry>,
939 block: &TripleBlock<'_>,
940 ) -> &'e GroupDirectory {
941 let (dir, built) = entry.group_dir(|| block.group_directory());
942 if built {
943 self.cache.charge_extra(
944 (section as u8, tile as u32),
945 entry,
946 dir.heap_bytes() + std::mem::size_of::<GroupDirectory>() as u64,
947 );
948 }
949 dir
950 }
951
952 /// The tile's decompressed block image as a shared handle, for the file
953 /// writer (local indexes, all tiles resident). Empty on a miss.
954 pub(crate) fn tile_body(&self, section: usize, tile: usize) -> Arc<[u8]> {
955 self.tile_entry(section, tile)
956 .map(|e| e.body_arc())
957 .unwrap_or_else(|| Arc::from(Vec::new()))
958 }
959
960 /// Total triple count (sum of the SPO tiles' zone counts). For a remote
961 /// index this faults in the SPO tiles — prefer the header's quad count.
962 pub fn triple_count(&self) -> u32 {
963 self.prefetch_span(0, 0, self.sections[0].len());
964 (0..self.sections[0].len())
965 .filter_map(|ti| {
966 let entry = self.tile_entry(0, ti)?;
967 TripleBlock::parse(entry.body())
968 .ok()
969 .map(|b| b.zone().count)
970 })
971 .sum()
972 }
973
974 /// The tiles of each permutation section (in `ALL_PERMS` order), for the
975 /// file writer.
976 pub fn tile_sections(&self) -> [&[Tile]; NUM_PERMS] {
977 [
978 &self.sections[0],
979 &self.sections[1],
980 &self.sections[2],
981 &self.sections[3],
982 &self.sections[4],
983 &self.sections[5],
984 ]
985 }
986
987 /// The permutation selected for a pattern: the one with the longest bound
988 /// prefix. Ties keep the canonical SPO order (then POS, then OSP), which
989 /// makes provenance stable for unbound or equally selective shapes and routes
990 /// a fully unbound pattern to the SPO block rather than fetching all three.
991 ///
992 /// Six-permutation shorthand for [`best_permutation_in`]. Its answer is
993 /// always inside [`PermSet::CORE`] (see `perm_routing_never_leaves_core`),
994 /// so a file with any legal [`PermSet`] routes identically — but call the
995 /// `_in` form wherever the file's set is at hand, so that stays true by
996 /// construction rather than by argument.
997 ///
998 /// [`best_permutation_in`]: GraphIndex::best_permutation_in
999 pub fn best_permutation(pattern: Pattern) -> IndexPermutation {
1000 Self::best_permutation_in(PermSet::ALL, pattern)
1001 }
1002
1003 /// [`best_permutation`](GraphIndex::best_permutation) restricted to the
1004 /// permutations a file carries.
1005 pub fn best_permutation_in(perms: PermSet, pattern: Pattern) -> IndexPermutation {
1006 let mut best = IndexPermutation::Spo;
1007 let mut best_score = best.leading_bound(pattern);
1008 for perm in perms.iter() {
1009 let score = perm.leading_bound(pattern);
1010 if score > best_score {
1011 best = perm;
1012 best_score = score;
1013 }
1014 }
1015 best
1016 }
1017
1018 /// Choose a permutation that **routes** on `pattern`'s bound prefix *and*
1019 /// streams sorted on the canonical column `sort_col` (0=subject, 1=predicate,
1020 /// 2=object) — i.e. `sort_col` is the leading *free* component after the bound
1021 /// prefix. Returns `None` if `sort_col` is itself bound (then every row shares
1022 /// that value — any permutation is "sorted" on it) or no permutation qualifies.
1023 /// This is the precondition a merge join needs: both inputs sorted on the join
1024 /// key. Among qualifiers, the longest bound prefix (best routing) wins.
1025 ///
1026 /// Six-permutation shorthand for [`permutation_sorted_on_in`].
1027 ///
1028 /// [`permutation_sorted_on_in`]: GraphIndex::permutation_sorted_on_in
1029 pub fn permutation_sorted_on(pattern: Pattern, sort_col: usize) -> Option<IndexPermutation> {
1030 Self::permutation_sorted_on_in(PermSet::ALL, pattern, sort_col)
1031 }
1032
1033 /// [`permutation_sorted_on`](GraphIndex::permutation_sorted_on) restricted
1034 /// to the permutations a file carries — **and it will not trade routing for
1035 /// sort order**.
1036 ///
1037 /// A qualifier must match the bound prefix that
1038 /// [`best_permutation_in`](GraphIndex::best_permutation_in) achieves.
1039 /// With all six that costs nothing: every ordering of `(s, p, o)` exists, so
1040 /// "the bound components first, then `sort_col`" is always available at the
1041 /// maximal prefix. With [`PermSet::CORE`] it is what stops a merge join from
1042 /// buying its co-sorted stream with a **whole-section scan** — e.g.
1043 /// `?s :p ?o` sorted on `?s` has no `P*S` order left, and the only remaining
1044 /// sorted-on-subject stream is an unrouted SPO scan of the entire graph. The
1045 /// merge seed then declines and the hash/probe path answers, which is
1046 /// strictly the cheaper plan.
1047 pub fn permutation_sorted_on_in(
1048 perms: PermSet,
1049 pattern: Pattern,
1050 sort_col: usize,
1051 ) -> Option<IndexPermutation> {
1052 let bound = [
1053 pattern.0.is_some(),
1054 pattern.1.is_some(),
1055 pattern.2.is_some(),
1056 ];
1057 if bound[sort_col] {
1058 return None;
1059 }
1060 let routed = Self::best_permutation_in(perms, pattern).leading_bound(pattern);
1061 let mut best: Option<(IndexPermutation, usize)> = None;
1062 for perm in perms.iter() {
1063 let roles = perm.roles();
1064 let lead = perm.leading_bound(pattern);
1065 // The component at slot `lead` is the first free one; it must be the
1066 // sort column (so the stream is sorted on it after the bound prefix).
1067 if lead < 3 && roles[lead] == sort_col && best.map(|(_, s)| lead > s).unwrap_or(true) {
1068 best = Some((perm, lead));
1069 }
1070 }
1071 best.filter(|&(_, lead)| lead >= routed).map(|(p, _)| p)
1072 }
1073
1074 /// Match one already-decoded serialized permutation block (a single v0.1
1075 /// section or one v0.2 tile). This is the core primitive for range-routed
1076 /// readers: the caller fetches only the selected payload, then this scans
1077 /// it as if it came from a full [`GraphIndex`].
1078 pub fn match_serialized_block(
1079 bytes: &[u8],
1080 permutation: IndexPermutation,
1081 pattern: Pattern,
1082 ) -> Vec<Triple> {
1083 let [pa, pb, pc] = permutation.order_pattern(pattern);
1084 let mut out: Vec<Triple> = TripleBlock::parse(bytes)
1085 .ok()
1086 .filter(|b| b.zone().may_contain(pa, pb, pc))
1087 .map(|b| b.scan(pa, pb, pc))
1088 .into_iter()
1089 .flatten()
1090 .map(move |abc| permutation.back(abc))
1091 .collect();
1092 out.sort_unstable();
1093 out
1094 }
1095
1096 /// All triples matching `pattern`, returned in canonical `(s, p, o)` order.
1097 ///
1098 /// Thin eager wrapper over [`scan_iter`](Self::scan_iter): collect the lazy
1099 /// stream and restore the canonical sort (the stream is sorted in the chosen
1100 /// permutation's order, which differs from canonical once `perm.back`
1101 /// permutes the free components).
1102 pub fn match_pattern(&self, pattern: Pattern) -> Vec<Triple> {
1103 let mut out: Vec<Triple> = self.scan_iter(pattern).collect();
1104 out.sort_unstable();
1105 out
1106 }
1107
1108 /// Lazily stream the triples matching `pattern` in canonical `(s, p, o)`
1109 /// order *within the chosen permutation* — the streaming entry point for
1110 /// callers that can stop early (ASK, `LIMIT`, BGP probes) or that don't need
1111 /// the canonical re-sort. Decodes only the matching groups (see
1112 /// [`TripleBlock::scan`]); a malformed/absent block yields nothing rather
1113 /// than panicking. The permutation is chosen for the longest bound prefix.
1114 pub fn scan_iter(&self, pattern: Pattern) -> impl Iterator<Item = Triple> + '_ {
1115 self.scan_iter_with(pattern, Self::best_permutation(pattern))
1116 }
1117
1118 /// What [`scan_iter`](Self::scan_iter) *would* fetch for `pattern`, computed
1119 /// from the tile directories alone — **no tile is fetched, decoded, or even
1120 /// looked at**. This is the cost-preview half of the routed scan: it walks
1121 /// the same three decisions the scan makes (permutation, routed tile span,
1122 /// synopsis prune) and reports what survives, so a caller can say "this dump
1123 /// will pull 16 MB of index, not 376 MB" before starting it.
1124 ///
1125 /// It is a preview, not a promise: `tile_bytes` is an **upper bound** on the
1126 /// index bytes the scan reads (an admitted tile can still be rejected by its
1127 /// in-tile zone map once in hand, and a re-scan of an already-faulted tile
1128 /// reads nothing), and it says nothing about the dictionary, which is where
1129 /// a term-resolving dump's real cost usually lives.
1130 pub fn scan_plan(&self, pattern: Pattern) -> ScanPlan {
1131 let perm = Self::best_permutation_in(self.perms, pattern);
1132 let [_, pb, pc] = perm.order_pattern(pattern);
1133 let si = perm.section_index();
1134 let tiles = &self.sections[si];
1135 let (start, end) = self.tile_span(si, perm.order_pattern(pattern)[0]);
1136 let mut admitted = 0usize;
1137 let mut tile_bytes = 0u64;
1138 for t in &tiles[start..end] {
1139 if t.syn_admits(pb, pc) {
1140 admitted += 1;
1141 tile_bytes += t.encoded_len();
1142 }
1143 }
1144 ScanPlan {
1145 permutation: perm,
1146 tiles_total: tiles.len(),
1147 tiles_routed: end - start,
1148 tiles_admitted: admitted,
1149 tile_bytes,
1150 section_bytes: tiles.iter().map(|t| t.encoded_len()).sum(),
1151 }
1152 }
1153
1154 /// One bounded, **resumable** slice of `pattern`'s matches: the pull form of
1155 /// [`scan_iter`](Self::scan_iter), for a caller that cannot hold a borrow
1156 /// across calls.
1157 ///
1158 /// Returns `(triples, next_cursor, done)`; start at `cursor = 0` and feed the
1159 /// returned cursor back until `done`. The whole resume state is one opaque
1160 /// `u64` — `(tile index, next a-group id)` — so no iterator, no thread and no
1161 /// self-referential struct has to survive between calls. That is the shape a
1162 /// foreign-function boundary needs: a wasm module cannot suspend a Rust
1163 /// iterator mid-scan and hand control back to its host, but it can be handed
1164 /// a `u64` and told to carry on.
1165 ///
1166 /// `max_rows` is a **floor**, not a hard cut: a batch always ends on an
1167 /// a-group boundary of the chosen permutation, so no group is ever split
1168 /// across two calls and the overshoot is one group's fanout. Nothing is ever
1169 /// rescanned ([`TripleBlock::scan_resume`] jumps straight to the group
1170 /// through the tile's directory), so a full drain is O(n) overall — unlike
1171 /// `(offset, limit)`, which is O(n²/limit).
1172 ///
1173 /// Every call either yields at least one row or reports `done`, so a caller
1174 /// never has to guard against an empty non-final batch.
1175 ///
1176 /// **Order.** Rows arrive in the chosen permutation's order and each batch is
1177 /// re-sorted canonically, exactly as [`match_pattern`](Self::match_pattern)
1178 /// does for a whole result. For a fully unbound pattern (routed to SPO) that
1179 /// makes the concatenation of every batch identical to `match_pattern`'s
1180 /// output; for a bound pattern the *set* is identical but the canonical
1181 /// re-sort is per batch rather than global.
1182 ///
1183 /// **Memory** is O(`max_rows` + one a-group + the tiles faulted so far) —
1184 /// never O(matches). That is the whole point: an unbounded `(?s ?p ?o)` over
1185 /// a 26-million-quad graph used to materialize every match before the caller
1186 /// saw one row.
1187 pub fn scan_batch(
1188 &self,
1189 pattern: Pattern,
1190 cursor: u64,
1191 max_rows: usize,
1192 ) -> (Vec<Triple>, u64, bool) {
1193 let max_rows = max_rows.max(1);
1194 let perm = Self::best_permutation(pattern);
1195 let [pa, pb, pc] = perm.order_pattern(pattern);
1196 let si = perm.section_index();
1197 // Same routing as `scan_iter_with`: the tile directory alone decides the
1198 // span, so this is free on a lazy/remote open.
1199 let (start, end) = self.tile_span(si, pa);
1200 let mut ti = ((cursor >> 32) as usize).max(start);
1201 let mut from_a = cursor as u32;
1202 let mut out: Vec<Triple> = Vec::new();
1203 // Same geometric prefetch ramp as the streaming scan: a batch that stops
1204 // after one tile never fetches the ones behind it.
1205 let mut window = PREFETCH_WINDOW_START;
1206 while ti < end {
1207 // Synopsis pre-fault prune — no tile is fetched to reject it.
1208 if !self.sections[si][ti].syn_admits(pb, pc) {
1209 ti += 1;
1210 from_a = 0;
1211 continue;
1212 }
1213 if !self.tile_resident(si, ti) {
1214 self.prefetch_span(si, ti, (ti + window).min(end));
1215 window = window.saturating_mul(2).min(PREFETCH_WINDOW_MAX);
1216 }
1217 let entry = self.tile_entry(si, ti);
1218 let mut resume_at: Option<u32> = None;
1219 if let Some(block) = entry
1220 .as_deref()
1221 .and_then(|e| TripleBlock::parse(e.body()).ok())
1222 .filter(|b| b.zone().may_contain(pa, pb, pc))
1223 {
1224 let rows = match pa {
1225 // A bound leading id is one a-group; it cannot be split
1226 // inside a tile, only across tiles (a mega-group split), so
1227 // there is nothing finer to resume at than the tile.
1228 Some(a) => {
1229 let dir = self.tile_dir(si, ti, entry.as_ref().unwrap(), &block);
1230 block.scan_from(dir, a, pb, pc)
1231 }
1232 // Fresh tile: no directory needed, so a straight drain never
1233 // pays for one.
1234 None if from_a == 0 => block.scan(None, pb, pc),
1235 None => {
1236 let dir = self.tile_dir(si, ti, entry.as_ref().unwrap(), &block);
1237 block.scan_resume(dir, from_a, pb, pc)
1238 }
1239 };
1240 // Only a leading-unbound scan can be resumed mid-tile: with `pa`
1241 // bound there is one a-group and `scan_from` always restarts it
1242 // from the top, so cutting inside it would duplicate rows.
1243 let splittable = pa.is_none();
1244 let mut last_a: Option<u32> = None;
1245 for abc in rows {
1246 // Full, and this row opens a new a-group ⇒ cut here and
1247 // resume at this group. The row is dropped, not lost: the
1248 // next call re-enters at exactly this id.
1249 if splittable && out.len() >= max_rows && last_a != Some(abc.0) {
1250 resume_at = Some(abc.0);
1251 break;
1252 }
1253 last_a = Some(abc.0);
1254 out.push(perm.back(abc));
1255 }
1256 }
1257 if let Some(a) = resume_at {
1258 out.sort_unstable();
1259 return (out, ((ti as u64) << 32) | a as u64, false);
1260 }
1261 ti += 1;
1262 from_a = 0;
1263 if out.len() >= max_rows {
1264 break;
1265 }
1266 }
1267 let done = ti >= end;
1268 out.sort_unstable();
1269 (out, (ti as u64) << 32, done)
1270 }
1271
1272 /// Stream `pattern`'s matches **sorted on the canonical column `sort_col`**
1273 /// (0=subject, 1=predicate, 2=object): the stream's `sort_col` values are
1274 /// ascending. Chooses a permutation that routes on the bound prefix *and*
1275 /// orders by `sort_col` ([`permutation_sorted_on`](Self::permutation_sorted_on));
1276 /// `None` when none qualifies (e.g. `sort_col` is itself bound). The
1277 /// precondition for feeding a [merge join](crate::bgp): both inputs sorted on
1278 /// the shared join key.
1279 pub(crate) fn scan_iter_sorted_on(
1280 &self,
1281 pattern: Pattern,
1282 sort_col: usize,
1283 ) -> Option<impl Iterator<Item = Triple> + '_> {
1284 Some(self.scan_iter_with(
1285 pattern,
1286 Self::permutation_sorted_on_in(self.perms, pattern, sort_col)?,
1287 ))
1288 }
1289
1290 /// Stream `pattern`'s matches using a **specific** permutation `perm`; the
1291 /// stream is sorted in `perm`'s `(a, b, c)` order. Shared core of `scan_iter`
1292 /// and `scan_iter_sorted_on`.
1293 fn scan_iter_with(
1294 &self,
1295 pattern: Pattern,
1296 perm: IndexPermutation,
1297 ) -> impl Iterator<Item = Triple> + '_ {
1298 // Route: a bound leading id binary-searches the tile directory to exactly
1299 // one tile (groups are never split across tiles); an unbound one chains
1300 // every tile's cursor. Within a tile, a bound leading scan jumps to its
1301 // a-group via the tile's lazily-built group directory — built on first
1302 // use, costing one walk of that (budget-sized) tile.
1303 let [pa, pb, pc] = perm.order_pattern(pattern);
1304 let si = perm.section_index();
1305 let (start, end) = self.tile_span(si, pa);
1306 // Coalesce tile faults, but ramp the prefetch window geometrically as
1307 // the scan advances rather than fetching the whole span up front: a
1308 // small `LIMIT` (which stops pulling early) then never faults tiles
1309 // past the rows it needs, while a full scan still batches into a
1310 // handful of coalesced reads (4, 8, 16, … tiles). A bound leading scan
1311 // spans a single tile, so the prefetch no-ops and it faults just that
1312 // one tile, unchanged.
1313 let window = std::cell::Cell::new(PREFETCH_WINDOW_START);
1314 (start..end)
1315 // Synopsis pre-fault prune: drop a routed tile the directory proves
1316 // can't match a bound secondary component, **without fetching it**
1317 // (the remote win — a negative/sparse lookup costs zero tile reads).
1318 // A bound leading id routes to a single tile, so this is where it
1319 // bites; a fully-unbound leading scan leaves `pb`/`pc` unbound, so
1320 // `syn_admits` keeps every tile, unchanged.
1321 .filter(move |&ti| self.sections[si][ti].syn_admits(pb, pc))
1322 .flat_map(move |ti| {
1323 // Fault in (if remote), parse (untrusted bytes ⇒ `None` on
1324 // malformed), and zone-prune per tile, then stream the
1325 // matching groups.
1326 if !self.tile_resident(si, ti) {
1327 let w = window.get();
1328 self.prefetch_span(si, ti, (ti + w).min(end));
1329 window.set(w.saturating_mul(2).min(PREFETCH_WINDOW_MAX));
1330 }
1331 // Decode the tile once and materialize its matching rows into an
1332 // owned `Vec`, so the borrowed block/cursor never outlives the
1333 // tile's cache handle (an `Arc` dropped at the end of this
1334 // closure). The buffer is bounded to one tile's rows; the scan
1335 // stays lazy *across* tiles, so a `LIMIT` still stops early.
1336 let rows: Vec<Triple> = match self.tile_entry(si, ti) {
1337 Some(entry) => TripleBlock::parse(entry.body())
1338 .ok()
1339 .filter(|b| b.zone().may_contain(pa, pb, pc))
1340 .map(|b| match pa {
1341 Some(a) => {
1342 let dir = self.tile_dir(si, ti, &entry, &b);
1343 b.scan_from(dir, a, pb, pc).collect()
1344 }
1345 None => b.scan(pa, pb, pc).collect(),
1346 })
1347 .unwrap_or_default(),
1348 None => Vec::new(),
1349 };
1350 rows.into_iter()
1351 })
1352 .map(move |abc| perm.back(abc))
1353 }
1354
1355 /// A planner estimate of how many triples match `pattern`, read off the
1356 /// tile directories alone — no tile is fetched or decoded, so it costs the
1357 /// same on a lazy 50 GB file as on a resident one. `total` is the number
1358 /// of triples the index holds (an upper bound is fine).
1359 ///
1360 /// For every carried permutation that leads with a bound component, the
1361 /// routed tiles the synopsis admits are counted; a tile holds about
1362 /// `total / tiles` triples, and the routed run is charged half a tile less
1363 /// than its length, since a key rarely starts and ends on tile boundaries.
1364 /// The smallest figure wins, so `?s a :Rare` (a few tiles of OPS) beats
1365 /// `?s :p ?o` (every tile of `:p` in PSO). Its resolution is one tile:
1366 /// patterns inside one tile tie, which is all a join order needs. A
1367 /// pattern with no bound component estimates `total`; one the synopsis
1368 /// rules out estimates 0.
1369 pub(crate) fn estimate_matches(&self, pattern: Pattern, total: u64) -> f64 {
1370 let mut best = total as f64;
1371 for perm in self.perms.iter() {
1372 let [pa, pb, pc] = perm.order_pattern(pattern);
1373 if pa.is_none() {
1374 continue;
1375 }
1376 let si = perm.section_index();
1377 let tiles = &self.sections[si];
1378 if tiles.is_empty() {
1379 return 0.0;
1380 }
1381 let per_tile = total as f64 / tiles.len() as f64;
1382 let (start, end) = self.tile_span(si, pa);
1383 let admitted = tiles[start..end]
1384 .iter()
1385 .filter(|t| t.syn_admits(pb, pc))
1386 .count();
1387 let est = if admitted == 0 {
1388 0.0
1389 } else {
1390 (admitted as f64 - 0.5) * per_tile
1391 };
1392 best = best.min(est);
1393 }
1394 best
1395 }
1396
1397 /// The tile index span a scan must visit: every tile when the leading
1398 /// component is unbound, else the run of tiles whose leading-id ranges
1399 /// cover it. Tile ranges are ascending; consecutive tiles may SHARE a
1400 /// leading id when a mega-group was split across tiles (see
1401 /// [`build_tiles`]), so the span is a range scan, not a single hit —
1402 /// files without splits still yield a span of at most one tile.
1403 pub(crate) fn tile_span(&self, section: usize, pa: Option<u32>) -> (usize, usize) {
1404 let tiles = &self.sections[section];
1405 match pa {
1406 None => (0, tiles.len()),
1407 Some(a) => {
1408 let i = tiles.partition_point(|t| t.max_a < a);
1409 let mut j = i;
1410 while j < tiles.len() && tiles[j].min_a <= a {
1411 j += 1;
1412 }
1413 (i, j)
1414 }
1415 }
1416 }
1417}
1418
1419#[cfg(test)]
1420mod tests {
1421 use super::*;
1422
1423 fn graph() -> (GraphIndex, Vec<Triple>) {
1424 let data = vec![
1425 (1, 10, 100),
1426 (1, 10, 101),
1427 (1, 11, 100),
1428 (2, 10, 100),
1429 (2, 12, 200),
1430 (3, 11, 300),
1431 ];
1432 let mut b = GraphIndexBuilder::new();
1433 for &t in &data {
1434 b.push(t);
1435 }
1436 (b.build(), data)
1437 }
1438
1439 /// Brute-force reference for a pattern.
1440 fn reference(data: &[Triple], (s, p, o): Pattern) -> Vec<Triple> {
1441 let mut v: Vec<Triple> = data
1442 .iter()
1443 .copied()
1444 .filter(|&(a, b, c)| {
1445 s.is_none_or(|x| x == a) && p.is_none_or(|x| x == b) && o.is_none_or(|x| x == c)
1446 })
1447 .collect();
1448 v.sort_unstable();
1449 v
1450 }
1451
1452 /// The tile-directory estimate orders patterns the way their true sizes
1453 /// do, never fetches anything, and is exact at its extremes: unbound is the
1454 /// total, a key no tile can hold is zero.
1455 #[test]
1456 fn tile_estimates_rank_patterns_by_size() {
1457 // Predicate 1 on every subject, predicate 2 on a few; object 50 is a
1458 // "class" with 4000 instances, object 60 one with 3.
1459 let mut b = GraphIndexBuilder::new().with_tile_budget(256);
1460 let mut n = 0u64;
1461 for s in 0..4000u32 {
1462 b.push((s, 1, 50));
1463 b.push((s, 3, 1000 + s));
1464 n += 2;
1465 if s % 1000 == 0 {
1466 b.push((s, 2, 60));
1467 n += 1;
1468 }
1469 }
1470 let idx = b.build();
1471 let est = |p: Pattern| idx.estimate_matches(p, n);
1472 assert_eq!(est((None, None, None)), n as f64);
1473 assert!(est((None, Some(2), None)) < est((None, Some(1), None)));
1474 assert!(est((None, None, Some(60))) < est((None, None, Some(50))));
1475 assert!(est((Some(7), None, None)) < est((None, Some(3), None)));
1476 // A big predicate spans many tiles; the rare one fits in at most one.
1477 let per_tile = n as f64 / idx.tile_sections()[0].len() as f64;
1478 assert!(est((None, Some(2), None)) <= 1.5 * per_tile);
1479 assert!(est((None, Some(1), None)) > 10.0 * per_tile);
1480 // A leading id beyond every tile's range is provably absent.
1481 assert_eq!(est((Some(99_999), None, None)), 0.0);
1482 // An empty index estimates nothing for a bound pattern.
1483 let empty = GraphIndexBuilder::new().build();
1484 assert_eq!(empty.estimate_matches((Some(1), None, None), 0), 0.0);
1485 }
1486
1487 #[test]
1488 fn every_pattern_shape_matches_reference() {
1489 let (idx, data) = graph();
1490 let vals = |opts: &[u32]| {
1491 let mut v: Vec<Option<u32>> = opts.iter().map(|&x| Some(x)).collect();
1492 v.push(None);
1493 v
1494 };
1495 // Exercise all 8 bound/unbound shapes across representative values.
1496 for s in vals(&[1, 2, 9]) {
1497 for p in vals(&[10, 11, 99]) {
1498 for o in vals(&[100, 300, 999]) {
1499 let pat = (s, p, o);
1500 assert_eq!(
1501 idx.match_pattern(pat),
1502 reference(&data, pat),
1503 "pattern {pat:?}"
1504 );
1505 // The lazy stream must match the eager result once sorted —
1506 // same triples, just without the up-front canonical re-sort.
1507 let mut streamed: Vec<Triple> = idx.scan_iter(pat).collect();
1508 streamed.sort_unstable();
1509 assert_eq!(streamed, reference(&data, pat), "scan_iter {pat:?}");
1510 }
1511 }
1512 }
1513 }
1514
1515 #[test]
1516 fn unbound_returns_everything_sorted() {
1517 let (idx, data) = graph();
1518 let mut sorted = data.clone();
1519 sorted.sort_unstable();
1520 assert_eq!(idx.match_pattern((None, None, None)), sorted);
1521 }
1522
1523 /// A tiny tile budget must split sections into many tiles — including
1524 /// MID-GROUP cuts (budget 1/16 makes every a-group oversized) — and every
1525 /// pattern shape must still match the brute-force reference: bound
1526 /// leading ids route to the run of covering tiles, unbound scans chain
1527 /// all tiles.
1528 #[test]
1529 fn multi_tile_sections_match_reference_every_shape() {
1530 // Enough distinct leading ids to split under a tiny budget.
1531 let mut data: Vec<Triple> = Vec::new();
1532 for s in 1..=40u32 {
1533 for p in [10u32, 11] {
1534 for o in [100u32, 100 + s] {
1535 data.push((s, p, o));
1536 }
1537 }
1538 }
1539 for budget in [1usize, 16, 64, 1 << 20] {
1540 let mut b = GraphIndexBuilder::new().with_tile_budget(budget);
1541 for &t in &data {
1542 b.push(t);
1543 }
1544 let idx = b.build();
1545 let spo_tiles = idx.tile_sections()[0].len();
1546 if budget <= 16 {
1547 assert!(spo_tiles > 1, "budget {budget} should force tiling");
1548 }
1549 // Tile ranges must be ascending; a split mega-group may leave
1550 // consecutive tiles SHARING a leading id (never overlapping past it).
1551 for w in idx.tile_sections()[0].windows(2) {
1552 assert!(w[0].leading_range().1 <= w[1].leading_range().0);
1553 }
1554 assert_eq!(idx.triple_count() as usize, data.len(), "budget {budget}");
1555
1556 let vals = |opts: &[u32]| {
1557 let mut v: Vec<Option<u32>> = opts.iter().map(|&x| Some(x)).collect();
1558 v.push(None);
1559 v
1560 };
1561 for _round in 0..2 {
1562 for s in vals(&[1, 20, 40, 99]) {
1563 for p in vals(&[10, 11, 99]) {
1564 for o in vals(&[100, 120, 999]) {
1565 let pat = (s, p, o);
1566 assert_eq!(
1567 idx.match_pattern(pat),
1568 reference(&data, pat),
1569 "budget {budget} pattern {pat:?}"
1570 );
1571 }
1572 }
1573 }
1574 }
1575 }
1576 }
1577
1578 /// The Crossref shape: ONE mega-predicate carrying most of the graph. At
1579 /// the real 64 KiB budget its P-leading a-group must be split across
1580 /// multiple tiles (bounding builder memory), and a bound leading id must
1581 /// route to the whole run of covering tiles with complete results.
1582 #[test]
1583 fn mega_group_splits_across_tiles_and_lookups_stay_complete() {
1584 let hot_p = 7u32;
1585 let mut data: Vec<Triple> = Vec::new();
1586 for i in 0..40_000u32 {
1587 data.push((1_000 + i % 200, hot_p, 50_000 + i));
1588 }
1589 data.push((1, 1, 1));
1590 data.push((2, 2, 2));
1591 let mut b = GraphIndexBuilder::new(); // default INDEX_TILE_BUDGET
1592 for &t in &data {
1593 b.push(t);
1594 }
1595 let idx = b.build();
1596
1597 // PSO (a = predicate): the hot_p group must span several tiles.
1598 let pso = ALL_PERMS
1599 .iter()
1600 .position(|p| matches!(p, IndexPermutation::Pso))
1601 .unwrap();
1602 let covering = idx.tile_sections()[pso]
1603 .iter()
1604 .filter(|t| {
1605 let (lo, hi) = t.leading_range();
1606 lo <= hot_p && hot_p <= hi
1607 })
1608 .count();
1609 assert!(
1610 covering > 1,
1611 "expected the hot predicate split across tiles, got {covering}"
1612 );
1613
1614 // Bound-p lookup must still return every triple of the mega-group —
1615 // probing bound objects in the FIRST, MIDDLE and LAST slices of the
1616 // split run (a mid-run object once returned 0 on the first split file).
1617 for pat in [
1618 (None, Some(hot_p), None),
1619 (Some(1_050), Some(hot_p), None),
1620 (None, Some(hot_p), Some(50_123)), // first slice
1621 (None, Some(hot_p), Some(70_000)), // middle of the run
1622 (None, Some(hot_p), Some(89_999)), // last slice
1623 (None, Some(hot_p), Some(49_000)), // below the range → empty
1624 (None, Some(hot_p), Some(95_000)), // above the range → empty
1625 ] {
1626 assert_eq!(idx.match_pattern(pat), reference(&data, pat), "{pat:?}");
1627 }
1628 }
1629
1630 /// Scans must yield identical results across the directory lifecycle: the
1631 /// first leading-bound scan walks linearly, the second builds the
1632 /// directory, and later ones jump through it — including absent ids
1633 /// (between, below, and above the stored groups).
1634 #[test]
1635 fn directory_backed_scans_match_reference_every_shape() {
1636 let (idx, data) = graph();
1637 let vals = |opts: &[u32]| {
1638 let mut v: Vec<Option<u32>> = opts.iter().map(|&x| Some(x)).collect();
1639 v.push(None);
1640 v
1641 };
1642 for round in 0..3 {
1643 for s in vals(&[1, 2, 3, 0, 9]) {
1644 for p in vals(&[10, 11, 12, 99]) {
1645 for o in vals(&[100, 200, 300, 999]) {
1646 let pat = (s, p, o);
1647 let mut got: Vec<Triple> = idx.scan_iter(pat).collect();
1648 got.sort_unstable();
1649 assert_eq!(got, reference(&data, pat), "round {round} scan {pat:?}");
1650 }
1651 }
1652 }
1653 }
1654 }
1655
1656 /// A tile synopsis must let a routed scan **skip the fetch** of a tile its
1657 /// secondary-column range rules out — and never skip one that could match.
1658 #[test]
1659 fn synopsis_prunes_the_routed_tile_before_fetch() {
1660 use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
1661 use std::sync::Arc;
1662
1663 // One real SPO tile: subject a=5, predicates b∈{10,11}, object c=100.
1664 let block = {
1665 let mut b = TripleBlockBuilder::new();
1666 b.push((5, 10, 100));
1667 b.push((5, 11, 100));
1668 b.build()
1669 };
1670 let fetches = Arc::new(AtomicUsize::new(0));
1671 let (blk, fc) = (block.clone(), fetches.clone());
1672 // The loader returns the (already-decompressed) tile image and counts calls.
1673 let loader: TileLoader = Box::new(move |_si, _ti| {
1674 fc.fetch_add(1, SeqCst);
1675 Some(blk.clone())
1676 });
1677 // Remote SPO directory: one tile, leading a∈[5,5], synopsis b∈[10,11], c∈[100,100].
1678 let dirs = [
1679 vec![(5u32, 5u32, Some((10u32, 11u32, 100u32, 100u32)))],
1680 Vec::new(),
1681 Vec::new(),
1682 Vec::new(),
1683 Vec::new(),
1684 Vec::new(),
1685 ];
1686 let idx = GraphIndex::from_remote_directories(dirs, PermSet::ALL, loader);
1687
1688 // Predicate 99 is outside the tile's b-range → prune, zero fetches, empty.
1689 assert!(idx.match_pattern((Some(5), Some(99), None)).is_empty());
1690 assert_eq!(fetches.load(SeqCst), 0, "synopsis must skip the fetch");
1691
1692 // Object 999 outside the tile's c-range → prune, still zero fetches.
1693 assert!(idx.match_pattern((Some(5), None, Some(999))).is_empty());
1694 assert_eq!(
1695 fetches.load(SeqCst),
1696 0,
1697 "secondary-c prune also skips the fetch"
1698 );
1699
1700 // Predicate 10 is in range → the tile is fetched and the match returned.
1701 assert_eq!(
1702 idx.match_pattern((Some(5), Some(10), None)),
1703 vec![(5, 10, 100)]
1704 );
1705 assert_eq!(
1706 fetches.load(SeqCst),
1707 1,
1708 "an admissible secondary still fetches"
1709 );
1710 }
1711
1712 /// Without a synopsis (`None`), nothing is pruned early — the tile is always
1713 /// fetched and the in-tile zone map does the (correct) pruning, as before.
1714 #[test]
1715 fn absent_synopsis_never_prunes() {
1716 use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
1717 use std::sync::Arc;
1718 let block = {
1719 let mut b = TripleBlockBuilder::new();
1720 b.push((5, 10, 100));
1721 b.build()
1722 };
1723 let fetches = Arc::new(AtomicUsize::new(0));
1724 let (blk, fc) = (block.clone(), fetches.clone());
1725 let loader: TileLoader = Box::new(move |_si, _ti| {
1726 fc.fetch_add(1, SeqCst);
1727 Some(blk.clone())
1728 });
1729 let dirs = [
1730 vec![(5u32, 5u32, None)],
1731 Vec::new(),
1732 Vec::new(),
1733 Vec::new(),
1734 Vec::new(),
1735 Vec::new(),
1736 ];
1737 let idx = GraphIndex::from_remote_directories(dirs, PermSet::ALL, loader);
1738 // Predicate 99 absent, but with no synopsis the tile is fetched (then the
1739 // zone map yields no match) — correctness preserved, just no fetch saved.
1740 assert!(idx.match_pattern((Some(5), Some(99), None)).is_empty());
1741 assert_eq!(fetches.load(SeqCst), 1, "no synopsis ⇒ no early prune");
1742 }
1743
1744 /// The eight triple-pattern shapes, as `(s, p, o)` boundness.
1745 fn all_patterns() -> Vec<Pattern> {
1746 (0..8u8)
1747 .map(|mask| {
1748 (
1749 (mask & 1 != 0).then_some(1u32),
1750 (mask & 2 != 0).then_some(2u32),
1751 (mask & 4 != 0).then_some(3u32),
1752 )
1753 })
1754 .collect()
1755 }
1756
1757 /// The claim the whole option rests on: **{SPO, POS, OSP} ties the longest
1758 /// bound prefix on all eight pattern shapes**, so the other three never win
1759 /// routing — only sort order. Enumerated and printed rather than asserted in
1760 /// prose, because if it were ever false a lean file would answer a pattern
1761 /// from a worse index without anything failing.
1762 #[test]
1763 fn perm_routing_never_leaves_core() {
1764 for pat in all_patterns() {
1765 let best_all = ALL_PERMS
1766 .iter()
1767 .map(|p| p.leading_bound(pat))
1768 .max()
1769 .unwrap();
1770 let best_core = PermSet::CORE
1771 .iter()
1772 .map(|p| p.leading_bound(pat))
1773 .max()
1774 .unwrap();
1775 let scores: Vec<String> = ALL_PERMS
1776 .iter()
1777 .map(|p| format!("{}={}", p.name(), p.leading_bound(pat)))
1778 .collect();
1779 eprintln!(
1780 "s={} p={} o={} | {} | best6={best_all} best3={best_core} chosen={}",
1781 pat.0.is_some() as u8,
1782 pat.1.is_some() as u8,
1783 pat.2.is_some() as u8,
1784 scores.join(" "),
1785 GraphIndex::best_permutation(pat).name(),
1786 );
1787 assert_eq!(
1788 best_core, best_all,
1789 "the three routing permutations must tie the best of six on {pat:?}"
1790 );
1791 let chosen = GraphIndex::best_permutation(pat);
1792 assert!(
1793 PermSet::CORE.contains(chosen),
1794 "best_permutation chose {} for {pat:?}, outside the routing three",
1795 chosen.name()
1796 );
1797 assert_eq!(
1798 chosen,
1799 GraphIndex::best_permutation_in(PermSet::CORE, pat),
1800 "routing must be identical with three permutations and with six"
1801 );
1802 }
1803 }
1804
1805 /// Restricting the set may never make a merge join pick a *worse-routed*
1806 /// stream than the plain lookup would use: with six the co-sorted
1807 /// permutation always ties the best prefix, and with three the guard
1808 /// declines rather than buying sort order with a whole-section scan.
1809 #[test]
1810 fn sorted_permutation_never_sacrifices_routing() {
1811 let mut declined = Vec::new();
1812 for pat in all_patterns() {
1813 for col in 0..3usize {
1814 let routed_all = GraphIndex::best_permutation(pat).leading_bound(pat);
1815 if let Some(p) = GraphIndex::permutation_sorted_on(pat, col) {
1816 assert_eq!(
1817 p.leading_bound(pat),
1818 routed_all,
1819 "six permutations must always co-sort at the best prefix"
1820 );
1821 assert_eq!(p.roles()[p.leading_bound(pat)], col);
1822 }
1823 match GraphIndex::permutation_sorted_on_in(PermSet::CORE, pat, col) {
1824 Some(p) => {
1825 assert!(PermSet::CORE.contains(p));
1826 assert_eq!(
1827 p.leading_bound(pat),
1828 GraphIndex::best_permutation_in(PermSet::CORE, pat).leading_bound(pat)
1829 );
1830 }
1831 None => {
1832 if GraphIndex::permutation_sorted_on(pat, col).is_some() {
1833 declined.push((pat, col));
1834 }
1835 }
1836 }
1837 }
1838 }
1839 // Exactly the three shapes SOP / PSO / OPS exist for: one bound
1840 // component, sorted on a column no remaining order can lead with after
1841 // it — subject-bound sorted on object, predicate-bound sorted on
1842 // subject, object-bound sorted on predicate.
1843 for (pat, col) in &declined {
1844 let bound: Vec<usize> = (0..3)
1845 .filter(|&i| [pat.0, pat.1, pat.2][i].is_some())
1846 .collect();
1847 assert_eq!(
1848 bound.len(),
1849 1,
1850 "only single-bound shapes lose a merge order"
1851 );
1852 assert_ne!(bound[0], *col);
1853 }
1854 eprintln!("three-permutation merge-join declines: {declined:?}");
1855 assert_eq!(declined.len(), 3, "exactly three (bound, sort) shapes lost");
1856 }
1857
1858 #[test]
1859 fn perm_set_masks_and_positions() {
1860 assert_eq!(PermSet::ALL.len(), 6);
1861 assert_eq!(PermSet::CORE.len(), 3);
1862 assert_eq!(PermSet::CORE.bits(), 0b0000_0111);
1863 assert_eq!(PermSet::CORE.names(), vec!["SPO", "POS", "OSP"]);
1864 assert_eq!(
1865 PermSet::ALL.names(),
1866 vec!["SPO", "POS", "OSP", "SOP", "PSO", "OPS"]
1867 );
1868 // Container position is rank among the STORED permutations, which is
1869 // why the routing three had to lead ALL_PERMS.
1870 for (i, p) in PermSet::CORE.iter().enumerate() {
1871 assert_eq!(PermSet::CORE.position(p), Some(i));
1872 assert_eq!(p.section_index(), i);
1873 }
1874 assert_eq!(PermSet::CORE.position(IndexPermutation::Sop), None);
1875 assert_eq!(PermSet::ALL.position(IndexPermutation::Ops), Some(5));
1876 // Only supersets of the routing three are legal.
1877 assert!(PermSet::from_bits(0b0000_0111).is_ok());
1878 assert!(PermSet::from_bits(0b0011_1111).is_ok());
1879 assert!(PermSet::from_bits(0b0000_1111).is_ok());
1880 assert!(PermSet::from_bits(0b0000_0011).is_err());
1881 assert!(PermSet::from_bits(0b0011_1000).is_err());
1882 assert!(PermSet::from_bits(0b1000_0111).is_err());
1883 }
1884
1885 /// A lean index answers every pattern shape with exactly the rows a full
1886 /// one does — the property that makes the option safe at all.
1887 #[test]
1888 fn three_and_six_agree_on_every_pattern() {
1889 let triples: Vec<Triple> = (0..200u32)
1890 .map(|i| (i % 17 + 1, i % 5 + 1, i % 23 + 1))
1891 .collect();
1892 let six = GraphIndexBuilder::from_triples(triples.clone())
1893 .with_tile_budget(128)
1894 .build();
1895 let three = GraphIndexBuilder::from_triples(triples)
1896 .with_tile_budget(128)
1897 .with_perms(PermSet::CORE)
1898 .build();
1899 assert_eq!(six.perms(), PermSet::ALL);
1900 assert_eq!(three.perms(), PermSet::CORE);
1901 for perm in [
1902 IndexPermutation::Sop,
1903 IndexPermutation::Pso,
1904 IndexPermutation::Ops,
1905 ] {
1906 assert!(three.tile_sections()[perm.section_index()].is_empty());
1907 }
1908 for a in [None, Some(3u32)] {
1909 for b in [None, Some(2u32)] {
1910 for c in [None, Some(9u32)] {
1911 let mut x = six.match_pattern((a, b, c));
1912 let mut y = three.match_pattern((a, b, c));
1913 x.sort_unstable();
1914 y.sort_unstable();
1915 assert_eq!(x, y, "pattern {:?} disagreed", (a, b, c));
1916 }
1917 }
1918 }
1919 }
1920}