1use std::fmt;
4use std::path::{Path, PathBuf};
5
6use crate::encode::{
7 AxisHeadCountHit, CATALOG_MIN_PREFIX_SIZE, COMMIT_TS_LEN, CatalogPut, CatalogRebuildStats,
8 ComparisonMask, DomainCountMode, DomainScanCountHit, DomainScanHit, EncodedQuad, EncodedTerm,
9 EncodedTriplePattern, GByteFilter, GEO_CELL_ID_LEN, GEO_INDEX_CF, GEO_INDEX_EPOCH_KEY,
10 GEO_INDEX_LIVENESS_KEY, GEO_INDEX_META_CF, GWindowKind, GeoCandidateDecision,
11 GeoCandidateState, GeoCellInterval, GeoEnvelope, GeoIndexPut, GraphCatalogState, HeadVerdict,
12 HexastorePut, HexastoreVersion, IndexPermutation, IriOnlyMask, KeyRow, MERGE_NEXT_CHAIN_LIMIT,
13 MERGE_TRIPLE_PREFIX_MAX, MatchDecision, NAMED_GRAPHS_CATALOG_CF, QuadSlot, RowMatcher,
14 RunCounter, SnapshotScanState, TEMPORAL_INDEX_CF, TEMPORAL_INDEX_EPOCH_KEY,
15 TEMPORAL_INDEX_META_CF, TEMPORAL_INDEX_ORIGIN_KEY, TEMPORAL_KEY_LEN, TEMPORAL_ORIGIN_VERSION,
16 TemporalCandidateDecision, TemporalCandidateState, TemporalCellInterval, TemporalIndexPut,
17 TemporalQueryPredicate, TermReader, WRITTEN_TERM_MAX_SIZE, byte_successor, catalog_prefix,
18 classify_g_window, collect_dedup_visible_catalog_graphs, consider_axis_head_key,
19 consider_head_key, decode_catalog_value, decode_geo_epoch, decode_geo_liveness,
20 decode_index_key, decode_storage_value, decode_temporal_epoch, decode_temporal_origin,
21 decode_temporal_posting_value, decode_versioned_key, encode_geo_epoch, encode_geo_liveness,
22 encode_index_key, encode_quad, encode_temporal_epoch, encode_temporal_origin,
23 encode_term_bytes, graph_hops_after_head, head_prefix_resume_seek, head_resume_seek,
24 head_term_from_region, is_catalog_graph, prepare_constraints_sorted, prepare_head_prefixes,
25 prepare_hexastore_puts, record_first_put_graph, region_after_head, require_catalog_graph,
26 stage_catalog_puts, term_in_quad_slot, triple_prefix_len, versioned_key_term_prefix,
27};
28use crate::rocksdb_db::{
29 BottommostLevelCompaction, ColumnFamily, ColumnFamilyDefinition, Db, warm_walk,
30};
31
32use crate::types::{
33 CommitTs, PartitionAxis, ReplacePair, ScanExhaustion, ScanPage, SnapshotId, StorageOp,
34 VisibilityLabel,
35};
36use crate::worker_pool::{self, PoolUnit, UnitOutcome};
37use crate::{Quad, StorageError, StrHash};
38
39use std::sync::Arc;
40use std::sync::OnceLock;
41use std::sync::atomic::{AtomicUsize, Ordering};
42
43pub use crate::rocksdb_db::{
44 BULK_MAX_WRITE_BUFFER_NUMBER, BULK_WRITE_BUFFER_BYTES, COMPACTION_READAHEAD_BYTES,
45 DEFAULT_BLOCK_SIZE_BYTES, DEFAULT_ITERATOR_READAHEAD_BYTES, DEFAULT_MAX_WRITE_BUFFER_NUMBER,
46 DEFAULT_WRITE_BUFFER_BYTES, PREFIX_FILTER_BITS_PER_KEY, REGISTRY_BLOCK_SIZE_BYTES,
47 RocksDbOptionsHooks, RocksDbTuning, TICKER_BLOCK_CACHE_FILTER_HIT,
48 TICKER_BLOCK_CACHE_FILTER_MISS, TICKER_BLOOM_FILTER_PREFIX_CHECKED,
49 TICKER_BLOOM_FILTER_PREFIX_USEFUL, TICKER_SEEK_FILTER_MATCH, TICKER_SEEK_FILTERED,
50 WARM_CACHE_FILL_FRACTION, WARM_CACHE_PROBE_INTERVAL, WarmBlockCacheStats,
51 disable_auto_compactions, hexastore_readahead_env_bytes, iterator_readahead_bytes,
52 pin_index_env_enabled, scan_async_io_env_enabled, sst_filter_env_enabled,
53 warm_cache_env_enabled,
54};
55
56pub(crate) const DOMAIN_SEEK_UNION_ENV: &str = "WARATAH_DOMAIN_SEEK_UNION";
59pub(crate) const DOMAIN_WALKS_ENV: &str = "WARATAH_DOMAIN_WALKS";
65pub(crate) const DOMAIN_WALKS_MIN: usize = 2;
67pub(crate) const DOMAIN_WALKS_MAX: usize = 64;
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub(crate) enum DomainScanMode {
86 Legacy,
89 ParallelWalks(usize),
93}
94
95pub(crate) fn domain_scan_mode() -> DomainScanMode {
108 static MODE: OnceLock<DomainScanMode> = OnceLock::new();
109 *MODE.get_or_init(|| {
110 if let Ok(raw) = std::env::var(DOMAIN_SEEK_UNION_ENV) {
111 eprintln!(
112 "waratah-storage: ignoring WARATAH_DOMAIN_SEEK_UNION={raw:?}: the seek-union \
113 mode was removed; domain scans are legacy or WARATAH_DOMAIN_WALKS=K parallel"
114 );
115 }
116 match std::env::var(DOMAIN_WALKS_ENV).ok() {
117 None => DomainScanMode::ParallelWalks(worker_pool::default_walk_width()),
123 Some(raw) => domain_walks_from_env(Some(raw.as_str()))
126 .map(DomainScanMode::ParallelWalks)
127 .unwrap_or(DomainScanMode::Legacy),
128 }
129 })
130}
131
132fn domain_walks_from_env(raw: Option<&str>) -> Option<usize> {
139 let raw = raw?;
140 match raw.trim().parse::<usize>() {
141 Ok(workers) if (DOMAIN_WALKS_MIN..=DOMAIN_WALKS_MAX).contains(&workers) => Some(workers),
142 Ok(workers) if workers > DOMAIN_WALKS_MAX => {
143 eprintln!(
144 "waratah-storage: clamping WARATAH_DOMAIN_WALKS={raw} to {DOMAIN_WALKS_MAX} workers"
145 );
146 Some(DOMAIN_WALKS_MAX)
147 }
148 Ok(_) => {
149 eprintln!(
150 "waratah-storage: ignoring WARATAH_DOMAIN_WALKS={raw} (needs >= \
151 {DOMAIN_WALKS_MIN}); using legacy domain scans"
152 );
153 None
154 }
155 Err(_) => {
156 eprintln!(
157 "waratah-storage: ignoring invalid WARATAH_DOMAIN_WALKS {raw:?} (expected a \
158 worker count >= {DOMAIN_WALKS_MIN}); using legacy domain scans"
159 );
160 None
161 }
162 }
163}
164
165fn attest_domain_scan_mode(mode: DomainScanMode) {
168 static ATTESTED: OnceLock<()> = OnceLock::new();
169 if mode == DomainScanMode::Legacy {
170 return;
171 }
172 if ATTESTED.set(()).is_ok() {
173 match mode {
174 DomainScanMode::Legacy => unreachable!("checked above"),
175 DomainScanMode::ParallelWalks(workers) => {
176 eprintln!("storage-trace domain scan: parallel K={workers}");
177 }
178 }
179 }
180}
181
182pub(crate) const COUNT_WALKS_ENV: &str = "WARATAH_COUNT_WALKS";
192pub(crate) const COUNT_WALKS_MIN: usize = 2;
194pub(crate) const COUNT_WALKS_MAX: usize = 64;
196const COUNT_WALKS_DEBUG_ENV: &str = "WARATAH_COUNT_WALKS_DEBUG";
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub(crate) enum CountWalkMode {
209 Serial,
211 Parallel(usize),
214}
215
216pub(crate) fn count_walk_mode() -> CountWalkMode {
221 static MODE: OnceLock<CountWalkMode> = OnceLock::new();
222 *MODE.get_or_init(|| match std::env::var(COUNT_WALKS_ENV).ok() {
223 None => CountWalkMode::Parallel(worker_pool::default_walk_width()),
229 Some(raw) => count_walks_from_env(Some(raw.as_str()))
232 .map(CountWalkMode::Parallel)
233 .unwrap_or(CountWalkMode::Serial),
234 })
235}
236
237fn count_walks_from_env(raw: Option<&str>) -> Option<usize> {
244 let raw = raw?;
245 match raw.trim().parse::<usize>() {
246 Ok(workers) if (COUNT_WALKS_MIN..=COUNT_WALKS_MAX).contains(&workers) => Some(workers),
247 Ok(workers) if workers > COUNT_WALKS_MAX => {
248 eprintln!(
249 "waratah-storage: clamping WARATAH_COUNT_WALKS={raw} to {COUNT_WALKS_MAX} workers"
250 );
251 Some(COUNT_WALKS_MAX)
252 }
253 Ok(_) => {
254 eprintln!(
255 "waratah-storage: ignoring WARATAH_COUNT_WALKS={raw} (needs >= \
256 {COUNT_WALKS_MIN}); using serial pattern counts"
257 );
258 None
259 }
260 Err(_) => {
261 eprintln!(
262 "waratah-storage: ignoring invalid WARATAH_COUNT_WALKS {raw:?} (expected a \
263 worker count >= {COUNT_WALKS_MIN}); using serial pattern counts"
264 );
265 None
266 }
267 }
268}
269
270fn count_walks_debug_enabled() -> bool {
273 static DEBUG: OnceLock<bool> = OnceLock::new();
274 *DEBUG.get_or_init(|| std::env::var(COUNT_WALKS_DEBUG_ENV).ok().as_deref() == Some("1"))
275}
276
277fn attest_count_walk_mode(mode: CountWalkMode) {
280 static ATTESTED: OnceLock<()> = OnceLock::new();
281 if let CountWalkMode::Parallel(workers) = mode
282 && ATTESTED.set(()).is_ok()
283 {
284 eprintln!("storage-trace pattern count: parallel K={workers}");
285 }
286}
287
288#[derive(Debug, Clone)]
291pub(crate) struct CountSlice {
292 pub(crate) start: Vec<u8>,
294 pub(crate) end: Option<Vec<u8>>,
297}
298
299struct CountWalkPlan {
301 prefix: Vec<u8>,
304 slices: Vec<CountSlice>,
306}
307
308fn graph_window_names_terms(filter: &GByteFilter) -> bool {
313 match filter {
314 GByteFilter::Unconstrained | GByteFilter::EmptyWindow => false,
315 GByteFilter::Window { named, extras, .. } => !named.is_empty() || !extras.is_empty(),
316 }
317}
318
319fn count_walk_plan(
348 workers: usize,
349 permutation: IndexPermutation,
350 pattern: &EncodedTriplePattern,
351 graph_filter: &GByteFilter,
352 class_totals: &[(StrHash, u64)],
353 arena_tag: impl Fn() -> u8,
357) -> Option<CountWalkPlan> {
358 let graph_scoping_only = pattern
362 .graph_name
363 .as_ref()
364 .is_none_or(|term| matches!(term, EncodedTerm::DefaultGraph));
365 if !graph_scoping_only {
366 return None;
367 }
368 let slots = permutation.slot_order();
369 let leading_bound = pattern.bound_slot(slots[0]).is_some();
370 let non_leading_bound = slots[1..]
371 .iter()
372 .filter(|slot| **slot != QuadSlot::Graph)
373 .any(|slot| pattern.bound_slot(*slot).is_some());
374 let prefix = pattern.build_scan_prefix_bytes(permutation);
375 let slices = if permutation == IndexPermutation::Tsg {
376 if non_leading_bound || graph_window_names_terms(graph_filter) {
380 return None;
381 }
382 if leading_bound {
383 count_slices_even(&prefix, arena_tag(), workers)
385 } else {
386 count_slices_tsg_classes(class_totals, workers)
389 .unwrap_or_else(|| count_slices_even(&prefix, arena_tag(), workers))
390 }
391 } else if leading_bound {
392 if non_leading_bound {
393 return None;
394 }
395 count_slices_even(&prefix, arena_tag(), workers)
397 } else if non_leading_bound {
398 return None;
399 } else {
400 count_slices_even(&prefix, arena_tag(), workers)
402 };
403 Some(CountWalkPlan { prefix, slices })
404}
405
406fn even_boundaries(prefix: &[u8], arena_tag: u8, workers: usize) -> Vec<Vec<u8>> {
422 let mut out = Vec::with_capacity(workers.saturating_sub(1));
423 if workers < 2 {
424 return out;
425 }
426 let step = (u64::MAX / workers as u64).max(1);
428 for j in 1..workers as u64 {
429 let mut boundary = prefix.to_vec();
430 boundary.push(arena_tag);
431 boundary.extend_from_slice(&step.saturating_mul(j).to_be_bytes());
432 out.push(boundary);
433 }
434 out
435}
436
437fn count_slices_even(prefix: &[u8], arena_tag: u8, workers: usize) -> Vec<CountSlice> {
440 let boundaries = even_boundaries(prefix, arena_tag, workers);
441 let mut slices = Vec::with_capacity(boundaries.len() + 1);
442 let mut start = prefix.to_vec();
443 for boundary in &boundaries {
444 slices.push(CountSlice {
445 start,
446 end: Some(boundary.clone()),
447 });
448 start = boundary.clone();
449 }
450 slices.push(CountSlice { start, end: None });
451 slices
452}
453
454fn count_slices_tsg_classes(
465 class_totals: &[(StrHash, u64)],
466 workers: usize,
467) -> Option<Vec<CountSlice>> {
468 let total: u64 = class_totals.iter().map(|(_, rows)| *rows).sum();
469 if workers < 2 || class_totals.len() < 2 || total == 0 {
470 return None;
471 }
472 debug_assert!(
477 class_totals.windows(2).all(|w| w[0].0 < w[1].0),
478 "class_totals hint must ascend by StrHash"
479 );
480 let class_prefix =
481 |hash: &StrHash| encode_term_bytes(&EncodedTerm::NamedNode { iri_id: *hash });
482 let target = total.div_ceil(workers as u64);
483 let mut slices = Vec::new();
484 let mut open_start: Option<Vec<u8>> = None;
487 let mut accumulated = 0u64;
488 for index in 0..class_totals.len() - 1 {
489 accumulated = accumulated.saturating_add(class_totals[index].1);
490 if accumulated >= target {
491 let boundary = class_prefix(&class_totals[index + 1].0);
492 slices.push(CountSlice {
493 start: open_start.unwrap_or_default(),
494 end: Some(boundary.clone()),
495 });
496 open_start = Some(boundary);
497 accumulated = 0;
498 }
499 }
500 slices.push(CountSlice {
501 start: open_start.unwrap_or_default(),
502 end: None,
503 });
504 Some(slices)
505}
506
507#[derive(Clone)]
513struct WalkConstraint {
514 constraint: EncodedTerm,
515 c_bytes: Vec<u8>,
517 seek: Vec<u8>,
520}
521
522struct DomainWalkCtx<'a> {
524 permutation: IndexPermutation,
525 snapshot: SnapshotId,
526 g_window: GWindowKind,
527 graph_name: Option<&'a EncodedTerm>,
528 graph_filter_terms: &'a [EncodedTerm],
529 graph_filter_allow: bool,
530 iri_only_head: bool,
531}
532
533impl<'a> DomainWalkCtx<'a> {
534 fn new(
535 permutation: IndexPermutation,
536 snapshot: SnapshotId,
537 graph_name: Option<&'a EncodedTerm>,
538 graph_filter_terms: &'a [EncodedTerm],
539 graph_filter_allow: bool,
540 iri_only_head: bool,
541 ) -> Self {
542 Self {
543 permutation,
544 snapshot,
545 g_window: classify_g_window(graph_name, graph_filter_terms, graph_filter_allow),
546 graph_name,
547 graph_filter_terms,
548 graph_filter_allow,
549 iri_only_head,
550 }
551 }
552
553 fn into_owned(self) -> DomainWalkCtxOwned {
557 DomainWalkCtxOwned {
558 permutation: self.permutation,
559 snapshot: self.snapshot,
560 g_window: self.g_window,
561 graph_name: self.graph_name.cloned(),
562 graph_filter_terms: self.graph_filter_terms.to_vec(),
563 graph_filter_allow: self.graph_filter_allow,
564 iri_only_head: self.iri_only_head,
565 }
566 }
567}
568
569struct DomainWalkCtxOwned {
572 permutation: IndexPermutation,
573 snapshot: SnapshotId,
574 g_window: GWindowKind,
575 graph_name: Option<EncodedTerm>,
576 graph_filter_terms: Vec<EncodedTerm>,
577 graph_filter_allow: bool,
578 iri_only_head: bool,
579}
580
581impl DomainWalkCtxOwned {
582 fn as_borrowed(&self) -> DomainWalkCtx<'_> {
584 DomainWalkCtx {
585 permutation: self.permutation,
586 snapshot: self.snapshot,
587 g_window: self.g_window,
588 graph_name: self.graph_name.as_ref(),
589 graph_filter_terms: &self.graph_filter_terms,
590 graph_filter_allow: self.graph_filter_allow,
591 iri_only_head: self.iri_only_head,
592 }
593 }
594}
595
596fn build_walk_constraints(
604 permutation: IndexPermutation,
605 constraints: &[EncodedTerm],
606 start_after_constraint: Option<&EncodedTerm>,
607 start_after_term: Option<&EncodedTerm>,
608) -> Result<Vec<WalkConstraint>, StorageError> {
609 let sorted = prepare_constraints_sorted(permutation, constraints)?;
610 let mut out = Vec::with_capacity(sorted.len());
611 for constraint in sorted {
612 let Some(seek) = head_resume_seek(&constraint, start_after_constraint, start_after_term)
613 else {
614 continue;
616 };
617 let c_bytes = encode_term_bytes(&constraint);
618 out.push(WalkConstraint {
619 constraint,
620 c_bytes,
621 seek,
622 });
623 }
624 Ok(out)
625}
626
627fn limit_budget(limit: u64) -> Option<AtomicUsize> {
637 (limit > 0).then(|| AtomicUsize::new(limit_to_usize(limit)))
638}
639
640fn limit_to_usize(limit: u64) -> usize {
646 usize::try_from(limit).unwrap_or(usize::MAX)
647}
648
649fn take_budget(budget: Option<&AtomicUsize>) -> bool {
651 match budget {
652 None => true,
653 Some(budget) => budget
654 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |left| {
655 left.checked_sub(1)
656 })
657 .is_ok(),
658 }
659}
660
661pub(crate) fn split_slices(len: usize, workers: usize) -> Vec<std::ops::Range<usize>> {
668 if len == 0 {
669 return Vec::new();
670 }
671 let count = workers.clamp(1, len);
672 let base = len / count;
673 let rem = len % count;
674 let mut slices = Vec::with_capacity(count);
675 let mut start = 0;
676 for index in 0..count {
677 let size = base + usize::from(index < rem);
678 slices.push(start..start + size);
679 start += size;
680 }
681 slices
682}
683
684struct DomainHitsUnit {
691 db: Db,
692 cf: ColumnFamily,
693 ctx: Arc<DomainWalkCtxOwned>,
694 slice: Vec<WalkConstraint>,
695 budget: Option<AtomicUsize>,
696}
697
698impl PoolUnit for DomainHitsUnit {
699 type Output = Result<Vec<DomainScanHit>, StorageError>;
700
701 fn execute(self) -> Self::Output {
702 let ctx = self.ctx.as_borrowed();
703 confined_hits_on(&self.db, &self.cf, &ctx, &self.slice, self.budget.as_ref())
704 }
705}
706
707fn confined_hits_on(
713 db: &Db,
714 cf: &ColumnFamily,
715 ctx: &DomainWalkCtx<'_>,
716 slice: &[WalkConstraint],
717 budget: Option<&AtomicUsize>,
718) -> Result<Vec<DomainScanHit>, StorageError> {
719 let mut hits = Vec::new();
720 for item in slice {
721 if let Some(budget) = budget
722 && budget.load(Ordering::Relaxed) == 0
723 {
724 break;
725 }
726 let mut iter = db.scan_prefix(cf, &item.c_bytes);
727 if item.seek.as_slice() > item.c_bytes.as_slice() {
728 iter.seek(&item.seek);
729 }
730 let mut state = SnapshotScanState::default();
731 while iter.is_valid() {
732 let Some(key) = iter.key() else { break };
733 if !key.starts_with(&item.c_bytes) {
734 break;
735 }
736 let Some(value) = iter.value() else {
737 return Err(StorageError::Corrupt(
738 "iterator key without value".to_owned(),
739 ));
740 };
741 let head = match consider_head_key(
742 &mut state,
743 ctx.snapshot,
744 key,
745 value,
746 item.c_bytes.len(),
747 graph_hops_after_head(ctx.permutation, true),
748 ctx.g_window,
749 ctx.graph_name,
750 ctx.graph_filter_terms,
751 ctx.graph_filter_allow,
752 ctx.iri_only_head,
753 )? {
754 HeadVerdict::Candidate { head } => head,
755 HeadVerdict::Skip => {
756 iter.next();
757 continue;
758 }
759 };
760 let mut skip = Vec::with_capacity(item.c_bytes.len() + head.len());
767 skip.extend_from_slice(&item.c_bytes);
768 skip.extend_from_slice(&key[head.clone()]);
769 let step = byte_successor(&skip);
770 if !take_budget(budget) {
771 break;
772 }
773 hits.push(DomainScanHit {
774 constraint: item.constraint.clone(),
775 term: head_term_from_region(&key[head.clone()])?,
776 });
777 match step {
778 Some(next) => iter.seek(&next),
779 None => break,
780 }
781 state = SnapshotScanState::default();
782 }
783 iter.status()?;
784 }
785 Ok(hits)
786}
787
788struct DomainCountsUnit {
795 db: Db,
796 cf: ColumnFamily,
797 ctx: Arc<DomainWalkCtxOwned>,
798 slice: Vec<WalkConstraint>,
799 budget: Option<AtomicUsize>,
800 merge_default_graph: bool,
801 count_mode: DomainCountMode,
802}
803
804impl PoolUnit for DomainCountsUnit {
805 type Output = Result<Vec<DomainScanCountHit>, StorageError>;
806
807 fn execute(self) -> Self::Output {
808 let ctx = self.ctx.as_borrowed();
809 confined_counts_on(
810 &self.db,
811 &self.cf,
812 &ctx,
813 &self.slice,
814 self.budget.as_ref(),
815 self.merge_default_graph,
816 self.count_mode,
817 )
818 }
819}
820
821fn confined_counts_on(
832 db: &Db,
833 cf: &ColumnFamily,
834 ctx: &DomainWalkCtx<'_>,
835 slice: &[WalkConstraint],
836 budget: Option<&AtomicUsize>,
837 merge_default_graph: bool,
838 count_mode: DomainCountMode,
839) -> Result<Vec<DomainScanCountHit>, StorageError> {
840 let mut hits = Vec::new();
841 for item in slice {
842 if let Some(budget) = budget
843 && budget.load(Ordering::Relaxed) == 0
844 {
845 break;
846 }
847 let mut iter = db.scan_prefix(cf, &item.c_bytes);
848 if item.seek.as_slice() > item.c_bytes.as_slice() {
849 iter.seek(&item.seek);
850 }
851 let mut state = SnapshotScanState::default();
852 let mut run_head = [0u8; WRITTEN_TERM_MAX_SIZE];
859 let mut run_len = 0usize;
860 let mut current: Option<RunCounter> = None;
861 while iter.is_valid() {
862 let Some(key) = iter.key() else { break };
863 if !key.starts_with(&item.c_bytes) {
864 break;
865 }
866 let Some(value) = iter.value() else {
867 return Err(StorageError::Corrupt(
868 "iterator key without value".to_owned(),
869 ));
870 };
871 let head = match consider_head_key(
872 &mut state,
873 ctx.snapshot,
874 key,
875 value,
876 item.c_bytes.len(),
877 graph_hops_after_head(ctx.permutation, true),
878 ctx.g_window,
879 ctx.graph_name,
880 ctx.graph_filter_terms,
881 ctx.graph_filter_allow,
882 ctx.iri_only_head,
883 )? {
884 HeadVerdict::Candidate { head } => head,
885 HeadVerdict::Skip => {
886 iter.next();
887 continue;
888 }
889 };
890 let opens_new_run = current.is_none() || run_head[..run_len] != key[head.clone()];
891 if opens_new_run {
892 if let Some(run) = current.take() {
893 if !take_budget(budget) {
898 break;
899 }
900 hits.push(DomainScanCountHit {
901 constraint: item.constraint.clone(),
902 term: head_term_from_region(&run_head[..run_len])?,
903 count: run.total(),
904 });
905 }
906 run_head[..head.len()].copy_from_slice(&key[head.clone()]);
907 run_len = head.len();
908 current = Some(RunCounter::new(count_mode));
909 }
910 if let Some(run) = &mut current {
911 match count_mode {
912 DomainCountMode::Rows => run.observe_rows(),
913 DomainCountMode::DistinctTerms => {
914 let slot2 = region_after_head(key, head.end)?;
915 run.observe_distinct_terms(key, &slot2);
916 }
917 DomainCountMode::DistinctGraphs => {
918 let slot2 = region_after_head(key, head.end)?;
919 let logical_end = key.len() - COMMIT_TS_LEN;
920 run.observe_distinct_graphs(&key[slot2.end..logical_end]);
921 }
922 }
923 }
924 if merge_default_graph {
925 let mut stop_walk = false;
935 let tp_len = {
936 let logical = versioned_key_term_prefix(key)?;
937 triple_prefix_len(logical)?
938 };
939 let mut prefix = [0u8; MERGE_TRIPLE_PREFIX_MAX];
940 prefix[..tp_len].copy_from_slice(&key[..tp_len]);
941 let mut chained = 0usize;
942 loop {
943 iter.next();
944 let Some(next_key) = iter.is_valid().then(|| iter.key()).flatten() else {
945 break; };
947 if !next_key.starts_with(&prefix[..tp_len]) {
948 break; }
950 chained += 1;
951 if chained < MERGE_NEXT_CHAIN_LIMIT {
952 continue;
953 }
954 match byte_successor(&prefix[..tp_len]) {
963 Some(next) => {
964 iter.seek(&next);
965 state = SnapshotScanState::default();
966 }
967 None => stop_walk = true,
968 }
969 break;
970 }
971 if stop_walk {
972 break;
973 }
974 } else {
975 iter.next();
976 }
977 }
978 if let Some(run) = current.take() {
983 if take_budget(budget) {
984 hits.push(DomainScanCountHit {
985 constraint: item.constraint.clone(),
986 term: head_term_from_region(&run_head[..run_len])?,
987 count: run.total(),
988 });
989 } else {
990 break;
991 }
992 }
993 iter.status()?;
994 }
995 Ok(hits)
996}
997
998pub struct RocksDbStorage {
1000 axis: PartitionAxis,
1001 path: PathBuf,
1005 db: Db,
1006 cf0: ColumnFamily,
1007 cf1: ColumnFamily,
1008 cf_catalog: Option<ColumnFamily>,
1013 cf_geo: Option<ColumnFamily>,
1017 cf_temporal: Option<ColumnFamily>,
1018 cf_temporal_meta: Option<ColumnFamily>,
1019 cf_geo_meta: Option<ColumnFamily>,
1022 permutations: [IndexPermutation; 2],
1023}
1024
1025impl fmt::Debug for RocksDbStorage {
1026 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027 f.debug_struct("RocksDbStorage")
1028 .field("axis", &self.axis)
1029 .field("permutations", &self.permutations)
1030 .finish_non_exhaustive()
1031 }
1032}
1033
1034impl RocksDbStorage {
1035 pub fn open(path: &Path, axis: PartitionAxis) -> Result<Self, StorageError> {
1037 Self::open_with_hooks(path, axis, RocksDbOptionsHooks::default())
1038 }
1039
1040 pub fn open_with_hooks(
1042 path: &Path,
1043 axis: PartitionAxis,
1044 hooks: RocksDbOptionsHooks<'_>,
1045 ) -> Result<Self, StorageError> {
1046 if let Some(parent) = path.parent() {
1047 std::fs::create_dir_all(parent).map_err(|e| StorageError::Backend(e.to_string()))?;
1048 }
1049 std::fs::create_dir_all(path).map_err(|e| StorageError::Backend(e.to_string()))?;
1050
1051 let permutations = IndexPermutation::for_axis(axis);
1052 let mut column_families: Vec<ColumnFamilyDefinition> = permutations
1053 .into_iter()
1054 .map(|p| ColumnFamilyDefinition {
1055 name: p.cf_name(),
1056 min_prefix_size: match p {
1066 IndexPermutation::Opsg => 0,
1067 _ => 17,
1068 },
1069 prefix_filter: matches!(
1079 p,
1080 IndexPermutation::Spog | IndexPermutation::Sopg | IndexPermutation::Tsg
1081 ),
1082 permutation: Some(p),
1083 })
1084 .collect();
1085 if axis == PartitionAxis::S {
1086 column_families.push(ColumnFamilyDefinition {
1087 name: NAMED_GRAPHS_CATALOG_CF,
1088 min_prefix_size: CATALOG_MIN_PREFIX_SIZE,
1089 prefix_filter: false,
1090 permutation: None,
1091 });
1092 }
1093 if axis == PartitionAxis::O {
1094 column_families.push(ColumnFamilyDefinition {
1097 name: GEO_INDEX_CF,
1098 min_prefix_size: 0,
1099 prefix_filter: false,
1100 permutation: None,
1101 });
1102 column_families.push(ColumnFamilyDefinition {
1105 name: GEO_INDEX_META_CF,
1106 min_prefix_size: 0,
1107 prefix_filter: false,
1108 permutation: None,
1109 });
1110 column_families.push(ColumnFamilyDefinition {
1113 name: TEMPORAL_INDEX_CF,
1114 min_prefix_size: 0,
1115 prefix_filter: false,
1116 permutation: None,
1117 });
1118 column_families.push(ColumnFamilyDefinition {
1120 name: TEMPORAL_INDEX_META_CF,
1121 min_prefix_size: 0,
1122 prefix_filter: false,
1123 permutation: None,
1124 });
1125 }
1126
1127 let mut hooks = hooks;
1133 if let Some(bytes) = hexastore_readahead_env_bytes() {
1134 hooks.tuning.iterator_readahead_bytes = bytes;
1135 eprintln!(
1136 "storage-trace hexastore readahead: {} KiB \
1137 (TEST_HEXASTORE_READAHEAD_SIZE)",
1138 bytes / 1024
1139 );
1140 }
1141
1142 let db = Db::open_read_write_with_hooks(path, column_families, hooks)?;
1143 let cf0 = db.column_family(permutations[0].cf_name())?;
1144 let cf1 = db.column_family(permutations[1].cf_name())?;
1145 let cf_catalog = if axis == PartitionAxis::S {
1146 Some(db.column_family(NAMED_GRAPHS_CATALOG_CF)?)
1147 } else {
1148 None
1149 };
1150 let cf_geo = if axis == PartitionAxis::O {
1151 Some(db.column_family(GEO_INDEX_CF)?)
1152 } else {
1153 None
1154 };
1155 let cf_geo_meta = if axis == PartitionAxis::O {
1156 Some(db.column_family(GEO_INDEX_META_CF)?)
1157 } else {
1158 None
1159 };
1160 let cf_temporal = if axis == PartitionAxis::O {
1161 Some(db.column_family(TEMPORAL_INDEX_CF)?)
1162 } else {
1163 None
1164 };
1165 let cf_temporal_meta = if axis == PartitionAxis::O {
1166 Some(db.column_family(TEMPORAL_INDEX_META_CF)?)
1167 } else {
1168 None
1169 };
1170 Ok(Self {
1171 axis,
1172 path: path.to_path_buf(),
1173 db,
1174 cf0,
1175 cf1,
1176 cf_catalog,
1177 cf_geo,
1178 cf_temporal,
1179 cf_temporal_meta,
1180 cf_geo_meta,
1181 permutations,
1182 })
1183 }
1184
1185 pub fn axis(&self) -> PartitionAxis {
1187 self.axis
1188 }
1189
1190 pub fn data_path(&self) -> &Path {
1192 &self.path
1193 }
1194
1195 pub fn insert_quad_version(
1197 &self,
1198 quad: &Quad,
1199 commit_ts: CommitTs,
1200 op: StorageOp,
1201 visibility: VisibilityLabel,
1202 ) -> Result<(), StorageError> {
1203 self.insert_encoded_quad_version(&encode_quad(quad)?, commit_ts, op, visibility)
1204 }
1205
1206 pub fn insert_encoded_quad_version(
1208 &self,
1209 encoded: &EncodedQuad,
1210 commit_ts: CommitTs,
1211 op: StorageOp,
1212 visibility: VisibilityLabel,
1213 ) -> Result<(), StorageError> {
1214 let puts = prepare_hexastore_puts(
1215 self.axis,
1216 [HexastoreVersion {
1217 quad: encoded,
1218 commit_ts,
1219 op,
1220 visibility,
1221 }],
1222 );
1223 let catalog = self.catalog_puts_for_encoded(encoded, commit_ts, op)?;
1224 self.apply_prepared_puts_with_catalog(&puts, &catalog)
1225 }
1226
1227 pub fn apply_prepared_puts(&self, puts: &[HexastorePut]) -> Result<(), StorageError> {
1233 self.apply_prepared_puts_with_catalog(puts, &[])
1234 }
1235
1236 pub fn apply_prepared_puts_with_catalog(
1240 &self,
1241 puts: &[HexastorePut],
1242 catalog: &[CatalogPut],
1243 ) -> Result<(), StorageError> {
1244 if puts.is_empty() && catalog.is_empty() {
1245 return Ok(());
1246 }
1247 if !catalog.is_empty() && self.cf_catalog.is_none() {
1248 return Err(StorageError::CatalogNotOnAxis(self.axis));
1249 }
1250 let mut batch = self.db.write_batch();
1251 for put in puts {
1252 let cf = match put.cf_index {
1253 0 => &self.cf0,
1254 1 => &self.cf1,
1255 other => {
1256 return Err(StorageError::Backend(format!(
1257 "hexastore put cf_index {other} is not 0 or 1"
1258 )));
1259 }
1260 };
1261 batch.insert(cf, &put.key, &put.value);
1262 }
1263 if let Some(cf) = &self.cf_catalog {
1264 for put in catalog {
1265 batch.insert(cf, &put.key, &put.value);
1266 }
1267 }
1268 batch.commit()
1269 }
1270
1271 pub fn catalog_puts_for_insert(
1273 &self,
1274 graphs: &[(EncodedTerm, CommitTs)],
1275 ) -> Result<Vec<CatalogPut>, StorageError> {
1276 if self.axis != PartitionAxis::S {
1277 return Err(StorageError::CatalogNotOnAxis(self.axis));
1278 }
1279 stage_catalog_puts(graphs, |graph| self.catalog_newest_state(graph))
1280 }
1281
1282 pub fn add_named_graph(
1284 &self,
1285 graph: &EncodedTerm,
1286 commit_ts: CommitTs,
1287 ) -> Result<(), StorageError> {
1288 require_catalog_graph(graph)?;
1289 let puts = self.catalog_puts_for_insert(&[(graph.clone(), commit_ts)])?;
1290 self.apply_prepared_puts_with_catalog(&[], &puts)
1291 }
1292
1293 pub fn list_named_graphs(
1297 &self,
1298 snapshot: SnapshotId,
1299 ) -> Result<Vec<EncodedTerm>, StorageError> {
1300 let cf = self.catalog_cf()?;
1301 let mut iter = self.db.scan_prefix(cf, &[]);
1302 let mut entries = Vec::new();
1303 while iter.is_valid() {
1304 let Some(key) = iter.key() else { break };
1305 let Some(value) = iter.value() else {
1306 return Err(StorageError::Corrupt(
1307 "catalog iterator key without value".to_owned(),
1308 ));
1309 };
1310 entries.push((key.to_vec(), value.to_vec()));
1311 iter.next();
1312 }
1313 iter.status()?;
1314 collect_dedup_visible_catalog_graphs(
1315 entries
1316 .iter()
1317 .map(|(key, value)| (key.as_slice(), value.as_slice())),
1318 snapshot,
1319 )
1320 }
1321
1322 pub fn rebuild_named_graph_catalog(&self) -> Result<CatalogRebuildStats, StorageError> {
1328 let _ = self.catalog_cf()?;
1329 let mut first_puts = Vec::new();
1330 self.visit_index_versions(IndexPermutation::Spog, |quad, commit_ts, op| {
1331 record_first_put_graph(&mut first_puts, &quad.graph_name, commit_ts, op);
1332 Ok(())
1333 })?;
1334 let mut stats = CatalogRebuildStats::default();
1335 let mut staged = Vec::new();
1336 for (graph, commit_ts) in &first_puts {
1337 if self.catalog_prefix_occupied(graph)? {
1338 stats.graphs_skipped += 1;
1339 } else {
1340 staged.push(CatalogPut::new(
1341 graph,
1342 *commit_ts,
1343 GraphCatalogState::Present,
1344 )?);
1345 stats.graphs_inserted += 1;
1346 }
1347 }
1348 self.apply_prepared_puts_with_catalog(&[], &staged)?;
1349 Ok(stats)
1350 }
1351
1352 pub fn visit_index_versions(
1354 &self,
1355 permutation: IndexPermutation,
1356 mut visit: impl FnMut(&EncodedQuad, CommitTs, StorageOp) -> Result<(), StorageError>,
1357 ) -> Result<(), StorageError> {
1358 let cf = self.cf_for(permutation)?;
1359 let mut iter = self.db.scan_prefix(cf, &[]);
1360 while iter.is_valid() {
1361 let Some(key) = iter.key() else { break };
1362 let Some(value) = iter.value() else {
1363 return Err(StorageError::Corrupt(
1364 "iterator key without value".to_owned(),
1365 ));
1366 };
1367 let (quad, commit_ts) = decode_versioned_key(permutation, key)?;
1368 let (op, _visibility) = decode_storage_value(value)?;
1369 visit(&quad, commit_ts, op)?;
1370 iter.next();
1371 }
1372 iter.status()
1373 }
1374
1375 pub fn scan_pattern(
1380 &self,
1381 pattern: &EncodedTriplePattern,
1382 snapshot: SnapshotId,
1383 ) -> Result<Vec<EncodedQuad>, StorageError> {
1384 self.scan_pattern_in(pattern.best_permutation(self.axis), pattern, snapshot)
1385 }
1386
1387 pub fn scan_pattern_in(
1392 &self,
1393 permutation: IndexPermutation,
1394 pattern: &EncodedTriplePattern,
1395 snapshot: SnapshotId,
1396 ) -> Result<Vec<EncodedQuad>, StorageError> {
1397 self.scan_pattern_page(
1400 permutation,
1401 pattern,
1402 snapshot,
1403 0,
1404 None,
1405 GByteFilter::Unconstrained,
1406 false,
1407 IriOnlyMask::NONE,
1408 )
1409 .map(|page| page.rows)
1410 }
1411
1412 #[allow(clippy::too_many_arguments)]
1419 pub fn scan_pattern_page(
1420 &self,
1421 permutation: IndexPermutation,
1422 pattern: &EncodedTriplePattern,
1423 snapshot: SnapshotId,
1424 limit: u64,
1425 start_after: Option<&EncodedQuad>,
1426 graph_filter: GByteFilter,
1427 merge_default_graph: bool,
1428 iri_only: IriOnlyMask,
1429 ) -> Result<ScanPage, StorageError> {
1430 self.scan_pattern_page_with_comparisons(
1431 permutation,
1432 pattern,
1433 snapshot,
1434 limit,
1435 start_after,
1436 graph_filter,
1437 merge_default_graph,
1438 iri_only,
1439 &ComparisonMask::default(),
1440 )
1441 }
1442
1443 #[allow(clippy::too_many_arguments)]
1446 pub fn scan_pattern_page_with_comparisons(
1447 &self,
1448 permutation: IndexPermutation,
1449 pattern: &EncodedTriplePattern,
1450 snapshot: SnapshotId,
1451 limit: u64,
1452 start_after: Option<&EncodedQuad>,
1453 graph_filter: GByteFilter,
1454 merge_default_graph: bool,
1455 iri_only: IriOnlyMask,
1456 mask: &ComparisonMask,
1457 ) -> Result<ScanPage, StorageError> {
1458 let mut out = Vec::new();
1462 let exhausted = self.visit_pattern_quads(
1463 permutation,
1464 pattern,
1465 snapshot,
1466 limit,
1467 start_after,
1468 graph_filter,
1469 merge_default_graph,
1470 iri_only,
1471 mask,
1472 |mut quad| {
1473 if merge_default_graph {
1474 quad = quad.into_merged_default();
1475 }
1476 out.push(quad);
1477 Ok(true)
1478 },
1479 )?;
1480 Ok(ScanPage {
1481 rows: out,
1482 exhausted: Some(exhausted),
1483 })
1484 }
1485
1486 #[allow(clippy::too_many_arguments)]
1502 pub fn count_pattern_impl(
1503 &self,
1504 permutation: IndexPermutation,
1505 pattern: &EncodedTriplePattern,
1506 snapshot: SnapshotId,
1507 limit: u64,
1508 graph_filter: GByteFilter,
1509 merge_default_graph: bool,
1510 ) -> Result<u64, StorageError> {
1511 let mode = count_walk_mode();
1512 self.count_pattern_impl_with_mode(
1513 mode,
1514 permutation,
1515 pattern,
1516 snapshot,
1517 limit,
1518 graph_filter,
1519 merge_default_graph,
1520 &[],
1521 )
1522 }
1523
1524 #[allow(clippy::too_many_arguments)]
1534 pub fn count_pattern_impl_with_class_totals(
1535 &self,
1536 permutation: IndexPermutation,
1537 pattern: &EncodedTriplePattern,
1538 snapshot: SnapshotId,
1539 limit: u64,
1540 graph_filter: GByteFilter,
1541 merge_default_graph: bool,
1542 class_totals: &[(StrHash, u64)],
1543 force_serial: bool,
1544 ) -> Result<u64, StorageError> {
1545 let mode = if force_serial {
1546 CountWalkMode::Serial
1547 } else {
1548 count_walk_mode()
1549 };
1550 self.count_pattern_impl_with_mode(
1551 mode,
1552 permutation,
1553 pattern,
1554 snapshot,
1555 limit,
1556 graph_filter,
1557 merge_default_graph,
1558 class_totals,
1559 )
1560 }
1561
1562 #[allow(clippy::too_many_arguments)]
1565 pub(crate) fn count_pattern_impl_with_mode(
1566 &self,
1567 mode: CountWalkMode,
1568 permutation: IndexPermutation,
1569 pattern: &EncodedTriplePattern,
1570 snapshot: SnapshotId,
1571 limit: u64,
1572 graph_filter: GByteFilter,
1573 merge_default_graph: bool,
1574 class_totals: &[(StrHash, u64)],
1575 ) -> Result<u64, StorageError> {
1576 attest_count_walk_mode(mode);
1577 if let CountWalkMode::Parallel(workers) = mode
1583 && limit == 0
1584 && !merge_default_graph
1585 {
1586 let workers = workers.min(worker_pool::effective_width());
1587 if workers >= 2 {
1591 let cf = self.cf_for(permutation)?;
1592 let prefix = pattern.build_scan_prefix_bytes(permutation);
1593 if let Some(plan) = count_walk_plan(
1601 workers,
1602 permutation,
1603 pattern,
1604 &graph_filter,
1605 class_totals,
1606 || {
1607 let probe = self.db.scan_prefix(cf, &prefix);
1608 let tag = probe.key().and_then(|key| key.get(prefix.len()).copied());
1609 tag.unwrap_or(0x01)
1610 },
1611 ) {
1612 return self.count_pattern_sliced(
1613 permutation,
1614 pattern,
1615 snapshot,
1616 graph_filter,
1617 merge_default_graph,
1618 plan,
1619 );
1620 }
1621 }
1622 }
1623 let mut count = 0u64;
1624 self.visit_pattern_rows(
1625 permutation,
1626 pattern,
1627 snapshot,
1628 None,
1629 graph_filter,
1630 merge_default_graph,
1631 IriOnlyMask::NONE,
1632 &ComparisonMask::default(),
1633 |_row| {
1634 count += 1;
1635 Ok(limit == 0 || count < limit)
1636 },
1637 )?;
1638 Ok(count)
1639 }
1640
1641 fn count_pattern_sliced(
1651 &self,
1652 permutation: IndexPermutation,
1653 pattern: &EncodedTriplePattern,
1654 snapshot: SnapshotId,
1655 graph_filter: GByteFilter,
1656 merge_default_graph: bool,
1657 plan: CountWalkPlan,
1658 ) -> Result<u64, StorageError> {
1659 let cf = *self.cf_for(permutation)?;
1660 let units: Vec<CountSliceUnit> = plan
1664 .slices
1665 .into_iter()
1666 .enumerate()
1667 .map(|(index, slice)| CountSliceUnit {
1668 db: self.db.clone(),
1669 cf,
1670 permutation,
1671 pattern: pattern.clone(),
1672 snapshot,
1673 graph_filter: graph_filter.clone(),
1674 merge_default_graph,
1675 prefix: plan.prefix.clone(),
1676 slice,
1677 is_first: index == 0,
1678 })
1679 .collect();
1680 let outcomes = worker_pool::run_units(units);
1681 let mut counts = Vec::with_capacity(outcomes.len());
1682 for outcome in outcomes {
1683 match outcome {
1684 UnitOutcome::Ok(part) => counts.push(part?),
1685 UnitOutcome::Panicked(message) => {
1686 return Err(StorageError::Backend(format!(
1687 "pattern count worker panicked: {message}"
1688 )));
1689 }
1690 }
1691 }
1692 if count_walks_debug_enabled() {
1693 let total: u64 = counts.iter().sum();
1694 eprintln!(
1695 "storage-trace pattern count: cf={} slices={} rows={counts:?} total={total}",
1696 permutation.cf_name(),
1697 counts.len(),
1698 );
1699 }
1700 Ok(counts.iter().sum())
1701 }
1702
1703 pub fn count_pattern_best_permutation(
1708 &self,
1709 pattern: &EncodedTriplePattern,
1710 snapshot: SnapshotId,
1711 limit: u64,
1712 ) -> Result<u64, StorageError> {
1713 self.count_pattern_in(
1714 pattern.best_permutation(self.axis),
1715 pattern,
1716 snapshot,
1717 limit,
1718 )
1719 }
1720
1721 pub fn count_pattern_in(
1726 &self,
1727 permutation: IndexPermutation,
1728 pattern: &EncodedTriplePattern,
1729 snapshot: SnapshotId,
1730 limit: u64,
1731 ) -> Result<u64, StorageError> {
1732 let mut count = 0u64;
1734 self.visit_pattern_rows(
1735 permutation,
1736 pattern,
1737 snapshot,
1738 None,
1739 GByteFilter::Unconstrained,
1740 false,
1741 IriOnlyMask::NONE,
1742 &ComparisonMask::default(),
1743 |_row| {
1744 count += 1;
1745 Ok(limit == 0 || count < limit)
1746 },
1747 )?;
1748 Ok(count)
1749 }
1750
1751 #[allow(clippy::too_many_arguments)]
1761 pub(crate) fn visit_pattern_rows(
1762 &self,
1763 permutation: IndexPermutation,
1764 pattern: &EncodedTriplePattern,
1765 snapshot: SnapshotId,
1766 start_after: Option<&EncodedQuad>,
1767 graph_filter: GByteFilter,
1768 merge_default_graph: bool,
1769 iri_only: IriOnlyMask,
1770 mask: &ComparisonMask,
1771 mut on_match: impl FnMut(&KeyRow) -> Result<bool, StorageError>,
1772 ) -> Result<ScanExhaustion, StorageError> {
1773 let cf = self.cf_for(permutation)?;
1774 let prefix = pattern.build_scan_prefix_bytes(permutation);
1775
1776 let mut state = SnapshotScanState::default();
1777 let mut matcher = RowMatcher::compile(
1778 pattern,
1779 permutation,
1780 graph_filter,
1781 merge_default_graph,
1782 start_after,
1783 iri_only,
1784 );
1785 let cursor_key = start_after.map(|quad| encode_index_key(permutation, quad));
1789 let seek = cursor_key
1790 .as_deref()
1791 .filter(|key| *key > prefix.as_slice())
1792 .unwrap_or(prefix.as_slice());
1793 let mut iter = if seek == prefix.as_slice() {
1794 self.db.scan_prefix(cf, &prefix)
1795 } else {
1796 self.db.scan_prefix_from(cf, &prefix, seek)
1797 };
1798 let mut verdict = ScanExhaustion::ExhaustedScan;
1804 while iter.is_valid() {
1805 let Some(key) = iter.key() else { break };
1806 if !key.starts_with(&prefix) {
1807 break;
1808 }
1809 if let Some(cursor) = cursor_key.as_deref() {
1810 let logical = versioned_key_term_prefix(key)?;
1811 if logical <= cursor {
1812 iter.next();
1813 continue;
1814 }
1815 }
1816 let decision = {
1817 let Some(value) = iter.value() else {
1818 return Err(StorageError::Corrupt(
1819 "iterator key without value".to_owned(),
1820 ));
1821 };
1822 matcher.matches_row(key, value, snapshot, &mut state)?
1823 };
1824 if let MatchDecision::Emit {
1825 slot_starts,
1826 commit_ts,
1827 } = decision
1828 {
1829 let row = KeyRow {
1830 key,
1831 permutation,
1832 seg_starts: slot_starts,
1833 commit_ts,
1834 };
1835 if mask.keeps(row.logical(), &row.seg_starts) && !on_match(&row)? {
1838 verdict = ScanExhaustion::Limited;
1839 break;
1840 }
1841 }
1842 iter.next();
1843 }
1844 iter.status()?;
1845 Ok(verdict)
1846 }
1847
1848 #[allow(clippy::too_many_arguments)]
1849 pub(crate) fn visit_pattern_quads(
1850 &self,
1851 permutation: IndexPermutation,
1852 pattern: &EncodedTriplePattern,
1853 snapshot: SnapshotId,
1854 limit: u64,
1855 start_after: Option<&EncodedQuad>,
1856 graph_filter: GByteFilter,
1857 merge_default_graph: bool,
1858 iri_only: IriOnlyMask,
1859 mask: &ComparisonMask,
1860 mut on_match: impl FnMut(EncodedQuad) -> Result<bool, StorageError>,
1863 ) -> Result<ScanExhaustion, StorageError> {
1864 let mut error = None;
1865 let mut matched = 0u64;
1866 let verdict = self.visit_pattern_rows(
1872 permutation,
1873 pattern,
1874 snapshot,
1875 start_after,
1876 graph_filter,
1877 merge_default_graph,
1878 iri_only,
1879 mask,
1880 |row| {
1881 if error.is_some() {
1882 return Ok(false);
1883 }
1884 match decode_index_key(permutation, row.logical()) {
1885 Ok(quad) => {
1886 if limit > 0 && matched >= limit {
1893 return Ok(false);
1894 }
1895 match on_match(quad) {
1896 Ok(keep_going) => {
1897 matched += 1;
1898 Ok(keep_going)
1899 }
1900 Err(e) => {
1901 error = Some(e);
1902 Ok(false)
1903 }
1904 }
1905 }
1906 Err(e) => {
1907 error = Some(e);
1908 Ok(false)
1909 }
1910 }
1911 },
1912 )?;
1913 match error {
1914 Some(e) => Err(e),
1915 None => Ok(verdict),
1916 }
1917 }
1918
1919 #[allow(clippy::too_many_arguments)]
1926 pub fn scan_pattern_page_allow_list(
1927 &self,
1928 permutation: IndexPermutation,
1929 pattern: &EncodedTriplePattern,
1930 snapshot: SnapshotId,
1931 limit: u64,
1932 start_after: Option<&EncodedQuad>,
1933 allow_list_slot: QuadSlot,
1934 allow_terms: &[EncodedTerm],
1935 graph_filter: GByteFilter,
1936 merge_default_graph: bool,
1937 iri_only: IriOnlyMask,
1938 ) -> Result<Option<ScanPage>, StorageError> {
1939 self.scan_pattern_page_allow_list_with_comparisons(
1940 permutation,
1941 pattern,
1942 snapshot,
1943 limit,
1944 start_after,
1945 allow_list_slot,
1946 allow_terms,
1947 graph_filter,
1948 merge_default_graph,
1949 iri_only,
1950 &ComparisonMask::default(),
1951 )
1952 }
1953
1954 #[allow(clippy::too_many_arguments)]
1957 pub fn scan_pattern_page_allow_list_with_comparisons(
1958 &self,
1959 permutation: IndexPermutation,
1960 pattern: &EncodedTriplePattern,
1961 snapshot: SnapshotId,
1962 limit: u64,
1963 start_after: Option<&EncodedQuad>,
1964 allow_list_slot: QuadSlot,
1965 allow_terms: &[EncodedTerm],
1966 graph_filter: GByteFilter,
1967 merge_default_graph: bool,
1968 iri_only: IriOnlyMask,
1969 mask: &ComparisonMask,
1970 ) -> Result<Option<ScanPage>, StorageError> {
1971 let mut out = Vec::new();
1972 let verdict = self.visit_allow_list_rows(
1973 permutation,
1974 pattern,
1975 snapshot,
1976 start_after,
1977 allow_list_slot,
1978 allow_terms,
1979 graph_filter,
1980 merge_default_graph,
1981 iri_only,
1982 mask,
1983 |row| {
1984 if limit > 0 && (out.len() as u64) >= limit {
1991 return Ok(false);
1992 }
1993 let mut quad = decode_index_key(permutation, row.logical())?;
1994 if merge_default_graph {
1995 quad = quad.into_merged_default();
1996 }
1997 out.push(quad);
1998 Ok(true)
1999 },
2000 )?;
2001 Ok(verdict.map(|exhausted| ScanPage {
2002 rows: out,
2003 exhausted: Some(exhausted),
2004 }))
2005 }
2006
2007 #[allow(clippy::too_many_arguments)]
2024 pub fn scan_domain(
2025 &self,
2026 permutation: IndexPermutation,
2027 constraints: &[EncodedTerm],
2028 snapshot: SnapshotId,
2029 limit: u64,
2030 start_after_constraint: Option<&EncodedTerm>,
2031 start_after_term: Option<&EncodedTerm>,
2032 graph_name: Option<&EncodedTerm>,
2033 graph_filter_terms: &[EncodedTerm],
2034 graph_filter_allow: bool,
2035 iri_only_head: bool,
2036 ) -> Result<Vec<DomainScanHit>, StorageError> {
2037 let mode = domain_scan_mode();
2038 attest_domain_scan_mode(mode);
2039 self.scan_domain_with_mode(
2040 mode,
2041 permutation,
2042 constraints,
2043 snapshot,
2044 limit,
2045 start_after_constraint,
2046 start_after_term,
2047 graph_name,
2048 graph_filter_terms,
2049 graph_filter_allow,
2050 iri_only_head,
2051 )
2052 }
2053
2054 #[allow(clippy::too_many_arguments)]
2057 pub(crate) fn scan_domain_with_mode(
2058 &self,
2059 mode: DomainScanMode,
2060 permutation: IndexPermutation,
2061 constraints: &[EncodedTerm],
2062 snapshot: SnapshotId,
2063 limit: u64,
2064 start_after_constraint: Option<&EncodedTerm>,
2065 start_after_term: Option<&EncodedTerm>,
2066 graph_name: Option<&EncodedTerm>,
2067 graph_filter_terms: &[EncodedTerm],
2068 graph_filter_allow: bool,
2069 iri_only_head: bool,
2070 ) -> Result<Vec<DomainScanHit>, StorageError> {
2071 match mode {
2072 DomainScanMode::Legacy => self.scan_domain_legacy(
2073 permutation,
2074 constraints,
2075 snapshot,
2076 limit,
2077 start_after_constraint,
2078 start_after_term,
2079 graph_name,
2080 graph_filter_terms,
2081 graph_filter_allow,
2082 iri_only_head,
2083 ),
2084 DomainScanMode::ParallelWalks(workers) => self.scan_domain_parallel(
2085 workers,
2086 permutation,
2087 constraints,
2088 snapshot,
2089 limit,
2090 start_after_constraint,
2091 start_after_term,
2092 graph_name,
2093 graph_filter_terms,
2094 graph_filter_allow,
2095 iri_only_head,
2096 ),
2097 }
2098 }
2099
2100 #[allow(clippy::too_many_arguments)]
2105 fn scan_domain_legacy(
2106 &self,
2107 permutation: IndexPermutation,
2108 constraints: &[EncodedTerm],
2109 snapshot: SnapshotId,
2110 limit: u64,
2111 start_after_constraint: Option<&EncodedTerm>,
2112 start_after_term: Option<&EncodedTerm>,
2113 graph_name: Option<&EncodedTerm>,
2114 graph_filter_terms: &[EncodedTerm],
2115 graph_filter_allow: bool,
2116 iri_only_head: bool,
2117 ) -> Result<Vec<DomainScanHit>, StorageError> {
2118 let prepared = build_walk_constraints(
2126 permutation,
2127 constraints,
2128 start_after_constraint,
2129 start_after_term,
2130 )?;
2131 if prepared.is_empty() {
2132 return Ok(Vec::new());
2133 }
2134 let cf = self.cf_for(permutation)?;
2135 let ctx = DomainWalkCtx::new(
2136 permutation,
2137 snapshot,
2138 graph_name,
2139 graph_filter_terms,
2140 graph_filter_allow,
2141 iri_only_head,
2142 );
2143 let budget = limit_budget(limit);
2144 confined_hits_on(&self.db, cf, &ctx, &prepared, budget.as_ref())
2145 }
2146
2147 #[allow(clippy::too_many_arguments)]
2168 fn scan_domain_parallel(
2169 &self,
2170 workers: usize,
2171 permutation: IndexPermutation,
2172 constraints: &[EncodedTerm],
2173 snapshot: SnapshotId,
2174 limit: u64,
2175 start_after_constraint: Option<&EncodedTerm>,
2176 start_after_term: Option<&EncodedTerm>,
2177 graph_name: Option<&EncodedTerm>,
2178 graph_filter_terms: &[EncodedTerm],
2179 graph_filter_allow: bool,
2180 iri_only_head: bool,
2181 ) -> Result<Vec<DomainScanHit>, StorageError> {
2182 let cf = *self.cf_for(permutation)?;
2183 let prepared = build_walk_constraints(
2184 permutation,
2185 constraints,
2186 start_after_constraint,
2187 start_after_term,
2188 )?;
2189 if prepared.is_empty() {
2190 return Ok(Vec::new());
2191 }
2192 let ctx = Arc::new(
2195 DomainWalkCtx::new(
2196 permutation,
2197 snapshot,
2198 graph_name,
2199 graph_filter_terms,
2200 graph_filter_allow,
2201 iri_only_head,
2202 )
2203 .into_owned(),
2204 );
2205 let workers = workers.min(worker_pool::effective_width());
2206 if workers < 2 {
2210 return self.scan_domain_legacy(
2211 permutation,
2212 constraints,
2213 snapshot,
2214 limit,
2215 start_after_constraint,
2216 start_after_term,
2217 graph_name,
2218 graph_filter_terms,
2219 graph_filter_allow,
2220 iri_only_head,
2221 );
2222 }
2223 let slices = split_slices(prepared.len(), workers);
2224 let units: Vec<DomainHitsUnit> = slices
2225 .iter()
2226 .map(|slice| DomainHitsUnit {
2227 db: self.db.clone(),
2228 cf,
2229 ctx: Arc::clone(&ctx),
2230 slice: prepared[slice.clone()].to_vec(),
2233 budget: limit_budget(limit),
2234 })
2235 .collect();
2236 let outcomes = worker_pool::run_units(units);
2237 let mut hits = Vec::new();
2238 for outcome in outcomes {
2239 match outcome {
2242 UnitOutcome::Ok(part) => {
2243 let mut part = part?;
2244 hits.append(&mut part);
2245 }
2246 UnitOutcome::Panicked(message) => {
2247 return Err(StorageError::Backend(format!(
2248 "domain scan worker panicked: {message}"
2249 )));
2250 }
2251 }
2252 }
2253 if limit > 0 && hits.len() > limit_to_usize(limit) {
2254 hits.truncate(limit_to_usize(limit));
2255 }
2256 Ok(hits)
2257 }
2258
2259 #[allow(clippy::too_many_arguments)]
2274 pub fn scan_domain_counts(
2275 &self,
2276 permutation: IndexPermutation,
2277 constraints: &[EncodedTerm],
2278 snapshot: SnapshotId,
2279 limit: u64,
2280 start_after_constraint: Option<&EncodedTerm>,
2281 start_after_term: Option<&EncodedTerm>,
2282 graph_name: Option<&EncodedTerm>,
2283 graph_filter_terms: &[EncodedTerm],
2284 graph_filter_allow: bool,
2285 iri_only_head: bool,
2286 merge_default_graph: bool,
2287 mode: DomainCountMode,
2288 ) -> Result<Vec<DomainScanCountHit>, StorageError> {
2289 let exec = domain_scan_mode();
2290 attest_domain_scan_mode(exec);
2291 self.scan_domain_counts_with_mode(
2292 exec,
2293 permutation,
2294 constraints,
2295 snapshot,
2296 limit,
2297 start_after_constraint,
2298 start_after_term,
2299 graph_name,
2300 graph_filter_terms,
2301 graph_filter_allow,
2302 iri_only_head,
2303 merge_default_graph,
2304 mode,
2305 )
2306 }
2307
2308 #[allow(clippy::too_many_arguments)]
2310 pub(crate) fn scan_domain_counts_with_mode(
2311 &self,
2312 mode: DomainScanMode,
2313 permutation: IndexPermutation,
2314 constraints: &[EncodedTerm],
2315 snapshot: SnapshotId,
2316 limit: u64,
2317 start_after_constraint: Option<&EncodedTerm>,
2318 start_after_term: Option<&EncodedTerm>,
2319 graph_name: Option<&EncodedTerm>,
2320 graph_filter_terms: &[EncodedTerm],
2321 graph_filter_allow: bool,
2322 iri_only_head: bool,
2323 merge_default_graph: bool,
2324 count_mode: DomainCountMode,
2325 ) -> Result<Vec<DomainScanCountHit>, StorageError> {
2326 if permutation == IndexPermutation::Tsg && count_mode != DomainCountMode::Rows {
2332 return Err(StorageError::DistinctCountsNotOnTsg);
2333 }
2334 match mode {
2335 DomainScanMode::Legacy => self.scan_domain_counts_legacy(
2336 permutation,
2337 constraints,
2338 snapshot,
2339 limit,
2340 start_after_constraint,
2341 start_after_term,
2342 graph_name,
2343 graph_filter_terms,
2344 graph_filter_allow,
2345 iri_only_head,
2346 merge_default_graph,
2347 count_mode,
2348 ),
2349 DomainScanMode::ParallelWalks(workers) => self.scan_domain_counts_parallel(
2350 workers,
2351 permutation,
2352 constraints,
2353 snapshot,
2354 limit,
2355 start_after_constraint,
2356 start_after_term,
2357 graph_name,
2358 graph_filter_terms,
2359 graph_filter_allow,
2360 iri_only_head,
2361 merge_default_graph,
2362 count_mode,
2363 ),
2364 }
2365 }
2366
2367 #[allow(clippy::too_many_arguments)]
2372 fn scan_domain_counts_legacy(
2373 &self,
2374 permutation: IndexPermutation,
2375 constraints: &[EncodedTerm],
2376 snapshot: SnapshotId,
2377 limit: u64,
2378 start_after_constraint: Option<&EncodedTerm>,
2379 start_after_term: Option<&EncodedTerm>,
2380 graph_name: Option<&EncodedTerm>,
2381 graph_filter_terms: &[EncodedTerm],
2382 graph_filter_allow: bool,
2383 iri_only_head: bool,
2384 merge_default_graph: bool,
2385 count_mode: DomainCountMode,
2386 ) -> Result<Vec<DomainScanCountHit>, StorageError> {
2387 let prepared = build_walk_constraints(
2395 permutation,
2396 constraints,
2397 start_after_constraint,
2398 start_after_term,
2399 )?;
2400 if prepared.is_empty() {
2401 return Ok(Vec::new());
2402 }
2403 let cf = self.cf_for(permutation)?;
2404 let ctx = DomainWalkCtx::new(
2405 permutation,
2406 snapshot,
2407 graph_name,
2408 graph_filter_terms,
2409 graph_filter_allow,
2410 iri_only_head,
2411 );
2412 let budget = limit_budget(limit);
2413 confined_counts_on(
2414 &self.db,
2415 cf,
2416 &ctx,
2417 &prepared,
2418 budget.as_ref(),
2419 merge_default_graph,
2420 count_mode,
2421 )
2422 }
2423
2424 #[allow(clippy::too_many_arguments)]
2433 fn scan_domain_counts_parallel(
2434 &self,
2435 workers: usize,
2436 permutation: IndexPermutation,
2437 constraints: &[EncodedTerm],
2438 snapshot: SnapshotId,
2439 limit: u64,
2440 start_after_constraint: Option<&EncodedTerm>,
2441 start_after_term: Option<&EncodedTerm>,
2442 graph_name: Option<&EncodedTerm>,
2443 graph_filter_terms: &[EncodedTerm],
2444 graph_filter_allow: bool,
2445 iri_only_head: bool,
2446 merge_default_graph: bool,
2447 count_mode: DomainCountMode,
2448 ) -> Result<Vec<DomainScanCountHit>, StorageError> {
2449 let cf = *self.cf_for(permutation)?;
2450 let prepared = build_walk_constraints(
2451 permutation,
2452 constraints,
2453 start_after_constraint,
2454 start_after_term,
2455 )?;
2456 if prepared.is_empty() {
2457 return Ok(Vec::new());
2458 }
2459 let ctx = Arc::new(
2461 DomainWalkCtx::new(
2462 permutation,
2463 snapshot,
2464 graph_name,
2465 graph_filter_terms,
2466 graph_filter_allow,
2467 iri_only_head,
2468 )
2469 .into_owned(),
2470 );
2471 let workers = workers.min(worker_pool::effective_width());
2472 if workers < 2 {
2474 return self.scan_domain_counts_legacy(
2475 permutation,
2476 constraints,
2477 snapshot,
2478 limit,
2479 start_after_constraint,
2480 start_after_term,
2481 graph_name,
2482 graph_filter_terms,
2483 graph_filter_allow,
2484 iri_only_head,
2485 merge_default_graph,
2486 count_mode,
2487 );
2488 }
2489 let slices = split_slices(prepared.len(), workers);
2490 let units: Vec<DomainCountsUnit> = slices
2491 .iter()
2492 .map(|slice| DomainCountsUnit {
2493 db: self.db.clone(),
2494 cf,
2495 ctx: Arc::clone(&ctx),
2496 slice: prepared[slice.clone()].to_vec(),
2500 budget: limit_budget(limit),
2501 merge_default_graph,
2502 count_mode,
2503 })
2504 .collect();
2505 let outcomes = worker_pool::run_units(units);
2506 let mut hits = Vec::new();
2507 for outcome in outcomes {
2508 match outcome {
2509 UnitOutcome::Ok(part) => {
2510 let mut part = part?;
2511 hits.append(&mut part);
2512 }
2513 UnitOutcome::Panicked(message) => {
2514 return Err(StorageError::Backend(format!(
2515 "domain count scan worker panicked: {message}"
2516 )));
2517 }
2518 }
2519 }
2520 if limit > 0 && hits.len() > limit_to_usize(limit) {
2521 hits.truncate(limit_to_usize(limit));
2522 }
2523 Ok(hits)
2524 }
2525
2526 #[allow(clippy::too_many_arguments)]
2540 pub fn scan_axis_head(
2541 &self,
2542 permutation: IndexPermutation,
2543 snapshot: SnapshotId,
2544 limit: u64,
2545 start_after_term: Option<&EncodedTerm>,
2546 graph_name: Option<&EncodedTerm>,
2547 graph_filter_terms: &[EncodedTerm],
2548 graph_filter_allow: bool,
2549 iri_only_head: bool,
2550 head_prefixes: &[Vec<u8>],
2551 ) -> Result<Vec<EncodedTerm>, StorageError> {
2552 let cf = self.cf_for(permutation)?;
2553 let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
2554 let after_bytes = start_after_term.map(encode_term_bytes);
2555 let prefixes = prepare_head_prefixes(head_prefixes);
2556 let mut terms = Vec::new();
2557 let mut iter = self.db.scan_prefix_total_order(cf, &[]);
2563 let mut state = SnapshotScanState::default();
2564 if prefixes.is_empty() {
2565 if let Some(after) = &after_bytes {
2566 let next = match byte_successor(after) {
2567 Some(next) => next,
2568 None => return Ok(terms),
2569 };
2570 iter.seek(&next);
2571 }
2572 while iter.is_valid() {
2573 let Some(key) = iter.key() else { break };
2574 let Some(value) = iter.value() else {
2575 return Err(StorageError::Corrupt(
2576 "iterator key without value".to_owned(),
2577 ));
2578 };
2579 let head = match consider_axis_head_key(
2580 permutation,
2581 &mut state,
2582 snapshot,
2583 key,
2584 value,
2585 g_window,
2586 graph_name,
2587 graph_filter_terms,
2588 graph_filter_allow,
2589 iri_only_head,
2590 )? {
2591 HeadVerdict::Candidate { head } => head,
2592 HeadVerdict::Skip => {
2593 iter.next();
2594 continue;
2595 }
2596 };
2597 let step = byte_successor(&key[..head.end]);
2600 terms.push(head_term_from_region(&key[head.clone()])?);
2601 if limit > 0 && terms.len() as u64 >= limit {
2602 break;
2603 }
2604 match step {
2605 Some(next) => iter.seek(&next),
2606 None => break,
2607 }
2608 state = SnapshotScanState::default();
2609 }
2610 } else {
2611 'prefix: for prefix in &prefixes {
2615 let Some(seek) = head_prefix_resume_seek(prefix, after_bytes.as_deref()) else {
2616 continue;
2617 };
2618 iter.seek(&seek);
2619 state = SnapshotScanState::default();
2620 while iter.is_valid() {
2621 let Some(key) = iter.key() else { break };
2622 if !key.starts_with(prefix) {
2623 break;
2624 }
2625 let Some(value) = iter.value() else {
2626 return Err(StorageError::Corrupt(
2627 "iterator key without value".to_owned(),
2628 ));
2629 };
2630 let head = match consider_axis_head_key(
2631 permutation,
2632 &mut state,
2633 snapshot,
2634 key,
2635 value,
2636 g_window,
2637 graph_name,
2638 graph_filter_terms,
2639 graph_filter_allow,
2640 iri_only_head,
2641 )? {
2642 HeadVerdict::Candidate { head } => head,
2643 HeadVerdict::Skip => {
2644 iter.next();
2645 continue;
2646 }
2647 };
2648 let step = byte_successor(&key[..head.end]);
2652 terms.push(head_term_from_region(&key[head.clone()])?);
2653 if limit > 0 && terms.len() as u64 >= limit {
2654 break 'prefix;
2655 }
2656 match step {
2657 Some(next) => iter.seek(&next),
2658 None => break,
2659 }
2660 state = SnapshotScanState::default();
2661 }
2662 }
2663 }
2664 iter.status()?;
2665 Ok(terms)
2666 }
2667
2668 pub fn max_commit_ts_under_prefixes(
2682 &self,
2683 permutation: IndexPermutation,
2684 head_prefixes: &[Vec<u8>],
2685 ) -> Result<u64, StorageError> {
2686 let cf = self.cf_for(permutation)?;
2687 let prefixes = prepare_head_prefixes(head_prefixes);
2688 let mut max_ts = 0u64;
2689 let mut iter = self.db.scan_prefix_total_order(cf, &[]);
2697 if prefixes.is_empty() {
2698 while iter.is_valid() {
2699 let Some(key) = iter.key() else { break };
2700 if key.len() >= crate::encode::COMMIT_TS_LEN {
2701 let ts = CommitTs::from_descending_be_bytes(
2702 key[key.len() - crate::encode::COMMIT_TS_LEN..]
2703 .try_into()
2704 .expect("slice length checked above"),
2705 );
2706 max_ts = max_ts.max(ts.0);
2707 }
2708 iter.next();
2709 }
2710 } else {
2711 for prefix in &prefixes {
2712 iter.seek(prefix);
2713 while iter.is_valid() {
2714 let Some(key) = iter.key() else { break };
2715 if !key.starts_with(prefix) {
2716 break;
2717 }
2718 if key.len() >= crate::encode::COMMIT_TS_LEN {
2719 let ts = CommitTs::from_descending_be_bytes(
2720 key[key.len() - crate::encode::COMMIT_TS_LEN..]
2721 .try_into()
2722 .expect("slice length checked above"),
2723 );
2724 max_ts = max_ts.max(ts.0);
2725 }
2726 iter.next();
2727 }
2728 }
2729 }
2730 iter.status()?;
2731 Ok(max_ts)
2732 }
2733
2734 #[allow(clippy::too_many_arguments)]
2739 pub fn count_axis_heads(
2740 &self,
2741 permutation: IndexPermutation,
2742 snapshot: SnapshotId,
2743 graph_name: Option<&EncodedTerm>,
2744 graph_filter_terms: &[EncodedTerm],
2745 graph_filter_allow: bool,
2746 iri_only_head: bool,
2747 ) -> Result<u64, StorageError> {
2748 let cf = self.cf_for(permutation)?;
2749 let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
2750 let mut total = 0u64;
2751 let mut iter = self.db.scan_prefix_total_order(cf, &[]);
2754 let mut state = SnapshotScanState::default();
2755 while iter.is_valid() {
2756 let Some(key) = iter.key() else { break };
2757 let Some(value) = iter.value() else {
2758 return Err(StorageError::Corrupt(
2759 "iterator key without value".to_owned(),
2760 ));
2761 };
2762 let head = match consider_axis_head_key(
2763 permutation,
2764 &mut state,
2765 snapshot,
2766 key,
2767 value,
2768 g_window,
2769 graph_name,
2770 graph_filter_terms,
2771 graph_filter_allow,
2772 iri_only_head,
2773 )? {
2774 HeadVerdict::Candidate { head } => head,
2775 HeadVerdict::Skip => {
2776 iter.next();
2777 continue;
2778 }
2779 };
2780 total += 1;
2781 let _ = head_term_from_region(&key[head.clone()])?;
2789 let step = byte_successor(&key[..head.end]);
2792 match step {
2793 Some(next) => iter.seek(&next),
2794 None => break,
2795 }
2796 state = SnapshotScanState::default();
2797 }
2798 iter.status()?;
2799 Ok(total)
2800 }
2801
2802 #[allow(clippy::too_many_arguments)]
2809 pub fn scan_axis_head_counts(
2810 &self,
2811 permutation: IndexPermutation,
2812 snapshot: SnapshotId,
2813 limit: u64,
2814 start_after_term: Option<&EncodedTerm>,
2815 graph_name: Option<&EncodedTerm>,
2816 graph_filter_terms: &[EncodedTerm],
2817 graph_filter_allow: bool,
2818 iri_only_head: bool,
2819 ) -> Result<Vec<AxisHeadCountHit>, StorageError> {
2820 let cf = self.cf_for(permutation)?;
2821 let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
2822 let mut hits = Vec::new();
2823 let mut iter = self.db.scan_prefix_total_order(cf, &[]);
2828 if let Some(after) = start_after_term {
2829 let next = match byte_successor(&encode_term_bytes(after)) {
2830 Some(next) => next,
2831 None => return Ok(hits),
2832 };
2833 iter.seek(&next);
2834 }
2835 let mut state = SnapshotScanState::default();
2836 let mut run_head = [0u8; WRITTEN_TERM_MAX_SIZE];
2842 let mut run_len = 0usize;
2843 type Slot1RunAcc = (u64, Option<([u8; WRITTEN_TERM_MAX_SIZE], usize)>);
2847 let mut current: Option<Slot1RunAcc> = None;
2848 let mut full = false;
2849 while iter.is_valid() {
2850 let Some(key) = iter.key() else { break };
2851 let Some(value) = iter.value() else {
2852 return Err(StorageError::Corrupt(
2853 "iterator key without value".to_owned(),
2854 ));
2855 };
2856 let head = match consider_axis_head_key(
2857 permutation,
2858 &mut state,
2859 snapshot,
2860 key,
2861 value,
2862 g_window,
2863 graph_name,
2864 graph_filter_terms,
2865 graph_filter_allow,
2866 iri_only_head,
2867 )? {
2868 HeadVerdict::Candidate { head } => head,
2869 HeadVerdict::Skip => {
2870 iter.next();
2871 continue;
2872 }
2873 };
2874 let slot1 = region_after_head(key, head.end)?;
2877 let opens_new_run = current.is_none() || run_head[..run_len] != key[head.clone()];
2878 if opens_new_run {
2879 if let Some((count, _)) = current.take() {
2880 hits.push(AxisHeadCountHit {
2881 term: head_term_from_region(&run_head[..run_len])?,
2882 count,
2883 });
2884 if limit > 0 && hits.len() as u64 >= limit {
2885 full = true;
2886 break;
2887 }
2888 }
2889 run_head[..head.len()].copy_from_slice(&key[head.clone()]);
2895 run_len = head.len();
2896 current = Some((0, None));
2897 }
2898 if let Some((count, last)) = &mut current {
2899 let changed = match last.as_ref() {
2900 Some((prev, prev_len)) => prev[..*prev_len] != key[slot1.clone()],
2901 None => true,
2902 };
2903 if changed {
2904 *count += 1;
2905 let mut saved = [0u8; WRITTEN_TERM_MAX_SIZE];
2906 saved[..slot1.len()].copy_from_slice(&key[slot1.clone()]);
2907 *last = Some((saved, slot1.len()));
2908 }
2909 }
2910 iter.next();
2911 }
2912 if !full && let Some((count, _)) = current {
2916 hits.push(AxisHeadCountHit {
2917 term: head_term_from_region(&run_head[..run_len])?,
2918 count,
2919 });
2920 }
2921 iter.status()?;
2922 Ok(hits)
2923 }
2924
2925 #[allow(clippy::too_many_arguments)]
2932 pub fn count_pattern_allow_list(
2933 &self,
2934 permutation: IndexPermutation,
2935 pattern: &EncodedTriplePattern,
2936 snapshot: SnapshotId,
2937 limit: u64,
2938 allow_list_slot: QuadSlot,
2939 allow_terms: &[EncodedTerm],
2940 graph_filter: GByteFilter,
2941 merge_default_graph: bool,
2942 ) -> Result<Option<u64>, StorageError> {
2943 let mut count = 0u64;
2944 let verdict = self.visit_allow_list_rows(
2945 permutation,
2946 pattern,
2947 snapshot,
2948 None,
2949 allow_list_slot,
2950 allow_terms,
2951 graph_filter,
2952 merge_default_graph,
2953 IriOnlyMask::NONE,
2954 &ComparisonMask::default(),
2955 |_row| {
2956 count += 1;
2957 Ok(limit == 0 || count < limit)
2958 },
2959 )?;
2960 Ok(verdict.map(|_| count))
2961 }
2962
2963 #[allow(clippy::too_many_arguments)]
2977 pub(crate) fn visit_allow_list_rows(
2978 &self,
2979 permutation: IndexPermutation,
2980 pattern: &EncodedTriplePattern,
2981 snapshot: SnapshotId,
2982 start_after: Option<&EncodedQuad>,
2983 allow_list_slot: QuadSlot,
2984 allow_terms: &[EncodedTerm],
2985 graph_filter: GByteFilter,
2986 merge_default_graph: bool,
2987 iri_only: IriOnlyMask,
2988 mask: &ComparisonMask,
2989 mut on_match: impl FnMut(&KeyRow) -> Result<bool, StorageError>,
2990 ) -> Result<Option<ScanExhaustion>, StorageError> {
2991 let Some(prepared) =
2992 pattern.prepare_tight_allow_list(permutation, allow_list_slot, allow_terms)
2993 else {
2994 return Ok(None);
2997 };
2998 let cf = self.cf_for(permutation)?;
2999 let start_after_prefix_bytes = start_after.map(|after_quad| {
3000 let mut bound = pattern.clone();
3001 bound.bind_slot(
3002 allow_list_slot,
3003 term_in_quad_slot(after_quad, allow_list_slot).clone(),
3004 );
3005 bound.build_scan_prefix_bytes(permutation)
3006 });
3007 let resume_key = start_after.map(|quad| encode_index_key(permutation, quad));
3008
3009 let mut verdict = ScanExhaustion::ExhaustedFilterTerms;
3017 let mut iter = self.db.scan_prefix(cf, &prepared.shared_prefix);
3018 for (tight_prefix, term) in &prepared.terms {
3019 if start_after_prefix_bytes
3020 .as_ref()
3021 .is_some_and(|cursor| tight_prefix.as_slice() < cursor.as_slice())
3022 {
3023 continue;
3024 }
3025 let mut bound = pattern.clone();
3026 bound.bind_slot(allow_list_slot, term.clone());
3027 let resuming = start_after_prefix_bytes
3028 .as_ref()
3029 .is_some_and(|cursor| tight_prefix.as_slice() == cursor.as_slice());
3030 let seek: &[u8] = if resuming {
3031 let resume = resume_key.as_ref().expect("resuming implies start_after");
3032 if resume.as_slice() > tight_prefix.as_slice() {
3033 resume.as_slice()
3034 } else {
3035 tight_prefix.as_slice()
3036 }
3037 } else {
3038 tight_prefix.as_slice()
3039 };
3040 iter.seek(seek);
3041 let mut state = SnapshotScanState::default();
3042 let mut matcher = RowMatcher::compile(
3054 &bound,
3055 permutation,
3056 graph_filter.clone(),
3057 merge_default_graph,
3058 if resuming { start_after } else { None },
3059 iri_only,
3060 );
3061 while iter.is_valid() {
3062 let Some(key) = iter.key() else { break };
3063 if !key.starts_with(tight_prefix) {
3064 break;
3065 }
3066 if resuming {
3067 let logical = versioned_key_term_prefix(key)?;
3070 if logical <= resume_key.as_deref().expect("resuming implies start_after") {
3071 iter.next();
3072 continue;
3073 }
3074 }
3075 let decision = {
3076 let Some(value) = iter.value() else {
3077 return Err(StorageError::Corrupt(
3078 "iterator key without value".to_owned(),
3079 ));
3080 };
3081 matcher.matches_row(key, value, snapshot, &mut state)?
3082 };
3083 if let MatchDecision::Emit {
3084 slot_starts,
3085 commit_ts,
3086 } = decision
3087 {
3088 let row = KeyRow {
3089 key,
3090 permutation,
3091 seg_starts: slot_starts,
3092 commit_ts,
3093 };
3094 if mask.keeps(row.logical(), &row.seg_starts) && !on_match(&row)? {
3097 verdict = ScanExhaustion::Limited;
3098 break;
3099 }
3100 }
3101 iter.next();
3102 }
3103 if verdict == ScanExhaustion::Limited {
3104 break;
3105 }
3106 }
3107 iter.status()?;
3108 Ok(Some(verdict))
3109 }
3110
3111 pub fn apply_geo_puts(&self, puts: &[GeoIndexPut]) -> Result<(), StorageError> {
3116 if puts.is_empty() {
3117 return Ok(());
3118 }
3119 let Some(cf) = &self.cf_geo else {
3120 return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3121 };
3122 let mut batch = self.db.write_batch();
3123 for put in puts {
3124 batch.insert(cf, &put.encode_key(), &put.encode_value());
3125 }
3126 batch.commit()
3127 }
3128
3129 pub fn delete_geo_term(&self, term: &[u8]) -> Result<u64, StorageError> {
3138 let Some(cf) = &self.cf_geo else {
3139 return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3140 };
3141 let mut victims: Vec<Vec<u8>> = Vec::new();
3142 let mut iter = self.db.scan_prefix(cf, &[]);
3143 while iter.is_valid() {
3144 if let Some(key) = iter.key() {
3145 let logical_len = key.len().saturating_sub(crate::encode::COMMIT_TS_LEN);
3146 if logical_len > GEO_CELL_ID_LEN && key[GEO_CELL_ID_LEN..logical_len] == *term {
3147 victims.push(key.to_vec());
3148 }
3149 }
3150 iter.next();
3151 }
3152 iter.status()?;
3153 if victims.is_empty() {
3154 return Ok(0);
3155 }
3156 let mut batch = self.db.write_batch();
3157 for key in &victims {
3158 batch.delete(cf, key);
3159 }
3160 batch.commit()?;
3161 Ok(victims.len() as u64)
3162 }
3163
3164 pub fn visit_geo_postings(
3170 &self,
3171 on_posting: &mut dyn FnMut(&GeoIndexPut) -> Result<(), StorageError>,
3172 ) -> Result<(), StorageError> {
3173 let Some(cf) = &self.cf_geo else {
3174 return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3175 };
3176 let mut iter = self.db.scan_prefix(cf, &[]);
3177 while iter.is_valid() {
3178 if let (Some(key), Some(value)) = (iter.key(), iter.value()) {
3179 on_posting(&GeoIndexPut::decode(key, value)?)?;
3180 }
3181 iter.next();
3182 }
3183 iter.status()
3184 }
3185
3186 pub fn geo_index_epoch(&self) -> Result<Option<u64>, StorageError> {
3197 let Some(cf) = &self.cf_geo_meta else {
3198 return Ok(None);
3199 };
3200 let epoch = decode_geo_epoch(self.db.get(cf, GEO_INDEX_EPOCH_KEY)?.as_deref());
3201 let liveness = decode_geo_liveness(self.db.get(cf, GEO_INDEX_LIVENESS_KEY)?.as_deref());
3202 Ok(match (epoch, liveness) {
3203 (Some(epoch), Some(live)) if epoch == live => Some(epoch),
3204 _ => None,
3205 })
3206 }
3207
3208 pub fn set_geo_index_epoch(&self, epoch: u64) -> Result<(), StorageError> {
3219 let Some(cf) = &self.cf_geo_meta else {
3220 return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3221 };
3222 let mut batch = self.db.write_batch();
3223 batch.insert(cf, GEO_INDEX_EPOCH_KEY, &encode_geo_epoch(epoch));
3224 batch.insert(cf, GEO_INDEX_LIVENESS_KEY, &encode_geo_liveness(epoch));
3225 batch.commit()
3226 }
3227
3228 pub fn geo_index_epoch_number(&self) -> Result<u64, StorageError> {
3238 let Some(cf) = &self.cf_geo_meta else {
3239 return Ok(0);
3240 };
3241 Ok(decode_geo_epoch(self.db.get(cf, GEO_INDEX_EPOCH_KEY)?.as_deref()).unwrap_or(0))
3242 }
3243
3244 pub fn geo_scan_candidates(
3254 &self,
3255 intervals: &[GeoCellInterval],
3256 snapshot: SnapshotId,
3257 query_envelope: Option<&GeoEnvelope>,
3258 limit: u64,
3259 state: &mut GeoCandidateState,
3260 mut emit: impl FnMut(&EncodedTerm) -> Result<bool, StorageError>,
3261 ) -> Result<(), StorageError> {
3262 let Some(cf) = &self.cf_geo else {
3263 return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3264 };
3265 let mut emitted = 0u64;
3266 let mut iter = self.db.scan_prefix(cf, &[]);
3267 for interval in intervals {
3268 let seek_key = interval.min_cell_id.to_be_bytes();
3269 iter.seek(&seek_key);
3270 let max_cell = interval.max_cell_id.to_be_bytes();
3271 while iter.is_valid() {
3272 let Some(key) = iter.key() else { break };
3273 if key.len() < GEO_CELL_ID_LEN || key[..GEO_CELL_ID_LEN] > max_cell[..] {
3274 break; }
3276 let Some(value) = iter.value() else {
3277 return Err(StorageError::Corrupt(
3278 "geo index iterator key without value".to_owned(),
3279 ));
3280 };
3281 let ts_at = key
3282 .len()
3283 .checked_sub(crate::encode::COMMIT_TS_LEN)
3284 .ok_or_else(|| StorageError::Corrupt("geo index key too short".to_owned()))?;
3285 let commit_ts = CommitTs::from_descending_be_bytes(
3286 key[ts_at..]
3287 .try_into()
3288 .map_err(|_| StorageError::Corrupt("geo commit_ts suffix".to_owned()))?,
3289 );
3290 let header = value
3291 .get(..crate::encode::STORAGE_VALUE_LEN)
3292 .ok_or_else(|| StorageError::Corrupt("truncated storage value".to_owned()))?;
3293 let (op, _visibility) = decode_storage_value(header)?;
3294 let stored_envelope = if query_envelope.is_some() && value.len() > 5 {
3297 Some(GeoEnvelope::decode(&value[5..])?)
3298 } else {
3299 None
3300 };
3301 let decision = state.consider_posting(
3302 key,
3303 commit_ts,
3304 op,
3305 snapshot,
3306 stored_envelope.as_ref(),
3307 query_envelope,
3308 )?;
3309 if decision == GeoCandidateDecision::Emit {
3310 let term_len = key.len() - GEO_CELL_ID_LEN - crate::encode::COMMIT_TS_LEN;
3311 let mut cursor = &key[GEO_CELL_ID_LEN..GEO_CELL_ID_LEN + term_len];
3312 let term = cursor.read_term()?;
3313 if !emit(&term)? {
3314 return Ok(());
3315 }
3316 emitted += 1;
3317 if limit > 0 && emitted >= limit {
3318 return Ok(());
3319 }
3320 }
3321 iter.next();
3322 }
3323 }
3324 iter.status()?;
3325 Ok(())
3326 }
3327
3328 pub fn apply_replace_pairs(
3334 &self,
3335 pairs: &[ReplacePair],
3336 commit_ts: CommitTs,
3337 ) -> Result<u64, StorageError> {
3338 if pairs.is_empty() {
3339 return Ok(0);
3340 }
3341 let mut versions: Vec<HexastoreVersion<'_>> = Vec::with_capacity(pairs.len() * 2);
3342 let quads: Vec<(crate::encode::EncodedQuad, crate::encode::EncodedQuad)> = pairs
3343 .iter()
3344 .map(|pair| (pair.old_quad(), pair.new_quad()))
3345 .collect();
3346 for (pair, (old, new)) in pairs.iter().zip(&quads) {
3347 let _ = pair;
3348 versions.push(HexastoreVersion {
3349 quad: old,
3350 commit_ts,
3351 op: StorageOp::Delete,
3352 visibility: VisibilityLabel::default(),
3353 });
3354 versions.push(HexastoreVersion {
3355 quad: new,
3356 commit_ts,
3357 op: StorageOp::Put,
3358 visibility: VisibilityLabel::default(),
3359 });
3360 }
3361 let puts = prepare_hexastore_puts(self.axis, versions);
3362 self.apply_prepared_puts(&puts)?;
3363 Ok(pairs.len() as u64)
3364 }
3365
3366 pub fn wipe_geo_index(&self) -> Result<u64, StorageError> {
3370 let Some(cf) = &self.cf_geo else {
3371 return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3372 };
3373 let mut deleted = 0u64;
3374 let mut batch = self.db.write_batch();
3375 let mut iter = self.db.scan_prefix(cf, &[]);
3376 while iter.is_valid() {
3377 if let Some(key) = iter.key() {
3378 batch.delete(cf, key);
3379 deleted += 1;
3380 }
3381 iter.next();
3382 }
3383 iter.status()?;
3384 if let Some(meta) = &self.cf_geo_meta {
3387 batch.delete(meta, GEO_INDEX_LIVENESS_KEY);
3388 }
3389 batch.commit()?;
3390 Ok(deleted)
3391 }
3392
3393 pub fn apply_temporal_puts(&self, puts: &[TemporalIndexPut]) -> Result<(), StorageError> {
3398 if puts.is_empty() {
3399 return Ok(());
3400 }
3401 let Some(cf) = &self.cf_temporal else {
3402 return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
3403 };
3404 let mut batch = self.db.write_batch();
3405 for put in puts {
3406 batch.insert(cf, &put.encode_key(), &put.encode_value());
3407 }
3408 batch.commit()
3409 }
3410
3411 pub fn temporal_index_epoch(&self) -> Result<Option<u64>, StorageError> {
3425 let Some(cf) = &self.cf_temporal_meta else {
3426 return Ok(None);
3427 };
3428 let epoch = decode_temporal_epoch(self.db.get(cf, TEMPORAL_INDEX_EPOCH_KEY)?.as_deref());
3429 let origin = decode_temporal_origin(self.db.get(cf, TEMPORAL_INDEX_ORIGIN_KEY)?.as_deref());
3430 Ok(match (epoch, origin) {
3431 (Some(epoch), Some(version)) if version == TEMPORAL_ORIGIN_VERSION => Some(epoch),
3432 _ => None,
3433 })
3434 }
3435
3436 pub fn set_temporal_index_epoch(&self, epoch: u64) -> Result<(), StorageError> {
3448 let Some(cf) = &self.cf_temporal_meta else {
3449 return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
3450 };
3451 let mut batch = self.db.write_batch();
3452 batch.insert(cf, TEMPORAL_INDEX_EPOCH_KEY, &encode_temporal_epoch(epoch));
3453 batch.insert(
3454 cf,
3455 TEMPORAL_INDEX_ORIGIN_KEY,
3456 &encode_temporal_origin(TEMPORAL_ORIGIN_VERSION),
3457 );
3458 batch.commit()
3459 }
3460
3461 pub fn temporal_scan_candidates(
3470 &self,
3471 intervals: &[TemporalCellInterval],
3472 snapshot: SnapshotId,
3473 predicate: &TemporalQueryPredicate,
3474 limit: u64,
3475 state: &mut TemporalCandidateState,
3476 mut emit: impl FnMut(&EncodedTerm) -> Result<bool, StorageError>,
3477 ) -> Result<(), StorageError> {
3478 let Some(cf) = &self.cf_temporal else {
3479 return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
3480 };
3481 let mut emitted = 0u64;
3482 let mut iter = self.db.scan_prefix(cf, &[]);
3483 for interval in intervals {
3484 let seek_key = interval.min_key.to_be_bytes();
3485 iter.seek(&seek_key);
3486 let max_key = interval.max_key.to_be_bytes();
3487 while iter.is_valid() {
3488 let Some(key) = iter.key() else { break };
3489 if key.len() < TEMPORAL_KEY_LEN || key[..TEMPORAL_KEY_LEN] > max_key[..] {
3490 break; }
3492 let Some(value) = iter.value() else {
3493 return Err(StorageError::Corrupt(
3494 "temporal index iterator key without value".to_owned(),
3495 ));
3496 };
3497 let ts_at = key
3498 .len()
3499 .checked_sub(crate::encode::COMMIT_TS_LEN)
3500 .ok_or_else(|| {
3501 StorageError::Corrupt("temporal index key too short".to_owned())
3502 })?;
3503 let commit_ts =
3504 CommitTs::from_descending_be_bytes(key[ts_at..].try_into().map_err(|_| {
3505 StorageError::Corrupt("temporal commit_ts suffix".to_owned())
3506 })?);
3507 let (op, _visibility, begin, end) = decode_temporal_posting_value(value)?;
3508 let decision =
3509 state.consider_posting(key, commit_ts, op, snapshot, begin, end, predicate)?;
3510 if decision == TemporalCandidateDecision::Emit {
3511 let term_len = key.len() - TEMPORAL_KEY_LEN - crate::encode::COMMIT_TS_LEN;
3512 let mut cursor = &key[TEMPORAL_KEY_LEN..TEMPORAL_KEY_LEN + term_len];
3513 let term = cursor.read_term()?;
3514 if !emit(&term)? {
3515 return Ok(());
3516 }
3517 emitted += 1;
3518 if limit > 0 && emitted >= limit {
3519 return Ok(());
3520 }
3521 }
3522 iter.next();
3523 }
3524 }
3525 iter.status()?;
3526 Ok(())
3527 }
3528
3529 pub fn wipe_temporal_index(&self) -> Result<(), StorageError> {
3534 let Some(cf) = &self.cf_temporal else {
3535 return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
3536 };
3537 let mut batch = self.db.write_batch();
3538 let mut iter = self.db.scan_prefix(cf, &[]);
3539 while iter.is_valid() {
3540 if let Some(key) = iter.key() {
3541 batch.delete(cf, key);
3542 }
3543 iter.next();
3544 }
3545 iter.status()?;
3546 if let Some(meta) = &self.cf_temporal_meta {
3557 batch.delete(meta, TEMPORAL_INDEX_EPOCH_KEY);
3558 batch.delete(meta, TEMPORAL_INDEX_ORIGIN_KEY);
3559 }
3560 batch.commit()
3561 }
3562
3563 fn fold_quad_run(
3567 quad_run: &mut Option<(Vec<u8>, StorageOp)>,
3568 term_run: &mut Option<(Vec<u8>, EncodedTerm, bool)>,
3569 ) {
3570 if let Some((_, quad_op)) = quad_run.take()
3571 && quad_op == StorageOp::Put
3572 && let Some((_, _, alive)) = term_run.as_mut()
3573 {
3574 *alive = true;
3575 }
3576 }
3577
3578 pub fn temporal_rebuild_terms(&self) -> Result<(Vec<EncodedTerm>, CommitTs), StorageError> {
3594 if self.axis != PartitionAxis::O {
3595 return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
3596 }
3597 let mut epoch = CommitTs(0);
3598 let mut term_run: Option<(Vec<u8>, EncodedTerm, bool)> = None;
3601 let mut quad_run: Option<(Vec<u8>, StorageOp)> = None;
3605 let mut alive_terms: Vec<EncodedTerm> = Vec::new();
3606 let mut iter = self.db.scan_prefix(&self.cf0, &[]);
3607 while iter.is_valid() {
3608 let row = match (iter.key(), iter.value()) {
3609 (Some(key), Some(value)) => (key, value),
3610 _ => {
3611 iter.next();
3612 continue;
3613 }
3614 };
3615 let (key, value) = row;
3616 let mut cursor: &[u8] = key;
3617 let term = match cursor.read_term() {
3618 Ok(term) => term,
3619 Err(_) => {
3621 iter.next();
3622 continue;
3623 }
3624 };
3625 let term_len = key.len() - cursor.len();
3626 if crate::encode::temporal_term_interval(&term).is_none() {
3627 iter.next();
3631 continue;
3632 }
3633 let ts_at = key
3634 .len()
3635 .checked_sub(crate::encode::COMMIT_TS_LEN)
3636 .ok_or_else(|| StorageError::Corrupt("hexastore key too short".to_owned()))?;
3637 let commit_ts = CommitTs::from_descending_be_bytes(
3638 key[ts_at..]
3639 .try_into()
3640 .map_err(|_| StorageError::Corrupt("hexastore commit_ts".to_owned()))?,
3641 );
3642 let header = value
3643 .get(..crate::encode::STORAGE_VALUE_LEN)
3644 .ok_or_else(|| StorageError::Corrupt("truncated storage value".to_owned()))?;
3645 let (op, _) = decode_storage_value(header)?;
3646 if commit_ts.0 > epoch.0 {
3647 epoch = commit_ts;
3648 }
3649 let quad_key = &key[..ts_at];
3650 let same_term = term_run
3651 .as_ref()
3652 .is_some_and(|(bytes, _, _)| bytes.as_slice() == &key[..term_len]);
3653 if !same_term {
3654 Self::fold_quad_run(&mut quad_run, &mut term_run);
3657 if let Some((_, term, true)) = term_run.take() {
3658 alive_terms.push(term);
3659 }
3660 term_run = Some((key[..term_len].to_vec(), term, false));
3661 }
3662 let same_quad = quad_run
3666 .as_ref()
3667 .is_some_and(|(prefix, _)| prefix.as_slice() == quad_key);
3668 if !same_quad {
3669 Self::fold_quad_run(&mut quad_run, &mut term_run);
3670 quad_run = Some((quad_key.to_vec(), op));
3671 }
3672 iter.next();
3673 }
3674 iter.status()?;
3675 Self::fold_quad_run(&mut quad_run, &mut term_run);
3677 if let Some((_, term, true)) = term_run.take() {
3678 alive_terms.push(term);
3679 }
3680 Ok((alive_terms, epoch))
3681 }
3682
3683 pub fn flush_memtables(&self) -> Result<(), StorageError> {
3685 let mut cfs: Vec<&ColumnFamily> = vec![&self.cf0, &self.cf1];
3686 if let Some(cf) = &self.cf_catalog {
3687 cfs.push(cf);
3688 }
3689 if let Some(cf) = &self.cf_geo {
3690 cfs.push(cf);
3691 }
3692 if let Some(cf) = &self.cf_geo_meta {
3693 cfs.push(cf);
3694 }
3695 if let Some(cf) = &self.cf_temporal {
3700 cfs.push(cf);
3701 }
3702 if let Some(cf) = &self.cf_temporal_meta {
3703 cfs.push(cf);
3704 }
3705 self.db.flush_cfs(&cfs)
3706 }
3707
3708 pub fn warm_block_cache(
3716 &self,
3717 fill_fraction: f64,
3718 ) -> Result<crate::WarmBlockCacheStats, StorageError> {
3719 let capacity = self.db.block_cache_capacity();
3720 let target = (capacity as f64 * fill_fraction.max(0.0)) as usize;
3721 let usage_before = self.db.block_cache_usage();
3722 let mut cfs: Vec<&ColumnFamily> = vec![&self.cf0, &self.cf1];
3723 if let Some(cf) = &self.cf_catalog {
3724 cfs.push(cf);
3725 }
3726 if let Some(cf) = &self.cf_geo {
3727 cfs.push(cf);
3728 }
3729 if let Some(cf) = &self.cf_geo_meta {
3730 cfs.push(cf);
3731 }
3732 if let Some(cf) = &self.cf_temporal {
3733 cfs.push(cf);
3734 }
3735 if let Some(cf) = &self.cf_temporal_meta {
3736 cfs.push(cf);
3737 }
3738 let entries_touched = if target == 0 {
3739 0
3740 } else {
3741 warm_walk(&self.db, &cfs, target)?
3742 };
3743 Ok(WarmBlockCacheStats {
3744 entries_touched,
3745 usage_before,
3746 usage_after: self.db.block_cache_usage(),
3747 capacity,
3748 })
3749 }
3750
3751 pub fn compact_range(&self) {
3756 self.compact_cfs(BottommostLevelCompaction::Force);
3757 }
3758
3759 pub fn compact_range_skip_bottommost(&self) {
3765 self.compact_cfs(BottommostLevelCompaction::Skip);
3766 }
3767
3768 fn compact_cfs(&self, bottommost: BottommostLevelCompaction) {
3769 self.db.compact_cf_bottommost(&self.cf0, bottommost);
3770 self.db.compact_cf_bottommost(&self.cf1, bottommost);
3771 if let Some(cf) = &self.cf_catalog {
3772 self.db.compact_cf_bottommost(cf, bottommost);
3773 }
3774 if let Some(cf) = &self.cf_geo {
3775 self.db.compact_cf_bottommost(cf, bottommost);
3776 }
3777 if let Some(cf) = &self.cf_geo_meta {
3778 self.db.compact_cf_bottommost(cf, bottommost);
3779 }
3780 if let Some(cf) = &self.cf_temporal {
3783 self.db.compact_cf_bottommost(cf, bottommost);
3784 }
3785 if let Some(cf) = &self.cf_temporal_meta {
3786 self.db.compact_cf_bottommost(cf, bottommost);
3787 }
3788 }
3789
3790 pub fn block_cache_bytes(&self) -> Option<(u64, u64)> {
3795 self.db.block_cache_bytes()
3796 }
3797
3798 pub fn lsm_metrics(&self) -> crate::LsmMetrics {
3803 let mut cfs: Vec<&ColumnFamily> = vec![&self.cf0, &self.cf1];
3804 if let Some(catalog) = &self.cf_catalog {
3805 cfs.push(catalog);
3806 }
3807 if let Some(geo) = &self.cf_geo {
3808 cfs.push(geo);
3809 }
3810 self.db.lsm_metrics_for_cfs(&cfs)
3811 }
3812
3813 pub fn hexastore_level0_files(&self) -> Option<u64> {
3819 let level0 = "rocksdb.num-files-at-level0";
3820 let left = self
3821 .db
3822 .property_value_cf(&self.cf0, level0)
3823 .and_then(|s| s.parse().ok());
3824 let right = self
3825 .db
3826 .property_value_cf(&self.cf1, level0)
3827 .and_then(|s| s.parse().ok());
3828 match (left, right) {
3829 (None, None) => None,
3830 (left, right) => Some(left.unwrap_or(0) + right.unwrap_or(0)),
3831 }
3832 }
3833
3834 pub fn stats_property_blobs(&self, key: &[u8]) -> Result<Vec<Vec<u8>>, StorageError> {
3841 let mut blobs = self.db.user_property_blobs(&self.cf0, key)?;
3842 if let Some(cf) = &self.cf_catalog {
3843 blobs.extend(self.db.user_property_blobs(cf, key)?);
3844 }
3845 if let Some(cf) = &self.cf_temporal {
3846 blobs.extend(self.db.user_property_blobs(cf, key)?);
3847 }
3848 if let Some(cf) = &self.cf_geo {
3849 blobs.extend(self.db.user_property_blobs(cf, key)?);
3850 }
3851 Ok(blobs)
3852 }
3853
3854 fn cf_for(&self, permutation: IndexPermutation) -> Result<&ColumnFamily, StorageError> {
3855 if permutation == self.permutations[0] {
3856 Ok(&self.cf0)
3857 } else if permutation == self.permutations[1] {
3858 Ok(&self.cf1)
3859 } else {
3860 Err(StorageError::PermutationNotOwned {
3861 index: permutation.cf_name(),
3862 axis: self.axis,
3863 })
3864 }
3865 }
3866
3867 fn catalog_cf(&self) -> Result<&ColumnFamily, StorageError> {
3868 self.cf_catalog
3869 .as_ref()
3870 .ok_or(StorageError::CatalogNotOnAxis(self.axis))
3871 }
3872
3873 fn catalog_puts_for_encoded(
3874 &self,
3875 encoded: &EncodedQuad,
3876 commit_ts: CommitTs,
3877 op: StorageOp,
3878 ) -> Result<Vec<CatalogPut>, StorageError> {
3879 if self.axis != PartitionAxis::S
3880 || op != StorageOp::Put
3881 || !is_catalog_graph(&encoded.graph_name)
3882 {
3883 return Ok(Vec::new());
3884 }
3885 self.catalog_puts_for_insert(&[(encoded.graph_name.clone(), commit_ts)])
3886 }
3887
3888 fn catalog_newest_state(
3889 &self,
3890 graph: &EncodedTerm,
3891 ) -> Result<Option<GraphCatalogState>, StorageError> {
3892 let cf = self.catalog_cf()?;
3893 let prefix = catalog_prefix(graph)?;
3894 let iter = self.db.scan_prefix(cf, &prefix);
3895 if !iter.is_valid() {
3896 iter.status()?;
3897 return Ok(None);
3898 }
3899 let Some(key) = iter.key() else {
3900 iter.status()?;
3901 return Ok(None);
3902 };
3903 if !key.starts_with(&prefix) {
3904 iter.status()?;
3905 return Ok(None);
3906 }
3907 let Some(value) = iter.value() else {
3908 return Err(StorageError::Corrupt(
3909 "catalog iterator key without value".to_owned(),
3910 ));
3911 };
3912 let state = decode_catalog_value(value)?;
3913 iter.status()?;
3914 Ok(Some(state))
3915 }
3916
3917 fn catalog_prefix_occupied(&self, graph: &EncodedTerm) -> Result<bool, StorageError> {
3918 Ok(self.catalog_newest_state(graph)?.is_some())
3919 }
3920}
3921
3922#[allow(clippy::too_many_arguments)]
3964fn count_walk_slice(
3965 db: &Db,
3966 cf: &ColumnFamily,
3967 permutation: IndexPermutation,
3968 pattern: &EncodedTriplePattern,
3969 snapshot: SnapshotId,
3970 graph_filter: &GByteFilter,
3971 merge_default_graph: bool,
3972 prefix: &[u8],
3973 slice: &CountSlice,
3974 is_first: bool,
3975) -> Result<u64, StorageError> {
3976 let mut matcher = RowMatcher::compile(
3977 pattern,
3978 permutation,
3979 graph_filter.clone(),
3980 merge_default_graph,
3981 None,
3982 IriOnlyMask::NONE,
3983 );
3984 let mut state = SnapshotScanState::default();
3985 let mut iter = db.scan_prefix_from_total_order(cf, prefix, &slice.start);
4001 let mut skip_logical: Option<Vec<u8>> = None;
4009 let mut crossing_logical: Option<Vec<u8>> = None;
4014 if !is_first && iter.is_valid() {
4015 let Some(key) = iter.key() else {
4016 return Err(StorageError::Corrupt(
4017 "valid iterator without key".to_owned(),
4018 ));
4019 };
4020 let first_key = key.to_vec();
4021 let logical = versioned_key_term_prefix(&first_key)?.to_vec();
4022 iter.seek(&logical);
4023 if let Some(newest) = iter.key()
4024 && newest < first_key.as_slice()
4025 {
4026 skip_logical = Some(logical);
4031 iter.seek(&slice.start);
4032 }
4033 }
4034 let mut count = 0u64;
4035 while iter.is_valid() {
4036 let Some(key) = iter.key() else { break };
4037 let key_logical = versioned_key_term_prefix(key)?;
4038 if let Some(skip) = &skip_logical
4043 && key_logical == skip.as_slice()
4044 && key.len() == skip.len() + COMMIT_TS_LEN
4045 {
4046 iter.next();
4047 continue;
4048 }
4049 if let Some(cross) = &crossing_logical
4050 && key_logical != cross.as_slice()
4051 {
4052 break;
4055 }
4056 if crossing_logical.is_none()
4057 && let Some(end) = slice.end.as_deref()
4058 && key >= end
4059 {
4060 let logical = key_logical.to_vec();
4068 iter.seek(&logical);
4069 let owned = match iter.key() {
4070 Some(newest) => newest >= slice.start.as_slice() && newest < end,
4071 None => false,
4072 };
4073 if owned {
4074 crossing_logical = Some(logical);
4075 continue;
4076 }
4077 break;
4078 }
4079 let Some(value) = iter.value() else {
4080 return Err(StorageError::Corrupt(
4081 "iterator key without value".to_owned(),
4082 ));
4083 };
4084 if matches!(
4085 matcher.matches_row(key, value, snapshot, &mut state)?,
4086 MatchDecision::Emit { .. }
4087 ) {
4088 count += 1;
4089 }
4090 iter.next();
4091 }
4092 iter.status()?;
4093 Ok(count)
4094}
4095
4096struct CountSliceUnit {
4100 db: Db,
4101 cf: ColumnFamily,
4102 permutation: IndexPermutation,
4103 pattern: EncodedTriplePattern,
4104 snapshot: SnapshotId,
4105 graph_filter: GByteFilter,
4106 merge_default_graph: bool,
4107 prefix: Vec<u8>,
4108 slice: CountSlice,
4109 is_first: bool,
4110}
4111
4112impl PoolUnit for CountSliceUnit {
4113 type Output = Result<u64, StorageError>;
4114
4115 fn execute(self) -> Self::Output {
4116 count_walk_slice(
4117 &self.db,
4118 &self.cf,
4119 self.permutation,
4120 &self.pattern,
4121 self.snapshot,
4122 &self.graph_filter,
4123 self.merge_default_graph,
4124 &self.prefix,
4125 &self.slice,
4126 self.is_first,
4127 )
4128 }
4129}
4130
4131#[cfg(test)]
4132mod tests {
4133 use super::RocksDbStorage;
4134 use crate::encode::{TEMPORAL_INDEX_ORIGIN_KEY, encode_temporal_origin};
4135 use crate::rocksdb_db::DEFAULT_BLOCK_CACHE_BYTES;
4136 use crate::{
4137 BlankNode, CommitTs, DomainCountMode, DomainScanCountHit, EncodedTerm, GraphName,
4138 IndexPermutation, Literal, NamedNode, PartitionAxis, Quad, RocksDbOptionsHooks,
4139 RocksDbTuning, SnapshotId, StorageError, StorageOp, VisibilityLabel,
4140 WARM_CACHE_FILL_FRACTION, WARM_CACHE_PROBE_INTERVAL, encode_quad,
4141 };
4142
4143 fn named_spo(s: &str, o: &str, g: &str) -> Quad {
4144 Quad::new(
4145 NamedNode::new(format!("http://ex/{s}")).unwrap(),
4146 NamedNode::new("http://ex/p").unwrap(),
4147 NamedNode::new(format!("http://ex/{o}")).unwrap(),
4148 GraphName::NamedNode(NamedNode::new(format!("http://ex/{g}")).unwrap()),
4149 )
4150 }
4151
4152 fn count_posg(
4153 store: &RocksDbStorage,
4154 predicate: &EncodedTerm,
4155 allow: &[EncodedTerm],
4156 allow_on: bool,
4157 merge: bool,
4158 ) -> u64 {
4159 store
4160 .scan_domain_counts(
4161 IndexPermutation::Posg,
4162 std::slice::from_ref(predicate),
4163 SnapshotId(9),
4164 0,
4165 None,
4166 None,
4167 None,
4168 allow,
4169 allow_on,
4170 false,
4171 merge,
4172 DomainCountMode::Rows,
4173 )
4174 .unwrap()
4175 .iter()
4176 .map(|hit| hit.count)
4177 .sum()
4178 }
4179
4180 #[test]
4184 fn warm_block_cache_fills_and_stops_at_target() {
4185 let mk_dir = |tag: &str| {
4186 std::env::temp_dir().join(format!(
4187 "waratah-warm-{tag}-{}-{}",
4188 std::process::id(),
4189 std::time::SystemTime::now()
4190 .duration_since(std::time::UNIX_EPOCH)
4191 .unwrap()
4192 .as_nanos()
4193 ))
4194 };
4195 let store = RocksDbStorage::open(&mk_dir("full"), PartitionAxis::P).unwrap();
4196 for i in 0..3_000u64 {
4197 store
4198 .insert_quad_version(
4199 &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
4200 CommitTs(1),
4201 StorageOp::Put,
4202 VisibilityLabel::default(),
4203 )
4204 .unwrap();
4205 }
4206 store.flush_memtables().unwrap();
4207
4208 let stats = store.warm_block_cache(WARM_CACHE_FILL_FRACTION).unwrap();
4211 assert_eq!(stats.entries_touched, 6_000);
4212 assert!(
4213 stats.usage_after > stats.usage_before,
4214 "warm must fill data blocks into the cache"
4215 );
4216 assert_eq!(stats.capacity, DEFAULT_BLOCK_CACHE_BYTES);
4217
4218 let store = RocksDbStorage::open(&mk_dir("tiny"), PartitionAxis::P).unwrap();
4221 for i in 0..3_000u64 {
4222 store
4223 .insert_quad_version(
4224 &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
4225 CommitTs(1),
4226 StorageOp::Put,
4227 VisibilityLabel::default(),
4228 )
4229 .unwrap();
4230 }
4231 store.flush_memtables().unwrap();
4232 let stats = store.warm_block_cache(1e-5).unwrap();
4233 assert_eq!(stats.entries_touched, WARM_CACHE_PROBE_INTERVAL);
4234 }
4235
4236 #[test]
4241 fn scan_async_io_tuning_scans_and_warms_correctly() {
4242 let dir = std::env::temp_dir().join(format!(
4243 "waratah-scan-async-{}-{}",
4244 std::process::id(),
4245 std::time::SystemTime::now()
4246 .duration_since(std::time::UNIX_EPOCH)
4247 .unwrap()
4248 .as_nanos()
4249 ));
4250 let store = RocksDbStorage::open_with_hooks(
4251 &dir,
4252 PartitionAxis::P,
4253 RocksDbOptionsHooks {
4254 tuning: RocksDbTuning {
4255 scan_async_io: true,
4256 ..Default::default()
4257 },
4258 ..Default::default()
4259 },
4260 )
4261 .unwrap();
4262 for i in 0..500u64 {
4263 store
4264 .insert_quad_version(
4265 &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
4266 CommitTs(1),
4267 StorageOp::Put,
4268 VisibilityLabel::default(),
4269 )
4270 .unwrap();
4271 }
4272 store.flush_memtables().unwrap();
4273
4274 let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
4276 assert_eq!(count_posg(&store, &p, &[], false, true), 500);
4277
4278 let stats = store.warm_block_cache(WARM_CACHE_FILL_FRACTION).unwrap();
4281 assert!(stats.entries_touched > 0);
4282 assert!(stats.usage_after > stats.usage_before);
4283 }
4284
4285 #[test]
4288 fn domain_counts_merge_uniques_spo_not_heads() {
4289 let dir = std::env::temp_dir().join(format!(
4290 "waratah-merge-counts-{}-{}",
4291 std::process::id(),
4292 std::time::SystemTime::now()
4293 .duration_since(std::time::UNIX_EPOCH)
4294 .unwrap()
4295 .as_nanos()
4296 ));
4297 let store = RocksDbStorage::open(&dir, PartitionAxis::P).unwrap();
4298 let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
4299 for (ts, (s, o, g, op)) in (1u64..).zip([
4300 ("s", "o", "g1", StorageOp::Put),
4301 ("s", "o", "g2", StorageOp::Put),
4302 ("s1", "o", "g1", StorageOp::Put),
4303 ("s1", "o", "g2", StorageOp::Put),
4304 ("s2", "o", "g1", StorageOp::Put),
4305 ("s2", "o", "g2", StorageOp::Put),
4306 ("sd", "od", "a", StorageOp::Put),
4307 ("sd", "od", "a", StorageOp::Delete),
4308 ("sd", "od", "b", StorageOp::Put),
4309 ]) {
4310 store
4311 .insert_quad_version(
4312 &named_spo(s, o, g),
4313 CommitTs(ts),
4314 op,
4315 VisibilityLabel::default(),
4316 )
4317 .unwrap();
4318 }
4319 let g1 = encode_quad(&named_spo("s", "o", "g1")).unwrap().graph_name;
4320 let g2 = encode_quad(&named_spo("s", "o", "g2")).unwrap().graph_name;
4321 let gone = encode_quad(&named_spo("sd", "od", "a")).unwrap().graph_name;
4322
4323 assert_eq!(count_posg(&store, &p, &[], false, true), 4);
4326 assert_eq!(count_posg(&store, &p, &[], false, false), 7);
4327 assert_eq!(count_posg(&store, &p, &[g1, g2], true, true), 3);
4328 assert_eq!(
4329 count_posg(&store, &p, std::slice::from_ref(&gone), true, true),
4330 0
4331 );
4332 drop(store);
4333 let _ = std::fs::remove_dir_all(&dir);
4334 }
4335
4336 #[test]
4339 fn domain_counts_cursor_resumes_at_run_boundaries() {
4340 let dir = std::env::temp_dir().join(format!(
4341 "waratah-count-page-{}-{}",
4342 std::process::id(),
4343 std::time::SystemTime::now()
4344 .duration_since(std::time::UNIX_EPOCH)
4345 .unwrap()
4346 .as_nanos()
4347 ));
4348 let store = RocksDbStorage::open(&dir, PartitionAxis::P).unwrap();
4349 let p = NamedNode::new("http://ex/p").unwrap();
4350 let s1 = NamedNode::new("http://ex/s1").unwrap();
4351 let s2 = NamedNode::new("http://ex/s2").unwrap();
4352 let o1 = NamedNode::new("http://ex/o1").unwrap();
4353 let o2 = NamedNode::new("http://ex/o2").unwrap();
4354 for (ts, (subject, object)) in
4355 (1u64..).zip([(s1.clone(), o1.clone()), (s2, o1.clone()), (s1, o2.clone())])
4356 {
4357 store
4358 .insert_quad_version(
4359 &Quad::new(subject, p.clone(), object, GraphName::DefaultGraph),
4360 CommitTs(ts),
4361 StorageOp::Put,
4362 VisibilityLabel::default(),
4363 )
4364 .unwrap();
4365 }
4366 let predicate = EncodedTerm::from(&p);
4367 let page1 = store
4368 .scan_domain_counts(
4369 IndexPermutation::Posg,
4370 std::slice::from_ref(&predicate),
4371 SnapshotId(9),
4372 1,
4373 None,
4374 None,
4375 None,
4376 &[],
4377 false,
4378 false,
4379 false,
4380 DomainCountMode::Rows,
4381 )
4382 .unwrap();
4383 assert_eq!(page1.len(), 1);
4384 let page2 = store
4385 .scan_domain_counts(
4386 IndexPermutation::Posg,
4387 std::slice::from_ref(&predicate),
4388 SnapshotId(9),
4389 0,
4390 Some(&page1[0].constraint),
4391 Some(&page1[0].term),
4392 None,
4393 &[],
4394 false,
4395 false,
4396 false,
4397 DomainCountMode::Rows,
4398 )
4399 .unwrap();
4400 assert_eq!(page2.len(), 1);
4401 assert_ne!(page1[0].term, page2[0].term);
4402 let o1_term = EncodedTerm::from(&o1);
4403 let (o1_count, o2_count) = if page1[0].term == o1_term {
4404 (page1[0].count, page2[0].count)
4405 } else {
4406 (page2[0].count, page1[0].count)
4407 };
4408 assert_eq!((o1_count, o2_count), (2, 1));
4409 drop(store);
4410 let _ = std::fs::remove_dir_all(&dir);
4411 }
4412
4413 fn open_count_store(tag: &str) -> (std::path::PathBuf, RocksDbStorage) {
4414 let dir = std::env::temp_dir().join(format!(
4415 "waratah-count-modes-{tag}-{}-{}",
4416 std::process::id(),
4417 std::time::SystemTime::now()
4418 .duration_since(std::time::UNIX_EPOCH)
4419 .unwrap()
4420 .as_nanos()
4421 ));
4422 (
4423 dir.clone(),
4424 RocksDbStorage::open(&dir, PartitionAxis::P).unwrap(),
4425 )
4426 }
4427
4428 fn scan_posg_runs(
4429 store: &RocksDbStorage,
4430 predicate: &EncodedTerm,
4431 snapshot: u64,
4432 allow: &[EncodedTerm],
4433 allow_on: bool,
4434 merge: bool,
4435 mode: DomainCountMode,
4436 ) -> Vec<DomainScanCountHit> {
4437 store
4438 .scan_domain_counts(
4439 IndexPermutation::Posg,
4440 std::slice::from_ref(predicate),
4441 SnapshotId(snapshot),
4442 0,
4443 None,
4444 None,
4445 None,
4446 allow,
4447 allow_on,
4448 false,
4449 merge,
4450 mode,
4451 )
4452 .unwrap()
4453 }
4454
4455 fn head_count(hits: &[DomainScanCountHit], head: &EncodedTerm) -> u64 {
4456 hits.iter()
4457 .find(|h| h.term == *head)
4458 .unwrap_or_else(|| panic!("no hit for head {head:?}"))
4459 .count
4460 }
4461
4462 #[test]
4469 fn tsg_axis_walks_honor_graph_windows() {
4470 let dir = std::env::temp_dir().join(format!(
4471 "waratah-tsg-windows-{}-{}",
4472 std::process::id(),
4473 std::time::SystemTime::now()
4474 .duration_since(std::time::UNIX_EPOCH)
4475 .unwrap()
4476 .as_nanos()
4477 ));
4478 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
4479 let memory = Storage::memory(PartitionAxis::O);
4480 let t = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
4481 let type_quad = |s: &str, cls: &str, g: &str| {
4482 let graph = if g == "default" {
4483 GraphName::DefaultGraph
4484 } else {
4485 GraphName::NamedNode(NamedNode::new(format!("http://ex/{g}")).unwrap())
4486 };
4487 Quad::new(
4488 NamedNode::new(format!("http://ex/{s}")).unwrap(),
4489 t.clone(),
4490 NamedNode::new(format!("http://ex/{cls}")).unwrap(),
4491 graph,
4492 )
4493 };
4494 let rows = [
4496 ("s1", "cls1", "default"),
4497 ("s1", "cls1", "g1"),
4498 ("s2", "cls1", "g1"),
4499 ("s2", "cls1", "g2"),
4500 ("s3", "cls2", "default"),
4501 ("s3", "cls2", "g1"),
4502 ];
4503 for (ts, (s, cls, g)) in (1u64..).zip(rows) {
4504 let quad = type_quad(s, cls, g);
4505 store
4506 .insert_quad_version(
4507 &quad,
4508 CommitTs(ts),
4509 StorageOp::Put,
4510 VisibilityLabel::default(),
4511 )
4512 .unwrap();
4513 memory
4514 .insert_quad_version(
4515 &quad,
4516 CommitTs(ts),
4517 StorageOp::Put,
4518 VisibilityLabel::default(),
4519 )
4520 .unwrap();
4521 }
4522 let g1 = graph_term("g1");
4523 let g2 = graph_term("g2");
4524 let snap = SnapshotId(10);
4525
4526 let windows: Vec<(&str, Option<EncodedTerm>, Vec<EncodedTerm>, bool)> = vec![
4532 ("bound-g1", Some(g1.clone()), vec![], false),
4533 (
4534 "bound-default",
4535 Some(EncodedTerm::DefaultGraph),
4536 vec![],
4537 false,
4538 ),
4539 ("allow-g1g2", None, vec![g1.clone(), g2.clone()], true),
4540 ("deny-g1", None, vec![g1.clone()], false),
4541 ];
4542 for (name, graph_name, filter, allow) in &windows {
4543 let filter_ref: &[EncodedTerm] = filter;
4544 let hits = store
4545 .scan_axis_head(
4546 IndexPermutation::Tsg,
4547 snap,
4548 0,
4549 None,
4550 graph_name.as_ref(),
4551 filter_ref,
4552 *allow,
4553 false,
4554 &[],
4555 )
4556 .unwrap();
4557 let mem_hits = memory
4558 .scan_axis_head(
4559 IndexPermutation::Tsg,
4560 snap,
4561 0,
4562 None,
4563 graph_name.as_ref(),
4564 filter_ref,
4565 *allow,
4566 false,
4567 &[],
4568 )
4569 .unwrap();
4570 assert_eq!(hits, mem_hits, "hits parity under {name}");
4571 assert_eq!(hits.len(), 2, "both classes visible under {name}: {hits:?}");
4572
4573 let total = store
4574 .count_axis_heads(
4575 IndexPermutation::Tsg,
4576 snap,
4577 graph_name.as_ref(),
4578 filter_ref,
4579 *allow,
4580 false,
4581 )
4582 .unwrap();
4583 let mem_total = memory
4584 .count_axis_heads(
4585 IndexPermutation::Tsg,
4586 snap,
4587 graph_name.as_ref(),
4588 filter_ref,
4589 *allow,
4590 false,
4591 )
4592 .unwrap();
4593 assert_eq!(total, mem_total, "TOTAL parity under {name}");
4594 assert_eq!(total, 2, "TOTAL counts both classes under {name}");
4595
4596 let per_head = store
4597 .scan_axis_head_counts(
4598 IndexPermutation::Tsg,
4599 snap,
4600 0,
4601 None,
4602 graph_name.as_ref(),
4603 filter_ref,
4604 *allow,
4605 false,
4606 )
4607 .unwrap();
4608 let mem_per_head = memory
4609 .scan_axis_head_counts(
4610 IndexPermutation::Tsg,
4611 snap,
4612 0,
4613 None,
4614 graph_name.as_ref(),
4615 filter_ref,
4616 *allow,
4617 false,
4618 )
4619 .unwrap();
4620 assert_eq!(per_head, mem_per_head, "PER_HEAD parity under {name}");
4621 let mut counts: Vec<u64> = per_head.iter().map(|h| h.count).collect();
4622 counts.sort_unstable();
4623 let expected = match *name {
4624 "bound-default" => vec![1, 1],
4625 _ => vec![1, 2],
4626 };
4627 assert_eq!(
4628 counts, expected,
4629 "PER_HEAD distinct subjects under {name}: {per_head:?}"
4630 );
4631 }
4632
4633 drop(store);
4634 let _ = std::fs::remove_dir_all(&dir);
4635 }
4636
4637 #[test]
4643 fn distinct_count_modes_refuse_tsg() {
4644 let dir = std::env::temp_dir().join(format!(
4645 "waratah-tsg-distinct-refusal-{}-{}",
4646 std::process::id(),
4647 std::time::SystemTime::now()
4648 .duration_since(std::time::UNIX_EPOCH)
4649 .unwrap()
4650 .as_nanos()
4651 ));
4652 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
4653 let memory = Storage::memory(PartitionAxis::O);
4654 let t = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
4655 let quad = Quad::new(
4656 NamedNode::new("http://ex/s1").unwrap(),
4657 t.clone(),
4658 NamedNode::new("http://ex/cls1").unwrap(),
4659 GraphName::NamedNode(NamedNode::new("http://ex/g1").unwrap()),
4660 );
4661 store
4662 .insert_quad_version(
4663 &quad,
4664 CommitTs(1),
4665 StorageOp::Put,
4666 VisibilityLabel::default(),
4667 )
4668 .unwrap();
4669 memory
4670 .insert_quad_version(
4671 &quad,
4672 CommitTs(1),
4673 StorageOp::Put,
4674 VisibilityLabel::default(),
4675 )
4676 .unwrap();
4677 let cls1 = EncodedTerm::from(&NamedNode::new("http://ex/cls1").unwrap());
4678
4679 for mode in [
4680 DomainCountMode::DistinctTerms,
4681 DomainCountMode::DistinctGraphs,
4682 ] {
4683 let rocks = store.scan_domain_counts(
4684 IndexPermutation::Tsg,
4685 std::slice::from_ref(&cls1),
4686 SnapshotId(10),
4687 0,
4688 None,
4689 None,
4690 None,
4691 &[],
4692 false,
4693 false,
4694 false,
4695 mode,
4696 );
4697 assert!(
4698 matches!(rocks, Err(StorageError::DistinctCountsNotOnTsg)),
4699 "RocksDB must refuse TSG + {mode:?}: {rocks:?}"
4700 );
4701 let mem = memory.scan_domain_counts(
4702 IndexPermutation::Tsg,
4703 std::slice::from_ref(&cls1),
4704 SnapshotId(10),
4705 0,
4706 None,
4707 None,
4708 None,
4709 &[],
4710 false,
4711 false,
4712 false,
4713 mode,
4714 );
4715 assert!(
4716 matches!(mem, Err(StorageError::DistinctCountsNotOnTsg)),
4717 "memory must refuse TSG + {mode:?}: {mem:?}"
4718 );
4719 }
4720
4721 for hits in [
4723 store.scan_domain_counts(
4724 IndexPermutation::Tsg,
4725 std::slice::from_ref(&cls1),
4726 SnapshotId(10),
4727 0,
4728 None,
4729 None,
4730 None,
4731 &[],
4732 false,
4733 false,
4734 false,
4735 DomainCountMode::Rows,
4736 ),
4737 memory.scan_domain_counts(
4738 IndexPermutation::Tsg,
4739 std::slice::from_ref(&cls1),
4740 SnapshotId(10),
4741 0,
4742 None,
4743 None,
4744 None,
4745 &[],
4746 false,
4747 false,
4748 false,
4749 DomainCountMode::Rows,
4750 ),
4751 ] {
4752 let hits = hits.unwrap();
4753 assert_eq!(hits.len(), 1, "one head (the subject): {hits:?}");
4754 assert_eq!(hits[0].count, 1, "one row: {hits:?}");
4755 }
4756
4757 drop(store);
4758 let _ = std::fs::remove_dir_all(&dir);
4759 }
4760
4761 #[test]
4764 fn axis_head_counts_total_and_per_head() {
4765 let dir = std::env::temp_dir().join(format!(
4766 "waratah-count-axis-heads-{}-{}",
4767 std::process::id(),
4768 std::time::SystemTime::now()
4769 .duration_since(std::time::UNIX_EPOCH)
4770 .unwrap()
4771 .as_nanos()
4772 ));
4773 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
4774 let t = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
4775 let type_quad = |s: &str, cls: &str, g: &str| {
4776 Quad::new(
4777 NamedNode::new(format!("http://ex/{s}")).unwrap(),
4778 t.clone(),
4779 NamedNode::new(format!("http://ex/{cls}")).unwrap(),
4780 GraphName::NamedNode(NamedNode::new(format!("http://ex/{g}")).unwrap()),
4781 )
4782 };
4783 for (ts, (s, cls, g, op)) in (1u64..).zip([
4784 ("s1", "cls1", "g1", StorageOp::Put),
4785 ("s1", "cls1", "g2", StorageOp::Put),
4786 ("s2", "cls1", "g1", StorageOp::Put),
4787 ("s3", "cls2", "g1", StorageOp::Put),
4788 ("s1", "cls1", "g2", StorageOp::Delete),
4789 ]) {
4790 store
4791 .insert_quad_version(
4792 &type_quad(s, cls, g),
4793 CommitTs(ts),
4794 op,
4795 VisibilityLabel::default(),
4796 )
4797 .unwrap();
4798 }
4799
4800 let total = store
4801 .count_axis_heads(
4802 IndexPermutation::Tsg,
4803 SnapshotId(9),
4804 None,
4805 &[],
4806 false,
4807 false,
4808 )
4809 .unwrap();
4810 assert_eq!(total, 2, "two distinct classes");
4811
4812 let hits = store
4813 .scan_axis_head_counts(
4814 IndexPermutation::Tsg,
4815 SnapshotId(9),
4816 0,
4817 None,
4818 None,
4819 &[],
4820 false,
4821 false,
4822 )
4823 .unwrap();
4824 assert_eq!(hits.len(), 2);
4825 let counts: Vec<u64> = hits.iter().map(|h| h.count).collect();
4826 assert!(
4827 counts.contains(&2),
4828 "cls1 has two distinct subjects: {hits:?}"
4829 );
4830 assert!(counts.contains(&1), "cls2 has one subject: {hits:?}");
4831
4832 let g2 = encode_quad(&type_quad("s1", "cls1", "g2"))
4833 .unwrap()
4834 .graph_name;
4835 let total_g2 = store
4836 .count_axis_heads(
4837 IndexPermutation::Tsg,
4838 SnapshotId(9),
4839 None,
4840 std::slice::from_ref(&g2),
4841 true,
4842 false,
4843 )
4844 .unwrap();
4845 assert_eq!(total_g2, 0, "the g2 copy was deleted");
4846 let at4 = store
4847 .count_axis_heads(
4848 IndexPermutation::Tsg,
4849 SnapshotId(4),
4850 None,
4851 std::slice::from_ref(&g2),
4852 true,
4853 false,
4854 )
4855 .unwrap();
4856 assert_eq!(at4, 1, "one class visible in g2 before the delete");
4857
4858 let page1 = store
4859 .scan_axis_head_counts(
4860 IndexPermutation::Tsg,
4861 SnapshotId(9),
4862 1,
4863 None,
4864 None,
4865 &[],
4866 false,
4867 false,
4868 )
4869 .unwrap();
4870 assert_eq!(page1.len(), 1);
4871 let page2 = store
4872 .scan_axis_head_counts(
4873 IndexPermutation::Tsg,
4874 SnapshotId(9),
4875 0,
4876 Some(&page1[0].term),
4877 None,
4878 &[],
4879 false,
4880 false,
4881 )
4882 .unwrap();
4883 assert_eq!(page2.len(), 1);
4884 assert_ne!(page1[0].term, page2[0].term);
4885 drop(store);
4886 let _ = std::fs::remove_dir_all(&dir);
4887 }
4888
4889 #[test]
4893 fn domain_counts_modes_select_counting_dimension() {
4894 let (dir, store) = open_count_store("modes");
4895 let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
4896 for (ts, (s, o, g, op)) in (1u64..).zip([
4899 ("s1", "o", "g1", StorageOp::Put),
4900 ("s1", "o", "g2", StorageOp::Put),
4901 ("s2", "o", "g1", StorageOp::Put),
4902 ("s3", "o2", "g1", StorageOp::Put),
4903 ("s1", "o", "g2", StorageOp::Delete),
4904 ]) {
4905 store
4906 .insert_quad_version(
4907 &named_spo(s, o, g),
4908 CommitTs(ts),
4909 op,
4910 VisibilityLabel::default(),
4911 )
4912 .unwrap();
4913 }
4914
4915 let o_head = encode_quad(&named_spo("s1", "o", "g1")).unwrap().object;
4916 let o2_head = encode_quad(&named_spo("s3", "o2", "g1")).unwrap().object;
4917 let runs = |snapshot: u64, mode: DomainCountMode| {
4918 scan_posg_runs(&store, &p, snapshot, &[], false, false, mode)
4919 };
4920
4921 let at4 = runs(4, DomainCountMode::Rows);
4923 assert_eq!(head_count(&at4, &o_head), 3);
4924 assert_eq!(head_count(&at4, &o2_head), 1);
4925 let terms = runs(4, DomainCountMode::DistinctTerms);
4927 assert_eq!(head_count(&terms, &o_head), 2);
4928 assert_eq!(head_count(&terms, &o2_head), 1);
4929 let graphs = runs(4, DomainCountMode::DistinctGraphs);
4931 assert_eq!(head_count(&graphs, &o_head), 2);
4932 assert_eq!(head_count(&graphs, &o2_head), 1);
4933
4934 assert_eq!(head_count(&runs(9, DomainCountMode::Rows), &o_head), 2);
4936 assert_eq!(
4937 head_count(&runs(9, DomainCountMode::DistinctTerms), &o_head),
4938 2
4939 );
4940 assert_eq!(
4941 head_count(&runs(9, DomainCountMode::DistinctGraphs), &o_head),
4942 1
4943 );
4944 assert_eq!(
4945 head_count(&runs(9, DomainCountMode::DistinctGraphs), &o2_head),
4946 1
4947 );
4948 drop(store);
4949 let _ = std::fs::remove_dir_all(&dir);
4950 }
4951
4952 #[test]
4954 fn domain_counts_distinct_graphs_respects_graph_window() {
4955 let (dir, store) = open_count_store("graph-window");
4956 let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
4957 for (ts, g) in (1u64..).zip(["g1", "g2", "g3"]) {
4958 store
4959 .insert_quad_version(
4960 &named_spo("s", "o", g),
4961 CommitTs(ts),
4962 StorageOp::Put,
4963 VisibilityLabel::default(),
4964 )
4965 .unwrap();
4966 }
4967 let o_head = encode_quad(&named_spo("s", "o", "g1")).unwrap().object;
4968 let g1 = encode_quad(&named_spo("s", "o", "g1")).unwrap().graph_name;
4969 let g3 = encode_quad(&named_spo("s", "o", "g3")).unwrap().graph_name;
4970
4971 let all = scan_posg_runs(
4972 &store,
4973 &p,
4974 9,
4975 &[],
4976 false,
4977 false,
4978 DomainCountMode::DistinctGraphs,
4979 );
4980 assert_eq!(head_count(&all, &o_head), 3);
4981 let allowed = scan_posg_runs(
4982 &store,
4983 &p,
4984 9,
4985 std::slice::from_ref(&g1),
4986 true,
4987 false,
4988 DomainCountMode::DistinctGraphs,
4989 );
4990 assert_eq!(head_count(&allowed, &o_head), 1);
4991 let blocked = scan_posg_runs(
4993 &store,
4994 &p,
4995 9,
4996 std::slice::from_ref(&g3),
4997 false,
4998 false,
4999 DomainCountMode::DistinctGraphs,
5000 );
5001 assert_eq!(head_count(&blocked, &o_head), 2);
5002 drop(store);
5003 let _ = std::fs::remove_dir_all(&dir);
5004 }
5005
5006 #[test]
5010 fn domain_counts_merge_makes_rows_equal_distinct_terms() {
5011 let (dir, store) = open_count_store("merge-equiv");
5012 let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
5013 for (ts, (s, g)) in (1u64..).zip([("s1", "g1"), ("s1", "g2"), ("s2", "g1")]) {
5014 store
5015 .insert_quad_version(
5016 &named_spo(s, "o", g),
5017 CommitTs(ts),
5018 StorageOp::Put,
5019 VisibilityLabel::default(),
5020 )
5021 .unwrap();
5022 }
5023 let o_head = encode_quad(&named_spo("s1", "o", "g1")).unwrap().object;
5024 assert_eq!(
5025 head_count(
5026 &scan_posg_runs(&store, &p, 9, &[], false, true, DomainCountMode::Rows),
5027 &o_head
5028 ),
5029 2
5030 );
5031 assert_eq!(
5032 head_count(
5033 &scan_posg_runs(
5034 &store,
5035 &p,
5036 9,
5037 &[],
5038 false,
5039 false,
5040 DomainCountMode::DistinctTerms
5041 ),
5042 &o_head
5043 ),
5044 2
5045 );
5046 drop(store);
5047 let _ = std::fs::remove_dir_all(&dir);
5048 }
5049
5050 #[test]
5053 fn geo_index_epoch_persists_across_reopen() {
5054 let dir = std::env::temp_dir().join(format!(
5055 "waratah-geo-epoch-{}-{}",
5056 std::process::id(),
5057 std::time::SystemTime::now()
5058 .duration_since(std::time::UNIX_EPOCH)
5059 .unwrap()
5060 .as_nanos()
5061 ));
5062 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5063 assert_eq!(store.geo_index_epoch().unwrap(), None);
5064 store.set_geo_index_epoch(42).unwrap();
5065 assert_eq!(store.geo_index_epoch().unwrap(), Some(42));
5066 drop(store);
5067
5068 let reopened = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5070 assert_eq!(reopened.geo_index_epoch().unwrap(), Some(42));
5071 drop(reopened);
5072 let _ = std::fs::remove_dir_all(&dir);
5073 }
5074
5075 #[test]
5085 fn temporal_origin_version_gates_the_epoch_trust_decision() {
5086 let dir = std::env::temp_dir().join(format!(
5087 "waratah-temporal-origin-{}-{}",
5088 std::process::id(),
5089 std::time::SystemTime::now()
5090 .duration_since(std::time::UNIX_EPOCH)
5091 .unwrap()
5092 .as_nanos()
5093 ));
5094 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5095 assert_eq!(store.temporal_index_epoch().unwrap(), None, "fresh store");
5096
5097 store.set_temporal_index_epoch(42).unwrap();
5099 assert_eq!(
5100 store.temporal_index_epoch().unwrap(),
5101 Some(42),
5102 "stamped under the current origin"
5103 );
5104
5105 {
5108 let cf = store
5109 .cf_temporal_meta
5110 .as_ref()
5111 .expect("O axis has the meta CF");
5112 let mut batch = store.db.write_batch();
5113 batch.insert(cf, TEMPORAL_INDEX_ORIGIN_KEY, &encode_temporal_origin(0));
5114 batch.commit().unwrap();
5115 }
5116 assert_eq!(
5117 store.temporal_index_epoch().unwrap(),
5118 None,
5119 "an epoch stamped under a different origin must read untrusted"
5120 );
5121
5122 store.set_temporal_index_epoch(43).unwrap();
5124 assert_eq!(
5125 store.temporal_index_epoch().unwrap(),
5126 Some(43),
5127 "re-stamped"
5128 );
5129
5130 drop(store);
5131 let _ = std::fs::remove_dir_all(&dir);
5132 }
5133
5134 #[test]
5135 fn geo_index_liveness_gates_the_epoch_across_a_wipe() {
5136 let dir = std::env::temp_dir().join(format!(
5137 "waratah-geo-liveness-{}-{}",
5138 std::process::id(),
5139 std::time::SystemTime::now()
5140 .duration_since(std::time::UNIX_EPOCH)
5141 .unwrap()
5142 .as_nanos()
5143 ));
5144 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5145 assert_eq!(store.geo_index_epoch().unwrap(), None, "fresh store");
5146
5147 store.set_geo_index_epoch(42).unwrap();
5149 assert_eq!(store.geo_index_epoch().unwrap(), Some(42), "stamped");
5150
5151 store.wipe_geo_index().unwrap();
5154 assert_eq!(
5155 store.geo_index_epoch().unwrap(),
5156 None,
5157 "a wiped index with a surviving epoch must read untrusted"
5158 );
5159
5160 store.set_geo_index_epoch(43).unwrap();
5162 assert_eq!(store.geo_index_epoch().unwrap(), Some(43), "re-stamped");
5163
5164 drop(store);
5165 let _ = std::fs::remove_dir_all(&dir);
5166 }
5167
5168 #[test]
5169 fn temporal_wipe_untrusts_temporal_and_spares_geo() {
5170 let dir = std::env::temp_dir().join(format!(
5176 "waratah-temporal-wipe-{}-{}",
5177 std::process::id(),
5178 std::time::SystemTime::now()
5179 .duration_since(std::time::UNIX_EPOCH)
5180 .unwrap()
5181 .as_nanos()
5182 ));
5183 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5184 store.set_geo_index_epoch(7).unwrap();
5185 store.set_temporal_index_epoch(9).unwrap();
5186 assert_eq!(store.temporal_index_epoch().unwrap(), Some(9));
5187 assert_eq!(store.geo_index_epoch().unwrap(), Some(7), "geo trusted");
5188
5189 store.wipe_temporal_index().unwrap();
5190
5191 assert_eq!(store.temporal_index_epoch().unwrap(), None);
5194 assert_eq!(store.geo_index_epoch().unwrap(), Some(7));
5196
5197 store.set_temporal_index_epoch(10).unwrap();
5199 assert_eq!(store.temporal_index_epoch().unwrap(), Some(10));
5200
5201 drop(store);
5202 let _ = std::fs::remove_dir_all(&dir);
5203 }
5204
5205 #[test]
5206 fn geo_index_epoch_is_rejected_off_the_o_axis() {
5207 let dir = std::env::temp_dir().join(format!(
5208 "waratah-geo-epoch-axis-{}-{}",
5209 std::process::id(),
5210 std::time::SystemTime::now()
5211 .duration_since(std::time::UNIX_EPOCH)
5212 .unwrap()
5213 .as_nanos()
5214 ));
5215 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
5216 assert_eq!(store.geo_index_epoch().unwrap(), None);
5217 assert!(matches!(
5218 store.set_geo_index_epoch(1),
5219 Err(crate::StorageError::GeoIndexNotOnAxis(_))
5220 ));
5221 drop(store);
5222 let _ = std::fs::remove_dir_all(&dir);
5223 }
5224
5225 fn temporal_event_quad(subject: &str, when: &str) -> Quad {
5226 Quad::new(
5227 NamedNode::new(format!("http://ex/{subject}")).unwrap(),
5228 NamedNode::new("http://ex/observedAt").unwrap(),
5229 crate::Literal::new_typed_literal(
5230 when,
5231 NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#dateTime"),
5232 ),
5233 GraphName::DefaultGraph,
5234 )
5235 }
5236
5237 #[test]
5243 fn temporal_rebuild_terms_liveness_is_per_quad() {
5244 let dir = std::env::temp_dir().join(format!(
5245 "waratah-temporal-liveness-{}-{}",
5246 std::process::id(),
5247 std::time::SystemTime::now()
5248 .duration_since(std::time::UNIX_EPOCH)
5249 .unwrap()
5250 .as_nanos()
5251 ));
5252 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5253 let a = encode_quad(&temporal_event_quad("a", "2020-01-01T00:00:00Z")).unwrap();
5254 let b = encode_quad(&temporal_event_quad("b", "2020-01-01T00:00:00Z")).unwrap();
5255 let term = a.object.clone();
5256
5257 store
5259 .insert_encoded_quad_version(
5260 &a,
5261 CommitTs(1),
5262 StorageOp::Put,
5263 VisibilityLabel::default(),
5264 )
5265 .unwrap();
5266 store
5267 .insert_encoded_quad_version(
5268 &b,
5269 CommitTs(2),
5270 StorageOp::Put,
5271 VisibilityLabel::default(),
5272 )
5273 .unwrap();
5274 let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
5275 assert_eq!(terms, vec![term.clone()]);
5276 assert_eq!(epoch, CommitTs(2));
5277
5278 store
5281 .insert_encoded_quad_version(
5282 &b,
5283 CommitTs(3),
5284 StorageOp::Delete,
5285 VisibilityLabel::default(),
5286 )
5287 .unwrap();
5288 let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
5289 assert_eq!(terms, vec![term.clone()]);
5290 assert_eq!(epoch, CommitTs(3));
5291
5292 store
5294 .insert_encoded_quad_version(
5295 &a,
5296 CommitTs(4),
5297 StorageOp::Delete,
5298 VisibilityLabel::default(),
5299 )
5300 .unwrap();
5301 let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
5302 assert!(terms.is_empty());
5303 assert_eq!(epoch, CommitTs(4));
5304
5305 store
5307 .insert_encoded_quad_version(
5308 &b,
5309 CommitTs(5),
5310 StorageOp::Put,
5311 VisibilityLabel::default(),
5312 )
5313 .unwrap();
5314 let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
5315 assert_eq!(terms, vec![term.clone()]);
5316 assert_eq!(epoch, CommitTs(5));
5317 drop(store);
5318 let _ = std::fs::remove_dir_all(&dir);
5319 }
5320 use super::{
5329 DomainScanHit, DomainScanMode, domain_walks_from_env, encode_term_bytes, split_slices,
5330 };
5331 use crate::Storage;
5332 use crate::encode::{
5333 COMMIT_TS_LEN, encode_storage_value, encode_versioned_key, prepare_constraints_sorted,
5334 };
5335 use std::path::PathBuf;
5336
5337 const MODES: [DomainScanMode; 4] = [
5338 DomainScanMode::Legacy,
5339 DomainScanMode::ParallelWalks(2),
5340 DomainScanMode::ParallelWalks(3),
5341 DomainScanMode::ParallelWalks(64),
5342 ];
5343
5344 const SNAP: SnapshotId = SnapshotId(1_000);
5345
5346 fn fixture_rows() -> Vec<(
5351 &'static str,
5352 &'static str,
5353 &'static str,
5354 &'static str,
5355 u64,
5356 StorageOp,
5357 )> {
5358 vec![
5359 ("s1", "p1", "o1", "default", 1, StorageOp::Put),
5360 ("s1", "p1", "o2", "default", 2, StorageOp::Put),
5361 ("s2", "p1", "o3", "g1", 3, StorageOp::Put),
5362 ("s2", "p1", "o3", "g2", 4, StorageOp::Put),
5363 ("s3", "p1", "lit:foo", "default", 5, StorageOp::Put),
5364 ("s4", "p1", "o_dead", "default", 6, StorageOp::Put),
5365 ("s4", "p1", "o_dead", "default", 7, StorageOp::Delete),
5366 ("s5", "p2", "o1", "default", 8, StorageOp::Put),
5368 ("s6", "p3", "o4", "g1", 9, StorageOp::Put),
5369 ("s7", "p3", "o4", "default", 10, StorageOp::Put),
5370 ]
5371 }
5372
5373 fn fixture_quad(s: &str, p: &str, o: &str, g: &str) -> Quad {
5374 let object: crate::Term = if let Some(local) = o.strip_prefix("typed:") {
5375 crate::Literal::new_typed_literal(
5379 local,
5380 NamedNode::new("http://www.w3.org/2001/XMLSchema#nonNegativeInteger").unwrap(),
5381 )
5382 .into()
5383 } else {
5384 match o.strip_prefix("lit:") {
5385 Some(local) => crate::Literal::from(local).into(),
5386 None => NamedNode::new(format!("http://ex/{o}")).unwrap().into(),
5387 }
5388 };
5389 let graph = if g == "default" {
5390 GraphName::DefaultGraph
5391 } else {
5392 GraphName::NamedNode(NamedNode::new(format!("http://ex/{g}")).unwrap())
5393 };
5394 Quad::new(
5395 NamedNode::new(format!("http://ex/{s}")).unwrap(),
5396 NamedNode::new(format!("http://ex/{p}")).unwrap(),
5397 object,
5398 graph,
5399 )
5400 }
5401
5402 fn constraint(local: &str) -> EncodedTerm {
5403 EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap())
5404 }
5405
5406 fn graph_term(g: &str) -> EncodedTerm {
5407 encode_quad(&fixture_quad("s", "p", "o", g))
5408 .unwrap()
5409 .graph_name
5410 }
5411
5412 fn open_p_store(tag: &str) -> (RocksDbStorage, PathBuf) {
5413 let dir = std::env::temp_dir().join(format!(
5414 "waratah-domain-modes-{tag}-{}-{}",
5415 std::process::id(),
5416 std::time::SystemTime::now()
5417 .duration_since(std::time::UNIX_EPOCH)
5418 .unwrap()
5419 .as_nanos()
5420 ));
5421 let store = RocksDbStorage::open(&dir, PartitionAxis::P).unwrap();
5422 (store, dir)
5423 }
5424
5425 fn load_fixture(rocks: &RocksDbStorage, memory: &Storage) {
5427 for (s, p, o, g, ts, op) in fixture_rows() {
5428 let quad = fixture_quad(s, p, o, g);
5429 rocks
5430 .insert_quad_version(&quad, CommitTs(ts), op, VisibilityLabel::default())
5431 .unwrap();
5432 memory
5433 .insert_quad_version(&quad, CommitTs(ts), op, VisibilityLabel::default())
5434 .unwrap();
5435 }
5436 }
5437
5438 struct DomainArgs<'a> {
5439 graph_name: Option<&'a EncodedTerm>,
5440 filter_terms: &'a [EncodedTerm],
5441 filter_allow: bool,
5442 iri_only: bool,
5443 merge: bool,
5444 count_mode: DomainCountMode,
5447 }
5448
5449 impl Default for DomainArgs<'_> {
5450 fn default() -> Self {
5451 Self {
5452 graph_name: None,
5453 filter_terms: &[],
5454 filter_allow: false,
5455 iri_only: false,
5456 merge: false,
5457 count_mode: DomainCountMode::Rows,
5458 }
5459 }
5460 }
5461
5462 #[allow(clippy::too_many_arguments)]
5463 fn scan_hits(
5464 store: &RocksDbStorage,
5465 mode: DomainScanMode,
5466 constraints: &[EncodedTerm],
5467 limit: u64,
5468 after: Option<&(EncodedTerm, EncodedTerm)>,
5469 args: &DomainArgs<'_>,
5470 ) -> Result<Vec<DomainScanHit>, crate::StorageError> {
5471 store.scan_domain_with_mode(
5472 mode,
5473 IndexPermutation::Posg,
5474 constraints,
5475 SNAP,
5476 limit,
5477 after.map(|cursor| &cursor.0),
5478 after.map(|cursor| &cursor.1),
5479 args.graph_name,
5480 args.filter_terms,
5481 args.filter_allow,
5482 args.iri_only,
5483 )
5484 }
5485
5486 fn scan_counts(
5487 store: &RocksDbStorage,
5488 mode: DomainScanMode,
5489 constraints: &[EncodedTerm],
5490 limit: u64,
5491 after: Option<&(EncodedTerm, EncodedTerm)>,
5492 args: &DomainArgs<'_>,
5493 ) -> Result<Vec<DomainScanCountHit>, crate::StorageError> {
5494 store.scan_domain_counts_with_mode(
5495 mode,
5496 IndexPermutation::Posg,
5497 constraints,
5498 SNAP,
5499 limit,
5500 after.map(|cursor| &cursor.0),
5501 after.map(|cursor| &cursor.1),
5502 args.graph_name,
5503 args.filter_terms,
5504 args.filter_allow,
5505 args.iri_only,
5506 args.merge,
5507 args.count_mode,
5508 )
5509 }
5510
5511 fn memory_hits(
5513 memory: &Storage,
5514 constraints: &[EncodedTerm],
5515 limit: u64,
5516 after: Option<&(EncodedTerm, EncodedTerm)>,
5517 args: &DomainArgs<'_>,
5518 ) -> Vec<DomainScanHit> {
5519 memory
5520 .scan_domain(
5521 IndexPermutation::Posg,
5522 constraints,
5523 SNAP,
5524 limit,
5525 after.map(|cursor| &cursor.0),
5526 after.map(|cursor| &cursor.1),
5527 args.graph_name,
5528 args.filter_terms,
5529 args.filter_allow,
5530 args.iri_only,
5531 )
5532 .unwrap()
5533 }
5534
5535 fn memory_counts(
5536 memory: &Storage,
5537 constraints: &[EncodedTerm],
5538 limit: u64,
5539 after: Option<&(EncodedTerm, EncodedTerm)>,
5540 args: &DomainArgs<'_>,
5541 ) -> Vec<DomainScanCountHit> {
5542 memory
5543 .scan_domain_counts(
5544 IndexPermutation::Posg,
5545 constraints,
5546 SNAP,
5547 limit,
5548 after.map(|cursor| &cursor.0),
5549 after.map(|cursor| &cursor.1),
5550 args.graph_name,
5551 args.filter_terms,
5552 args.filter_allow,
5553 args.iri_only,
5554 args.merge,
5555 args.count_mode,
5556 )
5557 .unwrap()
5558 }
5559
5560 fn hit_keys(hits: &[DomainScanHit]) -> Vec<(Vec<u8>, Vec<u8>)> {
5561 hits.iter()
5562 .map(|hit| {
5563 (
5564 encode_term_bytes(&hit.constraint),
5565 encode_term_bytes(&hit.term),
5566 )
5567 })
5568 .collect()
5569 }
5570
5571 fn count_keys(hits: &[DomainScanCountHit]) -> Vec<(Vec<u8>, Vec<u8>, u64)> {
5572 hits.iter()
5573 .map(|hit| {
5574 (
5575 encode_term_bytes(&hit.constraint),
5576 encode_term_bytes(&hit.term),
5577 hit.count,
5578 )
5579 })
5580 .collect()
5581 }
5582
5583 fn assert_strictly_key_ordered(hits: &[DomainScanHit]) {
5585 let keys = hit_keys(hits);
5586 assert!(
5587 keys.windows(2).all(|window| window[0] < window[1]),
5588 "expected strict key order, got {keys:?}"
5589 );
5590 }
5591
5592 fn assert_counts_strictly_key_ordered(hits: &[DomainScanCountHit]) {
5593 let mut keys: Vec<(Vec<u8>, Vec<u8>)> = count_keys(hits)
5594 .into_iter()
5595 .map(|(constraint, term, _)| (constraint, term))
5596 .collect();
5597 keys.dedup();
5598 assert!(
5599 keys.windows(2).all(|window| window[0] < window[1]),
5600 "expected strict key order, got {keys:?}"
5601 );
5602 }
5603
5604 #[test]
5605 fn domain_mode_parsers_reject_junk_and_clamp() {
5606 assert_eq!(domain_walks_from_env(None), None);
5608 assert_eq!(domain_walks_from_env(Some("2")), Some(2));
5609 assert_eq!(domain_walks_from_env(Some("4")), Some(4));
5610 assert_eq!(domain_walks_from_env(Some("64")), Some(64));
5611 assert_eq!(domain_walks_from_env(Some("65")), Some(64));
5612 assert_eq!(domain_walks_from_env(Some("1000")), Some(64));
5613 assert_eq!(domain_walks_from_env(Some("1")), None);
5614 assert_eq!(domain_walks_from_env(Some("0")), None);
5615 assert_eq!(domain_walks_from_env(Some("junk")), None);
5616 assert_eq!(domain_walks_from_env(Some("")), None);
5617 }
5621
5622 #[test]
5623 fn split_slices_balances_and_covers() {
5624 assert!(split_slices(0, 8).is_empty());
5625 assert_eq!(split_slices(5, 2), vec![0..3, 3..5]);
5626 assert_eq!(split_slices(6, 4), vec![0..2, 2..4, 4..5, 5..6]);
5627 assert_eq!(split_slices(1, 8), vec![0..1]);
5628 assert_eq!(split_slices(2, 64), vec![0..1, 1..2]);
5629 assert_eq!(split_slices(4, 4), vec![0..1, 1..2, 2..3, 3..4]);
5630 for &(len, workers) in &[(7usize, 3usize), (1, 64), (64, 64), (3, 2)] {
5632 let slices = split_slices(len, workers);
5633 assert_eq!(slices.first().unwrap().start, 0);
5634 assert_eq!(slices.last().unwrap().end, len);
5635 for (a, b) in slices.iter().zip(slices.iter().skip(1)) {
5636 assert_eq!(a.end, b.start);
5637 }
5638 assert!(slices.iter().all(|slice| !slice.is_empty()));
5639 }
5640 }
5641
5642 #[test]
5643 fn prepare_constraints_sorted_matches_key_bytes() {
5644 let terms: Vec<EncodedTerm> = ["p1", "p2", "p3", "p4"]
5647 .iter()
5648 .map(|local| constraint(local))
5649 .collect();
5650 let sorted = prepare_constraints_sorted(IndexPermutation::Posg, &terms).unwrap();
5651 let keys: Vec<Vec<u8>> = sorted.iter().map(encode_term_bytes).collect();
5652 let mut want = keys.clone();
5653 want.sort();
5654 assert_eq!(keys, want);
5655 }
5656
5657 #[test]
5663 fn domain_scan_modes_match_memory_reference() {
5664 let (store, dir) = open_p_store("corpus");
5665 let memory = Storage::memory(PartitionAxis::P);
5666 load_fixture(&store, &memory);
5667
5668 let p1 = constraint("p1");
5669 let p2 = constraint("p2");
5670 let p3 = constraint("p3");
5671 let p4 = constraint("p4");
5672 let mut sorted_all = vec![p1.clone(), p2.clone(), p3.clone(), p4.clone()];
5674 sorted_all.sort_by_key(encode_term_bytes);
5675 let constraint_sets: Vec<Vec<EncodedTerm>> = vec![
5676 sorted_all,
5677 vec![p1.clone()],
5678 vec![], vec![p2.clone(), p1.clone(), p2.clone(), p3.clone()], vec![p3.clone(), p4.clone(), p1.clone()],
5681 vec![p4.clone()], ];
5683
5684 let g1 = graph_term("g1");
5685 let g2 = graph_term("g2");
5686 let graph_cases: Vec<(&str, Option<EncodedTerm>, Vec<EncodedTerm>, bool)> = vec![
5687 ("unconstrained", None, Vec::new(), false),
5688 ("bound-g1", Some(g1.clone()), Vec::new(), false),
5689 ("allow-g1g2", None, vec![g1.clone(), g2.clone()], true),
5690 ("block-g1", None, vec![g1.clone()], false),
5691 ];
5692
5693 for (case_name, graph_name, filter_terms, filter_allow) in &graph_cases {
5694 for &iri_only in &[false, true] {
5695 let args = DomainArgs {
5696 graph_name: graph_name.as_ref(),
5697 filter_terms,
5698 filter_allow: *filter_allow,
5699 iri_only,
5700 merge: false,
5701 count_mode: DomainCountMode::Rows,
5702 };
5703 for constraints in &constraint_sets {
5704 let memory_ref = memory_hits(&memory, constraints, 0, None, &args);
5705 for mode in MODES {
5706 let got = scan_hits(&store, mode, constraints, 0, None, &args).unwrap();
5707 let mut got_keys = hit_keys(&got);
5710 let mut want_keys = hit_keys(&memory_ref);
5711 got_keys.sort();
5712 want_keys.sort();
5713 assert_eq!(
5714 got_keys, want_keys,
5715 "mode {mode:?} case {case_name} iri {iri_only} constraints {constraints:?}"
5716 );
5717 if mode == DomainScanMode::Legacy {
5718 assert_eq!(got, memory_ref, "legacy case {case_name}");
5721 } else {
5722 assert_strictly_key_ordered(&got);
5723 }
5724 }
5725 }
5726 }
5727 }
5728 drop(store);
5729 let _ = std::fs::remove_dir_all(&dir);
5730 }
5731
5732 #[test]
5737 fn domain_scan_emission_order_is_key_order() {
5738 let (store, dir) = open_p_store("order");
5739 let memory = Storage::memory(PartitionAxis::P);
5740 load_fixture(&store, &memory);
5741
5742 let first = constraint("p1");
5743 let second = constraint("p2");
5744 let (first, second) = if encode_term_bytes(&first) < encode_term_bytes(&second) {
5745 (first, second)
5746 } else {
5747 (second, first)
5748 };
5749 let shuffled = [second.clone(), first.clone()]; let first_hits = scan_hits(
5754 &store,
5755 DomainScanMode::Legacy,
5756 std::slice::from_ref(&first),
5757 0,
5758 None,
5759 &Default::default(),
5760 )
5761 .unwrap();
5762 let second_hits = scan_hits(
5763 &store,
5764 DomainScanMode::Legacy,
5765 std::slice::from_ref(&second),
5766 0,
5767 None,
5768 &Default::default(),
5769 )
5770 .unwrap();
5771 let want = [first_hits, second_hits].concat();
5772
5773 for mode in [DomainScanMode::Legacy, DomainScanMode::ParallelWalks(2)] {
5774 let got = scan_hits(&store, mode, &shuffled, 0, None, &Default::default()).unwrap();
5775 assert_strictly_key_ordered(&got);
5776 assert_eq!(got, want, "mode {mode:?} must emit in key order");
5777 }
5778 assert_eq!(
5781 want,
5782 memory_hits(&memory, &shuffled, 0, None, &Default::default())
5783 );
5784 drop(store);
5785 let _ = std::fs::remove_dir_all(&dir);
5786 }
5787
5788 fn paginate_hits(
5789 store: &RocksDbStorage,
5790 mode: DomainScanMode,
5791 constraints: &[EncodedTerm],
5792 batch: u64,
5793 args: &DomainArgs<'_>,
5794 ) -> Vec<DomainScanHit> {
5795 let mut out = Vec::new();
5796 let mut after: Option<(EncodedTerm, EncodedTerm)> = None;
5797 for _ in 0..10_000 {
5798 let page = scan_hits(store, mode, constraints, batch, after.as_ref(), args).unwrap();
5799 let done = page.len() < batch as usize;
5800 if let Some(last) = page.last() {
5801 after = Some((last.constraint.clone(), last.term.clone()));
5802 }
5803 let empty = page.is_empty();
5804 out.extend(page);
5805 if done || empty {
5806 return out;
5807 }
5808 }
5809 panic!("pagination did not terminate");
5810 }
5811
5812 #[test]
5817 fn domain_scan_pagination_chains_cover_all_hits() {
5818 let (store, dir) = open_p_store("pages");
5819 let memory = Storage::memory(PartitionAxis::P);
5820 load_fixture(&store, &memory);
5821
5822 let p1 = constraint("p1");
5823 let p2 = constraint("p2");
5824 let p3 = constraint("p3");
5825 let p4 = constraint("p4");
5826 let mut sorted_all = vec![p1.clone(), p2.clone(), p3.clone(), p4.clone()];
5827 sorted_all.sort_by_key(encode_term_bytes);
5828 let shuffled_dup = vec![p2.clone(), p1.clone(), p2.clone(), p3.clone()];
5829
5830 for &batch in &[1u64, 2, 3, 100] {
5831 for mode in MODES {
5832 for constraints in [&sorted_all, &shuffled_dup] {
5833 let chain =
5834 paginate_hits(&store, mode, constraints, batch, &Default::default());
5835 let full =
5836 scan_hits(&store, mode, constraints, 0, None, &Default::default()).unwrap();
5837 assert_eq!(
5838 chain, full,
5839 "mode {mode:?} batch {batch} constraints {constraints:?}"
5840 );
5841 }
5842 }
5843 let chain = paginate_hits(
5845 &store,
5846 DomainScanMode::ParallelWalks(2),
5847 &sorted_all,
5848 batch,
5849 &Default::default(),
5850 );
5851 let reference = memory_hits(&memory, &sorted_all, 0, None, &Default::default());
5852 let mut chain_keys = hit_keys(&chain);
5853 let mut reference_keys = hit_keys(&reference);
5854 chain_keys.sort();
5855 reference_keys.sort();
5856 assert_eq!(chain_keys, reference_keys);
5857 }
5858 drop(store);
5859 let _ = std::fs::remove_dir_all(&dir);
5860 }
5861
5862 #[test]
5868 fn legacy_shuffled_pagination_chain_covers_every_constraint() {
5869 let (store, dir) = open_p_store("legacy-cursor");
5870 let memory = Storage::memory(PartitionAxis::P);
5871 load_fixture(&store, &memory);
5872
5873 let first = constraint("p1");
5874 let second = constraint("p2");
5875 let (first, second) = if encode_term_bytes(&first) < encode_term_bytes(&second) {
5876 (first, second)
5877 } else {
5878 (second, first)
5879 };
5880 let shuffled = [second.clone(), first.clone()];
5881
5882 let legacy_chain = paginate_hits(
5883 &store,
5884 DomainScanMode::Legacy,
5885 &shuffled,
5886 1,
5887 &Default::default(),
5888 );
5889 let legacy_full = scan_hits(
5890 &store,
5891 DomainScanMode::Legacy,
5892 &shuffled,
5893 0,
5894 None,
5895 &Default::default(),
5896 )
5897 .unwrap();
5898 assert_eq!(
5899 legacy_chain, legacy_full,
5900 "the legacy chain must cover both constraints under a shuffled caller order"
5901 );
5902 assert_eq!(
5903 legacy_chain,
5904 memory_hits(&memory, &shuffled, 0, None, &Default::default()),
5905 "the memory reference must agree on the same shuffled input"
5906 );
5907 drop(store);
5908 let _ = std::fs::remove_dir_all(&dir);
5909 }
5910
5911 #[test]
5915 fn domain_scan_limit_truncation_follows_mode_order() {
5916 let (store, dir) = open_p_store("limits");
5917 let p1 = constraint("p1");
5918 let p2 = constraint("p2");
5919 let p3 = constraint("p3");
5920 let shuffled = vec![p2, p3, p1]; let memory = Storage::memory(PartitionAxis::P);
5922 load_fixture(&store, &memory);
5923
5924 let legacy_full = scan_hits(
5925 &store,
5926 DomainScanMode::Legacy,
5927 &shuffled,
5928 0,
5929 None,
5930 &Default::default(),
5931 )
5932 .unwrap();
5933 assert!(
5934 legacy_full.len() > 3,
5935 "fixture too small for a truncation test"
5936 );
5937
5938 let limits = [1u64, 2, 3, 5, 7]
5939 .into_iter()
5940 .filter(|limit| *limit <= legacy_full.len() as u64);
5941 for limit in limits {
5942 let legacy = scan_hits(
5943 &store,
5944 DomainScanMode::Legacy,
5945 &shuffled,
5946 limit,
5947 None,
5948 &Default::default(),
5949 )
5950 .unwrap();
5951 assert_eq!(
5952 legacy,
5953 legacy_full[..limit as usize],
5954 "legacy limit {limit}"
5955 );
5956
5957 for workers in [2usize, 3usize, 64] {
5958 let parallel = scan_hits(
5959 &store,
5960 DomainScanMode::ParallelWalks(workers),
5961 &shuffled,
5962 limit,
5963 None,
5964 &Default::default(),
5965 )
5966 .unwrap();
5967 assert_eq!(
5968 parallel,
5969 legacy_full[..limit as usize],
5970 "parallel {workers} limit {limit}"
5971 );
5972 }
5973 }
5974 drop(store);
5975 let _ = std::fs::remove_dir_all(&dir);
5976 }
5977
5978 #[test]
5982 fn domain_scan_counts_modes_match_memory_reference() {
5983 let (store, dir) = open_p_store("counts");
5984 let memory = Storage::memory(PartitionAxis::P);
5985 load_fixture(&store, &memory);
5986
5987 let p1 = constraint("p1");
5988 let p2 = constraint("p2");
5989 let p3 = constraint("p3");
5990 let p4 = constraint("p4");
5991 let mut sorted_all = vec![p1.clone(), p2.clone(), p3.clone(), p4.clone()];
5992 sorted_all.sort_by_key(encode_term_bytes);
5993 let constraint_sets: Vec<Vec<EncodedTerm>> = vec![
5994 sorted_all,
5995 vec![p1.clone()],
5996 vec![],
5997 vec![p2.clone(), p1.clone(), p2.clone(), p3.clone()],
5998 vec![p3.clone(), p1.clone()],
5999 ];
6000
6001 let g1 = graph_term("g1");
6002 let g2 = graph_term("g2");
6003 let count_combos: Vec<(bool, DomainCountMode)> = vec![
6006 (false, DomainCountMode::Rows),
6007 (true, DomainCountMode::Rows),
6008 (false, DomainCountMode::DistinctTerms),
6009 (false, DomainCountMode::DistinctGraphs),
6010 ];
6011 for &(merge, count_mode) in &count_combos {
6012 let graph_cases: Vec<(&str, Option<EncodedTerm>, Vec<EncodedTerm>, bool)> = vec![
6013 ("unconstrained", None, Vec::new(), false),
6014 ("bound-g1", Some(g1.clone()), Vec::new(), false),
6015 (
6017 "bound-default",
6018 Some(EncodedTerm::DefaultGraph),
6019 Vec::new(),
6020 false,
6021 ),
6022 ("allow-g1g2", None, vec![g1.clone(), g2.clone()], true),
6023 ];
6024 for (case_name, graph_name, filter_terms, filter_allow) in &graph_cases {
6025 for constraints in &constraint_sets {
6026 let args = DomainArgs {
6027 graph_name: graph_name.as_ref(),
6028 filter_terms,
6029 filter_allow: *filter_allow,
6030 iri_only: false,
6031 merge,
6032 count_mode,
6033 };
6034 let memory_ref = memory_counts(&memory, constraints, 0, None, &args);
6035 for mode in MODES {
6036 let got = scan_counts(&store, mode, constraints, 0, None, &args).unwrap();
6037 let mut got_keys = count_keys(&got);
6038 let mut want_keys = count_keys(&memory_ref);
6039 got_keys.sort();
6040 want_keys.sort();
6041 assert_eq!(
6042 got_keys, want_keys,
6043 "counts mode {mode:?} merge {merge} count_mode {count_mode:?} case {case_name} constraints {constraints:?}"
6044 );
6045 if mode == DomainScanMode::Legacy {
6046 assert_eq!(got, memory_ref, "counts legacy case {case_name}");
6047 } else {
6048 assert_counts_strictly_key_ordered(&got);
6049 }
6050 }
6051 }
6052 }
6053 }
6054 drop(store);
6055 let _ = std::fs::remove_dir_all(&dir);
6056 }
6057
6058 #[test]
6062 fn domain_scan_counts_pagination_chains_cover_all_runs() {
6063 let (store, dir) = open_p_store("count-pages");
6064 let memory = Storage::memory(PartitionAxis::P);
6065 load_fixture(&store, &memory);
6066
6067 let p1 = constraint("p1");
6068 let p2 = constraint("p2");
6069 let p3 = constraint("p3");
6070 let p4 = constraint("p4");
6071 let mut sorted_all = vec![p1.clone(), p2.clone(), p3.clone(), p4.clone()];
6072 sorted_all.sort_by_key(encode_term_bytes);
6073 let shuffled_dup = vec![p2.clone(), p1.clone(), p2.clone(), p3.clone()];
6074
6075 fn paginate(
6076 store: &RocksDbStorage,
6077 mode: DomainScanMode,
6078 constraints: &[EncodedTerm],
6079 batch: u64,
6080 args: &DomainArgs<'_>,
6081 ) -> Vec<DomainScanCountHit> {
6082 let mut out = Vec::new();
6083 let mut after: Option<(EncodedTerm, EncodedTerm)> = None;
6084 for _ in 0..10_000 {
6085 let page =
6086 scan_counts(store, mode, constraints, batch, after.as_ref(), args).unwrap();
6087 let done = page.len() < batch as usize;
6088 if let Some(last) = page.last() {
6089 after = Some((last.constraint.clone(), last.term.clone()));
6090 }
6091 let empty = page.is_empty();
6092 out.extend(page);
6093 if done || empty {
6094 return out;
6095 }
6096 }
6097 panic!("count pagination did not terminate");
6098 }
6099
6100 let count_combos: Vec<(bool, DomainCountMode)> = vec![
6103 (false, DomainCountMode::Rows),
6104 (true, DomainCountMode::Rows),
6105 (false, DomainCountMode::DistinctTerms),
6106 (false, DomainCountMode::DistinctGraphs),
6107 ];
6108 for &(merge, count_mode) in &count_combos {
6109 let args = DomainArgs {
6110 merge,
6111 count_mode,
6112 ..Default::default()
6113 };
6114 for &batch in &[1u64, 2, 3, 100] {
6115 for mode in MODES {
6116 for constraints in [&sorted_all, &shuffled_dup] {
6117 let chain = paginate(&store, mode, constraints, batch, &args);
6118 let full = scan_counts(&store, mode, constraints, 0, None, &args).unwrap();
6119 if mode == DomainScanMode::Legacy && *constraints != sorted_all {
6120 continue; }
6122 assert_eq!(
6123 chain, full,
6124 "counts mode {mode:?} merge {merge} count_mode {count_mode:?} batch {batch}"
6125 );
6126 }
6127 }
6128 let chain = paginate(
6129 &store,
6130 DomainScanMode::ParallelWalks(2),
6131 &sorted_all,
6132 batch,
6133 &args,
6134 );
6135 let reference = memory_counts(&memory, &sorted_all, 0, None, &args);
6136 let mut chain_keys = count_keys(&chain);
6137 let mut reference_keys = count_keys(&reference);
6138 chain_keys.sort();
6139 reference_keys.sort();
6140 assert_eq!(
6141 chain_keys, reference_keys,
6142 "merge {merge} count_mode {count_mode:?} batch {batch}"
6143 );
6144 }
6145 }
6146 drop(store);
6147 let _ = std::fs::remove_dir_all(&dir);
6148 }
6149
6150 #[test]
6154 fn domain_scan_counts_limit_truncation_follows_mode_order() {
6155 let (store, dir) = open_p_store("count-limits");
6156 let p1 = constraint("p1");
6157 let p2 = constraint("p2");
6158 let p3 = constraint("p3");
6159 let shuffled = vec![p2, p3, p1];
6160 let memory = Storage::memory(PartitionAxis::P);
6161 load_fixture(&store, &memory);
6162
6163 let legacy_full = scan_counts(
6164 &store,
6165 DomainScanMode::Legacy,
6166 &shuffled,
6167 0,
6168 None,
6169 &Default::default(),
6170 )
6171 .unwrap();
6172 assert!(
6173 legacy_full.len() > 2,
6174 "fixture too small for a truncation test"
6175 );
6176
6177 let limits = [1u64, 2, 3, 5, 7]
6178 .into_iter()
6179 .filter(|limit| *limit <= legacy_full.len() as u64);
6180 for limit in limits {
6181 let legacy = scan_counts(
6182 &store,
6183 DomainScanMode::Legacy,
6184 &shuffled,
6185 limit,
6186 None,
6187 &Default::default(),
6188 )
6189 .unwrap();
6190 assert_eq!(
6191 legacy,
6192 legacy_full[..limit as usize],
6193 "legacy limit {limit}"
6194 );
6195
6196 for workers in [2usize, 3usize, 64] {
6197 let parallel = scan_counts(
6198 &store,
6199 DomainScanMode::ParallelWalks(workers),
6200 &shuffled,
6201 limit,
6202 None,
6203 &Default::default(),
6204 )
6205 .unwrap();
6206 assert_eq!(
6207 parallel,
6208 legacy_full[..limit as usize],
6209 "parallel {workers} limit {limit}"
6210 );
6211 }
6212 }
6213 drop(store);
6214 let _ = std::fs::remove_dir_all(&dir);
6215 }
6216
6217 #[test]
6230 fn domain_scan_parallel_edge_cases_match_legacy() {
6231 crate::worker_pool::init_worker_pool(None, 3);
6232 let (store, dir) = open_p_store("parallel-edges");
6233 let p1 = constraint("p1");
6234 let p2 = constraint("p2");
6235 let mut both = vec![p1.clone(), p2.clone()];
6236 both.sort_by_key(encode_term_bytes);
6237
6238 let legacy = scan_hits(
6239 &store,
6240 DomainScanMode::Legacy,
6241 &both,
6242 0,
6243 None,
6244 &Default::default(),
6245 )
6246 .unwrap();
6247
6248 let one_worker = scan_hits(
6250 &store,
6251 DomainScanMode::ParallelWalks(1),
6252 &both,
6253 0,
6254 None,
6255 &Default::default(),
6256 )
6257 .unwrap();
6258 assert_eq!(one_worker, legacy);
6259
6260 let many_workers = scan_hits(
6262 &store,
6263 DomainScanMode::ParallelWalks(64),
6264 &both,
6265 0,
6266 None,
6267 &Default::default(),
6268 )
6269 .unwrap();
6270 assert_eq!(many_workers, legacy);
6271
6272 let single_legacy = scan_hits(
6274 &store,
6275 DomainScanMode::Legacy,
6276 std::slice::from_ref(&p1),
6277 0,
6278 None,
6279 &Default::default(),
6280 )
6281 .unwrap();
6282 let single_parallel = scan_hits(
6283 &store,
6284 DomainScanMode::ParallelWalks(4),
6285 std::slice::from_ref(&p1),
6286 0,
6287 None,
6288 &Default::default(),
6289 )
6290 .unwrap();
6291 assert_eq!(single_parallel, single_legacy);
6292 drop(store);
6293 let _ = std::fs::remove_dir_all(&dir);
6294 }
6295
6296 #[test]
6316 fn confined_domain_scans_stay_correct_with_sst_filters_armed() {
6317 crate::worker_pool::init_worker_pool(None, 3);
6318 crate::rocksdb_db::TEST_SST_FILTER_FORCE_ON
6319 .store(true, std::sync::atomic::Ordering::Relaxed);
6320 let dir = std::env::temp_dir().join(format!(
6321 "waratah-domain-filtered-{}-{}",
6322 std::process::id(),
6323 std::time::SystemTime::now()
6324 .duration_since(std::time::UNIX_EPOCH)
6325 .unwrap()
6326 .as_nanos()
6327 ));
6328 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
6329 let memory = Storage::memory(PartitionAxis::S);
6330
6331 let quad = |subject: crate::NamedOrBlankNode, predicate: &str, object: &str| {
6332 Quad::new(
6333 subject,
6334 NamedNode::new(format!("http://ex/{predicate}")).unwrap(),
6335 NamedNode::new(format!("http://ex/{object}")).unwrap(),
6336 GraphName::DefaultGraph,
6337 )
6338 };
6339 let named = |local: &str| {
6340 crate::NamedOrBlankNode::from(NamedNode::new(format!("http://ex/{local}")).unwrap())
6341 };
6342 let blank = crate::BlankNode::new("b").unwrap();
6343 let mut ts = 1u64;
6344 let mut put = |quad: Quad| {
6345 store
6346 .insert_quad_version(
6347 &quad,
6348 CommitTs(ts),
6349 StorageOp::Put,
6350 VisibilityLabel::default(),
6351 )
6352 .unwrap();
6353 memory
6354 .insert_quad_version(
6355 &quad,
6356 CommitTs(ts),
6357 StorageOp::Put,
6358 VisibilityLabel::default(),
6359 )
6360 .unwrap();
6361 ts += 1;
6362 };
6363
6364 put(quad(named("s1"), "p1", "o1"));
6368 put(quad(named("s2"), "p1", "o2"));
6369 store.flush_memtables().unwrap();
6370 put(quad(named("s1"), "p2", "o3"));
6371 put(quad(
6372 crate::NamedOrBlankNode::from(blank.clone()),
6373 "p1",
6374 "o4",
6375 ));
6376 put(quad(named("s2"), "p2", "o1"));
6377 store.flush_memtables().unwrap();
6378
6379 let constraints = vec![
6381 EncodedTerm::from(&blank),
6382 constraint("s2"),
6383 constraint("s1"),
6384 constraint("absent"),
6385 ];
6386
6387 let sorted_hits = |mut hits: Vec<DomainScanHit>| {
6391 hits.sort_by_key(|hit| {
6392 (
6393 encode_term_bytes(&hit.constraint),
6394 encode_term_bytes(&hit.term),
6395 )
6396 });
6397 hits
6398 };
6399
6400 let reference = sorted_hits(
6401 memory
6402 .scan_domain(
6403 IndexPermutation::Sopg,
6404 &constraints,
6405 SNAP,
6406 0,
6407 None,
6408 None,
6409 None,
6410 &[],
6411 false,
6412 false,
6413 )
6414 .unwrap(),
6415 );
6416
6417 for mode in MODES {
6418 let full = store
6419 .scan_domain_with_mode(
6420 mode,
6421 IndexPermutation::Sopg,
6422 &constraints,
6423 SNAP,
6424 0,
6425 None,
6426 None,
6427 None,
6428 &[],
6429 false,
6430 false,
6431 )
6432 .unwrap();
6433 assert_eq!(full, reference, "sopg full {mode:?}");
6434
6435 for limit in [1u64, 2, 3] {
6436 let limited = store
6437 .scan_domain_with_mode(
6438 mode,
6439 IndexPermutation::Sopg,
6440 &constraints,
6441 SNAP,
6442 limit,
6443 None,
6444 None,
6445 None,
6446 &[],
6447 false,
6448 false,
6449 )
6450 .unwrap();
6451 assert_eq!(
6452 limited,
6453 reference[..limit as usize],
6454 "sopg limit {limit} {mode:?}"
6455 );
6456 }
6457
6458 let mut chain = Vec::new();
6462 let mut after: Option<(EncodedTerm, EncodedTerm)> = None;
6463 for _ in 0..100 {
6464 let page = store
6465 .scan_domain_with_mode(
6466 mode,
6467 IndexPermutation::Sopg,
6468 &constraints,
6469 SNAP,
6470 2,
6471 after.as_ref().map(|c| &c.0),
6472 after.as_ref().map(|c| &c.1),
6473 None,
6474 &[],
6475 false,
6476 false,
6477 )
6478 .unwrap();
6479 if page.is_empty() {
6480 break;
6481 }
6482 let done = page.len() < 2;
6483 if let Some(last) = page.last() {
6484 after = Some((last.constraint.clone(), last.term.clone()));
6485 }
6486 chain.extend(page);
6487 if done {
6488 break;
6489 }
6490 }
6491 assert_eq!(chain, reference, "sopg paged chain {mode:?}");
6492
6493 let spog = store
6496 .scan_domain_with_mode(
6497 mode,
6498 IndexPermutation::Spog,
6499 &constraints,
6500 SNAP,
6501 0,
6502 None,
6503 None,
6504 None,
6505 &[],
6506 false,
6507 false,
6508 )
6509 .unwrap();
6510 let spog_reference = sorted_hits(
6511 memory
6512 .scan_domain(
6513 IndexPermutation::Spog,
6514 &constraints,
6515 SNAP,
6516 0,
6517 None,
6518 None,
6519 None,
6520 &[],
6521 false,
6522 false,
6523 )
6524 .unwrap(),
6525 );
6526 assert_eq!(spog, spog_reference, "spog {mode:?}");
6527
6528 let counts = store
6530 .scan_domain_counts_with_mode(
6531 mode,
6532 IndexPermutation::Sopg,
6533 &constraints,
6534 SNAP,
6535 0,
6536 None,
6537 None,
6538 None,
6539 &[],
6540 false,
6541 false,
6542 false,
6543 DomainCountMode::Rows,
6544 )
6545 .unwrap();
6546 let mut counts_reference = memory
6547 .scan_domain_counts(
6548 IndexPermutation::Sopg,
6549 &constraints,
6550 SNAP,
6551 0,
6552 None,
6553 None,
6554 None,
6555 &[],
6556 false,
6557 false,
6558 false,
6559 DomainCountMode::Rows,
6560 )
6561 .unwrap();
6562 counts_reference.sort_by_key(|hit| {
6563 (
6564 encode_term_bytes(&hit.constraint),
6565 encode_term_bytes(&hit.term),
6566 )
6567 });
6568 assert_eq!(counts, counts_reference, "sopg counts {mode:?}");
6569 }
6570 drop(store);
6571 let _ = std::fs::remove_dir_all(&dir);
6572 }
6573
6574 #[test]
6590 fn axis_head_scans_stay_complete_with_sst_filters_armed() {
6591 crate::rocksdb_db::TEST_SST_FILTER_FORCE_ON
6592 .store(true, std::sync::atomic::Ordering::Relaxed);
6593 let dir = std::env::temp_dir().join(format!(
6594 "waratah-head-filtered-{}-{}",
6595 std::process::id(),
6596 std::time::SystemTime::now()
6597 .duration_since(std::time::UNIX_EPOCH)
6598 .unwrap()
6599 .as_nanos()
6600 ));
6601 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
6602 let memory = Storage::memory(PartitionAxis::O);
6603
6604 let type_node = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
6605 let quad = |subject: &str, class: &str| {
6606 Quad::new(
6607 NamedNode::new(format!("http://ex/{subject}")).unwrap(),
6608 type_node.clone(),
6609 NamedNode::new(format!("http://ex/{class}")).unwrap(),
6610 GraphName::DefaultGraph,
6611 )
6612 };
6613 let mut ts = 1u64;
6614 let mut put = |quad: Quad| {
6615 store
6616 .insert_quad_version(
6617 &quad,
6618 CommitTs(ts),
6619 StorageOp::Put,
6620 VisibilityLabel::default(),
6621 )
6622 .unwrap();
6623 memory
6624 .insert_quad_version(
6625 &quad,
6626 CommitTs(ts),
6627 StorageOp::Put,
6628 VisibilityLabel::default(),
6629 )
6630 .unwrap();
6631 ts += 1;
6632 };
6633 put(quad("s1", "C1"));
6637 put(quad("s2", "C1"));
6638 put(quad("s3", "C2"));
6639 store.flush_memtables().unwrap();
6640 put(quad("s4", "C2"));
6641 put(quad("s5", "C3"));
6642 store.flush_memtables().unwrap();
6643 put(quad("s6", "C4"));
6644 store.flush_memtables().unwrap();
6645
6646 let classes = |terms: Vec<EncodedTerm>| -> Vec<String> {
6647 terms
6648 .iter()
6649 .map(|t| match t {
6650 EncodedTerm::NamedNode { iri_id } => format!("{iri_id:?}"),
6651 other => panic!("unexpected head term {other:?}"),
6652 })
6653 .collect()
6654 };
6655 let want = memory
6656 .scan_axis_head(
6657 IndexPermutation::Tsg,
6658 SNAP,
6659 0,
6660 None,
6661 None,
6662 &[],
6663 false,
6664 false,
6665 &[],
6666 )
6667 .unwrap();
6668 assert_eq!(want.len(), 4, "fixture must hold four classes");
6669
6670 let full = store
6672 .scan_axis_head(
6673 IndexPermutation::Tsg,
6674 SNAP,
6675 0,
6676 None,
6677 None,
6678 &[],
6679 false,
6680 false,
6681 &[],
6682 )
6683 .unwrap();
6684 assert_eq!(
6685 classes(full),
6686 classes(want.clone()),
6687 "armed unconstrained walk"
6688 );
6689
6690 let mut chain = Vec::new();
6693 let mut after: Option<EncodedTerm> = None;
6694 for _ in 0..100 {
6695 let page = store
6696 .scan_axis_head(
6697 IndexPermutation::Tsg,
6698 SNAP,
6699 2,
6700 after.as_ref(),
6701 None,
6702 &[],
6703 false,
6704 false,
6705 &[],
6706 )
6707 .unwrap();
6708 if page.is_empty() {
6709 break;
6710 }
6711 let done = page.len() < 2;
6712 after = Some(page.last().unwrap().clone());
6713 chain.extend(page);
6714 if done {
6715 break;
6716 }
6717 }
6718 assert_eq!(classes(chain), classes(want.clone()), "armed resume chain");
6719
6720 let both = vec![
6726 encode_term_bytes(&want[1])[..10].to_vec(),
6727 encode_term_bytes(&want[3])[..10].to_vec(),
6728 ];
6729 let listed = store
6730 .scan_axis_head(
6731 IndexPermutation::Tsg,
6732 SNAP,
6733 0,
6734 None,
6735 None,
6736 &[],
6737 false,
6738 false,
6739 &both,
6740 )
6741 .unwrap();
6742 assert_eq!(classes(listed.clone()).len(), 2, "armed allow-list walk");
6743 let listed_want = memory
6744 .scan_axis_head(
6745 IndexPermutation::Tsg,
6746 SNAP,
6747 0,
6748 None,
6749 None,
6750 &[],
6751 false,
6752 false,
6753 &both,
6754 )
6755 .unwrap();
6756 assert_eq!(
6757 classes(listed),
6758 classes(listed_want),
6759 "armed allow-list reference"
6760 );
6761
6762 let total = store
6764 .count_axis_heads(IndexPermutation::Tsg, SNAP, None, &[], false, false)
6765 .unwrap();
6766 let total_want = memory
6767 .count_axis_heads(IndexPermutation::Tsg, SNAP, None, &[], false, false)
6768 .unwrap();
6769 assert_eq!(total, total_want, "armed count_axis_heads");
6770
6771 let counts = store
6773 .scan_axis_head_counts(
6774 IndexPermutation::Tsg,
6775 SNAP,
6776 0,
6777 None,
6778 None,
6779 &[],
6780 false,
6781 false,
6782 )
6783 .unwrap();
6784 let counts_want = memory
6785 .scan_axis_head_counts(
6786 IndexPermutation::Tsg,
6787 SNAP,
6788 0,
6789 None,
6790 None,
6791 &[],
6792 false,
6793 false,
6794 )
6795 .unwrap();
6796 assert_eq!(
6797 counts.len(),
6798 counts_want.len(),
6799 "armed scan_axis_head_counts"
6800 );
6801
6802 let all_prefixes: Vec<_> = want
6809 .iter()
6810 .map(|t| encode_term_bytes(t)[..10].to_vec())
6811 .collect();
6812 let max_rocks = store
6813 .max_commit_ts_under_prefixes(IndexPermutation::Tsg, &all_prefixes)
6814 .unwrap();
6815 let max_memory = memory
6816 .max_commit_ts_under_prefixes(IndexPermutation::Tsg, &all_prefixes)
6817 .unwrap();
6818 assert_eq!(max_rocks, max_memory, "armed max_commit_ts (prefixes)");
6819 assert_eq!(max_rocks, 6, "fixture ground truth: last put ts");
6820 let max_all = store
6821 .max_commit_ts_under_prefixes(IndexPermutation::Tsg, &[])
6822 .unwrap();
6823 assert_eq!(max_all, 6, "armed max_commit_ts (whole CF)");
6824
6825 drop(store);
6826 drop(memory);
6827 let _ = std::fs::remove_dir_all(&dir);
6828 }
6829
6830 #[test]
6833 fn domain_scan_modes_propagate_corrupt_rows() {
6834 for tag_mode in [
6835 DomainScanMode::Legacy,
6836 DomainScanMode::ParallelWalks(2),
6837 DomainScanMode::ParallelWalks(4),
6838 ] {
6839 let tag = match tag_mode {
6840 DomainScanMode::Legacy => "corrupt-legacy",
6841 DomainScanMode::ParallelWalks(2) => "corrupt-par2",
6842 DomainScanMode::ParallelWalks(_) => "corrupt-par4",
6843 };
6844 let (store, dir) = open_p_store(tag);
6845 let s5 = fixture_quad("s5", "p2", "o1", "default");
6848 store
6849 .insert_quad_version(&s5, CommitTs(8), StorageOp::Put, VisibilityLabel::default())
6850 .unwrap();
6851 let victim = fixture_quad("s1", "p1", "o1", "default");
6852 store
6853 .insert_quad_version(
6854 &victim,
6855 CommitTs(1),
6856 StorageOp::Put,
6857 VisibilityLabel::default(),
6858 )
6859 .unwrap();
6860 let encoded = encode_quad(&victim).unwrap();
6862 let key = encode_versioned_key(IndexPermutation::Posg, &encoded, CommitTs(1));
6863 let cf = store.cf_for(IndexPermutation::Posg).unwrap();
6864 store.db.insert(cf, &key, &[0x01]).unwrap();
6865
6866 let p1 = constraint("p1");
6867 let p2 = constraint("p2");
6868 let mut constraints = vec![p2.clone(), p1.clone()];
6869 constraints.sort_by_key(encode_term_bytes);
6870 let result = scan_hits(&store, tag_mode, &constraints, 0, None, &Default::default());
6871 assert!(
6872 matches!(&result, Err(crate::StorageError::Corrupt(_))),
6873 "mode {tag_mode:?} must propagate the corrupt row: {result:?}"
6874 );
6875 let counts = scan_counts(&store, tag_mode, &constraints, 0, None, &Default::default());
6876 assert!(
6877 matches!(&counts, Err(crate::StorageError::Corrupt(_))),
6878 "counts mode {tag_mode:?} must propagate the corrupt row: {counts:?}"
6879 );
6880 drop(store);
6881 let _ = std::fs::remove_dir_all(&dir);
6882 }
6883 }
6884
6885 #[test]
6894 fn head_walks_report_truncated_head_keys_as_corrupt() {
6895 let (store, dir) = open_p_store("corrupt-key");
6896 let victim = fixture_quad("s1", "p1", "o1", "default");
6900 store
6901 .insert_quad_version(
6902 &victim,
6903 CommitTs(1),
6904 StorageOp::Put,
6905 VisibilityLabel::default(),
6906 )
6907 .unwrap();
6908 let encoded = encode_quad(&victim).unwrap();
6909 let valid = encode_versioned_key(IndexPermutation::Posg, &encoded, CommitTs(1));
6910 let cf = store.cf_for(IndexPermutation::Posg).unwrap();
6911 let value = encode_storage_value(StorageOp::Put, VisibilityLabel::default());
6912 let c_len = encode_term_bytes(&constraint("p1")).len();
6913 let head_len = 17usize;
6914 let splice = |keep: usize| {
6915 let mut key = Vec::new();
6916 key.extend_from_slice(&valid[..keep]);
6917 key.extend_from_slice(&valid[valid.len() - COMMIT_TS_LEN..]);
6918 key
6919 };
6920
6921 store.db.insert(cf, &splice(c_len + 3), &value).unwrap();
6924 store
6928 .db
6929 .insert(cf, &splice(c_len + head_len - 4), &value)
6930 .unwrap();
6931 store
6935 .db
6936 .insert(cf, &splice(c_len + head_len + 13), &value)
6937 .unwrap();
6938 store.db.insert(cf, &splice(3), &value).unwrap();
6941
6942 let p1 = constraint("p1");
6943 let result = scan_hits(
6944 &store,
6945 DomainScanMode::Legacy,
6946 std::slice::from_ref(&p1),
6947 0,
6948 None,
6949 &Default::default(),
6950 );
6951 assert!(
6952 matches!(&result, Err(crate::StorageError::Corrupt(_))),
6953 "domain hits walk must report a truncated head key: {result:?}"
6954 );
6955 for count_mode in [
6956 DomainCountMode::Rows,
6957 DomainCountMode::DistinctTerms,
6958 DomainCountMode::DistinctGraphs,
6959 ] {
6960 let counts = scan_counts(
6961 &store,
6962 DomainScanMode::Legacy,
6963 std::slice::from_ref(&p1),
6964 0,
6965 None,
6966 &DomainArgs {
6967 count_mode,
6968 ..Default::default()
6969 },
6970 );
6971 assert!(
6972 matches!(&counts, Err(crate::StorageError::Corrupt(_))),
6973 "counts walk {count_mode:?} must report a truncated head key: {counts:?}"
6974 );
6975 }
6976
6977 let axis_err = store.scan_axis_head(
6996 IndexPermutation::Posg,
6997 SNAP,
6998 0,
6999 None,
7000 None,
7001 &[],
7002 false,
7003 false,
7004 &[],
7005 );
7006 assert!(
7007 matches!(&axis_err, Err(crate::StorageError::Corrupt(_))),
7008 "axis head scan must report a truncated head key: {axis_err:?}"
7009 );
7010 let axis_total =
7011 store.count_axis_heads(IndexPermutation::Posg, SNAP, None, &[], false, false);
7012 assert!(
7013 matches!(&axis_total, Err(crate::StorageError::Corrupt(_))),
7014 "axis head total must report a truncated head key: {axis_total:?}"
7015 );
7016 let axis_counts = store.scan_axis_head_counts(
7017 IndexPermutation::Posg,
7018 SNAP,
7019 0,
7020 None,
7021 None,
7022 &[],
7023 false,
7024 false,
7025 );
7026 assert!(
7027 matches!(&axis_counts, Err(crate::StorageError::Corrupt(_))),
7028 "axis PER_HEAD counts must report a truncated head key: {axis_counts:?}"
7029 );
7030
7031 let mid_hop = splice(c_len + head_len);
7040 store.db.insert(cf, &mid_hop, &value).unwrap();
7041 for (tag, graph_name) in [
7042 ("default-only", Some(EncodedTerm::DefaultGraph)),
7043 ("general", Some(constraint("g1"))),
7044 ] {
7045 let args = DomainArgs {
7046 graph_name: graph_name.as_ref(),
7047 ..Default::default()
7048 };
7049 let hits = scan_hits(
7050 &store,
7051 DomainScanMode::Legacy,
7052 std::slice::from_ref(&p1),
7053 0,
7054 None,
7055 &args,
7056 );
7057 assert!(
7058 matches!(&hits, Err(crate::StorageError::Corrupt(_))),
7059 "hits walk under {tag} window must report the mid-hop key: {hits:?}"
7060 );
7061 let counts = scan_counts(
7062 &store,
7063 DomainScanMode::Legacy,
7064 std::slice::from_ref(&p1),
7065 0,
7066 None,
7067 &args,
7068 );
7069 assert!(
7070 matches!(&counts, Err(crate::StorageError::Corrupt(_))),
7071 "counts walk under {tag} window must report the mid-hop key: {counts:?}"
7072 );
7073 }
7074
7075 drop(store);
7076 let _ = std::fs::remove_dir_all(&dir);
7077 }
7078
7079 #[test]
7091 fn axis_walks_report_payload_corrupt_heads_as_corrupt() {
7092 let (store, dir) = open_p_store("corrupt-payload");
7093 let victim = fixture_quad("s1", "p1", "o1", "default");
7094 store
7095 .insert_quad_version(
7096 &victim,
7097 CommitTs(1),
7098 StorageOp::Put,
7099 VisibilityLabel::default(),
7100 )
7101 .unwrap();
7102 let encoded = encode_quad(&victim).unwrap();
7103 let valid = encode_versioned_key(IndexPermutation::Posg, &encoded, CommitTs(1));
7104 let cf = store.cf_for(IndexPermutation::Posg).unwrap();
7105 let value = encode_storage_value(StorageOp::Put, VisibilityLabel::default());
7106 let c_len = encode_term_bytes(&constraint("p1")).len();
7107 let mut payload_corrupt = vec![16u8, 0xFF];
7112 payload_corrupt.extend_from_slice(&[0u8; 14]);
7113 payload_corrupt.push(4);
7114 payload_corrupt.extend_from_slice(&valid[c_len..]);
7115 store.db.insert(cf, &payload_corrupt, &value).unwrap();
7116
7117 let hits = store.scan_axis_head(
7118 IndexPermutation::Posg,
7119 SNAP,
7120 0,
7121 None,
7122 None,
7123 &[],
7124 false,
7125 false,
7126 &[],
7127 );
7128 assert!(
7129 matches!(&hits, Err(crate::StorageError::Corrupt(_))),
7130 "hits walk must decode-reject the payload-corrupt head: {hits:?}"
7131 );
7132 let total = store.count_axis_heads(IndexPermutation::Posg, SNAP, None, &[], false, false);
7133 assert!(
7134 matches!(&total, Err(crate::StorageError::Corrupt(_))),
7135 "TOTAL must decode-reject the payload-corrupt head (no silent \
7136 under-count): {total:?}"
7137 );
7138 let per_head = store.scan_axis_head_counts(
7139 IndexPermutation::Posg,
7140 SNAP,
7141 0,
7142 None,
7143 None,
7144 &[],
7145 false,
7146 false,
7147 );
7148 assert!(
7149 matches!(&per_head, Err(crate::StorageError::Corrupt(_))),
7150 "PER_HEAD must decode-reject the payload-corrupt head: {per_head:?}"
7151 );
7152
7153 drop(store);
7154 let _ = std::fs::remove_dir_all(&dir);
7155 }
7156
7157 #[test]
7168 fn counts_walks_cover_wide_terms_and_iri_only() {
7169 let typed_object = "typed:a typed literal value well over sixteen bytes";
7170 let rows: Vec<(&str, &str, &str, &str, u64, StorageOp)> = vec![
7171 ("s1", "p1", typed_object, "default", 1, StorageOp::Put),
7172 ("s2", "p1", "o1", "default", 2, StorageOp::Put),
7173 ("s2", "p1", typed_object, "g1", 3, StorageOp::Put),
7174 ("s3", "p1", "o2", "default", 4, StorageOp::Put),
7175 ];
7176 assert_eq!(
7179 encode_term_bytes(
7180 &encode_quad(&fixture_quad("s", "p", typed_object, "default"))
7181 .unwrap()
7182 .object
7183 )
7184 .len(),
7185 33
7186 );
7187
7188 let (store, dir) = open_p_store("counts-wide");
7189 let memory = Storage::memory(PartitionAxis::P);
7190 for (s, p, o, g, ts, op) in &rows {
7191 let quad = fixture_quad(s, p, o, g);
7192 store
7193 .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7194 .unwrap();
7195 memory
7196 .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7197 .unwrap();
7198 }
7199
7200 let p1 = constraint("p1");
7201 let g1 = graph_term("g1");
7202 let cases: Vec<(&str, Option<EncodedTerm>, bool)> = vec![
7203 ("unconstrained", None, false),
7204 ("bound-g1", Some(g1.clone()), false),
7205 ("unconstrained+iri", None, true),
7206 ("bound-g1+iri", Some(g1.clone()), true),
7207 ];
7208 for count_mode in [
7209 DomainCountMode::Rows,
7210 DomainCountMode::DistinctTerms,
7211 DomainCountMode::DistinctGraphs,
7212 ] {
7213 for (tag, graph_name, iri_only) in &cases {
7214 let args = DomainArgs {
7215 graph_name: graph_name.as_ref(),
7216 iri_only: *iri_only,
7217 count_mode,
7218 ..Default::default()
7219 };
7220 let rocks = scan_counts(
7221 &store,
7222 DomainScanMode::Legacy,
7223 std::slice::from_ref(&p1),
7224 0,
7225 None,
7226 &args,
7227 )
7228 .unwrap();
7229 let mem = memory_counts(&memory, std::slice::from_ref(&p1), 0, None, &args);
7230 assert_eq!(rocks, mem, "{count_mode:?} / {tag}: backends must agree");
7231 }
7232 }
7233
7234 let o1 = EncodedTerm::from(&NamedNode::new("http://ex/o1").unwrap());
7236 let o2 = EncodedTerm::from(&NamedNode::new("http://ex/o2").unwrap());
7237 let typed_head = encode_quad(&fixture_quad("s", "p", typed_object, "default"))
7238 .unwrap()
7239 .object;
7240 let rows_args = DomainArgs {
7241 count_mode: DomainCountMode::Rows,
7242 ..Default::default()
7243 };
7244 let hits = scan_counts(
7245 &store,
7246 DomainScanMode::Legacy,
7247 std::slice::from_ref(&p1),
7248 0,
7249 None,
7250 &rows_args,
7251 )
7252 .unwrap();
7253 assert_eq!(head_count(&hits, &typed_head), 2, "wide head in two graphs");
7254 assert_eq!(head_count(&hits, &o1), 1);
7255 assert_eq!(head_count(&hits, &o2), 1);
7256 let iri_args = DomainArgs {
7259 iri_only: true,
7260 count_mode: DomainCountMode::Rows,
7261 ..Default::default()
7262 };
7263 let iri_hits = scan_counts(
7264 &store,
7265 DomainScanMode::Legacy,
7266 std::slice::from_ref(&p1),
7267 0,
7268 None,
7269 &iri_args,
7270 )
7271 .unwrap();
7272 assert_eq!(iri_hits.len(), 2, "named-node heads only: {iri_hits:?}");
7273 assert_eq!(head_count(&iri_hits, &o1) + head_count(&iri_hits, &o2), 2);
7274
7275 drop(store);
7276 let _ = std::fs::remove_dir_all(&dir);
7277
7278 let dir = std::env::temp_dir().join(format!(
7282 "waratah-counts-wide-spog-{}-{}",
7283 std::process::id(),
7284 std::time::SystemTime::now()
7285 .duration_since(std::time::UNIX_EPOCH)
7286 .unwrap()
7287 .as_nanos()
7288 ));
7289 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
7290 let memory = Storage::memory(PartitionAxis::S);
7291 for (s, p, o, g, ts, op) in &rows {
7292 let quad = fixture_quad(s, p, o, g);
7293 store
7294 .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7295 .unwrap();
7296 memory
7297 .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7298 .unwrap();
7299 }
7300 let s2 = EncodedTerm::from(&NamedNode::new("http://ex/s2").unwrap());
7301 let p1_head = constraint("p1");
7302 let distinct = store
7303 .scan_domain_counts(
7304 IndexPermutation::Spog,
7305 std::slice::from_ref(&s2),
7306 SnapshotId(100),
7307 0,
7308 None,
7309 None,
7310 None,
7311 &[],
7312 false,
7313 false,
7314 false,
7315 DomainCountMode::DistinctTerms,
7316 )
7317 .unwrap();
7318 let mem_distinct = memory
7319 .scan_domain_counts(
7320 IndexPermutation::Spog,
7321 std::slice::from_ref(&s2),
7322 SnapshotId(100),
7323 0,
7324 None,
7325 None,
7326 None,
7327 &[],
7328 false,
7329 false,
7330 false,
7331 DomainCountMode::DistinctTerms,
7332 )
7333 .unwrap();
7334 assert_eq!(distinct, mem_distinct, "SPOG wide-slot-2 parity");
7335 assert_eq!(distinct.len(), 1, "one head (p1) under s2: {distinct:?}");
7336 assert_eq!(
7337 distinct[0].count, 2,
7338 "distinct objects {{o1, typed}}: {distinct:?}"
7339 );
7340 assert_eq!(distinct[0].term, p1_head);
7341
7342 drop(store);
7343 let _ = std::fs::remove_dir_all(&dir);
7344 }
7345
7346 #[test]
7359 fn counts_walks_see_older_versions_under_future_heads() {
7360 let (store, dir) = open_p_store("future-ts");
7361 let memory = Storage::memory(PartitionAxis::P);
7362 let rows: Vec<(&str, &str, &str, &str, u64, StorageOp)> = vec![
7363 ("s1", "p1", "o1", "default", 2000, StorageOp::Put),
7364 ("s1", "p1", "o1", "default", 5, StorageOp::Put),
7365 ("s2", "p1", "o1", "default", 6, StorageOp::Put),
7366 ("s3", "p1", "o2", "default", 3000, StorageOp::Put),
7367 ("s4", "p1", "o3", "default", 2500, StorageOp::Put),
7368 ("s4", "p1", "o3", "default", 7, StorageOp::Put),
7369 ("s5", "p1", "o3", "default", 8, StorageOp::Put),
7370 ];
7371 for (s, p, o, g, ts, op) in &rows {
7372 let quad = fixture_quad(s, p, o, g);
7373 store
7374 .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7375 .unwrap();
7376 memory
7377 .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7378 .unwrap();
7379 }
7380
7381 let p1 = constraint("p1");
7382 let o1 = encode_quad(&fixture_quad("s", "p", "o1", "default"))
7383 .unwrap()
7384 .object;
7385 let o3 = encode_quad(&fixture_quad("s", "p", "o3", "default"))
7386 .unwrap()
7387 .object;
7388 let combos: Vec<(bool, DomainCountMode)> = vec![
7390 (true, DomainCountMode::Rows),
7391 (true, DomainCountMode::DistinctTerms),
7392 (false, DomainCountMode::Rows),
7393 (false, DomainCountMode::DistinctTerms),
7394 (false, DomainCountMode::DistinctGraphs),
7395 ];
7396 for (merge, count_mode) in &combos {
7397 let args = DomainArgs {
7398 merge: *merge,
7399 count_mode: *count_mode,
7400 ..Default::default()
7401 };
7402 let rocks = scan_counts(
7403 &store,
7404 DomainScanMode::Legacy,
7405 std::slice::from_ref(&p1),
7406 0,
7407 None,
7408 &args,
7409 )
7410 .unwrap();
7411 let mem = memory_counts(&memory, std::slice::from_ref(&p1), 0, None, &args);
7412 assert_eq!(
7413 rocks, mem,
7414 "backends must agree (merge={merge}, {count_mode:?})"
7415 );
7416
7417 assert_eq!(rocks.len(), 2, "heads o1 and o3 only: {rocks:?}");
7418 let expected = match count_mode {
7423 DomainCountMode::DistinctGraphs => 1,
7424 _ => 2,
7425 };
7426 assert_eq!(
7427 head_count(&rocks, &o1),
7428 expected,
7429 "o1 (merge={merge}, {count_mode:?}): {rocks:?}"
7430 );
7431 assert_eq!(
7432 head_count(&rocks, &o3),
7433 expected,
7434 "o3 (merge={merge}, {count_mode:?}): {rocks:?}"
7435 );
7436 }
7437
7438 drop(store);
7439 let _ = std::fs::remove_dir_all(&dir);
7440 }
7441
7442 #[test]
7451 fn merge_counts_next_chain_and_bounded_seek_agree() {
7452 let (store, dir) = open_p_store("merge-chain");
7453 let memory = Storage::memory(PartitionAxis::P);
7454 let mut rows: Vec<(String, &str, &str, String)> = Vec::new();
7455 for i in 0..60 {
7457 rows.push(("s1".into(), "p1", "o1", format!("gc{i:02}")));
7458 }
7459 rows.push(("s2".into(), "p1", "o1", "default".into()));
7461 rows.push(("s3".into(), "p1", "o2", "default".into()));
7464 for g in ["ga", "gb", "gc"] {
7466 rows.push(("s4".into(), "p1", "o3", g.into()));
7467 }
7468 for (s, p, o, g) in &rows {
7469 let quad = fixture_quad(s, p, o, g);
7470 store
7471 .insert_quad_version(
7472 &quad,
7473 CommitTs(1),
7474 StorageOp::Put,
7475 VisibilityLabel::default(),
7476 )
7477 .unwrap();
7478 memory
7479 .insert_quad_version(
7480 &quad,
7481 CommitTs(1),
7482 StorageOp::Put,
7483 VisibilityLabel::default(),
7484 )
7485 .unwrap();
7486 }
7487
7488 let p1 = constraint("p1");
7489 for count_mode in [DomainCountMode::Rows, DomainCountMode::DistinctTerms] {
7490 let args = DomainArgs {
7491 merge: true,
7492 count_mode,
7493 ..Default::default()
7494 };
7495 let rocks = scan_counts(
7496 &store,
7497 DomainScanMode::Legacy,
7498 std::slice::from_ref(&p1),
7499 0,
7500 None,
7501 &args,
7502 )
7503 .unwrap();
7504 let mem = memory_counts(&memory, std::slice::from_ref(&p1), 0, None, &args);
7505 assert_eq!(rocks, mem, "backends must agree ({count_mode:?})");
7506
7507 let mut counts: Vec<u64> = rocks.iter().map(|h| h.count).collect();
7510 counts.sort_unstable();
7511 assert_eq!(
7512 counts,
7513 vec![1, 1, 2],
7514 "merged counts ({count_mode:?}): {rocks:?}"
7515 );
7516 assert_eq!(rocks.len(), 3, "one hit per head (o1, o2, o3): {rocks:?}");
7517 }
7518
7519 drop(store);
7520 let _ = std::fs::remove_dir_all(&dir);
7521 }
7522
7523 use super::{
7526 CountSlice, CountWalkMode, count_walk_plan, count_walk_slice, count_walks_from_env,
7527 even_boundaries,
7528 };
7529 use crate::StrHash;
7530 use crate::encode::{EncodedQuad, EncodedTriplePattern, GByteFilter};
7531
7532 fn count_store_dir(tag: &str) -> std::path::PathBuf {
7533 std::env::temp_dir().join(format!(
7534 "waratah-count-{tag}-{}-{}",
7535 std::process::id(),
7536 std::time::SystemTime::now()
7537 .duration_since(std::time::UNIX_EPOCH)
7538 .unwrap()
7539 .as_nanos()
7540 ))
7541 }
7542
7543 fn default_spo(s: &str, predicate_iri: &str, o: &str) -> Quad {
7545 Quad::new(
7546 NamedNode::new(format!("http://ex/{s}")).unwrap(),
7547 NamedNode::new(predicate_iri).unwrap(),
7548 NamedNode::new(format!("http://ex/{o}")).unwrap(),
7549 GraphName::DefaultGraph,
7550 )
7551 }
7552
7553 fn rdf_type_spo(s: &str, o: &str) -> Quad {
7555 default_spo(s, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", o)
7556 }
7557
7558 fn unbound_pattern() -> EncodedTriplePattern {
7560 EncodedTriplePattern {
7561 subject: None,
7562 predicate: None,
7563 object: None,
7564 graph_name: None,
7565 }
7566 }
7567
7568 #[allow(clippy::too_many_arguments)]
7569 fn count_run(
7570 store: &RocksDbStorage,
7571 mode: CountWalkMode,
7572 permutation: IndexPermutation,
7573 pattern: &EncodedTriplePattern,
7574 snapshot: SnapshotId,
7575 limit: u64,
7576 graph: &GByteFilter,
7577 merge: bool,
7578 class_totals: &[(StrHash, u64)],
7579 ) -> u64 {
7580 store
7581 .count_pattern_impl_with_mode(
7582 mode,
7583 permutation,
7584 pattern,
7585 snapshot,
7586 limit,
7587 graph.clone(),
7588 merge,
7589 class_totals,
7590 )
7591 .unwrap()
7592 }
7593
7594 fn mixed_kind_store(axis: PartitionAxis) -> (RocksDbStorage, std::path::PathBuf, u64, u64) {
7607 let dir = count_store_dir("perm-mixed");
7608 let store = RocksDbStorage::open(&dir, axis).unwrap();
7609 let integer = NamedNode::new("http://www.w3.org/2001/XMLSchema#integer").unwrap();
7610 let mut quads: Vec<Quad> = Vec::new();
7611 for i in 0..6 {
7612 quads.push(Quad::new(
7613 NamedNode::new(format!("http://ex/s{i}")).unwrap(),
7614 NamedNode::new("http://ex/p0").unwrap(),
7615 NamedNode::new(format!("http://ex/o{i}")).unwrap(),
7616 GraphName::DefaultGraph,
7617 ));
7618 }
7619 for i in 0..3 {
7620 quads.push(Quad::new(
7621 BlankNode::new_unchecked(format!("b{i}")),
7622 NamedNode::new("http://ex/p1").unwrap(),
7623 NamedNode::new(format!("http://ex/o{i}")).unwrap(),
7624 GraphName::DefaultGraph,
7625 ));
7626 }
7627 for i in 0..3 {
7628 quads.push(Quad::new(
7629 NamedNode::new(format!("http://ex/s{i}")).unwrap(),
7630 NamedNode::new("http://ex/p1").unwrap(),
7631 Literal::from(format!("lit{i}")),
7632 GraphName::DefaultGraph,
7633 ));
7634 }
7635 for i in 0..3 {
7636 quads.push(Quad::new(
7637 NamedNode::new(format!("http://ex/s{i}")).unwrap(),
7638 NamedNode::new("http://ex/p2").unwrap(),
7639 Literal::new_typed_literal(["7", "42", "-5"][i], integer.clone()),
7640 GraphName::DefaultGraph,
7641 ));
7642 }
7643 let rdf_type = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
7647 if axis == PartitionAxis::O {
7648 for i in 0..6 {
7649 quads.push(Quad::new(
7650 NamedNode::new(format!("http://ex/s{i}")).unwrap(),
7651 rdf_type.clone(),
7652 NamedNode::new(format!("http://ex/C{}", i % 2)).unwrap(),
7653 GraphName::DefaultGraph,
7654 ));
7655 }
7656 for (subject, value) in [("t0", "7"), ("t1", "42")] {
7657 quads.push(Quad::new(
7658 NamedNode::new(format!("http://ex/{subject}")).unwrap(),
7659 rdf_type.clone(),
7660 Literal::new_typed_literal(value, integer.clone()),
7661 GraphName::DefaultGraph,
7662 ));
7663 }
7664 }
7665 quads.push(named_spo("n0", "no0", "g0"));
7666 quads.push(named_spo("n1", "no1", "g0"));
7667 quads.push(named_spo("n2", "no2", "g1"));
7668 let mv = Quad::new(
7671 NamedNode::new("http://ex/s9").unwrap(),
7672 NamedNode::new("http://ex/p9").unwrap(),
7673 NamedNode::new("http://ex/o9").unwrap(),
7674 GraphName::DefaultGraph,
7675 );
7676 for ts in [10u64, 30] {
7677 store
7678 .insert_quad_version(
7679 &mv,
7680 CommitTs(ts),
7681 StorageOp::Put,
7682 VisibilityLabel::default(),
7683 )
7684 .unwrap();
7685 }
7686 for quad in &quads {
7687 store
7688 .insert_quad_version(
7689 quad,
7690 CommitTs(1),
7691 StorageOp::Put,
7692 VisibilityLabel::default(),
7693 )
7694 .unwrap();
7695 }
7696 store.flush_memtables().unwrap();
7697 let tsg_total = if axis == PartitionAxis::O { 8 } else { 0 };
7698 (store, dir, quads.len() as u64 + 1, tsg_total)
7699 }
7700
7701 #[test]
7709 fn count_parallel_matches_serial_on_every_permutation() {
7710 let (s_store, s_dir, no_type_total, _) = mixed_kind_store(PartitionAxis::S);
7711 let (p_store, p_dir, _, _) = mixed_kind_store(PartitionAxis::P);
7712 let (o_store, o_dir, full_total, tsg_total) = mixed_kind_store(PartitionAxis::O);
7713 let snapshot = SnapshotId(25);
7714 let store_for = |permutation| match permutation {
7715 IndexPermutation::Spog | IndexPermutation::Sopg => &s_store,
7716 IndexPermutation::Posg | IndexPermutation::Psog => &p_store,
7717 IndexPermutation::Opsg | IndexPermutation::Tsg => &o_store,
7718 };
7719 let permutations = [
7720 IndexPermutation::Spog,
7721 IndexPermutation::Sopg,
7722 IndexPermutation::Posg,
7723 IndexPermutation::Psog,
7724 IndexPermutation::Opsg,
7725 IndexPermutation::Tsg,
7726 ];
7727 for permutation in permutations {
7728 let store = store_for(permutation);
7729 let pattern = if permutation == IndexPermutation::Tsg {
7732 EncodedTriplePattern {
7733 predicate: Some(crate::RDF_TYPE),
7734 ..unbound_pattern()
7735 }
7736 } else {
7737 unbound_pattern()
7738 };
7739 let expected = match permutation {
7740 IndexPermutation::Tsg => tsg_total,
7741 IndexPermutation::Opsg => full_total,
7742 _ => no_type_total,
7743 };
7744 let serial = count_run(
7745 store,
7746 CountWalkMode::Serial,
7747 permutation,
7748 &pattern,
7749 snapshot,
7750 0,
7751 &GByteFilter::Unconstrained,
7752 false,
7753 &[],
7754 );
7755 let parallel = count_run(
7756 store,
7757 CountWalkMode::Parallel(4),
7758 permutation,
7759 &pattern,
7760 snapshot,
7761 0,
7762 &GByteFilter::Unconstrained,
7763 false,
7764 &[],
7765 );
7766 assert_eq!(serial, expected, "{permutation:?} full-axis serial total");
7767 assert_eq!(
7768 parallel, serial,
7769 "{permutation:?} full-axis parallel must equal serial"
7770 );
7771 }
7772
7773 let integer = NamedNode::new("http://www.w3.org/2001/XMLSchema#integer").unwrap();
7778 let term = |iri: &str| EncodedTerm::from(&NamedNode::new(iri).unwrap());
7779 let arena_cases: Vec<(&str, IndexPermutation, EncodedTriplePattern, bool)> = vec![
7780 (
7781 "IRI subject",
7782 IndexPermutation::Spog,
7783 EncodedTriplePattern {
7784 subject: Some(term("http://ex/s0")),
7785 ..unbound_pattern()
7786 },
7787 true,
7788 ),
7789 (
7790 "IRI subject (Sopg)",
7791 IndexPermutation::Sopg,
7792 EncodedTriplePattern {
7793 subject: Some(term("http://ex/s0")),
7794 ..unbound_pattern()
7795 },
7796 true,
7797 ),
7798 (
7799 "blank-node subject",
7800 IndexPermutation::Spog,
7801 EncodedTriplePattern {
7802 subject: Some(EncodedTerm::from(&BlankNode::new_unchecked("b0"))),
7803 ..unbound_pattern()
7804 },
7805 true,
7806 ),
7807 (
7808 "IRI predicate",
7809 IndexPermutation::Posg,
7810 EncodedTriplePattern {
7811 predicate: Some(term("http://ex/p0")),
7812 ..unbound_pattern()
7813 },
7814 true,
7815 ),
7816 (
7817 "IRI predicate (Psog)",
7818 IndexPermutation::Psog,
7819 EncodedTriplePattern {
7820 predicate: Some(term("http://ex/p0")),
7821 ..unbound_pattern()
7822 },
7823 true,
7824 ),
7825 (
7826 "IRI object",
7827 IndexPermutation::Opsg,
7828 EncodedTriplePattern {
7829 object: Some(term("http://ex/o0")),
7830 ..unbound_pattern()
7831 },
7832 true,
7833 ),
7834 (
7835 "plain literal object",
7836 IndexPermutation::Opsg,
7837 EncodedTriplePattern {
7838 object: Some(EncodedTerm::from(&Literal::from("lit0"))),
7839 ..unbound_pattern()
7840 },
7841 true,
7842 ),
7843 (
7844 "typed integer object (9-byte leading term)",
7845 IndexPermutation::Opsg,
7846 EncodedTriplePattern {
7847 object: Some(EncodedTerm::from(&Literal::new_typed_literal(
7848 "42",
7849 integer.clone(),
7850 ))),
7851 ..unbound_pattern()
7852 },
7853 true,
7854 ),
7855 (
7856 "IRI class (Tsg arena)",
7857 IndexPermutation::Tsg,
7858 EncodedTriplePattern {
7859 predicate: Some(crate::RDF_TYPE),
7860 object: Some(term("http://ex/C0")),
7861 ..unbound_pattern()
7862 },
7863 true,
7864 ),
7865 (
7866 "typed integer class (9-byte Tsg leading term)",
7867 IndexPermutation::Tsg,
7868 EncodedTriplePattern {
7869 predicate: Some(crate::RDF_TYPE),
7870 object: Some(EncodedTerm::from(&Literal::new_typed_literal(
7871 "7",
7872 integer.clone(),
7873 ))),
7874 ..unbound_pattern()
7875 },
7876 true,
7877 ),
7878 (
7879 "absent subject (empty arena)",
7880 IndexPermutation::Spog,
7881 EncodedTriplePattern {
7882 subject: Some(term("http://ex/absent")),
7883 ..unbound_pattern()
7884 },
7885 false,
7886 ),
7887 ];
7888 for (label, permutation, pattern, nonempty) in arena_cases {
7889 let store = store_for(permutation);
7890 let serial = count_run(
7891 store,
7892 CountWalkMode::Serial,
7893 permutation,
7894 &pattern,
7895 snapshot,
7896 0,
7897 &GByteFilter::Unconstrained,
7898 false,
7899 &[],
7900 );
7901 let parallel = count_run(
7902 store,
7903 CountWalkMode::Parallel(4),
7904 permutation,
7905 &pattern,
7906 snapshot,
7907 0,
7908 &GByteFilter::Unconstrained,
7909 false,
7910 &[],
7911 );
7912 assert_eq!(
7913 parallel, serial,
7914 "{label}: {permutation:?} arena parallel must equal serial"
7915 );
7916 assert_eq!(
7917 serial > 0,
7918 nonempty,
7919 "{label}: expected nonempty={nonempty}"
7920 );
7921 }
7922 drop(s_store);
7923 drop(p_store);
7924 drop(o_store);
7925 for dir in [&s_dir, &p_dir, &o_dir] {
7926 let _ = std::fs::remove_dir_all(dir);
7927 }
7928 }
7929
7930 #[test]
7940 fn count_walks_stay_exact_with_sst_filters_armed() {
7941 crate::rocksdb_db::TEST_SST_FILTER_FORCE_ON
7942 .store(true, std::sync::atomic::Ordering::Relaxed);
7943 let rdf_type = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
7944 let s_dir = count_store_dir("armed-s");
7945 let s_store = RocksDbStorage::open(&s_dir, PartitionAxis::S).unwrap();
7946 let s_memory = Storage::memory(PartitionAxis::S);
7947 let o_dir = count_store_dir("armed-o");
7948 let o_store = RocksDbStorage::open(&o_dir, PartitionAxis::O).unwrap();
7949 let o_memory = Storage::memory(PartitionAxis::O);
7950
7951 let put_both = |store: &RocksDbStorage, memory: &Storage, quad: &Quad, ts: u64| {
7952 store
7953 .insert_quad_version(
7954 quad,
7955 CommitTs(ts),
7956 StorageOp::Put,
7957 VisibilityLabel::default(),
7958 )
7959 .unwrap();
7960 memory
7961 .insert_quad_version(
7962 quad,
7963 CommitTs(ts),
7964 StorageOp::Put,
7965 VisibilityLabel::default(),
7966 )
7967 .unwrap();
7968 };
7969
7970 let mut s_expected = 0u64;
7974 let quad = |s: &str, p: &str, o: &str| {
7975 Quad::new(
7976 NamedNode::new(format!("http://ex/{s}")).unwrap(),
7977 NamedNode::new(format!("http://ex/{p}")).unwrap(),
7978 NamedNode::new(format!("http://ex/{o}")).unwrap(),
7979 GraphName::DefaultGraph,
7980 )
7981 };
7982 for i in 0..2 {
7983 put_both(&s_store, &s_memory, &quad("b1", "p0", &format!("w{i}")), 1);
7984 s_expected += 1;
7985 }
7986 s_store.flush_memtables().unwrap();
7987 s_memory.flush_memtables().unwrap();
7988 for i in 0..2 {
7989 put_both(&s_store, &s_memory, &quad("b2", "p1", &format!("x{i}")), 2);
7990 s_expected += 1;
7991 }
7992 let s_named = Quad::new(
7993 NamedNode::new("http://ex/b3").unwrap(),
7994 NamedNode::new("http://ex/p2").unwrap(),
7995 NamedNode::new("http://ex/n0").unwrap(),
7996 GraphName::NamedNode(NamedNode::new("http://ex/g0").unwrap()),
7997 );
7998 put_both(&s_store, &s_memory, &s_named, 3);
7999 s_expected += 1;
8000 s_store.flush_memtables().unwrap();
8001 s_memory.flush_memtables().unwrap();
8002 let m1 = quad("b4", "p0", "m1");
8005 put_both(&s_store, &s_memory, &m1, 1);
8006 s_store
8007 .insert_quad_version(
8008 &m1,
8009 CommitTs(2),
8010 StorageOp::Delete,
8011 VisibilityLabel::default(),
8012 )
8013 .unwrap();
8014 s_memory
8015 .insert_quad_version(
8016 &m1,
8017 CommitTs(2),
8018 StorageOp::Delete,
8019 VisibilityLabel::default(),
8020 )
8021 .unwrap();
8022 let m2 = quad("b5", "p0", "m2");
8023 put_both(&s_store, &s_memory, &m2, 3);
8024 s_store
8025 .insert_quad_version(&m2, CommitTs(9), StorageOp::Put, VisibilityLabel::default())
8026 .unwrap();
8027 s_memory
8028 .insert_quad_version(&m2, CommitTs(9), StorageOp::Put, VisibilityLabel::default())
8029 .unwrap();
8030 s_store.flush_memtables().unwrap();
8031 s_memory.flush_memtables().unwrap();
8032 let s_expected = s_expected + 1;
8035
8036 let mut o_expected = 0u64;
8039 let batch = |store: &RocksDbStorage,
8040 memory: &Storage,
8041 quads: Vec<Quad>,
8042 ts: u64,
8043 o_expected: &mut u64| {
8044 for quad in &quads {
8045 put_both(store, memory, quad, ts);
8046 *o_expected += 1;
8047 }
8048 };
8049 let c0: Vec<Quad> = (0..4)
8050 .map(|i| {
8051 Quad::new(
8052 NamedNode::new(format!("http://ex/s{i}")).unwrap(),
8053 rdf_type.clone(),
8054 NamedNode::new("http://ex/C0").unwrap(),
8055 GraphName::DefaultGraph,
8056 )
8057 })
8058 .collect();
8059 batch(&o_store, &o_memory, c0, 1, &mut o_expected);
8060 o_store.flush_memtables().unwrap();
8061 o_memory.flush_memtables().unwrap();
8062 let c1: Vec<Quad> = (4..8)
8063 .map(|i| {
8064 Quad::new(
8065 NamedNode::new(format!("http://ex/s{i}")).unwrap(),
8066 rdf_type.clone(),
8067 NamedNode::new("http://ex/C1").unwrap(),
8068 GraphName::DefaultGraph,
8069 )
8070 })
8071 .collect();
8072 batch(&o_store, &o_memory, c1, 2, &mut o_expected);
8073 let o_named = Quad::new(
8074 NamedNode::new("http://ex/n0").unwrap(),
8075 NamedNode::new("http://ex/p2").unwrap(),
8076 NamedNode::new("http://ex/n1").unwrap(),
8077 GraphName::NamedNode(NamedNode::new("http://ex/g0").unwrap()),
8078 );
8079 batch(&o_store, &o_memory, vec![o_named], 2, &mut o_expected);
8080 o_store.flush_memtables().unwrap();
8081 o_memory.flush_memtables().unwrap();
8082 let c2: Vec<Quad> = (8..12)
8083 .map(|i| {
8084 Quad::new(
8085 NamedNode::new(format!("http://ex/s{i}")).unwrap(),
8086 rdf_type.clone(),
8087 NamedNode::new("http://ex/C2").unwrap(),
8088 GraphName::DefaultGraph,
8089 )
8090 })
8091 .collect();
8092 batch(&o_store, &o_memory, c2, 3, &mut o_expected);
8093 batch(
8094 &o_store,
8095 &o_memory,
8096 vec![quad("p1", "q0", "y0")],
8097 3,
8098 &mut o_expected,
8099 );
8100 let om1 = Quad::new(
8101 NamedNode::new("http://ex/p2").unwrap(),
8102 NamedNode::new("http://ex/q1").unwrap(),
8103 NamedNode::new("http://ex/m1").unwrap(),
8104 GraphName::DefaultGraph,
8105 );
8106 batch(&o_store, &o_memory, vec![om1.clone()], 1, &mut o_expected);
8107 o_store
8108 .insert_quad_version(
8109 &om1,
8110 CommitTs(2),
8111 StorageOp::Delete,
8112 VisibilityLabel::default(),
8113 )
8114 .unwrap();
8115 o_memory
8116 .insert_quad_version(
8117 &om1,
8118 CommitTs(2),
8119 StorageOp::Delete,
8120 VisibilityLabel::default(),
8121 )
8122 .unwrap();
8123 let om2 = Quad::new(
8124 NamedNode::new("http://ex/p2").unwrap(),
8125 NamedNode::new("http://ex/q1").unwrap(),
8126 NamedNode::new("http://ex/m2").unwrap(),
8127 GraphName::DefaultGraph,
8128 );
8129 batch(&o_store, &o_memory, vec![om2.clone()], 3, &mut o_expected);
8130 o_store
8131 .insert_quad_version(
8132 &om2,
8133 CommitTs(9),
8134 StorageOp::Put,
8135 VisibilityLabel::default(),
8136 )
8137 .unwrap();
8138 o_memory
8139 .insert_quad_version(
8140 &om2,
8141 CommitTs(9),
8142 StorageOp::Put,
8143 VisibilityLabel::default(),
8144 )
8145 .unwrap();
8146 o_store.flush_memtables().unwrap();
8147 o_memory.flush_memtables().unwrap();
8148 let o_expected = o_expected - 1;
8151 let tsg_expected = 12u64;
8152 let snapshot = SnapshotId(5);
8153
8154 let s_serial = count_run(
8157 &s_store,
8158 CountWalkMode::Serial,
8159 IndexPermutation::Spog,
8160 &unbound_pattern(),
8161 snapshot,
8162 0,
8163 &GByteFilter::Unconstrained,
8164 false,
8165 &[],
8166 );
8167 let s_parallel = count_run(
8168 &s_store,
8169 CountWalkMode::Parallel(4),
8170 IndexPermutation::Spog,
8171 &unbound_pattern(),
8172 snapshot,
8173 0,
8174 &GByteFilter::Unconstrained,
8175 false,
8176 &[],
8177 );
8178 let s_memory_count = s_memory
8179 .count_pattern_impl(
8180 IndexPermutation::Spog,
8181 &unbound_pattern(),
8182 snapshot,
8183 0,
8184 GByteFilter::Unconstrained,
8185 false,
8186 )
8187 .unwrap();
8188 assert_eq!(s_serial, s_expected, "armed full-axis Spog serial");
8189 assert_eq!(s_parallel, s_serial, "armed full-axis Spog parallel");
8190 assert_eq!(s_memory_count, s_serial, "armed full-axis Spog vs memory");
8191
8192 let s_arena_pattern = EncodedTriplePattern {
8194 subject: Some(EncodedTerm::from(&NamedNode::new("http://ex/b2").unwrap())),
8195 ..unbound_pattern()
8196 };
8197 let s_arena_serial = count_run(
8198 &s_store,
8199 CountWalkMode::Serial,
8200 IndexPermutation::Spog,
8201 &s_arena_pattern,
8202 snapshot,
8203 0,
8204 &GByteFilter::Unconstrained,
8205 false,
8206 &[],
8207 );
8208 let s_arena_parallel = count_run(
8209 &s_store,
8210 CountWalkMode::Parallel(4),
8211 IndexPermutation::Spog,
8212 &s_arena_pattern,
8213 snapshot,
8214 0,
8215 &GByteFilter::Unconstrained,
8216 false,
8217 &[],
8218 );
8219 assert_eq!(s_arena_serial, 2, "armed arena Spog serial");
8220 assert_eq!(
8221 s_arena_parallel, s_arena_serial,
8222 "armed arena Spog parallel"
8223 );
8224
8225 let tsg_pattern = EncodedTriplePattern {
8227 predicate: Some(crate::RDF_TYPE),
8228 ..unbound_pattern()
8229 };
8230 let tsg_serial = count_run(
8231 &o_store,
8232 CountWalkMode::Serial,
8233 IndexPermutation::Tsg,
8234 &tsg_pattern,
8235 snapshot,
8236 0,
8237 &GByteFilter::Unconstrained,
8238 false,
8239 &[],
8240 );
8241 let tsg_parallel = count_run(
8242 &o_store,
8243 CountWalkMode::Parallel(4),
8244 IndexPermutation::Tsg,
8245 &tsg_pattern,
8246 snapshot,
8247 0,
8248 &GByteFilter::Unconstrained,
8249 false,
8250 &[],
8251 );
8252 assert_eq!(tsg_serial, tsg_expected, "armed full-axis TSG serial");
8253 assert_eq!(tsg_parallel, tsg_serial, "armed full-axis TSG parallel");
8254
8255 let mut hint: Vec<(StrHash, u64)> = ["http://ex/C0", "http://ex/C1", "http://ex/C2"]
8257 .iter()
8258 .map(|class| (StrHash::new(class), 4))
8259 .collect();
8260 hint.sort_by_key(|(hash, _)| *hash);
8261 let tsg_hint_parallel = count_run(
8262 &o_store,
8263 CountWalkMode::Parallel(4),
8264 IndexPermutation::Tsg,
8265 &tsg_pattern,
8266 snapshot,
8267 0,
8268 &GByteFilter::Unconstrained,
8269 false,
8270 &hint,
8271 );
8272 assert_eq!(
8273 tsg_hint_parallel, tsg_serial,
8274 "armed hint-aligned TSG parallel"
8275 );
8276
8277 let tsg_arena_pattern = EncodedTriplePattern {
8279 predicate: Some(crate::RDF_TYPE),
8280 object: Some(EncodedTerm::from(&NamedNode::new("http://ex/C0").unwrap())),
8281 ..unbound_pattern()
8282 };
8283 let tsg_arena_serial = count_run(
8284 &o_store,
8285 CountWalkMode::Serial,
8286 IndexPermutation::Tsg,
8287 &tsg_arena_pattern,
8288 snapshot,
8289 0,
8290 &GByteFilter::Unconstrained,
8291 false,
8292 &[],
8293 );
8294 let tsg_arena_parallel = count_run(
8295 &o_store,
8296 CountWalkMode::Parallel(4),
8297 IndexPermutation::Tsg,
8298 &tsg_arena_pattern,
8299 snapshot,
8300 0,
8301 &GByteFilter::Unconstrained,
8302 false,
8303 &[],
8304 );
8305 assert_eq!(tsg_arena_serial, 4, "armed TSG arena serial");
8306 assert_eq!(
8307 tsg_arena_parallel, tsg_arena_serial,
8308 "armed TSG arena parallel"
8309 );
8310
8311 let opsg_serial = count_run(
8313 &o_store,
8314 CountWalkMode::Serial,
8315 IndexPermutation::Opsg,
8316 &unbound_pattern(),
8317 snapshot,
8318 0,
8319 &GByteFilter::Unconstrained,
8320 false,
8321 &[],
8322 );
8323 let opsg_parallel = count_run(
8324 &o_store,
8325 CountWalkMode::Parallel(4),
8326 IndexPermutation::Opsg,
8327 &unbound_pattern(),
8328 snapshot,
8329 0,
8330 &GByteFilter::Unconstrained,
8331 false,
8332 &[],
8333 );
8334 let o_memory_count = o_memory
8335 .count_pattern_impl(
8336 IndexPermutation::Opsg,
8337 &unbound_pattern(),
8338 snapshot,
8339 0,
8340 GByteFilter::Unconstrained,
8341 false,
8342 )
8343 .unwrap();
8344 assert_eq!(opsg_serial, o_expected, "armed full-axis Opsg serial");
8345 assert_eq!(opsg_parallel, opsg_serial, "armed full-axis Opsg parallel");
8346 assert_eq!(
8347 o_memory_count, opsg_serial,
8348 "armed full-axis Opsg vs memory"
8349 );
8350 drop(s_store);
8351 drop(o_store);
8352 drop(s_memory);
8353 drop(o_memory);
8354 let _ = std::fs::remove_dir_all(&s_dir);
8355 let _ = std::fs::remove_dir_all(&o_dir);
8356 }
8357
8358 #[test]
8359 fn count_walks_env_parse_mirrors_domain_walks() {
8360 assert_eq!(count_walks_from_env(None), None);
8361 assert_eq!(count_walks_from_env(Some("8")), Some(8));
8362 assert_eq!(count_walks_from_env(Some(" 16 ")), Some(16));
8363 assert_eq!(count_walks_from_env(Some("0")), None);
8364 assert_eq!(count_walks_from_env(Some("1")), None);
8365 assert_eq!(count_walks_from_env(Some("junk")), None);
8366 assert_eq!(
8367 count_walks_from_env(Some("1000")),
8368 Some(super::COUNT_WALKS_MAX)
8369 );
8370 }
8371
8372 #[test]
8373 fn even_boundaries_ascending_and_region_scoped() {
8374 let prefix = vec![0x01, 0xAA];
8375 let boundaries = even_boundaries(&prefix, 0x01, 8);
8379 assert_eq!(boundaries.len(), 7);
8380 for boundary in &boundaries {
8381 assert!(boundary.starts_with(&prefix), "boundary shares the prefix");
8382 assert_eq!(
8383 boundary[prefix.len()],
8384 0x01,
8385 "boundary inside the dominant tag region"
8386 );
8387 }
8388 for pair in boundaries.windows(2) {
8389 assert!(pair[0] < pair[1], "boundaries strictly ascend");
8390 }
8391 assert!(even_boundaries(&prefix, 0x01, 1).is_empty());
8392 }
8393
8394 #[test]
8395 fn count_walk_plan_shape_matrix() {
8396 let unbound = EncodedTriplePattern {
8397 subject: None,
8398 predicate: None,
8399 object: None,
8400 graph_name: None,
8401 };
8402 let subject = EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap());
8403 let predicate = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
8404 let class = EncodedTerm::from(&NamedNode::new("http://ex/C").unwrap());
8405 let graph = EncodedTerm::from(&NamedNode::new("http://ex/g").unwrap());
8406
8407 let plan = count_walk_plan(
8409 4,
8410 IndexPermutation::Spog,
8411 &unbound,
8412 &GByteFilter::Unconstrained,
8413 &[],
8414 || 0x01,
8415 )
8416 .unwrap();
8417 assert!(plan.prefix.is_empty());
8418 assert_eq!(plan.slices.len(), 4);
8419 assert!(plan.slices[0].start.is_empty());
8420 assert!(plan.slices.last().unwrap().end.is_none());
8421 for pair in plan.slices.windows(2) {
8422 assert_eq!(pair[0].end.as_deref(), Some(pair[1].start.as_slice()));
8423 }
8424
8425 let bound_subject = EncodedTriplePattern {
8428 subject: Some(subject.clone()),
8429 predicate: None,
8430 object: None,
8431 graph_name: None,
8432 };
8433 let plan = count_walk_plan(
8434 4,
8435 IndexPermutation::Spog,
8436 &bound_subject,
8437 &GByteFilter::Unconstrained,
8438 &[],
8439 || 0x01,
8440 )
8441 .unwrap();
8442 assert!(!plan.prefix.is_empty());
8443 assert!(
8444 plan.slices
8445 .iter()
8446 .all(|slice| slice.start.starts_with(&plan.prefix))
8447 );
8448
8449 let bound_predicate = EncodedTriplePattern {
8451 subject: None,
8452 predicate: Some(predicate),
8453 object: None,
8454 graph_name: None,
8455 };
8456 assert!(
8457 count_walk_plan(
8458 4,
8459 IndexPermutation::Spog,
8460 &bound_predicate,
8461 &GByteFilter::Unconstrained,
8462 &[],
8463 || 0x01,
8464 )
8465 .is_none()
8466 );
8467
8468 let bound_graph = EncodedTriplePattern {
8471 subject: None,
8472 predicate: None,
8473 object: None,
8474 graph_name: Some(graph),
8475 };
8476 assert!(
8477 count_walk_plan(
8478 4,
8479 IndexPermutation::Spog,
8480 &bound_graph,
8481 &GByteFilter::Unconstrained,
8482 &[],
8483 || 0x01,
8484 )
8485 .is_none()
8486 );
8487 let default_scoped = EncodedTriplePattern {
8488 subject: None,
8489 predicate: None,
8490 object: None,
8491 graph_name: Some(EncodedTerm::DefaultGraph),
8492 };
8493 assert!(
8494 count_walk_plan(
8495 4,
8496 IndexPermutation::Spog,
8497 &default_scoped,
8498 &GByteFilter::Unconstrained,
8499 &[],
8500 || 0x01,
8501 )
8502 .is_some()
8503 );
8504
8505 let tsg_arena = EncodedTriplePattern {
8508 subject: None,
8509 predicate: Some(crate::RDF_TYPE),
8510 object: Some(class.clone()),
8511 graph_name: None,
8512 };
8513 let plan = count_walk_plan(
8514 4,
8515 IndexPermutation::Tsg,
8516 &tsg_arena,
8517 &GByteFilter::Unconstrained,
8518 &[],
8519 || 0x01,
8520 )
8521 .unwrap();
8522 assert!(!plan.prefix.is_empty());
8523 assert!(
8524 plan.slices
8525 .iter()
8526 .all(|slice| slice.start.starts_with(&plan.prefix))
8527 );
8528
8529 let tsg_subject = EncodedTriplePattern {
8531 subject: Some(subject),
8532 predicate: Some(crate::RDF_TYPE),
8533 object: Some(class),
8534 graph_name: None,
8535 };
8536 assert!(
8537 count_walk_plan(
8538 4,
8539 IndexPermutation::Tsg,
8540 &tsg_subject,
8541 &GByteFilter::Unconstrained,
8542 &[],
8543 || 0x01,
8544 )
8545 .is_none()
8546 );
8547
8548 let hash_a = StrHash::new("http://ex/A");
8552 let hash_b = StrHash::new("http://ex/B");
8553 let mut hint = vec![(hash_b, 40u64), (hash_a, 40u64)];
8554 hint.sort_by_key(|(hash, _)| *hash);
8555 let plan = count_walk_plan(
8556 2,
8557 IndexPermutation::Tsg,
8558 &unbound,
8559 &GByteFilter::Unconstrained,
8560 &hint,
8561 || 0x01,
8562 )
8563 .unwrap();
8564 let expected =
8565 crate::encode::encode_term_bytes(&EncodedTerm::NamedNode { iri_id: hint[1].0 });
8566 assert_eq!(plan.slices.len(), 2);
8567 assert_eq!(plan.slices[0].end.as_deref(), Some(expected.as_slice()));
8568 assert_eq!(plan.slices[0].start, Vec::<u8>::new());
8569 assert!(plan.slices[1].end.is_none());
8570
8571 let stale = vec![(hash_a, 0u64), (hash_b, 0u64)];
8573 let plan = count_walk_plan(
8574 2,
8575 IndexPermutation::Tsg,
8576 &unbound,
8577 &GByteFilter::Unconstrained,
8578 &stale,
8579 || 0x01,
8580 )
8581 .unwrap();
8582 assert!(
8583 plan.slices[0]
8584 .end
8585 .as_ref()
8586 .unwrap()
8587 .starts_with(&plan.prefix)
8588 );
8589 }
8590
8591 #[test]
8592 fn full_axis_count_parallel_matches_serial() {
8593 for permutation in [IndexPermutation::Spog, IndexPermutation::Sopg] {
8594 let dir = count_store_dir("fa");
8595 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
8596 for i in 0..300u64 {
8597 store
8598 .insert_quad_version(
8599 &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
8600 CommitTs(1),
8601 StorageOp::Put,
8602 VisibilityLabel::default(),
8603 )
8604 .unwrap();
8605 }
8606 store.flush_memtables().unwrap();
8607 let pattern = unbound_pattern();
8608 let serial = count_run(
8609 &store,
8610 CountWalkMode::Serial,
8611 permutation,
8612 &pattern,
8613 SnapshotId(9),
8614 0,
8615 &GByteFilter::Unconstrained,
8616 false,
8617 &[],
8618 );
8619 assert_eq!(serial, 300);
8620 for workers in [2usize, 3, 7, 64] {
8621 let parallel = count_run(
8622 &store,
8623 CountWalkMode::Parallel(workers),
8624 permutation,
8625 &pattern,
8626 SnapshotId(9),
8627 0,
8628 &GByteFilter::Unconstrained,
8629 false,
8630 &[],
8631 );
8632 assert_eq!(parallel, serial, "permutation {permutation:?} K={workers}");
8633 }
8634 drop(store);
8635 let _ = std::fs::remove_dir_all(&dir);
8636 }
8637 }
8638
8639 #[test]
8640 fn prefix_arena_count_parallel_matches_serial() {
8641 let dir = count_store_dir("arena");
8642 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
8643 for i in 0..120u64 {
8644 store
8645 .insert_quad_version(
8646 &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
8647 CommitTs(1),
8648 StorageOp::Put,
8649 VisibilityLabel::default(),
8650 )
8651 .unwrap();
8652 }
8653 store.flush_memtables().unwrap();
8654 let subject = EncodedTerm::from(&NamedNode::new("http://ex/s7").unwrap());
8655 let pattern = EncodedTriplePattern {
8656 subject: Some(subject),
8657 predicate: None,
8658 object: None,
8659 graph_name: None,
8660 };
8661 let serial = count_run(
8662 &store,
8663 CountWalkMode::Serial,
8664 IndexPermutation::Spog,
8665 &pattern,
8666 SnapshotId(9),
8667 0,
8668 &GByteFilter::Unconstrained,
8669 false,
8670 &[],
8671 );
8672 assert_eq!(serial, 1, "one quad for s7 in the Spog CF");
8673 for workers in [2usize, 5, 64] {
8674 let parallel = count_run(
8675 &store,
8676 CountWalkMode::Parallel(workers),
8677 IndexPermutation::Spog,
8678 &pattern,
8679 SnapshotId(9),
8680 0,
8681 &GByteFilter::Unconstrained,
8682 false,
8683 &[],
8684 );
8685 assert_eq!(parallel, serial, "K={workers}");
8686 }
8687 drop(store);
8688 let _ = std::fs::remove_dir_all(&dir);
8689 }
8690
8691 #[test]
8697 fn version_group_straddle_skip_decides_once() {
8698 let dir = count_store_dir("straddle");
8699 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
8700 let q = Quad::new(
8701 NamedNode::new("http://ex/q").unwrap(),
8702 NamedNode::new("http://ex/p").unwrap(),
8703 NamedNode::new("http://ex/oq").unwrap(),
8704 GraphName::DefaultGraph,
8705 );
8706 let r = Quad::new(
8707 NamedNode::new("http://ex/r").unwrap(),
8708 NamedNode::new("http://ex/p").unwrap(),
8709 NamedNode::new("http://ex/or").unwrap(),
8710 GraphName::DefaultGraph,
8711 );
8712 let q_enc = EncodedQuad::from(&q);
8713 store
8714 .insert_quad_version(&q, CommitTs(10), StorageOp::Put, VisibilityLabel::default())
8715 .unwrap();
8716 store
8717 .insert_quad_version(&q, CommitTs(20), StorageOp::Put, VisibilityLabel::default())
8718 .unwrap();
8719 store
8720 .insert_quad_version(
8721 &q,
8722 CommitTs(30),
8723 StorageOp::Delete,
8724 VisibilityLabel::default(),
8725 )
8726 .unwrap();
8727 store
8728 .insert_quad_version(&r, CommitTs(5), StorageOp::Put, VisibilityLabel::default())
8729 .unwrap();
8730 store.flush_memtables().unwrap();
8731
8732 let pattern = unbound_pattern();
8733 let serial = count_run(
8734 &store,
8735 CountWalkMode::Serial,
8736 IndexPermutation::Spog,
8737 &pattern,
8738 SnapshotId(100),
8739 0,
8740 &GByteFilter::Unconstrained,
8741 false,
8742 &[],
8743 );
8744 assert_eq!(serial, 1, "Q retired by its newest Delete; only R remains");
8745
8746 let mid_group = encode_versioned_key(IndexPermutation::Spog, &q_enc, CommitTs(20));
8750 let cf = store.cf_for(IndexPermutation::Spog).unwrap();
8751 let head = count_walk_slice(
8752 &store.db,
8753 cf,
8754 IndexPermutation::Spog,
8755 &pattern,
8756 SnapshotId(100),
8757 &GByteFilter::Unconstrained,
8758 false,
8759 &[],
8760 &CountSlice {
8761 start: Vec::new(),
8762 end: Some(mid_group.clone()),
8763 },
8764 true,
8765 )
8766 .unwrap();
8767 let tail = count_walk_slice(
8768 &store.db,
8769 cf,
8770 IndexPermutation::Spog,
8771 &pattern,
8772 SnapshotId(100),
8773 &GByteFilter::Unconstrained,
8774 false,
8775 &[],
8776 &CountSlice {
8777 start: mid_group,
8778 end: None,
8779 },
8780 false,
8781 )
8782 .unwrap();
8783 assert_eq!(
8784 head + tail,
8785 serial,
8786 "split inside the group must not double-count"
8787 );
8788 drop(store);
8789 let _ = std::fs::remove_dir_all(&dir);
8790 }
8791
8792 #[test]
8800 fn straddle_between_versions_owner_crosses_its_end() {
8801 let dir = count_store_dir("straddle-cross");
8802 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
8803 let q = Quad::new(
8804 NamedNode::new("http://ex/qx").unwrap(),
8805 NamedNode::new("http://ex/p").unwrap(),
8806 NamedNode::new("http://ex/ox").unwrap(),
8807 GraphName::DefaultGraph,
8808 );
8809 for ts in [10u64, 50, 90] {
8810 store
8811 .insert_quad_version(&q, CommitTs(ts), StorageOp::Put, VisibilityLabel::default())
8812 .unwrap();
8813 }
8814 store.flush_memtables().unwrap();
8815 let pattern = unbound_pattern();
8816 let serial = count_run(
8817 &store,
8818 CountWalkMode::Serial,
8819 IndexPermutation::Spog,
8820 &pattern,
8821 SnapshotId(60),
8822 0,
8823 &GByteFilter::Unconstrained,
8824 false,
8825 &[],
8826 );
8827 assert_eq!(serial, 1, "snapshot 60 sees exactly the ts=50 version");
8828
8829 let newest =
8835 encode_versioned_key(IndexPermutation::Spog, &EncodedQuad::from(&q), CommitTs(90));
8836 let boundary = {
8837 let mut b = newest.clone();
8838 b.push(0x00);
8839 b
8840 };
8841 let cf = store.cf_for(IndexPermutation::Spog).unwrap();
8842 let head = count_walk_slice(
8843 &store.db,
8844 cf,
8845 IndexPermutation::Spog,
8846 &pattern,
8847 SnapshotId(60),
8848 &GByteFilter::Unconstrained,
8849 false,
8850 &[],
8851 &CountSlice {
8852 start: Vec::new(),
8853 end: Some(boundary.clone()),
8854 },
8855 true,
8856 )
8857 .unwrap();
8858 let tail = count_walk_slice(
8859 &store.db,
8860 cf,
8861 IndexPermutation::Spog,
8862 &pattern,
8863 SnapshotId(60),
8864 &GByteFilter::Unconstrained,
8865 false,
8866 &[],
8867 &CountSlice {
8868 start: boundary,
8869 end: None,
8870 },
8871 false,
8872 )
8873 .unwrap();
8874 assert_eq!(
8875 head, 1,
8876 "owner crosses its end and emits the visible version"
8877 );
8878 assert_eq!(tail, 0, "the straddled group is skipped, not re-decided");
8879 assert_eq!(head + tail, serial);
8880 drop(store);
8881 let _ = std::fs::remove_dir_all(&dir);
8882 }
8883
8884 #[test]
8892 fn straddle_skip_spares_sibling_graph_variants() {
8893 let dir = count_store_dir("straddle-sib");
8894 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
8895 let dg = Quad::new(
8896 NamedNode::new("http://ex/qs").unwrap(),
8897 NamedNode::new("http://ex/p").unwrap(),
8898 NamedNode::new("http://ex/od").unwrap(),
8899 GraphName::DefaultGraph,
8900 );
8901 let named = Quad::new(
8902 NamedNode::new("http://ex/qs").unwrap(),
8903 NamedNode::new("http://ex/p").unwrap(),
8904 NamedNode::new("http://ex/od").unwrap(),
8905 GraphName::NamedNode(NamedNode::new("http://ex/g").unwrap()),
8906 );
8907 store
8908 .insert_quad_version(
8909 &dg,
8910 CommitTs(10),
8911 StorageOp::Put,
8912 VisibilityLabel::default(),
8913 )
8914 .unwrap();
8915 store
8916 .insert_quad_version(
8917 &dg,
8918 CommitTs(20),
8919 StorageOp::Delete,
8920 VisibilityLabel::default(),
8921 )
8922 .unwrap();
8923 store
8924 .insert_quad_version(
8925 &named,
8926 CommitTs(5),
8927 StorageOp::Put,
8928 VisibilityLabel::default(),
8929 )
8930 .unwrap();
8931 store.flush_memtables().unwrap();
8932 let pattern = unbound_pattern();
8933 let serial = count_run(
8934 &store,
8935 CountWalkMode::Serial,
8936 IndexPermutation::Spog,
8937 &pattern,
8938 SnapshotId(100),
8939 0,
8940 &GByteFilter::Unconstrained,
8941 false,
8942 &[],
8943 );
8944 assert_eq!(
8945 serial, 1,
8946 "default-graph group retired by its newest Delete; named variant counts"
8947 );
8948
8949 let tail_start = encode_versioned_key(
8952 IndexPermutation::Spog,
8953 &EncodedQuad::from(&dg),
8954 CommitTs(10),
8955 );
8956 let cf = store.cf_for(IndexPermutation::Spog).unwrap();
8957 let head = count_walk_slice(
8958 &store.db,
8959 cf,
8960 IndexPermutation::Spog,
8961 &pattern,
8962 SnapshotId(100),
8963 &GByteFilter::Unconstrained,
8964 false,
8965 &[],
8966 &CountSlice {
8967 start: Vec::new(),
8968 end: Some(tail_start.clone()),
8969 },
8970 true,
8971 )
8972 .unwrap();
8973 let tail = count_walk_slice(
8974 &store.db,
8975 cf,
8976 IndexPermutation::Spog,
8977 &pattern,
8978 SnapshotId(100),
8979 &GByteFilter::Unconstrained,
8980 false,
8981 &[],
8982 &CountSlice {
8983 start: tail_start,
8984 end: None,
8985 },
8986 false,
8987 )
8988 .unwrap();
8989 assert_eq!(head + tail, serial, "named variant counted exactly once");
8990 drop(store);
8991 let _ = std::fs::remove_dir_all(&dir);
8992 }
8993
8994 #[test]
8999 fn merge_default_graph_parallel_matches_serial() {
9000 let dir = count_store_dir("merge");
9001 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
9002 for i in 0..40u64 {
9003 store
9004 .insert_quad_version(
9005 &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
9006 CommitTs(1),
9007 StorageOp::Put,
9008 VisibilityLabel::default(),
9009 )
9010 .unwrap();
9011 }
9012 store.flush_memtables().unwrap();
9013 let pattern = unbound_pattern();
9014 let serial = count_run(
9015 &store,
9016 CountWalkMode::Serial,
9017 IndexPermutation::Spog,
9018 &pattern,
9019 SnapshotId(9),
9020 0,
9021 &GByteFilter::Unconstrained,
9022 true,
9023 &[],
9024 );
9025 assert_eq!(serial, 40);
9026 let parallel = count_run(
9027 &store,
9028 CountWalkMode::Parallel(4),
9029 IndexPermutation::Spog,
9030 &pattern,
9031 SnapshotId(9),
9032 0,
9033 &GByteFilter::Unconstrained,
9034 true,
9035 &[],
9036 );
9037 assert_eq!(parallel, serial);
9038 drop(store);
9039 let _ = std::fs::remove_dir_all(&dir);
9040 }
9041
9042 #[test]
9048 fn snapshot_visibility_identical_across_split() {
9049 let dir = count_store_dir("snapshot");
9050 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
9051 let q = Quad::new(
9052 NamedNode::new("http://ex/q2").unwrap(),
9053 NamedNode::new("http://ex/p").unwrap(),
9054 NamedNode::new("http://ex/o").unwrap(),
9055 GraphName::DefaultGraph,
9056 );
9057 for ts in [10u64, 50, 90] {
9058 store
9059 .insert_quad_version(&q, CommitTs(ts), StorageOp::Put, VisibilityLabel::default())
9060 .unwrap();
9061 }
9062 store.flush_memtables().unwrap();
9063 let pattern = unbound_pattern();
9064 let serial = count_run(
9065 &store,
9066 CountWalkMode::Serial,
9067 IndexPermutation::Spog,
9068 &pattern,
9069 SnapshotId(60),
9070 0,
9071 &GByteFilter::Unconstrained,
9072 false,
9073 &[],
9074 );
9075 assert_eq!(serial, 1);
9076 let newest =
9077 encode_versioned_key(IndexPermutation::Spog, &EncodedQuad::from(&q), CommitTs(90));
9078 let cf = store.cf_for(IndexPermutation::Spog).unwrap();
9079 let head = count_walk_slice(
9080 &store.db,
9081 cf,
9082 IndexPermutation::Spog,
9083 &pattern,
9084 SnapshotId(60),
9085 &GByteFilter::Unconstrained,
9086 false,
9087 &[],
9088 &CountSlice {
9089 start: Vec::new(),
9090 end: Some(newest.clone()),
9091 },
9092 true,
9093 )
9094 .unwrap();
9095 let tail = count_walk_slice(
9096 &store.db,
9097 cf,
9098 IndexPermutation::Spog,
9099 &pattern,
9100 SnapshotId(60),
9101 &GByteFilter::Unconstrained,
9102 false,
9103 &[],
9104 &CountSlice {
9105 start: newest,
9106 end: None,
9107 },
9108 false,
9109 )
9110 .unwrap();
9111 assert_eq!(
9112 head, 0,
9113 "the boundary sits on the group's newest key, so every group key sorts at or after it and the head slice holds none"
9114 );
9115 assert_eq!(
9116 tail, 1,
9117 "the tail owns the group: the too-new newest is transparent, then the visible version emits"
9118 );
9119 assert_eq!(head + tail, serial);
9120 drop(store);
9121 let _ = std::fs::remove_dir_all(&dir);
9122 }
9123
9124 #[test]
9128 fn tsg_full_axis_hint_slices_match_serial() {
9129 let dir = count_store_dir("tsg-hint");
9130 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
9131 for i in 0..40u64 {
9132 store
9133 .insert_quad_version(
9134 &rdf_type_spo(&format!("a{i}"), "A"),
9135 CommitTs(1),
9136 StorageOp::Put,
9137 VisibilityLabel::default(),
9138 )
9139 .unwrap();
9140 }
9141 for i in 0..4u64 {
9142 store
9143 .insert_quad_version(
9144 &rdf_type_spo(&format!("b{i}"), "B"),
9145 CommitTs(1),
9146 StorageOp::Put,
9147 VisibilityLabel::default(),
9148 )
9149 .unwrap();
9150 }
9151 store.flush_memtables().unwrap();
9152 let pattern = EncodedTriplePattern {
9153 subject: None,
9154 predicate: Some(crate::RDF_TYPE),
9155 object: None,
9156 graph_name: None,
9157 };
9158 let serial = count_run(
9159 &store,
9160 CountWalkMode::Serial,
9161 IndexPermutation::Tsg,
9162 &pattern,
9163 SnapshotId(9),
9164 0,
9165 &GByteFilter::Unconstrained,
9166 false,
9167 &[],
9168 );
9169 assert_eq!(serial, 44);
9170
9171 let hash_a = StrHash::new("http://ex/A");
9172 let hash_b = StrHash::new("http://ex/B");
9173 let mut hint = vec![(hash_a, 40u64), (hash_b, 4u64)];
9174 hint.sort_by_key(|(hash, _)| *hash);
9175 for (label, totals) in [
9176 ("hint", hint.as_slice()),
9177 ("empty", &[][..]),
9178 ("stale-zeros", &[(hash_a, 0), (hash_b, 0)][..]),
9179 ] {
9180 for workers in [2usize, 8, 64] {
9181 let parallel = count_run(
9182 &store,
9183 CountWalkMode::Parallel(workers),
9184 IndexPermutation::Tsg,
9185 &pattern,
9186 SnapshotId(9),
9187 0,
9188 &GByteFilter::Unconstrained,
9189 false,
9190 totals,
9191 );
9192 assert_eq!(parallel, serial, "{label} K={workers}");
9193 }
9194 }
9195 drop(store);
9196 let _ = std::fs::remove_dir_all(&dir);
9197 }
9198
9199 #[test]
9202 fn tsg_class_arena_count_parallel_matches_serial() {
9203 let dir = count_store_dir("tsg-arena");
9204 let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
9205 let class_a = EncodedTerm::from(&NamedNode::new("http://ex/Identification").unwrap());
9206 for i in 0..50u64 {
9207 store
9208 .insert_quad_version(
9209 &rdf_type_spo(&format!("i{i}"), "Identification"),
9210 CommitTs(1),
9211 StorageOp::Put,
9212 VisibilityLabel::default(),
9213 )
9214 .unwrap();
9215 }
9216 for i in 0..10u64 {
9217 store
9218 .insert_quad_version(
9219 &rdf_type_spo(&format!("o{i}"), "Occurrence"),
9220 CommitTs(1),
9221 StorageOp::Put,
9222 VisibilityLabel::default(),
9223 )
9224 .unwrap();
9225 }
9226 store.flush_memtables().unwrap();
9227 let pattern = EncodedTriplePattern {
9228 subject: None,
9229 predicate: Some(crate::RDF_TYPE),
9230 object: Some(class_a),
9231 graph_name: None,
9232 };
9233 let serial = count_run(
9234 &store,
9235 CountWalkMode::Serial,
9236 IndexPermutation::Tsg,
9237 &pattern,
9238 SnapshotId(9),
9239 0,
9240 &GByteFilter::Unconstrained,
9241 false,
9242 &[],
9243 );
9244 assert_eq!(serial, 50);
9245 for workers in [2usize, 6, 32] {
9246 let parallel = count_run(
9247 &store,
9248 CountWalkMode::Parallel(workers),
9249 IndexPermutation::Tsg,
9250 &pattern,
9251 SnapshotId(9),
9252 0,
9253 &GByteFilter::Unconstrained,
9254 false,
9255 &[],
9256 );
9257 assert_eq!(parallel, serial, "K={workers}");
9258 }
9259 drop(store);
9260 let _ = std::fs::remove_dir_all(&dir);
9261 }
9262
9263 #[test]
9264 fn count_with_limit_stays_exact() {
9265 let dir = count_store_dir("limit");
9266 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
9267 for i in 0..50u64 {
9268 store
9269 .insert_quad_version(
9270 &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
9271 CommitTs(1),
9272 StorageOp::Put,
9273 VisibilityLabel::default(),
9274 )
9275 .unwrap();
9276 }
9277 store.flush_memtables().unwrap();
9278 let pattern = unbound_pattern();
9279 for mode in [CountWalkMode::Serial, CountWalkMode::Parallel(4)] {
9282 let count = count_run(
9283 &store,
9284 mode,
9285 IndexPermutation::Spog,
9286 &pattern,
9287 SnapshotId(9),
9288 5,
9289 &GByteFilter::Unconstrained,
9290 false,
9291 &[],
9292 );
9293 assert_eq!(count, 5, "mode {mode:?}");
9294 }
9295 drop(store);
9296 let _ = std::fs::remove_dir_all(&dir);
9297 }
9298
9299 #[test]
9300 fn empty_store_parallel_count_is_zero() {
9301 let dir = count_store_dir("empty");
9302 let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
9303 let pattern = unbound_pattern();
9304 for workers in [2usize, 64] {
9305 let count = count_run(
9306 &store,
9307 CountWalkMode::Parallel(workers),
9308 IndexPermutation::Spog,
9309 &pattern,
9310 SnapshotId(9),
9311 0,
9312 &GByteFilter::Unconstrained,
9313 false,
9314 &[],
9315 );
9316 assert_eq!(count, 0, "K={workers}");
9317 }
9318 drop(store);
9319 let _ = std::fs::remove_dir_all(&dir);
9320 }
9321}