1use std::collections::{BTreeMap, BTreeSet};
4
5use waratah_storage::{EncodedTriplePattern, PartitionAxis, RDF_TYPE, StrHash};
6
7use crate::cms::CountMinSketch;
8use crate::hll::HyperLogLog;
9use crate::observe::{named_node_hash, term_key};
10
11pub const PUSHDOWN_TERMS_LIMIT: u64 = 24_576;
38
39pub const GRAPH_FILTER_TERM_CAP: u64 = 10_000;
41
42pub const STATS_WIRE_BUDGET_BYTES: usize = 3 * 1024 * 1024;
67
68pub const GEO_FINE_FRAME_BUDGET_BYTES: usize = 1792 * 1024;
81
82pub const GEO_COARSE_FRAME_BUDGET_BYTES: usize = 1792 * 1024;
92
93pub const GEO_REMAINDER_WIRE_BUDGET_BYTES: usize = 512 * 1024;
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum JoinKeySlot {
109 Subject,
111 Object,
113}
114
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
122pub struct ExtraBoundSlots {
123 pub subject: bool,
125 pub predicate: bool,
127 pub object: bool,
129 pub graph: bool,
131}
132
133impl ExtraBoundSlots {
134 pub fn count(self) -> usize {
136 usize::from(self.subject)
137 + usize::from(self.predicate)
138 + usize::from(self.object)
139 + usize::from(self.graph)
140 }
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum JoinStrategy {
146 Hash,
148 Broadcast,
150 Shuffle,
152 Semi,
160 SemiScan,
171}
172
173impl JoinStrategy {
174 pub fn from_cardinalities(left: u64, right: u64) -> Self {
176 Self::from_estimated_sizes(left, right)
177 }
178
179 pub fn from_cardinalities_and_domains(
184 left_rows: u64,
185 right_rows: u64,
186 left_domain: Option<u64>,
187 right_domain: Option<u64>,
188 ) -> Self {
189 let left = match left_domain {
190 Some(d) => d.min(left_rows).max(1),
191 None => left_rows,
192 };
193 let right = match right_domain {
194 Some(d) => d.min(right_rows).max(1),
195 None => right_rows,
196 };
197 Self::from_estimated_sizes(left, right)
198 }
199
200 fn from_estimated_sizes(left: u64, right: u64) -> Self {
201 if left > 0 && left <= PUSHDOWN_TERMS_LIMIT {
211 Self::Broadcast
212 } else if right > 0 && right <= PUSHDOWN_TERMS_LIMIT {
213 Self::Hash
215 } else if left > PUSHDOWN_TERMS_LIMIT && right > PUSHDOWN_TERMS_LIMIT {
216 Self::Shuffle
217 } else {
218 Self::Hash
219 }
220 }
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
235pub struct StatsProfile {
236 pub total_puts: u64,
238 pub predicate_counts: BTreeMap<StrHash, u64>,
240 pub class_counts: BTreeMap<StrHash, u64>,
242 pub subject_cms: CountMinSketch,
244 pub object_cms: CountMinSketch,
246 pub subjects_per_predicate: BTreeMap<StrHash, HyperLogLog>,
248 pub objects_per_predicate: BTreeMap<StrHash, HyperLogLog>,
250 pub subject_domains_per_predicate: BTreeMap<StrHash, u64>,
265 pub object_domains_per_predicate: BTreeMap<StrHash, u64>,
268 pub named_graph_count: u64,
273 pub temporal_histogram: crate::tick_histogram::TickHistogram,
278 pub geo_cell_histogram: crate::geo_cell_histogram::GeoCellHistogram,
283 pub text_seed_sketch: crate::text_seed_sketch::TextSeedSketch,
290}
291
292impl Default for StatsProfile {
293 fn default() -> Self {
294 Self {
295 total_puts: 0,
296 predicate_counts: BTreeMap::new(),
297 class_counts: BTreeMap::new(),
298 subject_cms: CountMinSketch::default_params(),
299 object_cms: CountMinSketch::default_params(),
300 subjects_per_predicate: BTreeMap::new(),
301 objects_per_predicate: BTreeMap::new(),
302 subject_domains_per_predicate: BTreeMap::new(),
303 object_domains_per_predicate: BTreeMap::new(),
304 named_graph_count: 0,
305 temporal_histogram: crate::tick_histogram::TickHistogram::default(),
306 geo_cell_histogram: crate::geo_cell_histogram::GeoCellHistogram::default(),
307 text_seed_sketch: crate::text_seed_sketch::TextSeedSketch::empty(),
308 }
309 }
310}
311
312impl StatsProfile {
313 pub fn has_predicate_sketch(&self, pattern: &EncodedTriplePattern) -> bool {
322 match pattern.predicate.as_ref().and_then(named_node_hash) {
323 Some(pred) => self.predicate_counts.contains_key(&pred),
324 None => true,
325 }
326 }
327
328 pub fn is_empty(&self) -> bool {
330 self.total_puts == 0
331 && self.predicate_counts.is_empty()
332 && self.class_counts.is_empty()
333 && self.named_graph_count == 0
334 }
335 pub fn capped_for_wire(&self) -> Self {
352 self.capped_for_wire_with_budget(STATS_WIRE_BUDGET_BYTES)
353 }
354
355 pub fn capped_geo_histogram_for_wire(&self) -> crate::geo_cell_histogram::GeoCellHistogram {
371 let mut trimmed = self.geo_cell_histogram.capped_for_wire(
372 crate::GEO_FINE_FRAME_BUDGET_BYTES,
373 crate::GEO_REMAINDER_WIRE_BUDGET_BYTES,
374 );
375 trimmed.coarse = self
376 .geo_cell_histogram
377 .capped_coarse_map(crate::GEO_COARSE_FRAME_BUDGET_BYTES);
378 trimmed
379 }
380
381 pub fn capped_for_wire_with_budget(&self, budget: usize) -> Self {
389 let mut capped = self.clone();
390 capped.subjects_per_predicate.clear();
391 capped.objects_per_predicate.clear();
392 capped.geo_cell_histogram = crate::geo_cell_histogram::GeoCellHistogram::default();
393 capped.text_seed_sketch = crate::text_seed_sketch::TextSeedSketch::empty();
394 capped.temporal_histogram = crate::tick_histogram::TickHistogram::default();
395 let fixed_bytes = crate::serde_bin::to_bytes(&capped).len();
398 let mut remaining = budget.saturating_sub(fixed_bytes);
399
400 let mut ranked: Vec<(StrHash, u64)> = self
404 .subjects_per_predicate
405 .keys()
406 .chain(self.objects_per_predicate.keys())
407 .collect::<BTreeSet<_>>()
408 .into_iter()
409 .map(|hash| (*hash, self.predicate_counts.get(hash).copied().unwrap_or(0)))
410 .collect();
411 ranked.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
412
413 for (hash, _) in ranked {
414 let cost = hll_wire_entry_bytes(self.subjects_per_predicate.get(&hash))
415 + hll_wire_entry_bytes(self.objects_per_predicate.get(&hash));
416 if cost > remaining {
417 break;
419 }
420 if let Some(hll) = self.subjects_per_predicate.get(&hash) {
421 capped.subjects_per_predicate.insert(hash, hll.clone());
422 }
423 if let Some(hll) = self.objects_per_predicate.get(&hash) {
424 capped.objects_per_predicate.insert(hash, hll.clone());
425 }
426 remaining -= cost;
427 }
428 capped.subject_domains_per_predicate.clear();
433 capped.object_domains_per_predicate.clear();
434 capped
435 }
436
437 pub fn derive_hll_domains(&mut self) {
449 self.subject_domains_per_predicate = self
450 .subjects_per_predicate
451 .iter()
452 .map(|(hash, hll)| (*hash, hll.cardinality().max(1)))
453 .collect();
454 self.object_domains_per_predicate = self
455 .objects_per_predicate
456 .iter()
457 .map(|(hash, hll)| (*hash, hll.cardinality().max(1)))
458 .collect();
459 }
460
461 pub fn subject_domain(&self, hash: &StrHash) -> Option<u64> {
470 if let Some(domain) = self.subject_domains_per_predicate.get(hash) {
471 return Some(*domain);
472 }
473 Some(self.subjects_per_predicate.get(hash)?.cardinality().max(1))
474 }
475
476 pub fn object_domain(&self, hash: &StrHash) -> Option<u64> {
478 if let Some(domain) = self.object_domains_per_predicate.get(hash) {
479 return Some(*domain);
480 }
481 Some(self.objects_per_predicate.get(hash)?.cardinality().max(1))
482 }
483
484 pub fn merge(&mut self, other: &Self) -> Result<(), crate::StatsError> {
486 self.subject_domains_per_predicate.clear();
492 self.object_domains_per_predicate.clear();
493 self.total_puts = self.total_puts.saturating_add(other.total_puts);
494 for (k, v) in &other.predicate_counts {
495 *self.predicate_counts.entry(*k).or_insert(0) = self
496 .predicate_counts
497 .get(k)
498 .copied()
499 .unwrap_or(0)
500 .saturating_add(*v);
501 }
502 for (k, v) in &other.class_counts {
503 *self.class_counts.entry(*k).or_insert(0) = self
504 .class_counts
505 .get(k)
506 .copied()
507 .unwrap_or(0)
508 .saturating_add(*v);
509 }
510 self.subject_cms.merge(&other.subject_cms)?;
511 self.object_cms.merge(&other.object_cms)?;
512 for (k, hll) in &other.subjects_per_predicate {
513 self.subjects_per_predicate
514 .entry(*k)
515 .or_insert_with(HyperLogLog::default_params)
516 .merge(hll)?;
517 }
518 for (k, hll) in &other.objects_per_predicate {
519 self.objects_per_predicate
520 .entry(*k)
521 .or_insert_with(HyperLogLog::default_params)
522 .merge(hll)?;
523 }
524 self.named_graph_count = self
525 .named_graph_count
526 .saturating_add(other.named_graph_count);
527 self.temporal_histogram.merge(&other.temporal_histogram);
528 self.geo_cell_histogram.merge(&other.geo_cell_histogram);
529 self.text_seed_sketch.merge(&other.text_seed_sketch);
530 Ok(())
531 }
532
533 pub fn estimate(&self, pattern: &EncodedTriplePattern) -> u64 {
535 estimate_pattern(self, pattern)
536 }
537
538 pub fn estimate_with_bound_slots(
540 &self,
541 pattern: &EncodedTriplePattern,
542 extra: ExtraBoundSlots,
543 ) -> u64 {
544 estimate_pattern_with_bound_slots(self, pattern, extra)
545 }
546
547 pub fn join_key_domain(
551 &self,
552 pattern: &EncodedTriplePattern,
553 slot: JoinKeySlot,
554 ) -> Option<u64> {
555 estimate_join_key_domain(self, pattern, slot)
556 }
557}
558
559#[derive(Debug, Clone, PartialEq, Eq)]
572pub struct LiveQuadsProfile {
573 pub total_puts: u64,
575 pub predicate_counts: BTreeMap<StrHash, u64>,
577 pub class_counts: BTreeMap<StrHash, u64>,
579 pub subject_cms: CountMinSketch,
581 pub object_cms: CountMinSketch,
583 pub subjects_per_predicate: BTreeMap<StrHash, HyperLogLog>,
585 pub objects_per_predicate: BTreeMap<StrHash, HyperLogLog>,
587}
588
589impl Default for LiveQuadsProfile {
590 fn default() -> Self {
591 Self {
592 total_puts: 0,
593 predicate_counts: BTreeMap::new(),
594 class_counts: BTreeMap::new(),
595 subject_cms: CountMinSketch::default_params(),
596 object_cms: CountMinSketch::default_params(),
597 subjects_per_predicate: BTreeMap::new(),
598 objects_per_predicate: BTreeMap::new(),
599 }
600 }
601}
602
603impl LiveQuadsProfile {
604 pub fn is_empty(&self) -> bool {
606 self.total_puts == 0 && self.predicate_counts.is_empty() && self.class_counts.is_empty()
607 }
608
609 pub fn merge(&mut self, other: &Self) -> Result<(), crate::StatsError> {
612 self.total_puts = self.total_puts.saturating_add(other.total_puts);
613 for (k, v) in &other.predicate_counts {
614 *self.predicate_counts.entry(*k).or_insert(0) = self
615 .predicate_counts
616 .get(k)
617 .copied()
618 .unwrap_or(0)
619 .saturating_add(*v);
620 }
621 for (k, v) in &other.class_counts {
622 *self.class_counts.entry(*k).or_insert(0) = self
623 .class_counts
624 .get(k)
625 .copied()
626 .unwrap_or(0)
627 .saturating_add(*v);
628 }
629 self.subject_cms.merge(&other.subject_cms)?;
630 self.object_cms.merge(&other.object_cms)?;
631 for (k, hll) in &other.subjects_per_predicate {
632 self.subjects_per_predicate
633 .entry(*k)
634 .or_insert_with(HyperLogLog::default_params)
635 .merge(hll)?;
636 }
637 for (k, hll) in &other.objects_per_predicate {
638 self.objects_per_predicate
639 .entry(*k)
640 .or_insert_with(HyperLogLog::default_params)
641 .merge(hll)?;
642 }
643 Ok(())
644 }
645}
646
647impl From<&LiveQuadsProfile> for StatsProfile {
648 fn from(live: &LiveQuadsProfile) -> Self {
649 Self {
650 total_puts: live.total_puts,
651 predicate_counts: live.predicate_counts.clone(),
652 class_counts: live.class_counts.clone(),
653 subject_cms: live.subject_cms.clone(),
654 object_cms: live.object_cms.clone(),
655 subjects_per_predicate: live.subjects_per_predicate.clone(),
656 objects_per_predicate: live.objects_per_predicate.clone(),
657 subject_domains_per_predicate: BTreeMap::new(),
660 object_domains_per_predicate: BTreeMap::new(),
661 named_graph_count: 0,
664 temporal_histogram: crate::tick_histogram::TickHistogram::default(),
665 geo_cell_histogram: crate::geo_cell_histogram::GeoCellHistogram::default(),
666 text_seed_sketch: crate::text_seed_sketch::TextSeedSketch::empty(),
667 }
668 }
669}
670
671impl From<LiveQuadsProfile> for StatsProfile {
672 fn from(live: LiveQuadsProfile) -> Self {
673 Self::from(&live)
674 }
675}
676
677pub fn estimate_pattern(profile: &StatsProfile, pattern: &EncodedTriplePattern) -> u64 {
687 estimate_pattern_with_bound_slots(profile, pattern, ExtraBoundSlots::default())
688}
689
690pub fn estimate_pattern_with_bound_slots(
697 profile: &StatsProfile,
698 pattern: &EncodedTriplePattern,
699 extra: ExtraBoundSlots,
700) -> u64 {
701 let s = pattern.subject.as_ref();
702 let p = pattern.predicate.as_ref();
703 let o = pattern.object.as_ref();
704 let s_bound = s.is_some() || extra.subject;
705 let o_bound = o.is_some() || extra.object;
706
707 if s.is_some() && p.is_some() && o.is_some() {
711 return 1;
712 }
713
714 if p.is_some_and(|pred| pred == &RDF_TYPE)
717 && let Some(obj) = o
718 && let Some(class) = named_node_hash(obj)
719 {
720 return profile
721 .class_counts
722 .get(&class)
723 .copied()
724 .unwrap_or(0)
725 .max(1);
726 }
727
728 let mut candidates = Vec::new();
729
730 let pred_hash = p.and_then(named_node_hash);
731 let pred_count = pred_hash.and_then(|h| profile.predicate_counts.get(&h).copied());
732
733 if pred_hash.is_some() {
738 candidates.push(pred_count.unwrap_or(0).max(1));
739 }
740 if extra.predicate && pred_hash.is_none() {
743 let n_preds = profile.predicate_counts.len().max(1) as u64;
744 candidates.push((profile.total_puts / n_preds).max(1));
745 }
746 if let Some(obj) = o {
747 candidates.push(profile.object_cms.estimate(term_key(obj)).max(1));
748 }
749 if let Some(sub) = s {
750 candidates.push(profile.subject_cms.estimate(term_key(sub)).max(1));
751 }
752
753 if let (Some(hash), Some(pc)) = (pred_hash, pred_count) {
757 if s_bound && !o_bound {
758 if let Some(distinct_s) = profile.subject_domain(&hash) {
760 candidates.push((pc / distinct_s).max(1));
761 }
762 }
763 if o_bound && !s_bound {
764 if let Some(distinct_o) = profile.object_domain(&hash) {
766 candidates.push((pc / distinct_o).max(1));
767 }
768 }
769 }
770
771 if candidates.is_empty() {
772 return profile.total_puts.max(1);
773 }
774 let mut estimate = candidates.into_iter().min().unwrap_or(1);
775 if !s_bound
789 && !o_bound
790 && let Some(hash) = pred_hash
791 {
792 if let Some(domain) = profile.subject_domain(&hash) {
793 estimate = estimate.max(domain);
794 }
795 if let Some(domain) = profile.object_domain(&hash) {
796 estimate = estimate.max(domain);
797 }
798 }
799 estimate.max(1)
800}
801
802pub fn estimate_join_key_domain(
827 profile: &StatsProfile,
828 pattern: &EncodedTriplePattern,
829 slot: JoinKeySlot,
830) -> Option<u64> {
831 let pred = pattern.predicate.as_ref()?;
832 if pred == &RDF_TYPE
833 && slot == JoinKeySlot::Subject
834 && let Some(obj) = &pattern.object
835 && let Some(class) = named_node_hash(obj)
836 && let Some(&count) = profile.class_counts.get(&class)
837 && count > 0
838 {
839 return Some(count);
840 }
841 if pred == &RDF_TYPE && slot == JoinKeySlot::Object && !profile.class_counts.is_empty() {
842 return Some(profile.class_counts.len() as u64);
843 }
844 let pred_hash = named_node_hash(pred)?;
845 match slot {
846 JoinKeySlot::Subject => profile.subject_domain(&pred_hash),
847 JoinKeySlot::Object => profile.object_domain(&pred_hash),
848 }
849}
850
851pub const VOCABULARY_OVERLAP_FULL_MILLI: u64 = 1_000;
858
859pub fn estimate_vocabulary_overlap(
897 profile: &StatsProfile,
898 driver_pattern: &EncodedTriplePattern,
899 driver_slot: JoinKeySlot,
900 probe_pattern: &EncodedTriplePattern,
901 probe_slot: JoinKeySlot,
902) -> Option<u64> {
903 if driver_slot == probe_slot
908 && driver_pattern.predicate.is_some()
909 && driver_pattern.predicate == probe_pattern.predicate
910 {
911 return Some(VOCABULARY_OVERLAP_FULL_MILLI);
912 }
913 if driver_pattern.predicate.as_ref() == Some(&RDF_TYPE)
920 || probe_pattern.predicate.as_ref() == Some(&RDF_TYPE)
921 {
922 return None;
923 }
924 let driver_pred = named_node_hash(driver_pattern.predicate.as_ref()?)?;
925 let probe_pred = named_node_hash(probe_pattern.predicate.as_ref()?)?;
926 let sketch = |pred: &StrHash, slot: JoinKeySlot| -> Option<&HyperLogLog> {
927 match slot {
928 JoinKeySlot::Subject => profile.subjects_per_predicate.get(pred),
929 JoinKeySlot::Object => profile.objects_per_predicate.get(pred),
930 }
931 };
932 let driver_hll = sketch(&driver_pred, driver_slot)?;
933 let probe_hll = sketch(&probe_pred, probe_slot)?;
934 if driver_hll.precision() != probe_hll.precision() {
935 return None;
936 }
937 let domain = |pred: &StrHash, slot: JoinKeySlot| -> Option<u64> {
942 match slot {
943 JoinKeySlot::Subject => profile.subject_domain(pred),
944 JoinKeySlot::Object => profile.object_domain(pred),
945 }
946 };
947 let mut union_hll = driver_hll.clone();
954 union_hll.merge(probe_hll).ok()?;
955 let card_a = domain(&driver_pred, driver_slot)?;
956 let card_b = domain(&probe_pred, probe_slot)?;
957 let card_union = union_hll.cardinality();
958 let intersection = card_a
959 .saturating_add(card_b)
960 .saturating_sub(card_union)
961 .min(card_a.min(card_b));
962 Some(intersection.saturating_mul(1000) / card_a)
963}
964
965pub fn estimate_join_rows_multi(
988 left_rows: u64,
989 right_rows: u64,
990 key_domains: &[(Option<u64>, Option<u64>)],
991) -> u64 {
992 let left = left_rows.max(1);
993 let right = right_rows.max(1);
994 let mut divisor: u128 = 1;
995 let mut any_known = false;
996 for (left_domain, right_domain) in key_domains {
997 let left_domain = left_domain.map(|d| d.min(left));
998 let right_domain = right_domain.map(|d| d.min(right));
999 let factor = match (left_domain, right_domain) {
1000 (None, None) => continue,
1001 (Some(l), Some(r)) => l.max(r),
1002 (Some(l), None) | (None, Some(l)) => l,
1003 }
1004 .max(1);
1005 any_known = true;
1006 divisor = divisor.saturating_mul(u128::from(factor));
1007 }
1008 if !any_known {
1009 return left.min(right);
1010 }
1011 let product = (u128::from(left)).saturating_mul(u128::from(right));
1012 u64::try_from(product / divisor).unwrap_or(u64::MAX).max(1)
1013}
1014
1015pub fn estimate_join_rows(
1020 left_rows: u64,
1021 right_rows: u64,
1022 left_domain: Option<u64>,
1023 right_domain: Option<u64>,
1024) -> u64 {
1025 estimate_join_rows_multi(left_rows, right_rows, &[(left_domain, right_domain)])
1026}
1027
1028pub fn bound_slots(pattern: &EncodedTriplePattern) -> usize {
1033 [
1034 pattern.subject.is_some(),
1035 pattern.predicate.is_some(),
1036 pattern.object.is_some(),
1037 pattern.graph_name.is_some(),
1038 ]
1039 .into_iter()
1040 .filter(|b| *b)
1041 .count()
1042}
1043
1044pub fn pattern_is_point_lookup(pattern: &EncodedTriplePattern) -> bool {
1046 bound_slots(pattern) == 4
1047}
1048
1049pub fn rollup_cluster(shards: &[(PartitionAxis, StatsProfile)]) -> StatsProfile {
1059 let mut by_axis: BTreeMap<PartitionAxis, StatsProfile> = BTreeMap::new();
1060 for (axis, profile) in shards {
1061 by_axis
1062 .entry(*axis)
1063 .and_modify(|existing| {
1064 let _ = existing.merge(profile);
1065 })
1066 .or_insert_with(|| profile.clone());
1067 }
1068 let named_graph_count = by_axis
1069 .get(&PartitionAxis::S)
1070 .map(|profile| profile.named_graph_count)
1071 .unwrap_or(0);
1072 for axis in [PartitionAxis::O, PartitionAxis::P, PartitionAxis::S] {
1073 if let Some(mut profile) = by_axis.remove(&axis) {
1074 profile.named_graph_count = named_graph_count;
1075 profile.subject_domains_per_predicate.clear();
1080 profile.object_domains_per_predicate.clear();
1081 return profile;
1082 }
1083 }
1084 StatsProfile::default()
1085}
1086
1087fn hll_wire_entry_bytes(hll: Option<&HyperLogLog>) -> usize {
1091 match hll {
1092 Some(hll) => 16 + 5 + (1usize << hll.precision()),
1093 None => 0,
1094 }
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099 use super::*;
1100 use crate::LiveQuadsProfile;
1101 use crate::observe::{observe_quad, term_key};
1102 use waratah_storage::{EncodedTerm, Literal, NamedNode, StorageOp, encode_quad};
1103
1104 #[test]
1105 fn full_extent_estimate_clamps_to_hll_floor() {
1106 let mut live = LiveQuadsProfile::default();
1112 let pred = NamedNode::new("http://ex/worksAt").unwrap();
1113 let objects: Vec<_> = (0..50)
1114 .map(|i| NamedNode::new(format!("http://ex/org{i}")).unwrap())
1115 .collect();
1116 for i in 0..2000u64 {
1117 let subject = NamedNode::new(format!("http://ex/p{i}")).unwrap();
1118 let q = encode_quad(&waratah_storage::Quad::new(
1119 subject,
1120 pred.clone(),
1121 objects[(i % 50) as usize].clone(),
1122 waratah_storage::GraphName::DefaultGraph,
1123 ))
1124 .unwrap();
1125 observe_quad(&mut live, &q, StorageOp::Put);
1126 }
1127 let mut profile = StatsProfile::from(live);
1128 let pred_hash = named_node_hash(&EncodedTerm::from(&pred)).unwrap();
1129 let subj_floor = profile
1130 .subjects_per_predicate
1131 .get(&pred_hash)
1132 .expect("subject HLL observed")
1133 .cardinality();
1134 let obj_floor = profile
1135 .objects_per_predicate
1136 .get(&pred_hash)
1137 .expect("object HLL observed")
1138 .cardinality();
1139 assert!(
1140 subj_floor > 1_900 && subj_floor < 2_100,
1141 "subj HLL ≈ 2000, got {subj_floor}"
1142 );
1143 assert!(
1144 obj_floor > 45 && obj_floor < 55,
1145 "obj HLL ≈ 50, got {obj_floor}"
1146 );
1147 profile.predicate_counts.insert(pred_hash, 7);
1148
1149 let var_var = EncodedTriplePattern {
1150 subject: None,
1151 predicate: Some(EncodedTerm::from(&pred)),
1152 object: None,
1153 graph_name: None,
1154 };
1155 let estimate = estimate_pattern(&profile, &var_var);
1156 assert_eq!(
1157 estimate,
1158 subj_floor.max(obj_floor),
1159 "full-extent estimate must clamp to the HLL floor, not the corrupted exact count"
1160 );
1161
1162 let bound = EncodedTriplePattern {
1165 subject: None,
1166 predicate: Some(EncodedTerm::from(&pred)),
1167 object: Some(EncodedTerm::from(&objects[3])),
1168 graph_name: None,
1169 };
1170 let bound_estimate = estimate_pattern(&profile, &bound);
1171 assert!(
1172 bound_estimate < subj_floor,
1173 "bound-slot estimate stays small ({bound_estimate}), no full-extent clamp"
1174 );
1175 }
1176
1177 #[test]
1178 fn selective_object_beats_broad_type() {
1179 let mut live = LiveQuadsProfile::default();
1180 let person = NamedNode::new("http://ex/Person").unwrap();
1181 let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
1182 let hometown = NamedNode::new("http://ex/hasHometown").unwrap();
1183 let brisbane = NamedNode::new("http://ex/Brisbane").unwrap();
1184
1185 for i in 0..100 {
1186 let s = NamedNode::new(format!("http://ex/p{i}")).unwrap();
1187 let q = encode_quad(&waratah_storage::Quad::new(
1188 s.clone(),
1189 type_pred.clone(),
1190 person.clone(),
1191 waratah_storage::GraphName::DefaultGraph,
1192 ))
1193 .unwrap();
1194 observe_quad(&mut live, &q, StorageOp::Put);
1195 if i < 5 {
1196 let q2 = encode_quad(&waratah_storage::Quad::new(
1197 s,
1198 hometown.clone(),
1199 brisbane.clone(),
1200 waratah_storage::GraphName::DefaultGraph,
1201 ))
1202 .unwrap();
1203 observe_quad(&mut live, &q2, StorageOp::Put);
1204 }
1205 }
1206 let profile = StatsProfile::from(live);
1207
1208 let pattern_a = EncodedTriplePattern {
1209 subject: None,
1210 predicate: Some(EncodedTerm::from(&type_pred)),
1211 object: Some(EncodedTerm::from(&person)),
1212 graph_name: Some(EncodedTerm::DefaultGraph),
1213 };
1214 let pattern_b = EncodedTriplePattern {
1215 subject: None,
1216 predicate: Some(EncodedTerm::from(&hometown)),
1217 object: Some(EncodedTerm::from(&brisbane)),
1218 graph_name: Some(EncodedTerm::DefaultGraph),
1219 };
1220 let est_a = profile.estimate(&pattern_a);
1221 let est_b = profile.estimate(&pattern_b);
1222 assert!(est_b < est_a, "est_b={est_b} est_a={est_a}");
1223 assert_eq!(est_a, 100);
1224 assert_eq!(est_b, 5);
1225 }
1226
1227 fn profile_with_predicate_pairs(counts: &[(StrHash, u64)]) -> StatsProfile {
1229 let mut profile = StatsProfile::default();
1230 for (hash, count) in counts {
1231 profile.predicate_counts.insert(*hash, *count);
1232 profile
1233 .subjects_per_predicate
1234 .insert(*hash, HyperLogLog::default_params());
1235 profile
1236 .objects_per_predicate
1237 .insert(*hash, HyperLogLog::default_params());
1238 }
1239 profile
1240 }
1241
1242 const PAIR_BYTES: usize = 2 * (16 + 5 + (1 << 12));
1244
1245 #[test]
1246 fn cap_keeps_heaviest_pairs_first_and_respects_budget() {
1247 let heavy = StrHash::new("http://ex/heavy");
1248 let mid = StrHash::new("http://ex/mid");
1249 let light = StrHash::new("http://ex/light");
1250 let profile = profile_with_predicate_pairs(&[(heavy, 1000), (mid, 50), (light, 3)]);
1251
1252 let mut skeleton = profile.clone();
1253 skeleton.subjects_per_predicate.clear();
1254 skeleton.objects_per_predicate.clear();
1255 let base = crate::serde_bin::to_bytes(&skeleton).len();
1256 let budget = base + 2 * PAIR_BYTES;
1258 let capped = profile.capped_for_wire_with_budget(budget);
1259
1260 assert!(crate::serde_bin::to_bytes(&capped).len() <= budget);
1261 assert!(capped.subjects_per_predicate.contains_key(&heavy));
1262 assert!(capped.objects_per_predicate.contains_key(&heavy));
1263 assert!(capped.subjects_per_predicate.contains_key(&mid));
1264 assert!(
1265 !capped.subjects_per_predicate.contains_key(&light),
1266 "the smallest-count pair must be the first dropped"
1267 );
1268 assert_eq!(capped.predicate_counts, profile.predicate_counts);
1270 assert_eq!(capped.subject_cms, profile.subject_cms);
1271 assert_eq!(capped.total_puts, profile.total_puts);
1272 }
1273
1274 #[test]
1275 fn cap_with_room_for_everything_is_identity() {
1276 let profile = profile_with_predicate_pairs(&[
1277 (StrHash::new("http://ex/a"), 7),
1278 (StrHash::new("http://ex/b"), 9),
1279 ]);
1280 let budget = crate::serde_bin::to_bytes(&profile).len();
1281 let capped = profile.capped_for_wire_with_budget(budget);
1282 assert_eq!(capped, profile);
1283 }
1284
1285 #[test]
1286 fn cap_beyond_fixed_parts_keeps_maps_empty() {
1287 let profile = profile_with_predicate_pairs(&[(StrHash::new("http://ex/a"), 7)]);
1288 let mut skeleton = profile.clone();
1289 skeleton.subjects_per_predicate.clear();
1290 skeleton.objects_per_predicate.clear();
1291 let budget = crate::serde_bin::to_bytes(&skeleton).len();
1292 let capped = profile.capped_for_wire_with_budget(budget);
1293 assert!(capped.subjects_per_predicate.is_empty());
1294 assert!(capped.objects_per_predicate.is_empty());
1295 }
1296
1297 #[test]
1298 fn asymmetric_pairs_cost_one_side_only() {
1299 let hash = StrHash::new("http://ex/a");
1302 let mut profile = StatsProfile::default();
1303 profile.predicate_counts.insert(hash, 10);
1304 profile
1305 .subjects_per_predicate
1306 .insert(hash, HyperLogLog::default_params());
1307
1308 let mut skeleton = profile.clone();
1309 skeleton.subjects_per_predicate.clear();
1310 let base = crate::serde_bin::to_bytes(&skeleton).len();
1311 let capped = profile.capped_for_wire_with_budget(base + PAIR_BYTES);
1312 assert!(capped.subjects_per_predicate.contains_key(&hash));
1313 }
1314
1315 #[test]
1316 fn rollup_prefers_o_axis() {
1317 let mut o = StatsProfile::default();
1318 let mut s = StatsProfile::default();
1319 o.total_puts = 10;
1320 s.total_puts = 99;
1321 let rolled = rollup_cluster(&[(PartitionAxis::S, s), (PartitionAxis::O, o.clone())]);
1322 assert_eq!(rolled.total_puts, 10);
1323 }
1324
1325 #[test]
1326 fn rollup_copies_named_graph_count_from_s() {
1327 let mut o = StatsProfile::default();
1328 let mut s = StatsProfile::default();
1329 o.total_puts = 10;
1330 s.named_graph_count = 42;
1331 let rolled = rollup_cluster(&[(PartitionAxis::S, s), (PartitionAxis::O, o)]);
1332 assert_eq!(rolled.total_puts, 10);
1333 assert_eq!(rolled.named_graph_count, 42);
1334 }
1335
1336 #[test]
1337 fn join_strategy_broadcast_when_left_small() {
1338 assert_eq!(
1339 JoinStrategy::from_cardinalities(5, 1_000_000),
1340 JoinStrategy::Broadcast
1341 );
1342 assert_eq!(
1343 JoinStrategy::from_cardinalities(50_000, 80_000),
1344 JoinStrategy::Shuffle
1345 );
1346 }
1347
1348 #[test]
1349 fn join_strategy_uses_hll_domain_for_broadcast_vs_shuffle() {
1350 assert_eq!(
1352 JoinStrategy::from_cardinalities_and_domains(100_000, 200_000, Some(50), Some(80_000),),
1353 JoinStrategy::Broadcast
1354 );
1355 assert_eq!(
1357 JoinStrategy::from_cardinalities_and_domains(
1358 100_000,
1359 200_000,
1360 Some(50_000),
1361 Some(80_000),
1362 ),
1363 JoinStrategy::Shuffle
1364 );
1365 assert_eq!(
1367 JoinStrategy::from_cardinalities_and_domains(5, 1_000_000, Some(50_000), None),
1368 JoinStrategy::Broadcast
1369 );
1370 }
1371
1372 #[test]
1373 fn hll_fanout_tightens_bound_object_estimate() {
1374 let mut profile = StatsProfile::default();
1378 let lives_in = NamedNode::new("http://ex/livesIn").unwrap();
1379 let brisbane = NamedNode::new("http://ex/Brisbane").unwrap();
1380 let pred = StrHash::new("http://ex/livesIn");
1381 let brisbane_term = EncodedTerm::from(&brisbane);
1382
1383 profile.total_puts = 1000;
1384 profile.predicate_counts.insert(pred, 1000);
1385 profile.object_cms.add(term_key(&brisbane_term), 800);
1386
1387 let mut objects = HyperLogLog::default_params();
1388 for i in 0..10u128 {
1389 objects.add(i);
1390 }
1391 profile.objects_per_predicate.insert(pred, objects);
1392
1393 let pattern = EncodedTriplePattern {
1394 subject: None,
1395 predicate: Some(EncodedTerm::from(&lives_in)),
1396 object: Some(brisbane_term),
1397 graph_name: Some(EncodedTerm::DefaultGraph),
1398 };
1399
1400 let with_hll = estimate_pattern(&profile, &pattern);
1401 let mut no_hll = profile.clone();
1402 no_hll.objects_per_predicate.clear();
1403 no_hll.subjects_per_predicate.clear();
1404 let without_hll = estimate_pattern(&no_hll, &pattern);
1405
1406 assert_eq!(without_hll, 800, "CMS/exact-only should take object CMS");
1407 assert!(
1408 with_hll < without_hll,
1409 "HLL fan-out should tighten: {with_hll} vs {without_hll}"
1410 );
1411 assert!(
1413 (50..=200).contains(&with_hll),
1414 "expected ~100 fan-out, got {with_hll}"
1415 );
1416
1417 let domain = estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Object).unwrap();
1418 assert!(
1419 (5..=20).contains(&domain),
1420 "object HLL domain should be ~10, got {domain}"
1421 );
1422 }
1423
1424 #[test]
1425 fn hll_join_rows_uses_domains() {
1426 assert_eq!(
1428 estimate_join_rows(10_000, 10_000, Some(100), Some(100)),
1429 1_000_000
1430 );
1431 assert_eq!(estimate_join_rows(10_000, 50_000, None, None), 10_000);
1432 }
1433
1434 #[test]
1439 fn join_rows_multi_multiplies_per_key_factors() {
1440 assert_eq!(
1441 estimate_join_rows_multi(
1442 500,
1443 237_016,
1444 &[(Some(5), Some(121)), (Some(100), Some(114_739))]
1445 ),
1446 8
1447 );
1448 }
1449
1450 #[test]
1454 fn join_rows_multi_reduces_to_single_key() {
1455 assert_eq!(
1456 estimate_join_rows_multi(10_000, 10_000, &[(Some(100), Some(100))]),
1457 estimate_join_rows(10_000, 10_000, Some(100), Some(100))
1458 );
1459 assert_eq!(
1460 estimate_join_rows_multi(10_000, 50_000, &[(None, None)]),
1461 10_000
1462 );
1463 }
1464
1465 #[test]
1470 fn join_rows_multi_known_side_only_for_missing_domains() {
1471 assert_eq!(
1472 estimate_join_rows_multi(2_000_000, 100, &[(Some(1_000_000), None)]),
1473 200
1474 );
1475 assert_eq!(
1478 estimate_join_rows_multi(1_000, 2_000, &[(None, None), (Some(10), Some(10))]),
1479 200_000
1480 );
1481 assert_eq!(
1484 estimate_join_rows_multi(2, 2, &[(Some(10), Some(10)), (Some(10), Some(10))]),
1485 1
1486 );
1487 }
1488
1489 #[test]
1493 fn type_scan_subject_domain_uses_exact_class_count() {
1494 let mut profile = StatsProfile::default();
1495 let dataset = EncodedTerm::from(&NamedNode::new("http://schema.org/Dataset").unwrap());
1496 let type_hash = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
1497 let mut typed_subjects = HyperLogLog::default_params();
1498 for i in 0..125_483u128 {
1499 typed_subjects.add(i);
1500 }
1501 profile
1502 .class_counts
1503 .insert(named_node_hash(&dataset).unwrap(), 5);
1504 profile
1505 .subjects_per_predicate
1506 .insert(type_hash, typed_subjects);
1507
1508 let pattern = EncodedTriplePattern {
1509 subject: None,
1510 predicate: Some(RDF_TYPE),
1511 object: Some(dataset),
1512 graph_name: Some(EncodedTerm::DefaultGraph),
1513 };
1514 assert_eq!(
1515 estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Subject),
1516 Some(5),
1517 "exact class count must beat the class-blind HLL"
1518 );
1519 let open_class = EncodedTriplePattern {
1523 object: None,
1524 ..pattern.clone()
1525 };
1526 assert_eq!(
1527 estimate_join_key_domain(&profile, &open_class, JoinKeySlot::Object),
1528 Some(1),
1529 "one class in class_counts → object domain 1, even with no objects HLL"
1530 );
1531 }
1532
1533 #[test]
1536 fn type_scan_subject_domain_falls_back_to_hll_without_exact_count() {
1537 let mut profile = StatsProfile::default();
1538 let dataset = EncodedTerm::from(&NamedNode::new("http://schema.org/Dataset").unwrap());
1539 let unseen = EncodedTerm::from(&NamedNode::new("http://ex/Unseen").unwrap());
1540 let type_hash = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
1541 let mut typed_subjects = HyperLogLog::default_params();
1542 for i in 0..9_000u128 {
1543 typed_subjects.add(i);
1544 }
1545 profile
1546 .subjects_per_predicate
1547 .insert(type_hash, typed_subjects);
1548 profile
1551 .class_counts
1552 .insert(named_node_hash(&unseen).unwrap(), 0);
1553
1554 let pattern = |obj: &EncodedTerm| EncodedTriplePattern {
1555 subject: None,
1556 predicate: Some(RDF_TYPE),
1557 object: Some(obj.clone()),
1558 graph_name: Some(EncodedTerm::DefaultGraph),
1559 };
1560 for (label, obj) in [("missing", &dataset), ("zero", &unseen)] {
1561 let domain =
1562 estimate_join_key_domain(&profile, &pattern(obj), JoinKeySlot::Subject).unwrap();
1563 assert!(
1564 (8_000..=10_000).contains(&domain),
1565 "{label} class count must fall back to the HLL (~9k), got {domain}"
1566 );
1567 }
1568 }
1569
1570 #[test]
1574 fn type_scan_object_domain_uses_exact_class_count() {
1575 let mut profile = StatsProfile::default();
1576 for iri in ["http://ex/A", "http://ex/B", "http://ex/C"] {
1577 let class = EncodedTerm::from(&NamedNode::new(iri).unwrap());
1578 profile
1579 .class_counts
1580 .insert(named_node_hash(&class).unwrap(), 7);
1581 }
1582 let type_hash = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
1583 let mut objects = HyperLogLog::default_params();
1584 for i in 0..10_000u128 {
1585 objects.add(i);
1586 }
1587 profile.objects_per_predicate.insert(type_hash, objects);
1588
1589 let pattern = EncodedTriplePattern {
1590 subject: None,
1591 predicate: Some(RDF_TYPE),
1592 object: None,
1593 graph_name: Some(EncodedTerm::DefaultGraph),
1594 };
1595 assert_eq!(
1596 estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Object),
1597 Some(3),
1598 "exact class_counts.len() must beat the ~10k objects HLL"
1599 );
1600 }
1601
1602 #[test]
1605 fn type_scan_object_domain_falls_back_to_hll_without_class_counts() {
1606 let mut profile = StatsProfile::default();
1607 let type_hash = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
1608 let mut objects = HyperLogLog::default_params();
1609 for i in 0..121u128 {
1610 objects.add(i);
1611 }
1612 profile.objects_per_predicate.insert(type_hash, objects);
1613
1614 let pattern = EncodedTriplePattern {
1615 subject: None,
1616 predicate: Some(RDF_TYPE),
1617 object: None,
1618 graph_name: Some(EncodedTerm::DefaultGraph),
1619 };
1620 let domain = estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Object).unwrap();
1621 assert!(
1622 (110..=130).contains(&domain),
1623 "empty class_counts → objects HLL (~121), got {domain}"
1624 );
1625 }
1626
1627 #[test]
1629 fn non_type_predicate_domain_stays_hll() {
1630 let mut profile = StatsProfile::default();
1631 let is_part_of = EncodedTerm::from(&NamedNode::new("http://ex/isPartOf").unwrap());
1632 let dataset = EncodedTerm::from(&NamedNode::new("http://schema.org/Dataset").unwrap());
1633 let pred_hash = StrHash::new("http://ex/isPartOf");
1634 let mut objects = HyperLogLog::default_params();
1635 for i in 0..121u128 {
1636 objects.add(i);
1637 }
1638 profile.objects_per_predicate.insert(pred_hash, objects);
1639 profile
1640 .class_counts
1641 .insert(named_node_hash(&dataset).unwrap(), 5);
1642
1643 let pattern = EncodedTriplePattern {
1644 subject: None,
1645 predicate: Some(is_part_of),
1646 object: None,
1647 graph_name: Some(EncodedTerm::DefaultGraph),
1648 };
1649 let domain = estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Object).unwrap();
1650 assert!(
1651 (110..=130).contains(&domain),
1652 "isPartOf object domain stays the HLL (~121), got {domain}"
1653 );
1654 }
1655
1656 #[test]
1657 fn literal_object_uses_cms() {
1658 let mut live = LiveQuadsProfile::default();
1659 let q = encode_quad(&waratah_storage::Quad::new(
1660 NamedNode::new("http://ex/c").unwrap(),
1661 NamedNode::new("http://ex/hasWeather").unwrap(),
1662 Literal::from("Sunny"),
1663 waratah_storage::GraphName::DefaultGraph,
1664 ))
1665 .unwrap();
1666 observe_quad(&mut live, &q, StorageOp::Put);
1667 let profile = StatsProfile::from(live);
1668 let pattern = EncodedTriplePattern {
1669 subject: None,
1670 predicate: Some(EncodedTerm::from(
1671 &NamedNode::new("http://ex/hasWeather").unwrap(),
1672 )),
1673 object: Some(EncodedTerm::from(&Literal::from("Sunny"))),
1674 graph_name: Some(EncodedTerm::DefaultGraph),
1675 };
1676 assert_eq!(profile.estimate(&pattern), 1);
1677 }
1678
1679 #[test]
1680 fn unseen_bound_predicate_is_one_not_total_puts() {
1681 let mut live = LiveQuadsProfile::default();
1682 let known = NamedNode::new("http://ex/name").unwrap();
1683 let q = encode_quad(&waratah_storage::Quad::new(
1684 NamedNode::new("http://ex/alice").unwrap(),
1685 known.clone(),
1686 Literal::from("Alice"),
1687 waratah_storage::GraphName::DefaultGraph,
1688 ))
1689 .unwrap();
1690 observe_quad(&mut live, &q, StorageOp::Put);
1691 let mut profile = StatsProfile::from(live);
1692 profile.total_puts = 360_000_000;
1693
1694 let unknown_p = EncodedTriplePattern {
1695 subject: None,
1696 predicate: Some(EncodedTerm::from(
1697 &NamedNode::new("http://ex/livesIn").unwrap(),
1698 )),
1699 object: None,
1700 graph_name: Some(EncodedTerm::DefaultGraph),
1701 };
1702 assert_eq!(
1703 estimate_pattern(&profile, &unknown_p),
1704 1,
1705 "bound IRI with no predicate_counts / subjects_per_predicate entry"
1706 );
1707
1708 let unbound_p = EncodedTriplePattern {
1709 subject: None,
1710 predicate: None,
1711 object: None,
1712 graph_name: Some(EncodedTerm::DefaultGraph),
1713 };
1714 assert_eq!(
1715 estimate_pattern(&profile, &unbound_p),
1716 360_000_000,
1717 "unbound ?p still falls back to total_puts"
1718 );
1719
1720 let known_p = EncodedTriplePattern {
1721 subject: None,
1722 predicate: Some(EncodedTerm::from(&known)),
1723 object: None,
1724 graph_name: Some(EncodedTerm::DefaultGraph),
1725 };
1726 assert_eq!(estimate_pattern(&profile, &known_p), 1);
1727 }
1728
1729 #[test]
1730 fn incoming_bound_object_uses_hll_fanout_not_cms() {
1731 let mut profile = StatsProfile::default();
1734 let located_in = NamedNode::new("http://ex/locatedIn").unwrap();
1735 let pred = StrHash::new("http://ex/locatedIn");
1736
1737 profile.total_puts = 10_000;
1738 profile.predicate_counts.insert(pred, 10_000);
1739
1740 let mut objects = HyperLogLog::default_params();
1741 for i in 0..100u128 {
1742 objects.add(i);
1743 }
1744 profile.objects_per_predicate.insert(pred, objects);
1745
1746 let pattern = EncodedTriplePattern {
1747 subject: None,
1748 predicate: Some(EncodedTerm::from(&located_in)),
1749 object: None,
1750 graph_name: Some(EncodedTerm::DefaultGraph),
1751 };
1752
1753 let unbound = estimate_pattern(&profile, &pattern);
1754 let incoming = estimate_pattern_with_bound_slots(
1755 &profile,
1756 &pattern,
1757 ExtraBoundSlots {
1758 object: true,
1759 ..ExtraBoundSlots::default()
1760 },
1761 );
1762
1763 assert_eq!(unbound, 10_000, "predicate-only should be |P|");
1764 assert!(
1765 incoming < unbound,
1766 "incoming-bound object should take HLL fan-out: {incoming} vs {unbound}"
1767 );
1768 assert!(
1769 (50..=200).contains(&incoming),
1770 "expected ~100 fan-out (10000/100), got {incoming}"
1771 );
1772 }
1773
1774 #[test]
1775 fn incoming_bound_predicate_uses_mean_predicate_count() {
1776 let mut profile = StatsProfile {
1779 total_puts: 10_000,
1780 ..StatsProfile::default()
1781 };
1782 profile
1783 .predicate_counts
1784 .insert(StrHash::new("http://ex/a"), 1_000);
1785 profile
1786 .predicate_counts
1787 .insert(StrHash::new("http://ex/b"), 9_000);
1788
1789 let pattern = EncodedTriplePattern {
1790 subject: None,
1791 predicate: None,
1792 object: None,
1793 graph_name: Some(EncodedTerm::DefaultGraph),
1794 };
1795
1796 let unbound = estimate_pattern(&profile, &pattern);
1797 let incoming = estimate_pattern_with_bound_slots(
1798 &profile,
1799 &pattern,
1800 ExtraBoundSlots {
1801 predicate: true,
1802 ..ExtraBoundSlots::default()
1803 },
1804 );
1805
1806 assert_eq!(unbound, 10_000, "unbound ?p should be total_puts");
1807 assert_eq!(incoming, 5_000, "incoming ?p should be mean |P| (10000/2)");
1808 }
1809
1810 #[test]
1811 fn incoming_type_object_without_class_iri_skips_class_map() {
1812 let mut profile = StatsProfile::default();
1813 let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
1814 let person = NamedNode::new("http://ex/Person").unwrap();
1815 profile
1816 .class_counts
1817 .insert(StrHash::new("http://ex/Person"), 5_000);
1818 profile.total_puts = 5_000;
1819
1820 let with_class = EncodedTriplePattern {
1821 subject: None,
1822 predicate: Some(EncodedTerm::from(&type_pred)),
1823 object: Some(EncodedTerm::from(&person)),
1824 graph_name: Some(EncodedTerm::DefaultGraph),
1825 };
1826 assert_eq!(estimate_pattern(&profile, &with_class), 5_000);
1827
1828 let fully_bound = EncodedTriplePattern {
1829 subject: Some(EncodedTerm::from(
1830 &NamedNode::new("http://ex/alice").unwrap(),
1831 )),
1832 predicate: Some(EncodedTerm::from(&type_pred)),
1833 object: Some(EncodedTerm::from(&person)),
1834 graph_name: Some(EncodedTerm::DefaultGraph),
1835 };
1836 assert_eq!(
1837 estimate_pattern(&profile, &fully_bound),
1838 1,
1839 "ground S/P/O is a point lookup, not the class map"
1840 );
1841
1842 let incoming_class_var = EncodedTriplePattern {
1843 subject: None,
1844 predicate: Some(EncodedTerm::from(&type_pred)),
1845 object: None,
1846 graph_name: Some(EncodedTerm::DefaultGraph),
1847 };
1848 let incoming = estimate_pattern_with_bound_slots(
1849 &profile,
1850 &incoming_class_var,
1851 ExtraBoundSlots {
1852 object: true,
1853 ..ExtraBoundSlots::default()
1854 },
1855 );
1856 assert_ne!(
1857 incoming, 5_000,
1858 "incoming ?class on rdf:type must not use the Person class map"
1859 );
1860 }
1861
1862 fn derived_domains_fixture() -> (StatsProfile, Vec<(StrHash, u64, u64)>) {
1865 let mut live = LiveQuadsProfile::default();
1866 let mut expected: Vec<(StrHash, u64, u64)> = Vec::new();
1867 for p in 0..3u8 {
1868 let pred = NamedNode::new(format!("http://ex/pred{p}")).unwrap();
1869 let pred_hash = crate::named_node_hash(&EncodedTerm::from(&pred)).unwrap();
1870 let distinct = 100 * (p as u64 + 1);
1871 for i in 0..distinct {
1872 let subject = NamedNode::new(format!("http://ex/s{p}-{i}")).unwrap();
1873 let object = NamedNode::new(format!("http://ex/o{p}-{i}")).unwrap();
1874 for _ in 0..2 {
1875 let q = encode_quad(&waratah_storage::Quad::new(
1876 subject.clone(),
1877 pred.clone(),
1878 object.clone(),
1879 waratah_storage::GraphName::DefaultGraph,
1880 ))
1881 .unwrap();
1882 observe_quad(&mut live, &q, StorageOp::Put);
1883 }
1884 }
1885 let subject_domain = live.subjects_per_predicate[&pred_hash].cardinality().max(1);
1886 let object_domain = live.objects_per_predicate[&pred_hash].cardinality().max(1);
1887 expected.push((pred_hash, subject_domain, object_domain));
1888 }
1889 (StatsProfile::from(live), expected)
1890 }
1891
1892 #[test]
1893 fn derive_hll_domains_matches_manual_cardinality() {
1894 let (mut profile, expected) = derived_domains_fixture();
1895 assert!(profile.subject_domains_per_predicate.is_empty());
1896 profile.derive_hll_domains();
1897 for (hash, subject_domain, object_domain) in &expected {
1898 assert_eq!(
1899 profile.subject_domains_per_predicate.get(hash),
1900 Some(subject_domain)
1901 );
1902 assert_eq!(
1903 profile.object_domains_per_predicate.get(hash),
1904 Some(object_domain)
1905 );
1906 assert_eq!(profile.subject_domain(hash), Some(*subject_domain));
1908 assert_eq!(profile.object_domain(hash), Some(*object_domain));
1909 }
1910 }
1911
1912 #[test]
1913 fn domain_readers_fall_back_to_on_the_fly_cardinality() {
1914 let (profile, expected) = derived_domains_fixture();
1917 for (hash, subject_domain, object_domain) in &expected {
1918 assert_eq!(profile.subject_domain(hash), Some(*subject_domain));
1919 assert_eq!(profile.object_domain(hash), Some(*object_domain));
1920 }
1921 assert_eq!(profile.subject_domain(&absent_hash()), None);
1922 assert_eq!(profile.object_domain(&absent_hash()), None);
1923 }
1924
1925 fn absent_hash() -> StrHash {
1926 crate::named_node_hash(&EncodedTerm::from(
1927 &NamedNode::new("http://ex/absent").unwrap(),
1928 ))
1929 .unwrap()
1930 }
1931
1932 #[test]
1933 fn cap_and_rollup_clear_inherited_domain_caches() {
1934 let (mut profile, _) = derived_domains_fixture();
1935 profile.derive_hll_domains();
1936 assert!(!profile.subject_domains_per_predicate.is_empty());
1937
1938 let capped = profile.capped_for_wire();
1939 assert!(capped.subject_domains_per_predicate.is_empty());
1940 assert!(capped.object_domains_per_predicate.is_empty());
1941
1942 let rolled = rollup_cluster(&[(PartitionAxis::S, profile)]);
1943 assert!(rolled.subject_domains_per_predicate.is_empty());
1944 assert!(rolled.object_domains_per_predicate.is_empty());
1945 }
1946
1947 #[test]
1948 fn tight_wire_cap_clears_cache_when_predicates_are_dropped() {
1949 let (mut profile, expected) = derived_domains_fixture();
1953 profile.derive_hll_domains();
1954
1955 let mut skeleton = profile.clone();
1956 skeleton.subjects_per_predicate.clear();
1957 skeleton.objects_per_predicate.clear();
1958 let skeleton_bytes = crate::serde_bin::to_bytes(&skeleton).len();
1959 let top = expected[2].0;
1960 let top_cost = hll_wire_entry_bytes(profile.subjects_per_predicate.get(&top))
1961 + hll_wire_entry_bytes(profile.objects_per_predicate.get(&top));
1962
1963 let capped = profile.capped_for_wire_with_budget(skeleton_bytes + top_cost);
1964 assert_eq!(capped.subjects_per_predicate.len(), 1);
1965 assert!(capped.subjects_per_predicate.contains_key(&top));
1966 assert!(!capped.subjects_per_predicate.contains_key(&expected[0].0));
1967 assert!(capped.subject_domains_per_predicate.is_empty());
1970 assert!(capped.object_domains_per_predicate.is_empty());
1971 assert_eq!(capped.subject_domain(&top), Some(expected[2].1));
1972 }
1973
1974 #[test]
1980 fn geo_frames_round_trip_and_merge_into_the_canonical_trim() {
1981 let mut profile = StatsProfile::default();
1982 *profile.geo_cell_histogram.fine.entry(100).or_insert(0) += 7;
1985 *profile.geo_cell_histogram.fine.entry(101).or_insert(0) += 1;
1986 *profile.geo_cell_histogram.fine.entry(102).or_insert(0) += 1;
1987 profile
1988 .geo_cell_histogram
1989 .observe_posting(1u64 << (60 - 2 * 8));
1990 profile
1991 .geo_cell_histogram
1992 .observe_posting(1u64 << (60 - 2 * 4));
1993
1994 let canonical = profile.capped_geo_histogram_for_wire();
1995 let fine_frame = crate::geo_cell_histogram::GeoCellHistogram {
2001 coarse: std::collections::BTreeMap::new(),
2002 ..canonical.clone()
2003 };
2004 let coarse_frame = crate::geo_cell_histogram::GeoCellHistogram {
2005 fine: std::collections::BTreeMap::new(),
2006 remainder: std::collections::BTreeMap::new(),
2007 ..canonical.clone()
2008 };
2009 let mut fine_bytes = Vec::new();
2010 fine_frame.encode_body(&mut fine_bytes);
2011 let mut coarse_bytes = Vec::new();
2012 coarse_frame.encode_body(&mut coarse_bytes);
2013 let mut fine_cursor = fine_bytes.as_slice();
2014 let mut coarse_cursor = coarse_bytes.as_slice();
2015 let mut reassembled =
2016 crate::geo_cell_histogram::GeoCellHistogram::decode_body(&mut fine_cursor)
2017 .expect("fine frame decodes");
2018 reassembled.merge(
2019 &crate::geo_cell_histogram::GeoCellHistogram::decode_body(&mut coarse_cursor)
2020 .expect("coarse frame decodes"),
2021 );
2022 assert_eq!(reassembled, canonical, "frames merge back into the trim");
2023
2024 let core = profile.capped_for_wire();
2027 assert!(core.geo_cell_histogram.is_empty());
2028 assert_eq!(
2029 core.temporal_histogram,
2030 crate::TickHistogram::default(),
2031 "the core blob's temporal section is empty — its frame carries it"
2032 );
2033 }
2034
2035 #[test]
2046 fn geo_frames_at_saturation_stay_under_the_message_ceiling() {
2047 const FRAME_HEADER_BYTES: usize = 2 + 3 * 4; const MESSAGE_FRAMING_BYTES: usize = 5;
2051 const GRPC_MAX_MESSAGE_SIZE: usize = 4 * 1024 * 1024;
2052
2053 let fine_kept = crate::GEO_FINE_FRAME_BUDGET_BYTES / crate::GEO_FINE_WIRE_ENTRY_BYTES;
2054 let remainder_kept =
2055 crate::GEO_REMAINDER_WIRE_BUDGET_BYTES / crate::GEO_REMAINDER_WIRE_ENTRY_BYTES;
2056 let coarse_kept = crate::GEO_COARSE_FRAME_BUDGET_BYTES / crate::GEO_COARSE_WIRE_ENTRY_BYTES;
2057
2058 let mut big = crate::geo_cell_histogram::GeoCellHistogram::default();
2059 for i in 0..(fine_kept + 40_000) {
2064 *big.fine.entry((i as u32) * 64).or_insert(0) += 1;
2065 }
2066 for i in 0..(coarse_kept + 8_000) {
2067 big.coarse.insert(0x8000_0000_0000_0000 + i as u64, 1);
2068 }
2069 let profile = StatsProfile {
2070 geo_cell_histogram: big,
2071 ..StatsProfile::default()
2072 };
2073
2074 let canonical = profile.capped_geo_histogram_for_wire();
2075 assert_eq!(
2076 canonical.fine.len(),
2077 fine_kept,
2078 "the fine map saturates exactly at its budget"
2079 );
2080 assert_eq!(
2081 canonical.remainder.len(),
2082 remainder_kept,
2083 "the remainder saturates INDEPENDENTLY — additive on top of the fine map"
2084 );
2085 assert_eq!(
2086 canonical.coarse.len(),
2087 coarse_kept,
2088 "the coarse map saturates exactly at its budget"
2089 );
2090
2091 let fine_frame = crate::geo_cell_histogram::GeoCellHistogram {
2093 coarse: std::collections::BTreeMap::new(),
2094 ..canonical.clone()
2095 };
2096 let coarse_frame = crate::geo_cell_histogram::GeoCellHistogram {
2097 fine: std::collections::BTreeMap::new(),
2098 remainder: std::collections::BTreeMap::new(),
2099 ..canonical.clone()
2100 };
2101 let mut fine_body = Vec::new();
2102 fine_frame.encode_body(&mut fine_body);
2103 let mut coarse_body = Vec::new();
2104 coarse_frame.encode_body(&mut coarse_body);
2105
2106 assert!(
2110 fine_body.len() > crate::GEO_FINE_FRAME_BUDGET_BYTES,
2111 "the remainder budget is additive, not carved out"
2112 );
2113 let fine_bound = crate::GEO_FINE_FRAME_BUDGET_BYTES
2114 + crate::GEO_REMAINDER_WIRE_BUDGET_BYTES
2115 + FRAME_HEADER_BYTES;
2116 assert!(
2117 fine_body.len() <= fine_bound,
2118 "FINE body {} exceeds fine + remainder budgets + header {}",
2119 fine_body.len(),
2120 fine_bound
2121 );
2122 let coarse_bound = crate::GEO_COARSE_FRAME_BUDGET_BYTES + FRAME_HEADER_BYTES;
2123 assert!(
2124 coarse_body.len() <= coarse_bound,
2125 "COARSE body {} exceeds its budget + header {}",
2126 coarse_body.len(),
2127 coarse_bound
2128 );
2129 assert!(
2131 fine_body.len() + MESSAGE_FRAMING_BYTES <= GRPC_MAX_MESSAGE_SIZE,
2132 "saturated FINE message must stay under the gRPC ceiling"
2133 );
2134 assert!(
2135 coarse_body.len() + MESSAGE_FRAMING_BYTES <= GRPC_MAX_MESSAGE_SIZE,
2136 "saturated COARSE message must stay under the gRPC ceiling"
2137 );
2138 }
2139
2140 #[test]
2141 fn merge_clears_hll_cardinality_cache() {
2142 let (mut profile, expected) = derived_domains_fixture();
2143 profile.derive_hll_domains();
2144 assert!(!profile.subject_domains_per_predicate.is_empty());
2145 assert!(!profile.object_domains_per_predicate.is_empty());
2146
2147 let (hash, cached_subject, _) = &expected[0];
2148 let mut live = LiveQuadsProfile::default();
2151 let pred = NamedNode::new("http://ex/pred0").unwrap();
2152 for i in 0..50 {
2153 let q = encode_quad(&waratah_storage::Quad::new(
2154 NamedNode::new(format!("http://ex/merge-s{i}")).unwrap(),
2155 pred.clone(),
2156 NamedNode::new(format!("http://ex/merge-o{i}")).unwrap(),
2157 waratah_storage::GraphName::DefaultGraph,
2158 ))
2159 .unwrap();
2160 observe_quad(&mut live, &q, StorageOp::Put);
2161 }
2162 let right = StatsProfile::from(live);
2163
2164 profile.merge(&right).expect("merge succeeds");
2165 assert!(profile.subject_domains_per_predicate.is_empty());
2166 assert!(profile.object_domains_per_predicate.is_empty());
2167 let merged = profile.subject_domain(hash).expect("merged sketch answers");
2168 assert!(
2169 merged > *cached_subject,
2170 "live answer must reflect the merged sketch, got {merged} <= {cached_subject}"
2171 );
2172 }
2173
2174 #[test]
2175 fn derived_domains_are_not_serialized() {
2176 let (mut profile, expected) = derived_domains_fixture();
2177 profile.derive_hll_domains();
2178 let decoded = crate::from_bytes(&crate::to_bytes(&profile)).expect("round-trips");
2179 assert!(decoded.subject_domains_per_predicate.is_empty());
2180 assert!(decoded.object_domains_per_predicate.is_empty());
2181 let (plain, _) = derived_domains_fixture();
2184 assert_eq!(crate::to_bytes(&profile), crate::to_bytes(&plain));
2185 for (hash, subject_domain, object_domain) in &expected {
2187 assert_eq!(decoded.subject_domain(hash), Some(*subject_domain));
2188 assert_eq!(decoded.object_domain(hash), Some(*object_domain));
2189 }
2190 }
2191
2192 #[test]
2193 fn estimators_agree_with_and_without_derived_domains() {
2194 let (mut profile, _) = derived_domains_fixture();
2195 profile.derive_hll_domains();
2196 let (plain, _) = derived_domains_fixture();
2197 let pred = NamedNode::new("http://ex/pred1").unwrap();
2198 let pattern = EncodedTriplePattern {
2199 subject: None,
2200 predicate: Some(EncodedTerm::from(&pred)),
2201 object: None,
2202 graph_name: Some(EncodedTerm::DefaultGraph),
2203 };
2204 assert_eq!(
2205 estimate_pattern(&profile, &pattern),
2206 estimate_pattern(&plain, &pattern)
2207 );
2208 assert_eq!(
2209 estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Subject),
2210 estimate_join_key_domain(&plain, &pattern, JoinKeySlot::Subject)
2211 );
2212 assert_eq!(
2213 estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Object),
2214 estimate_join_key_domain(&plain, &pattern, JoinKeySlot::Object)
2215 );
2216 }
2217 fn overlap_pattern(pred: Option<&str>) -> EncodedTriplePattern {
2221 EncodedTriplePattern {
2222 subject: Some(EncodedTerm::from(
2223 &NamedNode::new("http://ex/varS").unwrap(),
2224 )),
2225 predicate: pred.map(|p| EncodedTerm::from(&NamedNode::new(p).unwrap())),
2226 object: Some(EncodedTerm::from(
2227 &NamedNode::new("http://ex/varO").unwrap(),
2228 )),
2229 graph_name: None,
2230 }
2231 }
2232
2233 #[test]
2234 fn overlap_estimates_disjoint_vocabularies_near_zero() {
2235 let mut live = LiveQuadsProfile::default();
2240 let towns: Vec<_> = (0..300)
2241 .map(|i| NamedNode::new(format!("http://ex/town{i}")).unwrap())
2242 .collect();
2243 let ports: Vec<_> = (0..3)
2244 .map(|i| NamedNode::new(format!("http://ex/spaceport{i}")).unwrap())
2245 .collect();
2246 let from_town = NamedNode::new("http://ex/fromTown").unwrap();
2247 let has_port = NamedNode::new("http://ex/hasSpacePort").unwrap();
2248 for (i, town) in towns.iter().enumerate() {
2249 let q = encode_quad(&waratah_storage::Quad::new(
2250 NamedNode::new(format!("http://ex/person{i}")).unwrap(),
2251 from_town.clone(),
2252 town.clone(),
2253 waratah_storage::GraphName::DefaultGraph,
2254 ))
2255 .unwrap();
2256 observe_quad(&mut live, &q, StorageOp::Put);
2257 }
2258 for (i, port) in ports.iter().enumerate() {
2259 let q = encode_quad(&waratah_storage::Quad::new(
2260 NamedNode::new(format!("http://ex/sp{i}")).unwrap(),
2261 has_port.clone(),
2262 port.clone(),
2263 waratah_storage::GraphName::DefaultGraph,
2264 ))
2265 .unwrap();
2266 observe_quad(&mut live, &q, StorageOp::Put);
2267 }
2268 let profile = StatsProfile::from(live);
2269 let driver = overlap_pattern(Some("http://ex/fromTown"));
2270 let probe = overlap_pattern(Some("http://ex/hasSpacePort"));
2271 let overlap = estimate_vocabulary_overlap(
2272 &profile,
2273 &driver,
2274 JoinKeySlot::Object,
2275 &probe,
2276 JoinKeySlot::Object,
2277 )
2278 .expect("both sketches present");
2279 assert!(overlap <= 30, "disjoint vocabularies, got {overlap} milli");
2284 }
2285
2286 #[test]
2287 fn overlap_estimates_nested_vocabularies_high() {
2288 let mut live = LiveQuadsProfile::default();
2292 let plays = NamedNode::new("http://ex/playsFor").unwrap();
2293 let citizen = NamedNode::new("http://ex/isCitizenOf").unwrap();
2294 for i in 0..200u64 {
2295 let player = NamedNode::new(format!("http://ex/player{i}")).unwrap();
2296 let q = encode_quad(&waratah_storage::Quad::new(
2297 player.clone(),
2298 plays.clone(),
2299 NamedNode::new(format!("http://ex/team{i}")).unwrap(),
2300 waratah_storage::GraphName::DefaultGraph,
2301 ))
2302 .unwrap();
2303 observe_quad(&mut live, &q, StorageOp::Put);
2304 let q = encode_quad(&waratah_storage::Quad::new(
2305 player,
2306 citizen.clone(),
2307 NamedNode::new("http://ex/city").unwrap(),
2308 waratah_storage::GraphName::DefaultGraph,
2309 ))
2310 .unwrap();
2311 observe_quad(&mut live, &q, StorageOp::Put);
2312 }
2313 for i in 0..600u64 {
2314 let q = encode_quad(&waratah_storage::Quad::new(
2315 NamedNode::new(format!("http://ex/citizen{i}")).unwrap(),
2316 citizen.clone(),
2317 NamedNode::new("http://ex/city").unwrap(),
2318 waratah_storage::GraphName::DefaultGraph,
2319 ))
2320 .unwrap();
2321 observe_quad(&mut live, &q, StorageOp::Put);
2322 }
2323 let profile = StatsProfile::from(live);
2324 let driver = overlap_pattern(Some("http://ex/playsFor"));
2325 let probe = overlap_pattern(Some("http://ex/isCitizenOf"));
2326 let overlap = estimate_vocabulary_overlap(
2327 &profile,
2328 &driver,
2329 JoinKeySlot::Subject,
2330 &probe,
2331 JoinKeySlot::Subject,
2332 )
2333 .expect("both sketches present");
2334 assert!(overlap >= 700, "nested vocabularies, got {overlap} milli");
2338 }
2339
2340 #[test]
2341 fn overlap_identity_same_predicate_same_slot_is_full() {
2342 let mut live = LiveQuadsProfile::default();
2343 let from_town = NamedNode::new("http://ex/fromTown").unwrap();
2344 for i in 0..50u64 {
2345 let q = encode_quad(&waratah_storage::Quad::new(
2346 NamedNode::new(format!("http://ex/me{i}")).unwrap(),
2347 from_town.clone(),
2348 NamedNode::new(format!("http://ex/town{i}")).unwrap(),
2349 waratah_storage::GraphName::DefaultGraph,
2350 ))
2351 .unwrap();
2352 observe_quad(&mut live, &q, StorageOp::Put);
2353 }
2354 let profile = StatsProfile::from(live);
2355 let me = overlap_pattern(Some("http://ex/fromTown"));
2356 let mayor = overlap_pattern(Some("http://ex/fromTown"));
2357 let overlap = estimate_vocabulary_overlap(
2358 &profile,
2359 &me,
2360 JoinKeySlot::Object,
2361 &mayor,
2362 JoinKeySlot::Object,
2363 )
2364 .expect("identity pair");
2365 assert_eq!(overlap, VOCABULARY_OVERLAP_FULL_MILLI, "same vocabulary");
2366 let flipped = overlap_pattern(Some("http://ex/fromTown"));
2369 let overlap = estimate_vocabulary_overlap(
2370 &profile,
2371 &me,
2372 JoinKeySlot::Object,
2373 &flipped,
2374 JoinKeySlot::Subject,
2375 )
2376 .expect("both sketches present");
2377 assert_ne!(
2378 overlap, VOCABULARY_OVERLAP_FULL_MILLI,
2379 "object vocabulary vs subject vocabulary: 50 towns, 50 people"
2380 );
2381 }
2382
2383 #[test]
2384 fn overlap_degrades_to_none_on_unknowns() {
2385 let mut live = LiveQuadsProfile::default();
2386 let pred = NamedNode::new("http://ex/known").unwrap();
2387 for i in 0..10u64 {
2388 let q = encode_quad(&waratah_storage::Quad::new(
2389 NamedNode::new(format!("http://ex/s{i}")).unwrap(),
2390 pred.clone(),
2391 NamedNode::new(format!("http://ex/o{i}")).unwrap(),
2392 waratah_storage::GraphName::DefaultGraph,
2393 ))
2394 .unwrap();
2395 observe_quad(&mut live, &q, StorageOp::Put);
2396 }
2397 let profile = StatsProfile::from(live);
2398 let known = overlap_pattern(Some("http://ex/known"));
2399 let unbound = overlap_pattern(None);
2401 assert_eq!(
2402 None,
2403 estimate_vocabulary_overlap(
2404 &profile,
2405 &known,
2406 JoinKeySlot::Object,
2407 &unbound,
2408 JoinKeySlot::Object,
2409 )
2410 );
2411 let typed = overlap_pattern(Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"));
2413 assert_eq!(
2414 None,
2415 estimate_vocabulary_overlap(
2416 &profile,
2417 &typed,
2418 JoinKeySlot::Object,
2419 &known,
2420 JoinKeySlot::Object,
2421 )
2422 );
2423 let missing = overlap_pattern(Some("http://ex/never-seen"));
2425 assert_eq!(
2426 None,
2427 estimate_vocabulary_overlap(
2428 &profile,
2429 &known,
2430 JoinKeySlot::Object,
2431 &missing,
2432 JoinKeySlot::Object,
2433 )
2434 );
2435 assert_eq!(
2440 Some(VOCABULARY_OVERLAP_FULL_MILLI),
2441 estimate_vocabulary_overlap(
2442 &StatsProfile::default(),
2443 &known,
2444 JoinKeySlot::Object,
2445 &known,
2446 JoinKeySlot::Object,
2447 )
2448 );
2449 assert_eq!(
2450 None,
2451 estimate_vocabulary_overlap(
2452 &StatsProfile::default(),
2453 &known,
2454 JoinKeySlot::Object,
2455 &missing,
2456 JoinKeySlot::Object,
2457 )
2458 );
2459 }
2460}