1use std::sync::Arc;
22
23use rustc_hash::FxHashMap;
24
25use crate::query::caches::SCAN_MEMO_MAX_ENTRY_ROWS;
26use crate::query::scan_memo_eligible;
27use spargebra::Query;
28use spargebra::algebra::{
29 AggregateExpression, AggregateFunction, Expression, GraphPattern, OrderExpression,
30 PropertyPathExpression,
31};
32use spargebra::term::{GroundTerm, NamedNodePattern, TermPattern, TriplePattern};
33use waratah_proto::PatternSlot;
34use waratah_proto::{OMIT_GRAPH, OMIT_OBJECT, OMIT_PREDICATE, OMIT_SUBJECT};
35use waratah_stats::{
36 ExtraBoundSlots, GRAPH_FILTER_TERM_CAP, JoinKeySlot, JoinStrategy, PUSHDOWN_TERMS_LIMIT,
37 StatsProfile, VOCABULARY_OVERLAP_FULL_MILLI, bound_slots, estimate_join_key_domain,
38 estimate_join_rows_multi, estimate_pattern, estimate_pattern_with_bound_slots,
39 estimate_vocabulary_overlap, named_node_hash, pattern_is_point_lookup,
40};
41use waratah_storage::{
42 DomainCountMode, EncodedTerm, EncodedTriplePattern, IndexPermutation, IriOnlyMask,
43 PartitionAxis, QuadSlot, RDF_TYPE, SlotComparison, SnapshotId, StrHash, Term, Variable,
44 encode_term_bytes,
45};
46
47use crate::context::QueryContext;
48use crate::dataset::{
49 ComposedGraph, DefaultGraphWindow, GraphFilter, GraphScope, NamedGraphWindow, NamedVarWindow,
50 QueryDataset, push_graph_terms,
51};
52use crate::error::ComputeError;
53use crate::expr::{ExprCapability, and_fold, classify, flatten_and, variables_in_expression};
54use crate::liveness::{JoinSemiContext, annotate_liveness};
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Liveness {
59 Live,
61 Counted,
63 Dead,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum BagMark {
70 Insensitive,
75 Sensitive,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct SlotMark {
85 pub liveness: Liveness,
87 pub bag: BagMark,
92}
93
94impl SlotMark {
95 pub const LIVE_SENSITIVE: Self = Self {
97 liveness: Liveness::Live,
98 bag: BagMark::Sensitive,
99 };
100 pub const LIVE_INSENSITIVE: Self = Self {
102 liveness: Liveness::Live,
103 bag: BagMark::Insensitive,
104 };
105 pub const DEAD: Self = Self {
107 liveness: Liveness::Dead,
108 bag: BagMark::Insensitive,
109 };
110 pub const COUNTED_SENSITIVE: Self = Self {
114 liveness: Liveness::Counted,
115 bag: BagMark::Sensitive,
116 };
117 pub const COUNTED_INSENSITIVE: Self = Self {
122 liveness: Liveness::Counted,
123 bag: BagMark::Insensitive,
124 };
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum DomainScanKind {
138 PredicateDomain,
140 PredicateSubjects,
142 SubjectPreds,
144 SubjectDomain,
146 ObjectPreds,
148}
149
150pub(crate) const DOMAIN_SCAN_KINDS: [DomainScanKind; 5] = [
157 DomainScanKind::PredicateDomain,
158 DomainScanKind::PredicateSubjects,
159 DomainScanKind::SubjectPreds,
160 DomainScanKind::SubjectDomain,
161 DomainScanKind::ObjectPreds,
162];
163
164impl DomainScanKind {
165 pub fn permutation(self) -> IndexPermutation {
167 match self {
168 Self::PredicateDomain => IndexPermutation::Posg,
169 Self::PredicateSubjects => IndexPermutation::Psog,
170 Self::SubjectPreds => IndexPermutation::Spog,
171 Self::SubjectDomain => IndexPermutation::Sopg,
172 Self::ObjectPreds => IndexPermutation::Opsg,
173 }
174 }
175
176 pub fn axis(self) -> PartitionAxis {
178 self.permutation().into()
179 }
180
181 pub fn constraint_slot(self) -> PatternSlot {
183 match self {
184 Self::PredicateDomain | Self::PredicateSubjects => PatternSlot::Predicate,
185 Self::SubjectPreds | Self::SubjectDomain => PatternSlot::Subject,
186 Self::ObjectPreds => PatternSlot::Object,
187 }
188 }
189
190 pub fn head_slot(self) -> PatternSlot {
192 match self {
193 Self::PredicateDomain | Self::SubjectDomain => PatternSlot::Object,
194 Self::PredicateSubjects => PatternSlot::Subject,
195 Self::SubjectPreds | Self::ObjectPreds => PatternSlot::Predicate,
196 }
197 }
198
199 pub fn dead_slot(self) -> PatternSlot {
202 match self {
203 Self::PredicateDomain | Self::ObjectPreds => PatternSlot::Subject,
204 Self::PredicateSubjects | Self::SubjectPreds => PatternSlot::Object,
205 Self::SubjectDomain => PatternSlot::Predicate,
206 }
207 }
208
209 pub fn name(self) -> &'static str {
211 match self {
212 Self::PredicateDomain => "predicate_domain",
213 Self::PredicateSubjects => "predicate_subjects",
214 Self::SubjectPreds => "subject_preds",
215 Self::SubjectDomain => "subject_domain",
216 Self::ObjectPreds => "object_preds",
217 }
218 }
219}
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
226pub enum HeadScanKind {
227 Subjects,
229 Predicates,
231 Objects,
233 Classes,
236}
237
238impl HeadScanKind {
239 pub fn permutation(self) -> IndexPermutation {
241 match self {
242 Self::Subjects => IndexPermutation::Spog,
243 Self::Predicates => IndexPermutation::Psog,
244 Self::Objects => IndexPermutation::Opsg,
245 Self::Classes => IndexPermutation::Tsg,
246 }
247 }
248
249 pub fn axis(self) -> PartitionAxis {
251 self.permutation().into()
252 }
253
254 pub fn head_slot(self) -> PatternSlot {
256 match self {
257 Self::Subjects => PatternSlot::Subject,
258 Self::Predicates => PatternSlot::Predicate,
259 Self::Objects | Self::Classes => PatternSlot::Object,
260 }
261 }
262
263 pub fn name(self) -> &'static str {
265 match self {
266 Self::Subjects => "subjects",
267 Self::Predicates => "predicates",
268 Self::Objects => "objects",
269 Self::Classes => "classes",
270 }
271 }
272}
273
274#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
291pub(crate) enum JoinDomainStamp {
292 #[default]
294 NoProfile,
295 UnknownPredicate,
298 Deferred,
304 Unavailable,
307 Known(u64),
309}
310
311#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
313pub(crate) struct JoinDomainStamps {
314 subject: JoinDomainStamp,
315 object: JoinDomainStamp,
316}
317
318impl JoinDomainStamps {
319 fn classify(profile: Option<&StatsProfile>, pattern: &EncodedTriplePattern) -> Self {
321 Self {
322 subject: JoinDomainStamp::classify(profile, pattern, JoinKeySlot::Subject),
323 object: JoinDomainStamp::classify(profile, pattern, JoinKeySlot::Object),
324 }
325 }
326
327 fn get(self, slot: JoinKeySlot) -> JoinDomainStamp {
328 match slot {
329 JoinKeySlot::Subject => self.subject,
330 JoinKeySlot::Object => self.object,
331 }
332 }
333}
334
335impl JoinDomainStamp {
336 fn classify(
337 profile: Option<&StatsProfile>,
338 pattern: &EncodedTriplePattern,
339 slot: JoinKeySlot,
340 ) -> Self {
341 let Some(profile) = profile.filter(|p| !p.is_empty()) else {
342 return Self::NoProfile;
343 };
344 let Some(predicate) = pattern.predicate.as_ref() else {
345 return Self::UnknownPredicate;
346 };
347 if slot == JoinKeySlot::Subject
362 && predicate == &RDF_TYPE
363 && pattern.object.is_none()
364 && !profile.class_counts.is_empty()
365 {
366 return Self::Deferred;
367 }
368 match estimate_join_key_domain(profile, pattern, slot) {
369 Some(domain) => Self::Known(domain),
370 None => Self::Unavailable,
371 }
372 }
373}
374
375#[derive(Debug, Clone, PartialEq)]
377pub struct ScanOp {
378 pub pattern: EncodedTriplePattern,
380 pub subject: Option<Variable>,
382 pub predicate: Option<Variable>,
384 pub object: Option<Variable>,
386 pub graph: Option<Variable>,
388 pub produced_row_count_estimate: u64,
390 pub ancestor_push_return_bound: Option<u64>,
416 pub broadcasted: Option<(Variable, PatternSlot)>,
423 pub fetch_once: Option<u64>,
440 pub graph_filter: Option<GraphFilter>,
442 pub grounded: Vec<(Variable, PatternSlot)>,
446 pub merge_default_graph: bool,
451 pub marks: Vec<(Variable, Liveness, BagMark)>,
454 pub domain_scan: Option<DomainScanKind>,
457 pub head_scan: Option<HeadScanKind>,
461 pub domain_counts: Option<DomainScanKind>,
467 pub head_scan_counts: Option<HeadScanKind>,
474 pub iri_only: Vec<Variable>,
480 pub eager: Vec<SlotComparison>,
489 pub(crate) join_domains: JoinDomainStamps,
496}
497
498#[derive(Debug, Clone, PartialEq, Eq)]
510pub struct ScanOutputSlots {
511 #[cfg(test)]
516 pub slots: [Option<Variable>; 4],
517 pub repeats: Vec<(u8, u8)>,
523 pub materialized: Vec<(u8, Variable)>,
527}
528
529impl ScanOp {
530 pub fn for_plugin_pattern(
542 pattern: EncodedTriplePattern,
543 subject: Variable,
544 object: Variable,
545 graph: Option<Variable>,
546 graph_filter: Option<GraphFilter>,
547 merge_default_graph: bool,
548 produced_row_count_estimate: u64,
549 ) -> Self {
550 Self {
551 fetch_once: None,
552 ancestor_push_return_bound: None,
553 pattern,
554 subject: Some(subject),
555 predicate: None,
556 object: Some(object),
557 graph,
558 produced_row_count_estimate,
559 broadcasted: None,
560 graph_filter,
561 grounded: Vec::new(),
562 merge_default_graph,
563 marks: Vec::new(),
564 domain_scan: None,
565 head_scan: None,
566 head_scan_counts: None,
567 domain_counts: None,
568 iri_only: Vec::new(),
569 eager: Vec::new(),
570 join_domains: JoinDomainStamps::default(),
571 }
572 }
573
574 pub fn applied_graph(&self) -> AppliedGraph {
579 AppliedGraph {
580 graph_name: self.pattern.graph_name.clone(),
581 graph: self.graph.clone(),
582 graph_filter: self.graph_filter.clone(),
583 merge_default_graph: self.merge_default_graph,
584 }
585 }
586
587 pub fn variables(&self) -> Vec<Variable> {
591 let mut out = Vec::new();
592 for variable in [&self.subject, &self.predicate, &self.object, &self.graph]
593 .into_iter()
594 .flatten()
595 {
596 if !self.is_live(variable) {
597 continue;
598 }
599 if !out.contains(variable) {
600 out.push(variable.clone());
601 }
602 }
603 out
604 }
605
606 pub fn output_slots(&self) -> ScanOutputSlots {
611 let names = [
612 self.subject.as_ref(),
613 self.predicate.as_ref(),
614 self.object.as_ref(),
615 self.graph.as_ref(),
616 ];
617 let mut first: Vec<(&Variable, u8)> = Vec::new();
618 let mut repeats = Vec::new();
619 let mut materialized = Vec::new();
620 for (i, variable) in names.iter().enumerate() {
621 let Some(variable) = variable else { continue };
622 if let Some((_, first_i)) = first.iter().find(|(name, _)| *name == *variable) {
623 repeats.push((*first_i, i as u8));
624 continue;
625 }
626 first.push((variable, i as u8));
627 if !self.is_dropped(variable) {
628 materialized.push((i as u8, (*variable).clone()));
629 }
630 }
631 ScanOutputSlots {
632 #[cfg(test)]
633 slots: [
634 self.subject.clone(),
635 self.predicate.clone(),
636 self.object.clone(),
637 self.graph.clone(),
638 ],
639 repeats,
640 materialized,
641 }
642 }
643
644 pub fn materialized_variables(&self) -> Vec<Variable> {
653 self.output_slots()
654 .materialized
655 .into_iter()
656 .map(|(_, variable)| variable)
657 .collect()
658 }
659
660 pub fn omitted_slots(&self, effective: &EncodedTriplePattern, allow_dead: bool) -> u8 {
683 let repeats = self.repeat_slot_pairs();
684 let mut omitted = 0u8;
685 let slots = [
686 (&self.subject, &effective.subject, OMIT_SUBJECT, 0u8),
687 (&self.predicate, &effective.predicate, OMIT_PREDICATE, 1),
688 (&self.object, &effective.object, OMIT_OBJECT, 2),
689 (&self.graph, &effective.graph_name, OMIT_GRAPH, 3),
690 ];
691 for (variable, bound, bit, index) in slots {
692 if self.comparison_reads(index) {
697 continue;
698 }
699 if bound.is_some() {
700 omitted |= bit;
701 continue;
702 }
703 if !allow_dead {
704 continue;
705 }
706 let dead = match variable {
707 Some(variable) => self.is_dropped(variable),
708 None => true,
711 };
712 let repeated = repeats.iter().any(|(a, b)| *a == index || *b == index);
713 if dead && !repeated {
714 omitted |= bit;
715 }
716 }
717 omitted
718 }
719
720 fn comparison_reads(&self, index: u8) -> bool {
725 let slot = match index {
726 0 => QuadSlot::Subject,
727 1 => QuadSlot::Predicate,
728 2 => QuadSlot::Object,
729 _ => QuadSlot::Graph,
730 };
731 self.eager.iter().any(|comparison| comparison.slot == slot)
732 }
733
734 pub fn repeat_slot_pairs(&self) -> Vec<(u8, u8)> {
744 self.output_slots().repeats
745 }
746
747 pub fn slot_variables(&self) -> Vec<Variable> {
749 let mut out = Vec::new();
750 for variable in [&self.subject, &self.predicate, &self.object, &self.graph]
751 .into_iter()
752 .flatten()
753 {
754 if !out.contains(variable) {
755 out.push(variable.clone());
756 }
757 }
758 out
759 }
760
761 pub fn slot_mark(&self, variable: &Variable) -> Option<SlotMark> {
763 if let Some((_, liveness, bag)) = self.marks.iter().find(|(v, _, _)| v == variable) {
764 return Some(SlotMark {
765 liveness: *liveness,
766 bag: *bag,
767 });
768 }
769 if self.marks.is_empty() {
770 let on_scan = [&self.subject, &self.predicate, &self.object, &self.graph]
771 .into_iter()
772 .flatten()
773 .any(|v| v == variable);
774 return on_scan.then_some(SlotMark::LIVE_SENSITIVE);
775 }
776 None
777 }
778
779 pub fn bag_mark(&self, variable: &Variable) -> Option<BagMark> {
781 self.slot_mark(variable).map(|m| m.bag)
782 }
783
784 pub fn is_live(&self, variable: &Variable) -> bool {
786 self.slot_mark(variable)
787 .is_some_and(|m| m.liveness == Liveness::Live)
788 }
789
790 pub fn is_dropped(&self, variable: &Variable) -> bool {
794 self.slot_mark(variable)
795 .is_some_and(|m| m.liveness == Liveness::Dead)
796 }
797
798 pub(crate) fn ensure_materialized(&mut self, variable: &Variable) {
811 if self.marks.is_empty() {
812 return;
813 }
814 if let Some((_, liveness, _)) = self.marks.iter_mut().find(|(name, _, _)| name == variable)
815 {
816 *liveness = Liveness::Live;
817 return;
818 }
819 self.marks
820 .push((variable.clone(), Liveness::Live, BagMark::Sensitive));
821 }
822
823 pub fn is_counted(&self, variable: &Variable) -> bool {
827 self.slot_mark(variable)
828 .is_some_and(|m| m.liveness == Liveness::Counted && m.bag == BagMark::Sensitive)
829 }
830
831 pub fn is_counted_distinct(&self, variable: &Variable) -> bool {
836 self.slot_mark(variable)
837 .is_some_and(|m| m.liveness == Liveness::Counted && m.bag == BagMark::Insensitive)
838 }
839
840 pub fn head_count_is_total(&self, kind: HeadScanKind) -> bool {
845 let head = match kind.head_slot() {
846 PatternSlot::Subject => self.subject.as_ref(),
847 PatternSlot::Predicate => self.predicate.as_ref(),
848 PatternSlot::Object => self.object.as_ref(),
849 };
850 head.is_some_and(|v| self.is_counted_distinct(v))
851 }
852
853 pub fn domain_count_mode(&self) -> DomainCountMode {
859 if let Some(g) = &self.graph
860 && self.is_counted_distinct(g)
861 {
862 return DomainCountMode::DistinctGraphs;
863 }
864 if self
865 .slot_variables()
866 .iter()
867 .any(|v| self.is_counted_distinct(v))
868 {
869 return DomainCountMode::DistinctTerms;
870 }
871 DomainCountMode::Rows
872 }
873
874 pub(crate) fn has_specialized_rpc(&self) -> bool {
882 self.domain_scan.is_some()
883 || self.head_scan.is_some()
884 || self.domain_counts.is_some()
885 || self.head_scan_counts.is_some()
886 }
887
888 pub fn collapse_keys(&self) -> Vec<Variable> {
893 if self.has_specialized_rpc() {
894 return Vec::new();
895 }
896 for variable in self.slot_variables() {
897 if self.is_counted(&variable) || self.is_counted_distinct(&variable) {
898 return Vec::new();
899 }
900 if self.is_live(&variable) && self.bag_mark(&variable) == Some(BagMark::Sensitive) {
901 return Vec::new();
902 }
903 }
904 self.slot_variables()
905 .into_iter()
906 .filter(|v| self.is_live(v) && self.bag_mark(v) == Some(BagMark::Insensitive))
907 .collect()
908 }
909
910 pub fn will_collapse(&self) -> bool {
913 !self.collapse_keys().is_empty()
914 }
915
916 pub fn is_iri_only(&self, variable: &Variable) -> bool {
919 self.iri_only.iter().any(|v| v == variable)
920 }
921
922 pub fn iri_only_slots(&self) -> IriOnlyMask {
925 let mut mask = IriOnlyMask::NONE;
926 for variable in &self.iri_only {
927 for slot in self.slot_of(variable) {
928 match slot {
929 PatternSlot::Subject => mask.subject = true,
930 PatternSlot::Object => mask.object = true,
931 PatternSlot::Predicate => {}
932 }
933 }
934 }
935 mask
936 }
937
938 pub fn pushed_comparisons(&self) -> &[SlotComparison] {
953 debug_assert!(
954 self.eager
955 .iter()
956 .all(|comparison| comparison.slot != QuadSlot::Graph),
957 "the comparison wire is S/P/O only: a graph-slot entry would be \
958 rejected by the encoder and ignored by a transport default"
959 );
960 if self.has_specialized_rpc() {
961 return &[];
962 }
963 &self.eager
964 }
965
966 pub fn bound_slots(&self) -> usize {
968 bound_slots(&self.pattern)
969 }
970
971 pub fn slot_of(&self, variable: &Variable) -> Vec<PatternSlot> {
974 let mut slots = Vec::new();
975 if self.subject.as_ref() == Some(variable) {
976 slots.push(PatternSlot::Subject);
977 }
978 if self.predicate.as_ref() == Some(variable) {
979 slots.push(PatternSlot::Predicate);
980 }
981 if self.object.as_ref() == Some(variable) {
982 slots.push(PatternSlot::Object);
983 }
984 slots
985 }
986
987 pub fn first_slot_of(&self, variable: &Variable) -> Option<PatternSlot> {
989 self.slot_of(variable).into_iter().next()
990 }
991
992 pub(crate) fn known_join_domain(&self, variable: &Variable) -> Option<u64> {
999 let slot = if self.subject.as_ref() == Some(variable) {
1000 JoinKeySlot::Subject
1001 } else if self.object.as_ref() == Some(variable) {
1002 JoinKeySlot::Object
1003 } else {
1004 return None;
1005 };
1006 match self.join_domains.get(slot) {
1007 JoinDomainStamp::Known(n) => Some(n),
1008 _ => None,
1009 }
1010 }
1011
1012 #[cfg(test)]
1018 pub(crate) fn with_known_join_domain(mut self, slot: JoinKeySlot, domain: u64) -> Self {
1019 match slot {
1020 JoinKeySlot::Subject => self.join_domains.subject = JoinDomainStamp::Known(domain),
1021 JoinKeySlot::Object => self.join_domains.object = JoinDomainStamp::Known(domain),
1022 }
1023 self
1024 }
1025
1026 pub(crate) fn with_pattern(&self, pattern: EncodedTriplePattern) -> ScanOp {
1033 let mut grounded = self.clone();
1034 grounded.pattern = pattern;
1035 grounded.join_domains = JoinDomainStamps::default();
1036 grounded
1037 }
1038
1039 fn record_grounded(
1046 &mut self,
1047 variable: &Variable,
1048 slot: PatternSlot,
1049 profile: Option<&StatsProfile>,
1050 ) {
1051 let entry = (variable.clone(), slot);
1052 if !self.grounded.contains(&entry) {
1053 self.grounded.push(entry);
1054 }
1055 self.refresh_join_domains(profile);
1056 }
1057
1058 fn refresh_join_domains(&mut self, profile: Option<&StatsProfile>) {
1063 self.join_domains = JoinDomainStamps::classify(profile, &self.pattern);
1064 }
1065}
1066
1067#[derive(Debug, Clone, PartialEq)]
1069pub enum PropertyPath {
1070 Predicate(EncodedTerm),
1072 Reverse(Box<Self>),
1074 Sequence(Box<Self>, Box<Self>),
1076 Alternative(Box<Self>, Box<Self>),
1078 ZeroOrMore(Box<Self>),
1080 OneOrMore(Box<Self>),
1082 ZeroOrOne(Box<Self>),
1084 NegatedPropertySet(Vec<EncodedTerm>),
1086}
1087
1088impl PropertyPath {
1089 pub fn contains_star_or_plus(&self) -> bool {
1091 match self {
1092 Self::ZeroOrMore(_) | Self::OneOrMore(_) => true,
1093 Self::Reverse(inner) | Self::ZeroOrOne(inner) => inner.contains_star_or_plus(),
1094 Self::Sequence(a, b) | Self::Alternative(a, b) => {
1095 a.contains_star_or_plus() || b.contains_star_or_plus()
1096 }
1097 Self::Predicate(_) | Self::NegatedPropertySet(_) => false,
1098 }
1099 }
1100}
1101
1102#[derive(Debug, Clone, PartialEq)]
1108pub struct PathOp {
1109 pub subject_term: Option<EncodedTerm>,
1111 pub subject: Option<Variable>,
1113 pub path: PropertyPath,
1115 pub object_term: Option<EncodedTerm>,
1117 pub object: Option<Variable>,
1119 pub produced_row_count_estimate: u64,
1121 pub strings: Vec<(StrHash, String)>,
1124 pub graph: Option<Variable>,
1126 pub graph_name: Option<EncodedTerm>,
1128 pub graph_filter: Option<GraphFilter>,
1130 pub merge_default_graph: bool,
1134}
1135
1136impl PathOp {
1137 pub fn variables(&self) -> Vec<Variable> {
1139 let mut out = Vec::new();
1140 if let Some(variable) = &self.subject {
1141 out.push(variable.clone());
1142 }
1143 if let Some(variable) = &self.object
1144 && !out.contains(variable)
1145 {
1146 out.push(variable.clone());
1147 }
1148 if let Some(variable) = &self.graph
1149 && !out.contains(variable)
1150 {
1151 out.push(variable.clone());
1152 }
1153 out
1154 }
1155
1156 pub fn bound_ends(&self) -> usize {
1158 usize::from(self.subject_term.is_some()) + usize::from(self.object_term.is_some())
1159 }
1160
1161 pub fn end_of(&self, variable: &Variable) -> Option<PathEnd> {
1163 let start = self.subject.as_ref() == Some(variable);
1164 let end = self.object.as_ref() == Some(variable);
1165 match (start, end) {
1166 (true, true) => Some(PathEnd::Both),
1167 (true, false) => Some(PathEnd::Start),
1168 (false, true) => Some(PathEnd::End),
1169 (false, false) => None,
1170 }
1171 }
1172}
1173
1174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1176pub enum PathEnd {
1177 Start,
1179 End,
1181 Both,
1183}
1184
1185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1205pub struct SemiGateFacts {
1206 pub right_payload: bool,
1209 pub row_multiplicity_observed: bool,
1211 pub count_star: bool,
1213}
1214
1215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1223pub struct JoinMeta {
1224 pub strategy: JoinStrategy,
1226 pub produced_row_count_estimate: u64,
1255 pub own_push_removed_row_count_estimate: u64,
1287 pub star_arms: Option<u8>,
1303 pub semi_gate: Option<SemiGateFacts>,
1308}
1309
1310#[derive(Debug, Clone, PartialEq)]
1315pub struct JoinEdge {
1316 pub hash_keys: Vec<Variable>,
1319 pub meta: JoinMeta,
1321}
1322
1323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1337pub struct LeftJoinMeta {
1338 pub produced_row_count_estimate: u64,
1345 pub own_push_removed_row_count_estimate: u64,
1354}
1355
1356#[derive(Debug, Clone, PartialEq, Eq, Default)]
1358pub struct OutputVars {
1359 pub always_bound: Vec<Variable>,
1361 pub maybe_unbound: Vec<Variable>,
1363}
1364
1365impl OutputVars {
1366 pub fn all(&self) -> Vec<Variable> {
1368 let mut out = self.always_bound.clone();
1369 for v in &self.maybe_unbound {
1370 if !out.contains(v) {
1371 out.push(v.clone());
1372 }
1373 }
1374 out
1375 }
1376
1377 fn contains(&self, variable: &Variable) -> bool {
1378 self.always_bound.contains(variable) || self.maybe_unbound.contains(variable)
1379 }
1380
1381 fn is_always_bound(&self, variable: &Variable) -> bool {
1382 self.always_bound.contains(variable)
1383 }
1384}
1385
1386fn join_graph_var_output_vars(
1389 inner: &OutputVars,
1390 graph_var: &Variable,
1391 active_var: &Variable,
1392) -> OutputVars {
1393 let mut always_bound: Vec<Variable> = inner
1394 .always_bound
1395 .iter()
1396 .filter(|v| *v != active_var)
1397 .cloned()
1398 .collect();
1399 let maybe_unbound: Vec<Variable> = inner
1400 .maybe_unbound
1401 .iter()
1402 .filter(|v| *v != active_var && *v != graph_var)
1403 .cloned()
1404 .collect();
1405 if !always_bound.contains(graph_var) {
1406 always_bound.push(graph_var.clone());
1407 }
1408 OutputVars {
1409 always_bound,
1410 maybe_unbound,
1411 }
1412}
1413
1414fn hash_keys_for(left: &OutputVars, right: &OutputVars) -> Vec<Variable> {
1415 left.always_bound
1416 .iter()
1417 .filter(|v| right.is_always_bound(v))
1418 .cloned()
1419 .collect()
1420}
1421
1422fn extend_var_always_bound(inner: &OutputVars, expression: &Expression) -> bool {
1425 match expression {
1426 Expression::NamedNode(_) | Expression::Literal(_) => true,
1427 Expression::Variable(variable) => inner.is_always_bound(variable),
1428 Expression::Bound(_) => true,
1429 _ => false,
1430 }
1431}
1432
1433fn group_output_vars(
1434 inner: &OutputVars,
1435 keys: &[Variable],
1436 aggregates: &[(Variable, AggregateExpression)],
1437) -> OutputVars {
1438 let mut always_bound = Vec::new();
1439 let mut maybe_unbound = Vec::new();
1440 for key in keys {
1441 if inner.is_always_bound(key) {
1442 if !always_bound.contains(key) {
1443 always_bound.push(key.clone());
1444 }
1445 } else if !maybe_unbound.contains(key) {
1446 maybe_unbound.push(key.clone());
1447 }
1448 }
1449 for (variable, agg) in aggregates {
1450 if aggregate_result_always_bound(agg) {
1451 if !always_bound.contains(variable) {
1452 always_bound.push(variable.clone());
1453 }
1454 maybe_unbound.retain(|v| v != variable);
1455 } else if !always_bound.contains(variable) && !maybe_unbound.contains(variable) {
1456 maybe_unbound.push(variable.clone());
1457 }
1458 }
1459 OutputVars {
1460 always_bound,
1461 maybe_unbound,
1462 }
1463}
1464
1465fn aggregate_result_always_bound(agg: &AggregateExpression) -> bool {
1466 matches!(
1467 agg,
1468 AggregateExpression::CountSolutions { .. }
1469 | AggregateExpression::FunctionCall {
1470 name: AggregateFunction::Count,
1471 ..
1472 }
1473 )
1474}
1475
1476fn reject_unsupported_aggregates(
1477 aggregates: &[(Variable, AggregateExpression)],
1478) -> Result<(), ComputeError> {
1479 for (_, agg) in aggregates {
1480 match agg {
1481 AggregateExpression::CountSolutions { .. } => {}
1482 AggregateExpression::FunctionCall {
1483 name: AggregateFunction::Custom(name),
1484 ..
1485 } => {
1486 return Err(ComputeError::UnsupportedSparql(format!(
1487 "custom aggregate {name} is not supported"
1488 )));
1489 }
1490 AggregateExpression::FunctionCall { expr, .. } => match crate::expr::classify(expr) {
1491 crate::expr::ExprCapability::Unsupported => {
1492 return Err(ComputeError::UnsupportedSparql(format!(
1493 "aggregate argument is not supported: {expr}"
1494 )));
1495 }
1496 crate::expr::ExprCapability::AlwaysResolve
1497 | crate::expr::ExprCapability::AlwaysEncoded
1498 | crate::expr::ExprCapability::MaybeEncoded => {
1499 let _ = crate::expr::split_filter(expr)?;
1500 }
1501 },
1502 }
1503 }
1504 Ok(())
1505}
1506
1507pub(crate) fn eliminate_head_counts_groups(node: &mut PlanNode, profile: Option<&StatsProfile>) {
1520 match node {
1521 PlanNode::CustomNode(op) => {
1522 for child in &mut op.children {
1523 eliminate_head_counts_groups(child, profile);
1524 }
1525 }
1526 PlanNode::Group {
1527 inner,
1528 variables,
1529 aggregates,
1530 ..
1531 } => {
1532 eliminate_head_counts_groups(inner, profile);
1534 if let Some(replacement) =
1535 try_head_counts_plan_node(inner, variables, aggregates, profile)
1536 {
1537 *node = replacement;
1538 }
1539 }
1540 PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
1541 eliminate_head_counts_groups(left, profile);
1542 eliminate_head_counts_groups(right, profile);
1543 }
1544 PlanNode::Union { left, right } => {
1545 eliminate_head_counts_groups(left, profile);
1546 eliminate_head_counts_groups(right, profile);
1547 }
1548 PlanNode::Filter { inner, exists, .. } => {
1549 eliminate_head_counts_groups(inner, profile);
1550 for clause in exists {
1551 eliminate_head_counts_groups(&mut clause.body, profile);
1552 }
1553 }
1554 PlanNode::Extend { inner, .. }
1555 | PlanNode::Slice { inner, .. }
1556 | PlanNode::Distinct { inner, .. }
1557 | PlanNode::Sort { inner, .. }
1558 | PlanNode::JoinGraphVar { inner, .. } => eliminate_head_counts_groups(inner, profile),
1559 PlanNode::SubSelect(sub) => eliminate_head_counts_groups(&mut sub.inner, profile),
1560 PlanNode::Scan(_)
1561 | PlanNode::Path(_)
1562 | PlanNode::Values(_)
1563 | PlanNode::NamedGraphs { .. }
1564 | PlanNode::NamedGraphExists { .. }
1565 | PlanNode::DomainCounts { .. }
1569 | PlanNode::HeadCounts { .. }
1570 | PlanNode::PatternCount { .. }
1571 | PlanNode::Unit => {}
1572 }
1573}
1574
1575fn try_head_counts_plan_node(
1576 lowered: &PlanNode,
1577 keys: &[Variable],
1578 aggregates: &[(Variable, AggregateExpression)],
1579 profile: Option<&StatsProfile>,
1580) -> Option<PlanNode> {
1581 if aggregates.len() != 1 {
1582 return None;
1583 }
1584 let (count_var, counted_var) = match &aggregates[0] {
1585 (
1586 var,
1587 AggregateExpression::FunctionCall {
1588 name: AggregateFunction::Count,
1589 distinct: true,
1590 expr: Expression::Variable(v),
1591 },
1592 ) => (var.clone(), v.clone()),
1593 _ => return None,
1597 };
1598 let PlanNode::Scan(scan) = lowered else {
1599 return None;
1603 };
1604 if scan.broadcasted.is_some()
1605 || scan.graph.is_some()
1608 || crate::liveness::repeated_var_needs_dropped_slot(scan)
1609 {
1610 return None;
1611 }
1612 let mut candidates = Vec::new();
1616 if scan.pattern.predicate.as_ref() == Some(&RDF_TYPE) {
1617 if scan.pattern.subject.is_none() {
1618 candidates.push((
1619 HeadScanKind::Classes,
1620 PatternSlot::Object,
1621 PatternSlot::Subject,
1622 ));
1623 }
1624 } else if scan.pattern.subject.is_none()
1625 && scan.pattern.predicate.is_none()
1626 && scan.pattern.object.is_none()
1627 {
1628 candidates.push((
1629 HeadScanKind::Subjects,
1630 PatternSlot::Subject,
1631 PatternSlot::Predicate,
1632 ));
1633 candidates.push((
1634 HeadScanKind::Predicates,
1635 PatternSlot::Predicate,
1636 PatternSlot::Subject,
1637 ));
1638 candidates.push((
1639 HeadScanKind::Objects,
1640 PatternSlot::Object,
1641 PatternSlot::Predicate,
1642 ));
1643 }
1644 for (kind, head_slot, counted_slot) in candidates {
1645 let Some(head_var) = scan_slot_variable(scan, head_slot) else {
1646 continue;
1647 };
1648 let Some(slot1_var) = scan_slot_variable(scan, counted_slot) else {
1649 continue;
1650 };
1651 let total = keys.is_empty() && counted_var == *head_var;
1654 let per_head = keys.len() == 1 && &keys[0] == head_var && counted_var == *slot1_var;
1656 if !(total || per_head) {
1657 continue;
1658 }
1659 let produced_row_count_estimate = if total {
1660 1
1661 } else {
1662 profile
1663 .and_then(|profile| head_domain_estimate(profile, scan, head_slot))
1664 .unwrap_or(scan.produced_row_count_estimate)
1665 };
1666 return Some(PlanNode::HeadCounts {
1667 kind,
1668 total,
1669 counted: counted_var.clone(),
1670 group: per_head.then(|| head_var.clone()),
1671 count: count_var,
1672 graph_name: scan.pattern.graph_name.clone(),
1673 graph_filter: scan.graph_filter.clone(),
1674 iri_only: scan.is_iri_only(head_var),
1675 produced_row_count_estimate,
1676 });
1677 }
1678 None
1679}
1680
1681fn eliminate_count_split_groups(node: &mut PlanNode, profile: Option<&StatsProfile>) {
1687 let PlanNode::Group {
1688 inner,
1689 variables,
1690 aggregates,
1691 ..
1692 } = node
1693 else {
1694 return;
1695 };
1696 eliminate_domain_counts_groups(inner, profile);
1698 if let Some(replacement) = try_domain_counts_plan_node(inner, variables, aggregates, profile) {
1699 *node = replacement;
1702 } else if let Some(replacement) =
1703 try_count_split_plan_node(inner, variables, aggregates, profile)
1704 {
1705 *node = replacement;
1708 }
1709}
1710
1711pub(crate) fn eliminate_domain_counts_groups(node: &mut PlanNode, profile: Option<&StatsProfile>) {
1715 match node {
1716 PlanNode::CustomNode(op) => {
1717 for child in &mut op.children {
1718 eliminate_domain_counts_groups(child, profile);
1719 }
1720 }
1721 PlanNode::Group { .. } => eliminate_count_split_groups(node, profile),
1722 PlanNode::Join { left, right, .. } => {
1723 eliminate_domain_counts_groups(left, profile);
1724 eliminate_domain_counts_groups(right, profile);
1725 }
1726 PlanNode::LeftJoin { left, right, .. } => {
1727 eliminate_domain_counts_groups(left, profile);
1728 eliminate_domain_counts_groups(right, profile);
1729 }
1730 PlanNode::Union { left, right } => {
1731 eliminate_domain_counts_groups(left, profile);
1732 eliminate_domain_counts_groups(right, profile);
1733 }
1734 PlanNode::Filter { inner, exists, .. } => {
1735 eliminate_domain_counts_groups(inner, profile);
1736 for clause in exists {
1737 eliminate_domain_counts_groups(&mut clause.body, profile);
1738 }
1739 }
1740 PlanNode::Extend { inner, .. }
1741 | PlanNode::Slice { inner, .. }
1742 | PlanNode::Distinct { inner, .. }
1743 | PlanNode::Sort { inner, .. }
1744 | PlanNode::JoinGraphVar { inner, .. } => eliminate_domain_counts_groups(inner, profile),
1745 PlanNode::SubSelect(sub) => eliminate_domain_counts_groups(&mut sub.inner, profile),
1746 PlanNode::Scan(_)
1747 | PlanNode::Path(_)
1748 | PlanNode::Values(_)
1749 | PlanNode::NamedGraphs { .. }
1750 | PlanNode::NamedGraphExists { .. }
1751 | PlanNode::DomainCounts { .. }
1752 | PlanNode::HeadCounts { .. }
1753 | PlanNode::PatternCount { .. }
1754 | PlanNode::Unit => {}
1755 }
1756}
1757
1758pub(crate) fn eliminate_pattern_count_groups(node: &mut PlanNode) {
1765 match node {
1766 PlanNode::CustomNode(op) => {
1767 for child in &mut op.children {
1768 eliminate_pattern_count_groups(child);
1769 }
1770 }
1771 PlanNode::Group {
1772 inner,
1773 variables,
1774 aggregates,
1775 ..
1776 } => {
1777 eliminate_pattern_count_groups(inner);
1778 if let Some(replacement) = try_pattern_count_plan_node(inner, variables, aggregates) {
1779 *node = replacement;
1780 }
1781 }
1782 PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
1783 eliminate_pattern_count_groups(left);
1784 eliminate_pattern_count_groups(right);
1785 }
1786 PlanNode::Union { left, right } => {
1787 eliminate_pattern_count_groups(left);
1788 eliminate_pattern_count_groups(right);
1789 }
1790 PlanNode::Filter { inner, exists, .. } => {
1791 eliminate_pattern_count_groups(inner);
1792 for clause in exists {
1793 eliminate_pattern_count_groups(&mut clause.body);
1794 }
1795 }
1796 PlanNode::Extend { inner, .. }
1797 | PlanNode::Slice { inner, .. }
1798 | PlanNode::Distinct { inner, .. }
1799 | PlanNode::Sort { inner, .. }
1800 | PlanNode::JoinGraphVar { inner, .. } => eliminate_pattern_count_groups(inner),
1801 PlanNode::SubSelect(sub) => eliminate_pattern_count_groups(&mut sub.inner),
1802 PlanNode::Scan(_)
1803 | PlanNode::Path(_)
1804 | PlanNode::Values(_)
1805 | PlanNode::NamedGraphs { .. }
1806 | PlanNode::NamedGraphExists { .. }
1807 | PlanNode::DomainCounts { .. }
1808 | PlanNode::HeadCounts { .. }
1809 | PlanNode::PatternCount { .. }
1810 | PlanNode::Unit => {}
1811 }
1812}
1813
1814fn try_pattern_count_plan_node(
1815 lowered: &PlanNode,
1816 keys: &[Variable],
1817 aggregates: &[(Variable, AggregateExpression)],
1818) -> Option<PlanNode> {
1819 if !keys.is_empty() || aggregates.len() != 1 {
1820 return None;
1821 }
1822 let PlanNode::Scan(scan) = lowered else {
1823 return None;
1825 };
1826 if scan.broadcasted.is_some()
1827 || scan.graph.is_some()
1830 || crate::liveness::repeated_var_needs_dropped_slot(scan)
1831 {
1832 return None;
1833 }
1834 let (count_var, counted, count_star) = match &aggregates[0] {
1835 (var, AggregateExpression::CountSolutions { distinct: false }) => (var.clone(), None, true),
1836 (
1837 var,
1838 AggregateExpression::FunctionCall {
1839 name: AggregateFunction::Count,
1840 distinct: false,
1841 expr: Expression::Variable(v),
1842 },
1843 ) => {
1844 if !scan.slot_variables().iter().any(|s| s == v) {
1845 return None;
1846 }
1847 (var.clone(), Some(v.clone()), false)
1848 }
1849 _ => return None,
1852 };
1853 Some(PlanNode::PatternCount {
1854 pattern: scan.pattern.clone(),
1855 subject: scan.subject.clone(),
1856 predicate: scan.predicate.clone(),
1857 object: scan.object.clone(),
1858 count: count_var,
1859 count_star,
1860 counted,
1861 graph_filter: scan.graph_filter.clone(),
1862 merge_default_graph: scan.merge_default_graph,
1863 produced_row_count_estimate: 1,
1864 })
1865}
1866
1867fn scan_from_group_body(node: &PlanNode) -> Option<&ScanOp> {
1868 match node {
1869 PlanNode::Scan(scan) => Some(scan),
1870 PlanNode::Join { left, right, .. } => match (left.as_ref(), right.as_ref()) {
1871 (PlanNode::Values(_), PlanNode::Scan(scan))
1872 | (PlanNode::Scan(scan), PlanNode::Values(_)) => Some(scan),
1873 _ => None,
1874 },
1875 _ => None,
1876 }
1877}
1878
1879fn values_from_group_body(node: &PlanNode) -> Option<&ValuesOp> {
1881 match node {
1882 PlanNode::Join { left, right, .. } => match (left.as_ref(), right.as_ref()) {
1883 (PlanNode::Values(values), PlanNode::Scan(_))
1884 | (PlanNode::Scan(_), PlanNode::Values(values)) => Some(values),
1885 _ => None,
1886 },
1887 _ => None,
1888 }
1889}
1890
1891fn scan_op_pattern_term(scan: &ScanOp, slot: PatternSlot) -> Option<&EncodedTerm> {
1892 match slot {
1893 PatternSlot::Subject => scan.pattern.subject.as_ref(),
1894 PatternSlot::Predicate => scan.pattern.predicate.as_ref(),
1895 PatternSlot::Object => scan.pattern.object.as_ref(),
1896 }
1897}
1898
1899fn grounded_only_on_constraint(scan: &ScanOp, slot: PatternSlot) -> bool {
1900 scan.grounded.iter().all(|(variable, grounded_slot)| {
1901 *grounded_slot == slot
1902 && scan_slot_variable(scan, *grounded_slot) == Some(variable)
1903 && scan_op_pattern_term(scan, *grounded_slot).is_some()
1904 })
1905}
1906
1907fn constraint_terms_for_count_shortcut(
1908 inner: &PlanNode,
1909 scan: &ScanOp,
1910 kind: DomainScanKind,
1911) -> Option<(Vec<EncodedTerm>, Option<Variable>)> {
1912 let slot = kind.constraint_slot();
1913 if let Some(term) = scan_op_pattern_term(scan, slot) {
1914 let variable = scan_slot_variable(scan, slot);
1915 if let Some(v) = variable {
1916 if grounded_only_on_constraint(scan, slot) {
1917 return Some((vec![term.clone()], Some(v.clone())));
1918 }
1919 return None;
1920 }
1921 return Some((vec![term.clone()], None));
1922 }
1923 let variable = scan_slot_variable(scan, slot)?;
1924 let terms = allow_list_from_node(inner, variable)?;
1925 if terms.is_empty() {
1926 return None;
1927 }
1928 Some((terms.to_vec(), Some(variable.clone())))
1929}
1930
1931fn try_domain_counts_plan_node(
1932 lowered: &PlanNode,
1933 keys: &[Variable],
1934 aggregates: &[(Variable, AggregateExpression)],
1935 profile: Option<&StatsProfile>,
1936) -> Option<PlanNode> {
1937 if aggregates.len() != 1 {
1938 return None;
1939 }
1940 let scan = scan_from_group_body(lowered)?;
1941 if scan.graph.is_some() {
1945 return None;
1946 }
1947 let (count_var, counted, count_distinct) = match &aggregates[0] {
1948 (var, AggregateExpression::CountSolutions { distinct: false }) => {
1949 (var.clone(), None, false)
1950 }
1951 (
1952 var,
1953 AggregateExpression::FunctionCall {
1954 name: AggregateFunction::Count,
1955 distinct,
1956 expr: Expression::Variable(v),
1957 },
1958 ) => (var.clone(), Some(v.clone()), *distinct),
1959 _ => return None,
1962 };
1963 if keys.len() == 1 && scan.broadcasted.is_some() {
1964 return None;
1965 }
1966 match keys.len() {
1967 1 => try_domain_counts_one_key(
1968 lowered,
1969 scan,
1970 keys,
1971 &count_var,
1972 counted.as_ref(),
1973 count_distinct,
1974 profile,
1975 ),
1976 2 => try_domain_counts_two_keys(
1977 lowered,
1978 scan,
1979 keys,
1980 &count_var,
1981 counted.as_ref(),
1982 count_distinct,
1983 profile,
1984 ),
1985 _ => None,
1986 }
1987}
1988
1989fn try_domain_counts_one_key(
1990 inner: &PlanNode,
1991 scan: &ScanOp,
1992 keys: &[Variable],
1993 count_var: &Variable,
1994 counted: Option<&Variable>,
1995 count_distinct: bool,
1996 profile: Option<&StatsProfile>,
1997) -> Option<PlanNode> {
1998 if counted == Some(&keys[0]) {
1999 return None;
2000 }
2001 let slot_var = |slot: PatternSlot| scan_slot_variable(scan, slot);
2002 for kind in DOMAIN_SCAN_KINDS {
2003 let Some(head) = slot_var(kind.head_slot()) else {
2004 continue;
2005 };
2006 if head != &keys[0] {
2007 continue;
2008 }
2009 if scan
2010 .grounded
2011 .iter()
2012 .any(|(_, slot)| *slot != kind.constraint_slot())
2013 {
2014 continue;
2015 }
2016 let dead = slot_var(kind.dead_slot());
2017 if scan_op_pattern_term(scan, kind.head_slot()).is_some()
2018 || scan_op_pattern_term(scan, kind.dead_slot()).is_some()
2019 {
2020 continue;
2021 }
2022 let Some((constraints, constraint_var)) =
2023 constraint_terms_for_count_shortcut(inner, scan, kind)
2024 else {
2025 continue;
2026 };
2027 if constraint_var.is_some() || constraints.len() != 1 {
2028 continue;
2029 }
2030 let counted_ok = match counted {
2031 Some(v) => dead == Some(v),
2032 None => true,
2033 };
2034 if !counted_ok {
2035 continue;
2036 }
2037 if let Some(v) = counted
2038 && scan.slot_variables().iter().filter(|s| *s == v).count() != 1
2039 {
2040 continue;
2041 }
2042 if crate::liveness::repeated_var_needs_dropped_slot(scan) {
2043 continue;
2044 }
2045 let produced_row_count_estimate = profile
2046 .and_then(|profile| head_domain_estimate(profile, scan, kind.head_slot()))
2047 .unwrap_or(scan.produced_row_count_estimate);
2048 return Some(PlanNode::DomainCounts {
2049 kind,
2050 constraints,
2051 constraint_multiplicity: vec![1],
2053 constraint_var: None,
2054 head: keys[0].clone(),
2055 count: count_var.clone(),
2056 dead: dead.cloned(),
2057 count_star: counted.is_none(),
2058 count_distinct,
2059 graph_name: scan.pattern.graph_name.clone(),
2060 graph_filter: scan.graph_filter.clone(),
2061 merge_default_graph: scan.merge_default_graph,
2062 iri_only: scan.is_iri_only(head),
2063 produced_row_count_estimate,
2064 });
2065 }
2066 None
2067}
2068
2069fn try_domain_counts_two_keys(
2070 inner: &PlanNode,
2071 scan: &ScanOp,
2072 keys: &[Variable],
2073 count_var: &Variable,
2074 counted: Option<&Variable>,
2075 count_distinct: bool,
2076 profile: Option<&StatsProfile>,
2077) -> Option<PlanNode> {
2078 let slot_var = |slot: PatternSlot| scan_slot_variable(scan, slot);
2079 for kind in DOMAIN_SCAN_KINDS {
2080 let Some(head) = slot_var(kind.head_slot()) else {
2081 continue;
2082 };
2083 let constraint_v = scan_slot_variable(scan, kind.constraint_slot());
2084 let dead = slot_var(kind.dead_slot());
2085 let Some(constraint_v) = constraint_v else {
2086 continue;
2087 };
2088 if !keys.contains(head) || !keys.contains(constraint_v) {
2089 continue;
2090 }
2091 if scan_op_pattern_term(scan, kind.head_slot()).is_some()
2092 || scan_op_pattern_term(scan, kind.dead_slot()).is_some()
2093 {
2094 continue;
2095 }
2096 let Some((constraints, constraint_var)) =
2097 constraint_terms_for_count_shortcut(inner, scan, kind)
2098 else {
2099 continue;
2100 };
2101 if constraint_var.as_ref() != Some(constraint_v) {
2102 continue;
2103 }
2104 if constraints.is_empty() || constraints.len() > GRAPH_FILTER_TERM_CAP as usize {
2105 continue;
2106 }
2107 let Some(constraint_multiplicity) =
2112 constraint_multiplicity_for_two_keys(inner, scan, constraint_v, &constraints)
2113 else {
2114 continue;
2115 };
2116 let counted_ok = match counted {
2117 Some(v) => dead == Some(v),
2118 None => true,
2119 };
2120 if !counted_ok {
2121 continue;
2122 }
2123 if let Some(v) = counted
2124 && scan.slot_variables().iter().filter(|s| *s == v).count() != 1
2125 {
2126 continue;
2127 }
2128 if crate::liveness::repeated_var_needs_dropped_slot(scan) {
2129 continue;
2130 }
2131 let produced_row_count_estimate = profile
2132 .and_then(|profile| head_domain_estimate(profile, scan, kind.head_slot()))
2133 .unwrap_or(scan.produced_row_count_estimate);
2134 let mut keyed: Vec<(EncodedTerm, u64)> = constraints
2141 .into_iter()
2142 .zip(constraint_multiplicity)
2143 .collect();
2144 keyed.sort_by_key(|(term, _)| encode_term_bytes(term));
2145 let (constraints, constraint_multiplicity): (Vec<EncodedTerm>, Vec<u64>) =
2146 keyed.into_iter().unzip();
2147 return Some(PlanNode::DomainCounts {
2148 kind,
2149 constraints,
2150 constraint_multiplicity,
2151 constraint_var: Some(constraint_v.clone()),
2152 head: head.clone(),
2153 count: count_var.clone(),
2154 dead: dead.cloned(),
2155 count_star: counted.is_none(),
2156 count_distinct,
2157 graph_name: scan.pattern.graph_name.clone(),
2158 graph_filter: scan.graph_filter.clone(),
2159 merge_default_graph: scan.merge_default_graph,
2160 iri_only: scan.is_iri_only(head),
2161 produced_row_count_estimate,
2162 });
2163 }
2164 None
2165}
2166
2167const COUNT_SPLIT_MIN_PRODUCT_PER_HEAD: u64 = 256;
2177
2178#[derive(Clone, Copy)]
2180enum CountSplitRole {
2181 Storage(DomainScanKind),
2183 Collapse,
2185}
2186
2187fn try_count_split_plan_node(
2207 lowered: &PlanNode,
2208 keys: &[Variable],
2209 aggregates: &[(Variable, AggregateExpression)],
2210 profile: Option<&StatsProfile>,
2211) -> Option<PlanNode> {
2212 if aggregates.len() != 1 {
2214 return None;
2215 }
2216 let (count_var, counted) = match &aggregates[0] {
2217 (var, AggregateExpression::CountSolutions { distinct: false }) => (var.clone(), None),
2218 (
2219 var,
2220 AggregateExpression::FunctionCall {
2221 name: AggregateFunction::Count,
2222 distinct: false,
2223 expr: Expression::Variable(v),
2224 },
2225 ) => (var.clone(), Some(v.clone())),
2226 _ => return None,
2227 };
2228 if !keys.is_empty() {
2232 return None;
2233 }
2234 let PlanNode::Join {
2236 left,
2237 right,
2238 hash_keys,
2239 meta,
2240 ..
2241 } = lowered
2242 else {
2243 return None;
2244 };
2245 let [join_key] = hash_keys.as_slice() else {
2246 return None;
2247 };
2248 let left_storage = storage_countable(left, join_key, counted.as_ref());
2252 let right_storage = storage_countable(right, join_key, counted.as_ref());
2253 let (left_role, right_role) = match (left_storage, right_storage) {
2254 (Some(left_kind), Some(right_kind)) => {
2259 if counted.is_some() {
2260 return None;
2261 }
2262 (
2263 CountSplitRole::Storage(left_kind),
2264 CountSplitRole::Storage(right_kind),
2265 )
2266 }
2267 (Some(kind), None) => {
2268 if !collapse_countable(right) {
2269 return None;
2270 }
2271 (CountSplitRole::Storage(kind), CountSplitRole::Collapse)
2272 }
2273 (None, Some(kind)) => {
2274 if !collapse_countable(left) {
2275 return None;
2276 }
2277 (CountSplitRole::Collapse, CountSplitRole::Storage(kind))
2278 }
2279 (None, None) => return None,
2280 };
2281 let profile = profile?;
2292 let mut head_domain: Option<u64> = None;
2293 for (arm, kind) in [(left.as_ref(), left_role), (right.as_ref(), right_role)] {
2294 let CountSplitRole::Storage(kind) = kind else {
2295 continue;
2296 };
2297 let PlanNode::Scan(scan) = arm else {
2298 return None;
2299 };
2300 let estimate = head_domain_estimate(profile, scan, kind.head_slot())?;
2301 head_domain = Some(head_domain.map_or(estimate, |current: u64| current.max(estimate)));
2302 }
2303 let head_domain = head_domain?;
2304 if meta.produced_row_count_estimate
2305 < head_domain.saturating_mul(COUNT_SPLIT_MIN_PRODUCT_PER_HEAD)
2306 {
2307 return None;
2308 }
2309
2310 let (left_relation, left_count) =
2315 count_split_relation(left_role, left, join_key, counted.as_ref(), Some(profile))?;
2316 let (right_relation, right_count) =
2317 count_split_relation(right_role, right, join_key, counted.as_ref(), Some(profile))?;
2318 let count_join = join_nodes(left_relation, right_relation, Some(profile));
2319 let product = mint_count_split_var("product");
2320 let product_node = PlanNode::Extend {
2321 inner: Box::new(count_join),
2322 variable: product.clone(),
2323 expression: Expression::Multiply(
2324 Box::new(Expression::Variable(left_count)),
2325 Box::new(Expression::Variable(right_count)),
2326 ),
2327 const_strings: Vec::new(),
2328 const_blobs: Vec::new(),
2329 };
2330 Some(PlanNode::Group {
2331 inner: Box::new(product_node),
2332 variables: Vec::new(),
2333 aggregates: vec![(
2334 count_var,
2335 AggregateExpression::FunctionCall {
2336 name: AggregateFunction::Sum,
2337 expr: Expression::Variable(product),
2338 distinct: false,
2339 },
2340 )],
2341 const_strings: Vec::new(),
2342 const_blobs: Vec::new(),
2343 })
2344}
2345
2346fn storage_countable(
2366 arm: &PlanNode,
2367 join_key: &Variable,
2368 counted: Option<&Variable>,
2369) -> Option<DomainScanKind> {
2370 let PlanNode::Scan(scan) = arm else {
2371 return None;
2372 };
2373 if scan.graph.is_some() || crate::liveness::repeated_var_needs_dropped_slot(scan) {
2376 return None;
2377 }
2378 DOMAIN_SCAN_KINDS.into_iter().find(|kind| {
2379 if scan_slot_variable(scan, kind.head_slot()) != Some(join_key) {
2382 return false;
2383 }
2384 if scan_op_pattern_term(scan, kind.head_slot()).is_some()
2388 || scan_op_pattern_term(scan, kind.dead_slot()).is_some()
2389 {
2390 return false;
2391 }
2392 if let Some(counted) = counted {
2393 if scan_slot_variable(scan, kind.dead_slot()) != Some(counted) {
2397 return false;
2398 }
2399 if scan
2402 .slot_variables()
2403 .iter()
2404 .filter(|s| *s == counted)
2405 .count()
2406 != 1
2407 {
2408 return false;
2409 }
2410 }
2411 true
2412 })
2413}
2414
2415fn collapse_countable(arm: &PlanNode) -> bool {
2420 match arm {
2421 PlanNode::Scan(_) => true,
2422 PlanNode::Join { left, right, .. } => {
2423 matches!(left.as_ref(), PlanNode::Scan(_))
2424 && matches!(right.as_ref(), PlanNode::Scan(_))
2425 }
2426 _ => false,
2427 }
2428}
2429
2430fn count_split_relation(
2434 role: CountSplitRole,
2435 arm: &PlanNode,
2436 join_key: &Variable,
2437 counted: Option<&Variable>,
2438 profile: Option<&StatsProfile>,
2439) -> Option<(PlanNode, Variable)> {
2440 match role {
2441 CountSplitRole::Storage(kind) => {
2442 let PlanNode::Scan(scan) = arm else {
2443 return None;
2444 };
2445 let (constraints, constraint_var) =
2446 constraint_terms_for_count_shortcut(arm, scan, kind)?;
2447 if constraint_var.is_some() || constraints.len() != 1 {
2452 return None;
2453 }
2454 let count = mint_count_split_var("count");
2455 let dead = scan_slot_variable(scan, kind.dead_slot()).cloned();
2456 let produced = profile
2457 .and_then(|profile| head_domain_estimate(profile, scan, kind.head_slot()))
2458 .unwrap_or(scan.produced_row_count_estimate);
2459 let node = PlanNode::DomainCounts {
2460 kind,
2461 constraints,
2462 constraint_multiplicity: vec![1],
2463 constraint_var: None,
2464 head: join_key.clone(),
2465 count: count.clone(),
2466 dead,
2467 count_star: counted.is_none(),
2468 count_distinct: false,
2469 graph_name: scan.pattern.graph_name.clone(),
2470 graph_filter: scan.graph_filter.clone(),
2471 merge_default_graph: scan.merge_default_graph,
2472 iri_only: scan.is_iri_only(join_key),
2473 produced_row_count_estimate: produced,
2474 };
2475 Some((node, count))
2476 }
2477 CountSplitRole::Collapse => {
2478 let count = mint_count_split_var("count");
2479 Some((
2480 PlanNode::Group {
2481 inner: Box::new(arm.clone()),
2482 variables: vec![join_key.clone()],
2483 aggregates: vec![(
2484 count.clone(),
2485 AggregateExpression::CountSolutions { distinct: false },
2486 )],
2487 const_strings: Vec::new(),
2488 const_blobs: Vec::new(),
2489 },
2490 count,
2491 ))
2492 }
2493 }
2494}
2495
2496fn mint_count_split_var(suffix: &str) -> Variable {
2500 let sq = mint_scope_prefix();
2501 Variable::new_unchecked(format!(
2502 "cs_{}{}",
2503 sq.strip_prefix("sq_").unwrap_or(&sq),
2504 suffix
2505 ))
2506}
2507
2508fn constraint_multiplicity_for_two_keys(
2516 inner: &PlanNode,
2517 scan: &ScanOp,
2518 constraint: &Variable,
2519 constraints: &[EncodedTerm],
2520) -> Option<Vec<u64>> {
2521 let Some(values) = values_from_group_body(inner) else {
2522 return Some(vec![1; constraints.len()]);
2523 };
2524 let slots = scan.slot_variables();
2525 for column in &values.variables {
2526 if column != constraint && slots.iter().any(|slot| slot == column) {
2527 return None;
2528 }
2529 }
2530 let (terms, counts) = values.constraint_row_counts(constraint)?;
2531 if terms.as_slice() != constraints {
2532 return None;
2533 }
2534 Some(counts)
2535}
2536
2537pub(crate) fn domain_counts_schema_vars(
2538 constraint_var: &Option<Variable>,
2539 head: &Variable,
2540 count: &Variable,
2541) -> Vec<Variable> {
2542 match constraint_var {
2543 Some(cv) => vec![cv.clone(), head.clone(), count.clone()],
2544 None => vec![head.clone(), count.clone()],
2545 }
2546}
2547
2548pub(crate) fn head_counts_schema_vars(group: &Option<Variable>, count: &Variable) -> Vec<Variable> {
2551 match group {
2552 Some(g) => vec![g.clone(), count.clone()],
2553 None => vec![count.clone()],
2554 }
2555}
2556
2557fn join_output_vars(left: &OutputVars, right: &OutputVars) -> OutputVars {
2558 let mut always_bound = Vec::new();
2559 let mut maybe_unbound = Vec::new();
2560
2561 for v in &left.always_bound {
2562 if !always_bound.contains(v) {
2563 always_bound.push(v.clone());
2564 }
2565 }
2566 for v in &right.always_bound {
2567 if !always_bound.contains(v) {
2568 always_bound.push(v.clone());
2569 }
2570 }
2571 for v in left.maybe_unbound.iter().chain(right.maybe_unbound.iter()) {
2574 if always_bound.contains(v) || maybe_unbound.contains(v) {
2575 continue;
2576 }
2577 maybe_unbound.push(v.clone());
2580 }
2581 OutputVars {
2582 always_bound,
2583 maybe_unbound,
2584 }
2585}
2586
2587fn left_join_output_vars(left: &OutputVars, right: &OutputVars) -> OutputVars {
2588 let mut maybe_unbound = left.maybe_unbound.clone();
2589 for v in right.all() {
2590 if left.contains(&v) {
2591 continue; }
2593 if !maybe_unbound.contains(&v) {
2594 maybe_unbound.push(v);
2595 }
2596 }
2597 OutputVars {
2598 always_bound: left.always_bound.clone(),
2599 maybe_unbound,
2600 }
2601}
2602
2603fn union_output_vars(left: &OutputVars, right: &OutputVars) -> OutputVars {
2605 let always_bound: Vec<Variable> = left
2606 .always_bound
2607 .iter()
2608 .filter(|v| right.is_always_bound(v))
2609 .cloned()
2610 .collect();
2611 let mut maybe_unbound = Vec::new();
2612 for v in left.all().into_iter().chain(right.all()) {
2613 if always_bound.contains(&v) || maybe_unbound.contains(&v) {
2614 continue;
2615 }
2616 maybe_unbound.push(v);
2617 }
2618 OutputVars {
2619 always_bound,
2620 maybe_unbound,
2621 }
2622}
2623
2624pub(crate) fn union_arms(node: &PlanNode) -> Vec<&PlanNode> {
2632 let mut arms = Vec::new();
2633 collect_union_arms(node, &mut arms);
2634 arms
2635}
2636
2637fn collect_union_arms<'a>(node: &'a PlanNode, out: &mut Vec<&'a PlanNode>) {
2638 match node {
2639 PlanNode::Union { left, right } => {
2640 collect_union_arms(left, out);
2641 collect_union_arms(right, out);
2642 }
2643 other => out.push(other),
2644 }
2645}
2646
2647pub(crate) fn union_schema(arms: &[&PlanNode]) -> Vec<Variable> {
2656 let mut schema: Vec<Variable> = Vec::new();
2657 for arm in arms {
2658 for variable in arm.variables() {
2659 if !schema.contains(&variable) {
2660 schema.push(variable);
2661 }
2662 }
2663 }
2664 schema
2665}
2666
2667#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2669pub(crate) enum CountMode {
2670 Distinct,
2672 CountRows,
2675}
2676
2677#[derive(Debug, Clone)]
2685pub(crate) struct CountModePlan {
2686 pub(crate) dim: Variable,
2688 pub(crate) dim_index: usize,
2690 pub(crate) by_dim: FxHashMap<EncodedTerm, CountMode>,
2692}
2693
2694impl CountModePlan {
2695 pub(crate) fn for_key(&self, key_terms: &[Option<EncodedTerm>]) -> Option<CountMode> {
2698 let term = key_terms.get(self.dim_index)?.as_ref()?;
2699 self.by_dim.get(term).copied()
2700 }
2701
2702 pub(crate) fn summary(&self) -> String {
2704 let count_rows = self
2705 .by_dim
2706 .values()
2707 .filter(|mode| **mode == CountMode::CountRows)
2708 .count();
2709 format!(
2710 "dim=?{} arms_count_rows={} arms_distinct={}",
2711 self.dim.as_str(),
2712 count_rows,
2713 self.by_dim.len() - count_rows
2714 )
2715 }
2716}
2717
2718pub(crate) fn count_mode_plan(
2732 inner: &PlanNode,
2733 keys: &[Variable],
2734 aggregates: &[(Variable, AggregateExpression)],
2735) -> Option<CountModePlan> {
2736 let arms = match inner {
2737 PlanNode::Union { .. } => union_arms(inner),
2738 PlanNode::Join {
2739 left,
2740 right,
2741 hash_keys,
2742 meta,
2743 ..
2744 } if meta.strategy == JoinStrategy::SemiScan
2745 && matches!(left.as_ref(), PlanNode::Union { .. })
2746 && right.as_scan().is_some_and(|scan| {
2747 !scan.has_specialized_rpc() && scan_is_key_unique(scan, hash_keys)
2748 }) =>
2749 {
2750 union_arms(left)
2751 }
2752 _ => return None,
2753 };
2754 if arms.is_empty() || aggregates.len() != 1 {
2755 return None;
2756 }
2757 let counted = match &aggregates[0].1 {
2758 AggregateExpression::FunctionCall {
2759 name: AggregateFunction::Count,
2760 distinct: true,
2761 expr: Expression::Variable(variable),
2762 } => variable,
2763 _ => return None,
2764 };
2765 if keys.contains(counted) {
2766 return None;
2767 }
2768 let mut dims = keys.iter().filter(|key| {
2772 arms.iter()
2773 .all(|arm| walk_arm(arm, key).is_some_and(|(term, _)| term.is_some()))
2774 });
2775 let dim = dims.next()?.clone();
2776 if dims.next().is_some() {
2777 return None;
2778 }
2779 let dim_index = keys.iter().position(|key| key == &dim)?;
2780 let mut by_dim: FxHashMap<EncodedTerm, CountMode> = FxHashMap::default();
2781 for arm in &arms {
2782 let (term, scan) = walk_arm(arm, &dim)?;
2783 let term = term?;
2784 let mode = if scan.is_some_and(|scan| arm_count_rows_eligible(scan, counted, keys)) {
2785 CountMode::CountRows
2786 } else {
2787 CountMode::Distinct
2788 };
2789 match by_dim.get_mut(&term) {
2790 Some(existing) => {
2791 *existing = CountMode::Distinct;
2795 }
2796 None => {
2797 by_dim.insert(term, mode);
2798 }
2799 }
2800 }
2801 Some(CountModePlan {
2802 dim,
2803 dim_index,
2804 by_dim,
2805 })
2806}
2807
2808fn walk_arm<'a>(
2817 arm: &'a PlanNode,
2818 dim: &Variable,
2819) -> Option<(Option<EncodedTerm>, Option<&'a ScanOp>)> {
2820 let mut node = arm;
2821 let mut term = None;
2822 loop {
2823 match node {
2824 PlanNode::Extend {
2825 inner,
2826 variable,
2827 expression,
2828 ..
2829 } => {
2830 if variable != dim || term.is_some() || !crate::expr::is_row_invariant(expression) {
2831 return None;
2832 }
2833 term = Some(constant_encoded_term(expression)?);
2834 node = inner;
2835 }
2836 PlanNode::Filter { inner, .. } => node = inner,
2837 PlanNode::Scan(scan) => {
2838 if scan.slot_variables().iter().any(|variable| variable == dim) {
2839 return None;
2840 }
2841 return Some((term, Some(scan)));
2842 }
2843 _ => return Some((term, None)),
2844 }
2845 }
2846}
2847
2848fn constant_encoded_term(expression: &Expression) -> Option<EncodedTerm> {
2849 match expression {
2850 Expression::NamedNode(node) => Some(EncodedTerm::from(node)),
2851 Expression::Literal(literal) => Some(crate::plugin::encode_user_literal(literal)),
2852 _ => None,
2853 }
2854}
2855
2856fn arm_count_rows_eligible(scan: &ScanOp, counted: &Variable, keys: &[Variable]) -> bool {
2860 if scan.has_specialized_rpc()
2861 || scan.merge_default_graph
2862 || scan.graph_filter.is_some()
2863 || scan
2864 .grounded
2865 .iter()
2866 .any(|(variable, _)| variable == counted)
2867 || keys.contains(counted)
2868 {
2869 return false;
2870 }
2871 if let Some(graph) = &scan.graph
2872 && !keys.contains(graph)
2873 {
2874 return false;
2875 }
2876 if ![&scan.subject, &scan.predicate, &scan.object]
2881 .into_iter()
2882 .flatten()
2883 .any(|variable| variable == counted)
2884 {
2885 return false;
2886 }
2887 let mut counted_slots = 0usize;
2888 for variable in scan.slot_variables() {
2889 if variable == *counted {
2890 counted_slots += 1;
2891 continue;
2892 }
2893 if keys.contains(&variable)
2894 || scan
2895 .grounded
2896 .iter()
2897 .any(|(grounded, _)| *grounded == variable)
2898 {
2899 continue;
2900 }
2901 return false;
2902 }
2903 counted_slots == 1
2904}
2905
2906#[derive(Debug, Clone, PartialEq)]
2908pub struct ValuesOp {
2909 pub variables: Vec<Variable>,
2911 pub rows: Vec<Vec<Option<EncodedTerm>>>,
2913 pub strings: Vec<(StrHash, String)>,
2915 pub blobs: Vec<(StrHash, Vec<u8>)>,
2922}
2923
2924impl ValuesOp {
2925 pub fn produced_row_count_estimate(&self) -> u64 {
2927 self.rows.len() as u64
2928 }
2929
2930 pub fn output_vars(&self) -> OutputVars {
2932 let mut always_bound = Vec::new();
2933 let mut maybe_unbound = Vec::new();
2934 for (index, variable) in self.variables.iter().enumerate() {
2935 let has_undef = self
2936 .rows
2937 .iter()
2938 .any(|row| row.get(index).is_none_or(Option::is_none));
2939 if has_undef {
2940 maybe_unbound.push(variable.clone());
2941 } else {
2942 always_bound.push(variable.clone());
2943 }
2944 }
2945 OutputVars {
2946 always_bound,
2947 maybe_unbound,
2948 }
2949 }
2950
2951 pub(crate) fn distinct_key_count(&self, variable: &Variable) -> Option<u64> {
2953 let index = self.variables.iter().position(|known| known == variable)?;
2954 let mut seen: Vec<&EncodedTerm> = Vec::new();
2955 for row in &self.rows {
2956 if let Some(Some(term)) = row.get(index)
2957 && !seen.contains(&term)
2958 {
2959 seen.push(term);
2960 }
2961 }
2962 Some(seen.len() as u64)
2963 }
2964
2965 fn unique_term(&self, variable: &Variable) -> Option<EncodedTerm> {
2967 let index = self.variables.iter().position(|known| known == variable)?;
2968 let mut found: Option<&EncodedTerm> = None;
2969 for row in &self.rows {
2970 match row.get(index) {
2971 Some(Some(term)) => {
2972 if let Some(existing) = found {
2973 if existing != term {
2974 return None;
2975 }
2976 } else {
2977 found = Some(term);
2978 }
2979 }
2980 _ => return None,
2981 }
2982 }
2983 found.cloned()
2984 }
2985
2986 fn distinct_terms(&self, variable: &Variable) -> Option<Vec<EncodedTerm>> {
2988 let index = self.variables.iter().position(|known| known == variable)?;
2989 let mut seen: Vec<EncodedTerm> = Vec::new();
2990 for row in &self.rows {
2991 if let Some(Some(term)) = row.get(index)
2992 && !seen.iter().any(|existing| existing == term)
2993 {
2994 seen.push(term.clone());
2995 }
2996 }
2997 Some(seen)
2998 }
2999
3000 fn constraint_row_counts(&self, variable: &Variable) -> Option<(Vec<EncodedTerm>, Vec<u64>)> {
3005 let index = self.variables.iter().position(|known| known == variable)?;
3006 let mut terms: Vec<EncodedTerm> = Vec::new();
3007 let mut counts: Vec<u64> = Vec::new();
3008 for row in &self.rows {
3009 let Some(Some(term)) = row.get(index) else {
3010 return None;
3011 };
3012 if let Some(pos) = terms.iter().position(|existing| existing == term) {
3013 counts[pos] = counts[pos].saturating_add(1);
3014 } else {
3015 terms.push(term.clone());
3016 counts.push(1);
3017 }
3018 }
3019 if terms.is_empty() {
3020 return None;
3021 }
3022 Some((terms, counts))
3023 }
3024}
3025
3026const NAMED_GRAPHS_ESTIMATED_ROWS: u64 = 1_000_000;
3028
3029fn named_graphs_estimated_rows(profile: Option<&StatsProfile>) -> u64 {
3030 match profile {
3031 Some(p) => p.named_graph_count.max(1),
3032 None => NAMED_GRAPHS_ESTIMATED_ROWS,
3033 }
3034}
3035
3036#[derive(Debug, Clone, PartialEq)]
3038pub enum PlanNode {
3039 Scan(ScanOp),
3041 CustomNode(CustomOp),
3045 Path(PathOp),
3047 Join {
3049 left: Box<PlanNode>,
3051 right: Box<PlanNode>,
3053 hash_keys: Vec<Variable>,
3055 probe_key_domains: Vec<u64>,
3066 probe_key_overlap_milli: Vec<u64>,
3077 rhs_hostable_keys: Arc<[Variable]>,
3097 meta: JoinMeta,
3099 },
3100 LeftJoin {
3102 left: Box<PlanNode>,
3104 right: Box<PlanNode>,
3106 hash_keys: Vec<Variable>,
3108 early_filter: Option<Expression>,
3110 residual_filter: Option<Expression>,
3112 probe_key_domains: Vec<u64>,
3123 probe_key_overlap_milli: Vec<u64>,
3127 meta: LeftJoinMeta,
3130 },
3131 Filter {
3133 inner: Box<PlanNode>,
3135 early: Option<Expression>,
3137 residual: Option<Expression>,
3139 exists: Vec<ExistsClause>,
3144 one_to_one: bool,
3151 },
3152 Union {
3154 left: Box<PlanNode>,
3156 right: Box<PlanNode>,
3158 },
3159 Unit,
3161 Values(ValuesOp),
3163 NamedGraphs {
3169 variable: Variable,
3171 produced_row_count_estimate: u64,
3173 },
3174 NamedGraphExists {
3178 graph: EncodedTerm,
3180 },
3181 JoinGraphVar {
3188 inner: Box<PlanNode>,
3190 graph_var: Variable,
3192 active_var: Variable,
3194 },
3195 Extend {
3197 inner: Box<PlanNode>,
3199 variable: Variable,
3201 expression: Expression,
3203 const_strings: Vec<(StrHash, String)>,
3215 const_blobs: Vec<(StrHash, Vec<u8>)>,
3218 },
3219 Slice {
3221 inner: Box<PlanNode>,
3223 start: u64,
3225 length: Option<u64>,
3227 },
3228 Distinct {
3230 inner: Box<PlanNode>,
3232 columns: Vec<Variable>,
3238 },
3239 Sort {
3241 inner: Box<PlanNode>,
3243 keys: Vec<SortKey>,
3245 },
3246 Group {
3252 inner: Box<PlanNode>,
3254 variables: Vec<Variable>,
3256 aggregates: Vec<(Variable, AggregateExpression)>,
3258 const_strings: Vec<(StrHash, String)>,
3267 const_blobs: Vec<(StrHash, Vec<u8>)>,
3270 },
3271 DomainCounts {
3282 kind: DomainScanKind,
3284 constraints: Vec<EncodedTerm>,
3289 constraint_multiplicity: Vec<u64>,
3296 constraint_var: Option<Variable>,
3300 head: Variable,
3303 count: Variable,
3305 dead: Option<Variable>,
3310 count_star: bool,
3313 count_distinct: bool,
3318 graph_name: Option<EncodedTerm>,
3321 graph_filter: Option<GraphFilter>,
3323 merge_default_graph: bool,
3327 iri_only: bool,
3334 produced_row_count_estimate: u64,
3336 },
3337 HeadCounts {
3346 kind: HeadScanKind,
3348 total: bool,
3351 counted: Variable,
3354 group: Option<Variable>,
3357 count: Variable,
3359 graph_name: Option<EncodedTerm>,
3362 graph_filter: Option<GraphFilter>,
3364 iri_only: bool,
3367 produced_row_count_estimate: u64,
3369 },
3370 PatternCount {
3377 pattern: EncodedTriplePattern,
3379 subject: Option<Variable>,
3381 predicate: Option<Variable>,
3383 object: Option<Variable>,
3385 count: Variable,
3387 count_star: bool,
3389 counted: Option<Variable>,
3391 graph_filter: Option<GraphFilter>,
3393 merge_default_graph: bool,
3395 produced_row_count_estimate: u64,
3397 },
3398 SubSelect(SubSelectOp),
3408}
3409
3410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3451pub struct CustomOpCost {
3452 pub drain_rows: u64,
3458 pub per_key_unit: u64,
3464 pub inline_point_unit: u64,
3471 pub direct_probe: bool,
3477 pub probe_keyed_columns: u8,
3488 pub probe_filter_unit: u64,
3493 pub probe_memo_entry_rows: u64,
3499}
3500
3501#[derive(Debug, Clone, PartialEq)]
3510pub struct CustomOp {
3511 pub plugin_id: &'static str,
3513 pub op_id: &'static str,
3515 pub payload: crate::plugin::PluginPayloadBox,
3517 pub children: Vec<PlanNode>,
3519 pub variables: Vec<Variable>,
3521 pub produced_row_count_estimate: u64,
3523 pub cost: Option<CustomOpCost>,
3529 pub pinned: Vec<(Variable, EncodedTerm)>,
3539}
3540
3541impl CustomOp {
3542 pub fn sweep_cost(&self) -> Option<u64> {
3547 let cost = self.cost?;
3548 Some(
3549 cost.drain_rows.saturating_add(
3550 self.produced_row_count_estimate
3551 .saturating_mul(cost.per_key_unit),
3552 ),
3553 )
3554 }
3555
3556 pub fn probe_page_cost(
3572 &self,
3573 pushed_val_count: u64,
3574 pushed_column: Option<usize>,
3575 ) -> Option<(u64, bool)> {
3576 let cost = self.cost?;
3577 let direct = cost
3578 .direct_probe
3579 .then(|| pushed_val_count.saturating_mul(cost.per_key_unit));
3580 let keyed = pushed_column
3581 .is_some_and(|column| column < 8 && cost.probe_keyed_columns & (1u8 << column) != 0);
3582 let examined = if keyed {
3583 pushed_val_count.min(self.produced_row_count_estimate)
3584 } else {
3585 self.produced_row_count_estimate
3586 };
3587 let filter = examined.saturating_mul(cost.probe_filter_unit);
3588 Some(match direct {
3589 Some(direct) if direct <= filter => (direct, false),
3590 _ => (filter, true),
3591 })
3592 }
3593
3594 pub fn probe_drain_amortized(&self) -> bool {
3599 self.cost.is_some_and(|cost| {
3600 cost.probe_memo_entry_rows > 0
3601 && self.produced_row_count_estimate <= cost.probe_memo_entry_rows
3602 })
3603 }
3604
3605 pub fn keyed_cost(&self, pushed_val_count: u64, pushed_column: Option<usize>) -> Option<u64> {
3614 let (per_page, pays_drain) = self.probe_page_cost(pushed_val_count, pushed_column)?;
3615 Some(if pays_drain {
3616 self.cost?.drain_rows.saturating_add(per_page)
3617 } else {
3618 per_page
3619 })
3620 }
3621}
3622
3623#[derive(Debug, Clone, PartialEq)]
3625pub struct SortKey {
3626 pub expression: Expression,
3628 pub descending: bool,
3630}
3631
3632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3634pub enum ExistsKind {
3635 Uncorrelated,
3638 SemiJoin,
3641 NestedProbe,
3645}
3646
3647#[derive(Debug, Clone, PartialEq)]
3663pub struct ExistsClause {
3664 pub negated: bool,
3666 pub body: Box<PlanNode>,
3668 pub correlation: Vec<Variable>,
3670 pub kind: ExistsKind,
3672}
3673
3674#[derive(Debug, Clone, PartialEq)]
3676pub struct SubSelectOp {
3677 pub inner: Box<PlanNode>,
3682 pub variables: Vec<Variable>,
3688}
3689
3690impl SubSelectOp {
3691 pub fn variables(&self) -> &[Variable] {
3693 &self.variables
3694 }
3695
3696 pub fn produced_row_count_estimate(&self) -> u64 {
3700 self.inner.produced_row_count_estimate().max(1)
3701 }
3702}
3703
3704fn filter_row_cost_milli(early: Option<&Expression>, residual: Option<&Expression>) -> u64 {
3713 let mut total = 0u64;
3714 for expression in early.iter().chain(residual.iter()) {
3715 for conjunct in flatten_and(expression) {
3716 let rate = match classify(&conjunct) {
3717 ExprCapability::AlwaysEncoded => {
3718 crate::query::tunables::FILTER_ENCODED_ROW_EQUIV_MILLI
3719 }
3720 ExprCapability::MaybeEncoded => {
3721 crate::query::tunables::FILTER_MAYBE_ENCODED_ROW_EQUIV_MILLI
3722 }
3723 ExprCapability::AlwaysResolve | ExprCapability::Unsupported => {
3724 crate::query::tunables::FILTER_RESOLVE_ROW_EQUIV_MILLI
3725 }
3726 };
3727 total = total.saturating_add(rate);
3728 }
3729 }
3730 total
3731}
3732
3733fn filter_selectivity_milli(
3745 _early: Option<&Expression>,
3746 _residual: Option<&Expression>,
3747 _exists: &[ExistsClause],
3748) -> Option<u64> {
3749 None
3750}
3751
3752fn apply_filter_selectivity(
3756 rows: u64,
3757 early: Option<&Expression>,
3758 residual: Option<&Expression>,
3759 exists: &[ExistsClause],
3760) -> u64 {
3761 let rows = rows.max(1);
3762 filter_selectivity_milli(early, residual, exists).map_or(rows, |selectivity| {
3763 let scaled = u128::from(rows).saturating_mul(u128::from(selectivity)) / 1000;
3764 u64::try_from(scaled).unwrap_or(rows).clamp(1, rows)
3765 })
3766}
3767
3768fn filter_domain_bound(inner_domain: u64, inner_rows: u64, selectivity: u64) -> u64 {
3775 let output = u128::from(inner_rows.max(1)).saturating_mul(u128::from(selectivity)) / 1000;
3776 let output = u64::try_from(output).unwrap_or(inner_rows).max(1);
3777 inner_domain.min(output)
3778}
3779
3780impl PlanNode {
3781 pub(crate) fn own_push_removed_row_count_estimate(&self) -> Option<u64> {
3792 match self {
3793 Self::Scan(scan) => Some(scan.produced_row_count_estimate),
3794 Self::Join { meta, .. } => Some(meta.own_push_removed_row_count_estimate),
3795 _ => None,
3796 }
3797 }
3798
3799 pub fn inner_variables(&self) -> Vec<Variable> {
3805 match self {
3806 Self::Scan(scan) => scan.slot_variables(),
3807 Self::Path(path) => path.variables(),
3808 Self::Join { left, right, .. }
3809 | Self::LeftJoin { left, right, .. }
3810 | Self::Union { left, right } => {
3811 let mut out = left.inner_variables();
3812 for variable in right.inner_variables() {
3813 if !out.contains(&variable) {
3814 out.push(variable);
3815 }
3816 }
3817 out
3818 }
3819 Self::CustomNode(op) => {
3820 let mut out = op.variables.clone();
3821 for child in &op.children {
3822 for variable in child.inner_variables() {
3823 if !out.contains(&variable) {
3824 out.push(variable);
3825 }
3826 }
3827 }
3828 out
3829 }
3830 Self::Filter { inner, .. } | Self::Extend { inner, .. } => inner.inner_variables(),
3831 Self::JoinGraphVar {
3832 inner,
3833 graph_var,
3834 active_var,
3835 } => {
3836 let mut out = inner.inner_variables();
3837 out.retain(|v| v != active_var);
3838 if !out.contains(graph_var) {
3839 out.push(graph_var.clone());
3840 }
3841 out
3842 }
3843 Self::Unit | Self::NamedGraphExists { .. } => Vec::new(),
3844 Self::Values(values) => values.output_vars().all(),
3845 Self::NamedGraphs { variable, .. } => vec![variable.clone()],
3846 Self::Slice { inner, .. } | Self::Distinct { inner, .. } | Self::Sort { inner, .. } => {
3847 inner.inner_variables()
3848 }
3849 Self::Group {
3850 inner,
3851 variables,
3852 aggregates,
3853 ..
3854 } => {
3855 let mut out = inner.inner_variables();
3856 for variable in variables {
3857 if !out.contains(variable) {
3858 out.push(variable.clone());
3859 }
3860 }
3861 for (result, agg) in aggregates {
3862 if let AggregateExpression::FunctionCall { expr, .. } = agg {
3863 for variable in crate::expr::variables_in_expression(expr) {
3864 if !out.contains(&variable) {
3865 out.push(variable);
3866 }
3867 }
3868 }
3869 if !out.contains(result) {
3870 out.push(result.clone());
3871 }
3872 }
3873 out
3874 }
3875 Self::DomainCounts {
3878 constraint_var,
3879 head,
3880 count,
3881 ..
3882 } => domain_counts_schema_vars(constraint_var, head, count),
3883 Self::HeadCounts {
3884 counted: _,
3885 group,
3886 count,
3887 ..
3888 } => head_counts_schema_vars(group, count),
3889 Self::PatternCount { count, .. } => vec![count.clone()],
3890 Self::SubSelect(sub) => sub.inner.inner_variables(),
3891 }
3892 }
3893
3894 pub fn output_vars(&self) -> OutputVars {
3896 match self {
3897 Self::Scan(scan) => OutputVars {
3898 always_bound: scan.variables(),
3899 maybe_unbound: Vec::new(),
3900 },
3901 Self::Path(path) => OutputVars {
3902 always_bound: path.variables(),
3903 maybe_unbound: Vec::new(),
3904 },
3905 Self::CustomNode(op) if op.children.is_empty() => OutputVars {
3909 always_bound: op.variables.clone(),
3910 maybe_unbound: Vec::new(),
3911 },
3912 Self::CustomNode(op) => {
3913 let mut vars = OutputVars {
3914 always_bound: op.variables.clone(),
3915 maybe_unbound: Vec::new(),
3916 };
3917 for child in &op.children {
3918 vars = join_output_vars(&vars, &child.output_vars());
3919 }
3920 vars
3921 }
3922 Self::Join { left, right, .. } => {
3923 join_output_vars(&left.output_vars(), &right.output_vars())
3924 }
3925 Self::LeftJoin { left, right, .. } => {
3926 left_join_output_vars(&left.output_vars(), &right.output_vars())
3927 }
3928 Self::Filter { inner, .. } => inner.output_vars(),
3929 Self::JoinGraphVar {
3930 inner,
3931 graph_var,
3932 active_var,
3933 } => join_graph_var_output_vars(&inner.output_vars(), graph_var, active_var),
3934 Self::Union { left, right } => {
3935 union_output_vars(&left.output_vars(), &right.output_vars())
3936 }
3937 Self::Unit | Self::NamedGraphExists { .. } => OutputVars::default(),
3938 Self::Values(values) => values.output_vars(),
3939 Self::NamedGraphs { variable, .. } => OutputVars {
3940 always_bound: vec![variable.clone()],
3941 maybe_unbound: Vec::new(),
3942 },
3943 Self::DomainCounts {
3947 constraint_var,
3948 head,
3949 count,
3950 ..
3951 } => OutputVars {
3952 always_bound: domain_counts_schema_vars(constraint_var, head, count),
3953 maybe_unbound: Vec::new(),
3954 },
3955 Self::HeadCounts {
3956 counted: _,
3957 group,
3958 count,
3959 ..
3960 } => OutputVars {
3961 always_bound: head_counts_schema_vars(group, count),
3962 maybe_unbound: Vec::new(),
3963 },
3964 Self::PatternCount { count, .. } => OutputVars {
3965 always_bound: vec![count.clone()],
3966 maybe_unbound: Vec::new(),
3967 },
3968 Self::Extend {
3969 inner,
3970 variable,
3971 expression,
3972 ..
3973 } => {
3974 let mut out = inner.output_vars();
3975 if extend_var_always_bound(&out, expression) {
3976 if !out.always_bound.contains(variable) {
3977 out.always_bound.push(variable.clone());
3978 }
3979 out.maybe_unbound.retain(|v| v != variable);
3980 } else if !out.contains(variable) {
3981 out.maybe_unbound.push(variable.clone());
3982 }
3983 out
3984 }
3985 Self::Slice { inner, .. } | Self::Distinct { inner, .. } | Self::Sort { inner, .. } => {
3986 inner.output_vars()
3987 }
3988 Self::Group {
3989 inner,
3990 variables,
3991 aggregates,
3992 ..
3993 } => group_output_vars(&inner.output_vars(), variables, aggregates),
3994 Self::SubSelect(sub) => {
3995 let inner_out = sub.inner.output_vars();
3999 let mut always_bound = Vec::new();
4000 let mut maybe_unbound = Vec::new();
4001 for variable in &sub.variables {
4002 if inner_out.is_always_bound(variable) {
4003 always_bound.push(variable.clone());
4004 } else {
4005 maybe_unbound.push(variable.clone());
4006 }
4007 }
4008 OutputVars {
4009 always_bound,
4010 maybe_unbound,
4011 }
4012 }
4013 }
4014 }
4015
4016 pub fn variables(&self) -> Vec<Variable> {
4018 self.output_vars().all()
4019 }
4020
4021 pub fn produced_row_count_estimate(&self) -> u64 {
4023 match self {
4024 Self::Scan(scan) => scan.produced_row_count_estimate,
4025 Self::Path(path) => path.produced_row_count_estimate,
4026 Self::Join { meta, .. } => meta.produced_row_count_estimate,
4027 Self::LeftJoin { meta, .. } => meta.produced_row_count_estimate.max(1),
4028 Self::Filter {
4029 inner,
4030 early,
4031 residual,
4032 exists,
4033 ..
4034 } => apply_filter_selectivity(
4035 inner.produced_row_count_estimate().max(1),
4036 early.as_ref(),
4037 residual.as_ref(),
4038 exists,
4039 ),
4040 Self::Union { left, right } => left
4041 .produced_row_count_estimate()
4042 .saturating_add(right.produced_row_count_estimate())
4043 .max(1),
4044 Self::CustomNode(op) => op.produced_row_count_estimate,
4045 Self::Unit | Self::NamedGraphExists { .. } => 1,
4046 Self::Values(values) => values.produced_row_count_estimate(),
4047 Self::NamedGraphs {
4048 produced_row_count_estimate,
4049 ..
4050 } => *produced_row_count_estimate,
4051 Self::DomainCounts {
4052 produced_row_count_estimate,
4053 ..
4054 } => *produced_row_count_estimate,
4055 Self::HeadCounts {
4056 produced_row_count_estimate,
4057 ..
4058 } => *produced_row_count_estimate,
4059 Self::PatternCount {
4060 produced_row_count_estimate,
4061 ..
4062 } => *produced_row_count_estimate,
4063 Self::JoinGraphVar { inner, .. }
4064 | Self::Extend { inner, .. }
4065 | Self::Distinct { inner, .. }
4066 | Self::Sort { inner, .. } => inner.produced_row_count_estimate(),
4067 Self::Slice {
4068 inner,
4069 start,
4070 length,
4071 } => {
4072 let after_offset = inner.produced_row_count_estimate().saturating_sub(*start);
4073 match length {
4074 Some(n) => after_offset.min(*n),
4075 None => after_offset,
4076 }
4077 }
4078 Self::Group {
4079 inner, variables, ..
4080 } => {
4081 if variables.is_empty() {
4082 1
4083 } else {
4084 inner.produced_row_count_estimate().max(1)
4085 }
4086 }
4087 Self::SubSelect(sub) => sub.produced_row_count_estimate(),
4088 }
4089 }
4090
4091 pub fn as_scan(&self) -> Option<&ScanOp> {
4093 match self {
4094 Self::Scan(scan) => Some(scan),
4095 _ => None,
4096 }
4097 }
4098
4099 pub fn as_scan_mut(&mut self) -> Option<&mut ScanOp> {
4102 match self {
4103 Self::Scan(scan) => Some(scan),
4104 _ => None,
4105 }
4106 }
4107
4108 pub fn as_broadcast_scan(&self) -> Option<&ScanOp> {
4110 match self {
4111 Self::Scan(scan) => Some(scan),
4112 Self::Filter { inner, .. } | Self::Extend { inner, .. } => inner.as_broadcast_scan(),
4113 _ => None,
4114 }
4115 }
4116
4117 pub fn as_union(&self) -> Option<&PlanNode> {
4119 match self {
4120 Self::Union { .. } => Some(self),
4121 Self::Filter { inner, .. } | Self::Extend { inner, .. } => inner.as_union(),
4122 _ => None,
4123 }
4124 }
4125
4126 pub fn as_path(&self) -> Option<&PathOp> {
4128 match self {
4129 Self::Path(path) => Some(path),
4130 _ => None,
4131 }
4132 }
4133
4134 pub fn as_dependent_path(&self) -> Option<&PathOp> {
4136 match self {
4137 Self::Path(path) => Some(path),
4138 Self::Filter { inner, .. } | Self::Extend { inner, .. } => inner.as_dependent_path(),
4139 _ => None,
4140 }
4141 }
4142
4143 pub fn as_extend_path(&self) -> Option<&PathOp> {
4148 match self {
4149 Self::Path(path) => Some(path),
4150 Self::Extend { inner, .. } => inner.as_extend_path(),
4151 _ => None,
4152 }
4153 }
4154
4155 pub fn as_subselect(&self) -> Option<&SubSelectOp> {
4157 match self {
4158 Self::SubSelect(sub) => Some(sub),
4159 _ => None,
4160 }
4161 }
4162}
4163
4164#[derive(Debug, Clone, PartialEq)]
4166pub struct LogicalPlan {
4167 pub root: PlanNode,
4169 pub projection: Vec<Variable>,
4171 exact_filter_removed: bool,
4183}
4184
4185fn attach_const_seeds(node: &mut PlanNode) {
4196 match node {
4197 PlanNode::Extend {
4198 expression,
4199 const_strings,
4200 const_blobs,
4201 inner,
4202 ..
4203 } => {
4204 collect_expression_const_seeds(expression, const_strings, const_blobs);
4205 attach_const_seeds(inner);
4206 }
4207 PlanNode::Group {
4208 aggregates,
4209 const_strings,
4210 const_blobs,
4211 inner,
4212 ..
4213 } => {
4214 for (_, agg) in aggregates {
4215 match agg {
4216 AggregateExpression::FunctionCall { expr, .. } => {
4217 collect_expression_const_seeds(expr, const_strings, const_blobs);
4218 }
4219 AggregateExpression::CountSolutions { .. } => {}
4224 }
4225 }
4226 attach_const_seeds(inner);
4227 }
4228 PlanNode::Filter { inner, exists, .. } => {
4229 for clause in exists {
4230 attach_const_seeds(&mut clause.body);
4231 }
4232 attach_const_seeds(inner);
4233 }
4234 PlanNode::Join { left, right, .. }
4235 | PlanNode::LeftJoin { left, right, .. }
4236 | PlanNode::Union { left, right } => {
4237 attach_const_seeds(left);
4238 attach_const_seeds(right);
4239 }
4240 PlanNode::SubSelect(sub) => attach_const_seeds(&mut sub.inner),
4241 PlanNode::JoinGraphVar { inner, .. }
4242 | PlanNode::Slice { inner, .. }
4243 | PlanNode::Distinct { inner, .. }
4244 | PlanNode::Sort { inner, .. } => attach_const_seeds(inner),
4245 PlanNode::CustomNode(op) => {
4252 for child in &mut op.children {
4253 attach_const_seeds(child);
4254 }
4255 }
4256 PlanNode::Scan(_)
4257 | PlanNode::Path(_)
4258 | PlanNode::Values(_)
4259 | PlanNode::Unit
4260 | PlanNode::NamedGraphs { .. }
4261 | PlanNode::NamedGraphExists { .. }
4262 | PlanNode::DomainCounts { .. }
4263 | PlanNode::HeadCounts { .. }
4264 | PlanNode::PatternCount { .. } => {}
4265 }
4266}
4267
4268fn collect_expression_const_seeds(
4276 expression: &Expression,
4277 strings: &mut Vec<(StrHash, String)>,
4278 blobs: &mut Vec<(StrHash, Vec<u8>)>,
4279) {
4280 match expression {
4281 Expression::NamedNode(node) => {
4282 push_seed_entries_for(&Term::NamedNode(node.clone()), strings, blobs);
4283 }
4284 Expression::Literal(literal) => {
4285 push_seed_entries_for(&Term::Literal(literal.clone()), strings, blobs);
4286 }
4287 Expression::Variable(_) | Expression::Bound(_) | Expression::Exists(_) => {}
4288 Expression::Not(inner) | Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => {
4289 collect_expression_const_seeds(inner, strings, blobs);
4290 }
4291 Expression::And(a, b)
4292 | Expression::Or(a, b)
4293 | Expression::SameTerm(a, b)
4294 | Expression::Equal(a, b)
4295 | Expression::Greater(a, b)
4296 | Expression::GreaterOrEqual(a, b)
4297 | Expression::Less(a, b)
4298 | Expression::LessOrEqual(a, b)
4299 | Expression::Add(a, b)
4300 | Expression::Subtract(a, b)
4301 | Expression::Multiply(a, b)
4302 | Expression::Divide(a, b) => {
4303 collect_expression_const_seeds(a, strings, blobs);
4304 collect_expression_const_seeds(b, strings, blobs);
4305 }
4306 Expression::FunctionCall(_, args) => {
4307 for arg in args {
4308 collect_expression_const_seeds(arg, strings, blobs);
4309 }
4310 }
4311 Expression::If(a, b, c) => {
4312 collect_expression_const_seeds(a, strings, blobs);
4313 collect_expression_const_seeds(b, strings, blobs);
4314 collect_expression_const_seeds(c, strings, blobs);
4315 }
4316 Expression::Coalesce(args) => {
4317 for arg in args {
4318 collect_expression_const_seeds(arg, strings, blobs);
4319 }
4320 }
4321 Expression::In(left, args) => {
4322 collect_expression_const_seeds(left, strings, blobs);
4323 for arg in args {
4324 collect_expression_const_seeds(arg, strings, blobs);
4325 }
4326 }
4327 }
4328}
4329
4330fn push_seed_entries_for(
4336 term: &Term,
4337 strings: &mut Vec<(StrHash, String)>,
4338 blobs: &mut Vec<(StrHash, Vec<u8>)>,
4339) {
4340 let (_, (new_strings, new_blobs)) = crate::query::caches::mint_const_entries(term);
4341 for (hash, raw) in new_strings {
4342 if !strings.iter().any(|(existing, _)| *existing == hash) {
4343 strings.push((hash, raw));
4344 }
4345 }
4346 for (hash, payload) in new_blobs {
4347 if !blobs.iter().any(|(existing, _)| *existing == hash) {
4348 blobs.push((hash, payload));
4349 }
4350 }
4351}
4352
4353impl LogicalPlan {
4354 #[cfg(test)]
4359 pub(crate) fn from_root_for_test(root: PlanNode, projection: Vec<Variable>) -> Self {
4360 Self {
4361 root,
4362 projection,
4363 exact_filter_removed: false,
4364 }
4365 }
4366
4367 pub fn parse(sparql: &str) -> Result<Self, ComputeError> {
4369 Self::parse_with_profile(sparql, None)
4370 }
4371
4372 pub fn parse_with_context(sparql: &str, ctx: &QueryContext) -> Result<Self, ComputeError> {
4376 let parse_started = std::time::Instant::now();
4377 let query = crate::rephrase_error::parse_query(sparql)?;
4378 let Query::Select {
4379 pattern, dataset, ..
4380 } = query
4381 else {
4382 return Err(ComputeError::UnsupportedSparql(
4383 "only SELECT queries are supported".into(),
4384 ));
4385 };
4386 let ctx =
4387 ctx.clone()
4388 .with_dataset(QueryDataset::resolve(&[], &[], dataset.as_ref(), false)?);
4389 let (variables, optimized, slice, distinct, order) =
4390 prepare_algebra(pattern, ctx.eval_env())?;
4391 PLANNER_PARSE_US.with(|cell| cell.set(parse_started.elapsed().as_micros() as u64));
4392 Self::from_prepared(variables, optimized, slice, distinct, order, None, &ctx)
4393 }
4394
4395 pub fn parse_with_profile(
4397 sparql: &str,
4398 profile: Option<&StatsProfile>,
4399 ) -> Result<Self, ComputeError> {
4400 let parse_started = std::time::Instant::now();
4401 let query = crate::rephrase_error::parse_query(sparql)?;
4402 let Query::Select {
4403 pattern, dataset, ..
4404 } = query
4405 else {
4406 return Err(ComputeError::UnsupportedSparql(
4407 "only SELECT queries are supported".into(),
4408 ));
4409 };
4410 let ctx = QueryContext::from_snapshot(SnapshotId::latest())
4411 .with_dataset(QueryDataset::resolve(&[], &[], dataset.as_ref(), false)?);
4412 let (variables, optimized, slice, distinct, order) =
4413 prepare_algebra(pattern, ctx.eval_env())?;
4414 PLANNER_PARSE_US.with(|cell| cell.set(parse_started.elapsed().as_micros() as u64));
4415 Self::from_prepared(variables, optimized, slice, distinct, order, profile, &ctx)
4416 }
4417
4418 pub fn from_algebra(
4423 pattern: GraphPattern,
4424 profile: Option<&StatsProfile>,
4425 ) -> Result<Self, ComputeError> {
4426 Self::from_algebra_with_ctx(
4427 pattern,
4428 profile,
4429 &QueryContext::from_snapshot(SnapshotId::latest()),
4430 )
4431 }
4432
4433 pub(crate) fn from_algebra_with_ctx(
4435 pattern: GraphPattern,
4436 profile: Option<&StatsProfile>,
4437 ctx: &QueryContext,
4438 ) -> Result<Self, ComputeError> {
4439 let parse_started = std::time::Instant::now();
4440 let (variables, optimized, slice, distinct, order) =
4441 prepare_algebra(pattern, ctx.eval_env())?;
4442 PLANNER_PARSE_US.with(|cell| cell.set(parse_started.elapsed().as_micros() as u64));
4443 Self::from_prepared(variables, optimized, slice, distinct, order, profile, ctx)
4444 }
4445
4446 pub fn from_ask_algebra(
4452 pattern: GraphPattern,
4453 profile: Option<&StatsProfile>,
4454 ) -> Result<Self, ComputeError> {
4455 Self::from_ask_algebra_with_ctx(
4456 pattern,
4457 profile,
4458 &QueryContext::from_snapshot(SnapshotId::latest()),
4459 )
4460 }
4461
4462 pub(crate) fn from_ask_algebra_with_ctx(
4464 pattern: GraphPattern,
4465 profile: Option<&StatsProfile>,
4466 ctx: &QueryContext,
4467 ) -> Result<Self, ComputeError> {
4468 Self::from_algebra_with_ctx(cap_ask_slice(flatten_ask_subselect(pattern)), profile, ctx)
4469 }
4470
4471 fn from_prepared(
4472 variables: Vec<Variable>,
4473 optimized: GraphPattern,
4474 slice: Option<SliceSpec>,
4475 distinct: bool,
4476 order: Vec<SortKey>,
4477 profile: Option<&StatsProfile>,
4478 ctx: &QueryContext,
4479 ) -> Result<Self, ComputeError> {
4480 let plan_started = std::time::Instant::now();
4481 clear_union_domain_cache();
4482 let pass_started = std::time::Instant::now();
4483 let mut root = lower_pattern(
4484 &optimized,
4485 profile,
4486 &IncomingBound::default(),
4487 ctx,
4488 &GraphScope::Default,
4489 )?;
4490 fold_identity_filters(&mut root, profile);
4491 classify_exists_in_plan(&mut root)?;
4492 for plugin in crate::plugin::process_plugins().planner_plugins() {
4500 plugin.rewrite(&mut root, ctx)?;
4501 }
4502 let lower_us = pass_started.elapsed().as_micros() as u64;
4503 let pass_started = std::time::Instant::now();
4504 reassociate_inner_joins(&mut root, profile, Some(ctx));
4513 restamp_broadcast_marks(&mut root, profile);
4517 eliminate_head_counts_groups(&mut root, profile);
4518 eliminate_domain_counts_groups(&mut root, profile);
4519 eliminate_pattern_count_groups(&mut root);
4523 crate::iri_facts::derive_iri_facts(&mut root);
4528 let rewrite_us = pass_started.elapsed().as_micros() as u64;
4529 let pass_started = std::time::Instant::now();
4530 let mut order_keys: Vec<Variable> = Vec::new();
4550 for key in &order {
4551 let mut mentions = Vec::new();
4552 collect_expression_mentions(&mut mentions, &key.expression);
4553 for (variable, _) in mentions {
4554 if !order_keys.contains(&variable) {
4555 order_keys.push(variable);
4556 }
4557 }
4558 }
4559 for round in 0..2 {
4560 refinalize_joins(&mut root, profile, Some(ctx));
4561 restamp_broadcast_marks(&mut root, profile);
4562 let gate_ctx = (round == 1 && slice.is_none()).then_some(ctx);
4571 annotate_liveness(
4572 &mut root,
4573 &variables,
4574 &order_keys,
4575 distinct,
4576 profile,
4577 gate_ctx,
4578 );
4579 }
4580 let seat_us = pass_started.elapsed().as_micros() as u64;
4581 let pass_started = std::time::Instant::now();
4582 let exact_filter_removed =
4590 crate::scan_comparisons::derive_scan_comparisons(&mut root, ctx.eager_scan_filter());
4591 if distinct {
4593 root = PlanNode::Distinct {
4594 inner: Box::new(root),
4595 columns: variables.clone(),
4596 };
4597 }
4598 if !order.is_empty() {
4599 root = PlanNode::Sort {
4600 inner: Box::new(root),
4601 keys: order,
4602 };
4603 }
4604 let sliced = slice.is_some();
4607 if let Some(slice) = slice {
4608 prefer_broadcast_for_small_slice(&mut root, slice.start, slice.length);
4609 root = PlanNode::Slice {
4610 inner: Box::new(root),
4611 start: slice.start,
4612 length: slice.length,
4613 };
4614 }
4615 stamp_star_join_shapes(&mut root);
4628 restamp_fetch_once(&mut root, profile, Some(ctx), sliced);
4629 if !sliced {
4638 stamp_semi_join_strategy(&mut root, profile, sliced, Some(ctx), &[]);
4639 }
4640 ctx.log(
4644 crate::context::LogLevel::Debug,
4645 &format!(
4646 "fetch-once-stamps after restamp: {}",
4647 count_stamps_after_restamp(&root)
4648 ),
4649 );
4650 restamp_joins_produced_row_count_estimate(&mut root, profile);
4656 let stamps_us = pass_started.elapsed().as_micros() as u64;
4657 compile_regexes_in_node(&root, ctx.eval_env());
4658 let total_us = plan_started.elapsed().as_micros() as u64;
4659 let parse_us = PLANNER_PARSE_US.with(|cell| cell.replace(0));
4660 if ctx.log_sink().enabled_at(crate::context::LogLevel::Debug) {
4661 ctx.log(
4662 crate::context::LogLevel::Debug,
4663 &format!(
4664 "planner-time: parse={parse_us}µs lower={lower_us}µs \
4665 rewrite={rewrite_us}µs seat={seat_us}µs stamps={stamps_us}µs \
4666 total={total_us}µs"
4667 ),
4668 );
4669 }
4670 attach_const_seeds(&mut root);
4675 if ctx.log_sink().enabled_at(crate::context::LogLevel::Debug) {
4676 ctx.log(
4677 crate::context::LogLevel::Debug,
4678 &format!("plan-tree:\n{}", crate::explain::format_plan_tree(&root)),
4679 );
4680 }
4681 Ok(Self {
4682 root,
4683 projection: variables,
4684 exact_filter_removed,
4685 })
4686 }
4687
4688 pub fn depends_on_eager_scan_filter(&self) -> bool {
4697 self.exact_filter_removed
4698 }
4699
4700 pub fn scans(&self) -> Option<Vec<&ScanOp>> {
4702 let mut out = Vec::new();
4703 collect_bgp_scans(&self.root, &mut out)?;
4704 Some(out)
4705 }
4706
4707 pub fn join_ops(&self) -> Option<Vec<JoinEdge>> {
4709 let mut out = Vec::new();
4710 collect_join_edges(&self.root, &mut out)?;
4711 Some(out)
4712 }
4713}
4714
4715fn compile_regexes_in_node(node: &PlanNode, env: &crate::expr::ExprEvalEnv) {
4716 match node {
4717 PlanNode::CustomNode(op) => {
4718 for child in &op.children {
4719 compile_regexes_in_node(child, env);
4720 }
4721 }
4722 PlanNode::Filter {
4723 inner,
4724 early,
4725 residual,
4726 exists,
4727 ..
4728 } => {
4729 if let Some(expr) = early {
4730 env.precompile_from_expression(expr);
4731 }
4732 if let Some(expr) = residual {
4733 env.precompile_from_expression(expr);
4734 }
4735 compile_regexes_in_node(inner, env);
4736 for clause in exists {
4737 compile_regexes_in_node(&clause.body, env);
4738 }
4739 }
4740 PlanNode::LeftJoin {
4741 left,
4742 right,
4743 early_filter,
4744 residual_filter,
4745 ..
4746 } => {
4747 if let Some(expr) = early_filter {
4748 env.precompile_from_expression(expr);
4749 }
4750 if let Some(expr) = residual_filter {
4751 env.precompile_from_expression(expr);
4752 }
4753 compile_regexes_in_node(left, env);
4754 compile_regexes_in_node(right, env);
4755 }
4756 PlanNode::Extend {
4757 inner, expression, ..
4758 } => {
4759 env.precompile_from_expression(expression);
4760 compile_regexes_in_node(inner, env);
4761 }
4762 PlanNode::Group {
4763 inner, aggregates, ..
4764 } => {
4765 for (_, agg) in aggregates {
4766 if let spargebra::algebra::AggregateExpression::FunctionCall { expr, .. } = agg {
4767 env.precompile_from_expression(expr);
4768 }
4769 }
4770 compile_regexes_in_node(inner, env);
4771 }
4772 PlanNode::SubSelect(sub) => compile_regexes_in_node(&sub.inner, env),
4773 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right, .. } => {
4774 compile_regexes_in_node(left, env);
4775 compile_regexes_in_node(right, env);
4776 }
4777 PlanNode::Sort { inner, keys } => {
4778 for key in keys {
4779 env.precompile_from_expression(&key.expression);
4780 }
4781 compile_regexes_in_node(inner, env);
4782 }
4783 PlanNode::Slice { inner, .. }
4784 | PlanNode::Distinct { inner, .. }
4785 | PlanNode::JoinGraphVar { inner, .. } => {
4786 compile_regexes_in_node(inner, env);
4787 }
4788 PlanNode::Scan(_)
4789 | PlanNode::Path(_)
4790 | PlanNode::Values(_)
4791 | PlanNode::NamedGraphs { .. }
4792 | PlanNode::NamedGraphExists { .. }
4793 | PlanNode::DomainCounts { .. }
4794 | PlanNode::HeadCounts { .. }
4795 | PlanNode::PatternCount { .. }
4796 | PlanNode::Unit => {}
4797 }
4798}
4799
4800fn collect_bgp_scans<'a>(node: &'a PlanNode, out: &mut Vec<&'a ScanOp>) -> Option<()> {
4801 match node {
4802 PlanNode::Scan(scan) => {
4803 out.push(scan);
4804 Some(())
4805 }
4806 PlanNode::Path(_)
4807 | PlanNode::Values(_)
4808 | PlanNode::NamedGraphs { .. }
4809 | PlanNode::NamedGraphExists { .. }
4810 | PlanNode::DomainCounts { .. }
4811 | PlanNode::HeadCounts { .. }
4812 | PlanNode::PatternCount { .. } | PlanNode::CustomNode(_)
4815 | PlanNode::Unit => Some(()),
4816 PlanNode::Join { left, right, .. } => {
4817 collect_bgp_scans(left, out)?;
4818 collect_bgp_scans(right, out)
4819 }
4820 PlanNode::Slice { inner, .. }
4821 | PlanNode::Distinct { inner, .. }
4822 | PlanNode::Sort { inner, .. }
4823 | PlanNode::Group { inner, .. }
4824 | PlanNode::JoinGraphVar { inner, .. } => collect_bgp_scans(inner, out),
4825 PlanNode::LeftJoin { .. }
4826 | PlanNode::Filter { .. }
4827 | PlanNode::Union { .. }
4828 | PlanNode::Extend { .. }
4829 | PlanNode::SubSelect(_) => None,
4830 }
4831}
4832
4833fn collect_join_edges(node: &PlanNode, out: &mut Vec<JoinEdge>) -> Option<()> {
4834 match node {
4835 PlanNode::Scan(_)
4836 | PlanNode::Path(_)
4837 | PlanNode::Values(_)
4838 | PlanNode::NamedGraphs { .. }
4839 | PlanNode::NamedGraphExists { .. }
4840 | PlanNode::DomainCounts { .. }
4841 | PlanNode::HeadCounts { .. }
4842 | PlanNode::PatternCount { .. }
4843 | PlanNode::CustomNode(_)
4844 | PlanNode::Unit => Some(()),
4845 PlanNode::Join {
4846 left,
4847 right,
4848 hash_keys,
4849 probe_key_domains: _,
4850 probe_key_overlap_milli: _,
4851 rhs_hostable_keys: _,
4852 meta,
4853 } => {
4854 collect_join_edges(left, out)?;
4855 match right.as_ref() {
4856 PlanNode::Scan(_)
4857 | PlanNode::Path(_)
4858 | PlanNode::Values(_)
4859 | PlanNode::NamedGraphs { .. }
4860 | PlanNode::NamedGraphExists { .. }
4861 | PlanNode::Unit => {}
4862 _ => {
4863 collect_join_edges(right, out)?;
4864 }
4865 }
4866 out.push(JoinEdge {
4867 hash_keys: hash_keys.clone(),
4868 meta: *meta,
4869 });
4870 Some(())
4871 }
4872 PlanNode::Slice { inner, .. }
4873 | PlanNode::Distinct { inner, .. }
4874 | PlanNode::Sort { inner, .. }
4875 | PlanNode::Group { inner, .. }
4876 | PlanNode::JoinGraphVar { inner, .. } => collect_join_edges(inner, out),
4877 PlanNode::LeftJoin { .. }
4878 | PlanNode::Filter { .. }
4879 | PlanNode::Union { .. }
4880 | PlanNode::Extend { .. }
4881 | PlanNode::SubSelect(_) => None,
4882 }
4883}
4884
4885pub(crate) struct SliceSpec {
4887 pub(crate) start: u64,
4888 pub(crate) length: Option<u64>,
4889}
4890
4891pub(crate) fn flatten_ask_subselect(pattern: GraphPattern) -> GraphPattern {
4895 match pattern {
4896 GraphPattern::Slice {
4897 inner,
4898 start,
4899 length,
4900 } => GraphPattern::Slice {
4901 inner: Box::new(flatten_ask_subselect(*inner)),
4902 start,
4903 length,
4904 },
4905 GraphPattern::Distinct { inner } => GraphPattern::Distinct {
4906 inner: Box::new(flatten_ask_subselect(*inner)),
4907 },
4908 GraphPattern::Project { inner, variables } => match *inner {
4909 GraphPattern::Project {
4910 inner: nested_inner,
4911 ..
4912 } => GraphPattern::Project {
4913 inner: nested_inner,
4914 variables,
4915 },
4916 other => GraphPattern::Project {
4917 inner: Box::new(other),
4918 variables,
4919 },
4920 },
4921 other => other,
4922 }
4923}
4924
4925pub(crate) fn cap_ask_slice(pattern: GraphPattern) -> GraphPattern {
4927 match pattern {
4928 GraphPattern::Slice {
4929 inner,
4930 start,
4931 length: Some(0),
4932 } => GraphPattern::Slice {
4933 inner,
4934 start,
4935 length: Some(0),
4936 },
4937 GraphPattern::Slice { inner, start, .. } => GraphPattern::Slice {
4938 inner,
4939 start,
4940 length: Some(1),
4941 },
4942 GraphPattern::Distinct { inner } => GraphPattern::Distinct {
4943 inner: Box::new(cap_ask_slice(*inner)),
4944 },
4945 other => GraphPattern::Slice {
4946 inner: Box::new(other),
4947 start: 0,
4948 length: Some(1),
4949 },
4950 }
4951}
4952
4953fn prefer_broadcast_for_small_slice(root: &mut PlanNode, start: u64, length: Option<u64>) {
4956 let Some(n) = length else {
4957 return;
4958 };
4959 if n == 0 {
4960 return;
4961 }
4962 let budget = start.saturating_add(n);
4963 if !(1..=PUSHDOWN_TERMS_LIMIT).contains(&budget) {
4964 return;
4965 }
4966 replan_scan_joins_strat_broadcast(root);
4967}
4968
4969fn replan_scan_joins_strat_broadcast(node: &mut PlanNode) {
4970 match node {
4971 PlanNode::Join {
4972 left, right, meta, ..
4973 } => {
4974 if right.as_broadcast_scan().is_some() || right.as_dependent_path().is_some() {
4975 meta.strategy = JoinStrategy::Broadcast;
4976 }
4977 replan_scan_joins_strat_broadcast(left);
4978 replan_scan_joins_strat_broadcast(right);
4979 }
4980 PlanNode::CustomNode(op) => {
4981 for child in &mut op.children {
4982 replan_scan_joins_strat_broadcast(child);
4983 }
4984 }
4985 PlanNode::LeftJoin { left, right, .. } | PlanNode::Union { left, right } => {
4986 replan_scan_joins_strat_broadcast(left);
4987 replan_scan_joins_strat_broadcast(right);
4988 }
4989 PlanNode::Filter { inner, .. }
4990 | PlanNode::Extend { inner, .. }
4991 | PlanNode::Slice { inner, .. }
4992 | PlanNode::Distinct { inner, .. }
4993 | PlanNode::Sort { inner, .. }
4994 | PlanNode::Group { inner, .. }
4995 | PlanNode::JoinGraphVar { inner, .. } => replan_scan_joins_strat_broadcast(inner),
4996 PlanNode::SubSelect(_) => {}
4999 PlanNode::Scan(_)
5000 | PlanNode::Path(_)
5001 | PlanNode::Values(_)
5002 | PlanNode::NamedGraphs { .. }
5003 | PlanNode::NamedGraphExists { .. }
5004 | PlanNode::DomainCounts { .. }
5005 | PlanNode::HeadCounts { .. }
5006 | PlanNode::PatternCount { .. }
5007 | PlanNode::Unit => {}
5008 }
5009}
5010
5011pub(crate) fn wrap_project_slice(
5013 variables: Vec<Variable>,
5014 inner: GraphPattern,
5015 slice: Option<SliceSpec>,
5016 distinct: bool,
5017 order: Vec<SortKey>,
5018) -> GraphPattern {
5019 let mut pattern = GraphPattern::Project {
5020 inner: Box::new(inner),
5021 variables,
5022 };
5023 if distinct {
5024 pattern = GraphPattern::Distinct {
5025 inner: Box::new(pattern),
5026 };
5027 }
5028 if !order.is_empty() {
5029 pattern = GraphPattern::OrderBy {
5030 inner: Box::new(pattern),
5031 expression: order
5032 .into_iter()
5033 .map(|key| {
5034 if key.descending {
5035 OrderExpression::Desc(key.expression)
5036 } else {
5037 OrderExpression::Asc(key.expression)
5038 }
5039 })
5040 .collect(),
5041 };
5042 }
5043 if let Some(slice) = slice {
5044 pattern = GraphPattern::Slice {
5045 inner: Box::new(pattern),
5046 start: slice.start as usize,
5047 length: slice.length.map(|n| n as usize),
5048 };
5049 }
5050 pattern
5051}
5052
5053#[allow(clippy::type_complexity)]
5055pub(crate) fn prepare_algebra(
5056 pattern: GraphPattern,
5057 fold_eval: &crate::expr::ExprEvalEnv,
5058) -> Result<
5059 (
5060 Vec<Variable>,
5061 GraphPattern,
5062 Option<SliceSpec>,
5063 bool,
5064 Vec<SortKey>,
5065 ),
5066 ComputeError,
5067> {
5068 let mut pattern = pattern;
5069 let mut slice = None;
5070 let mut distinct = false;
5071 let mut order = Vec::new();
5072 loop {
5073 match pattern {
5074 GraphPattern::Slice {
5075 inner,
5076 start,
5077 length,
5078 } => {
5079 slice = Some(SliceSpec {
5080 start: start as u64,
5081 length: length.map(|n| n as u64),
5082 });
5083 pattern = *inner;
5084 }
5085 GraphPattern::OrderBy { inner, expression } => {
5086 order = expression
5087 .into_iter()
5088 .map(|oe| match oe {
5089 OrderExpression::Asc(expression) => SortKey {
5090 expression,
5091 descending: false,
5092 },
5093 OrderExpression::Desc(expression) => SortKey {
5094 expression,
5095 descending: true,
5096 },
5097 })
5098 .collect();
5099 pattern = *inner;
5100 }
5101 GraphPattern::Distinct { inner } => {
5102 distinct = true;
5103 pattern = *inner;
5104 }
5105 GraphPattern::Reduced { inner } => {
5106 pattern = *inner;
5110 }
5111 other => {
5112 pattern = other;
5113 break;
5114 }
5115 }
5116 }
5117
5118 let GraphPattern::Project { inner, variables } = pattern else {
5119 return Err(ComputeError::UnsupportedSparql(format!(
5120 "unsupported query shape: {}",
5121 shape_name(&pattern)
5122 )));
5123 };
5124
5125 let optimized = {
5126 let mut pins: Vec<PinnedConjunct> = Vec::new();
5140 let pinned = if crate::plugin::process_plugins()
5141 .planner_plugins()
5142 .next()
5143 .is_some()
5144 {
5145 let pin: &dyn Fn(&Expression) -> bool = &pins_candidate_conjunct;
5146 pin_candidate_conjuncts(*inner, pin, &mut pins)
5147 } else {
5148 *inner
5149 };
5150 let pins = PinnedConjuncts::new(pins);
5151 let restored = optimize_preserving_graph(pinned);
5152 let folded = crate::expr::fold_constants(restored, fold_eval);
5153 let flattened = crate::alt_to_union::flatten_alternative_paths(folded);
5157 let mut visible = variables.clone();
5161 let mut order_mentions = Vec::new();
5162 for key in &order {
5163 collect_expression_mentions(&mut order_mentions, &key.expression);
5164 }
5165 for (variable, _) in order_mentions {
5166 if !visible.contains(&variable) {
5167 visible.push(variable);
5168 }
5169 }
5170 for variable in pins.variables() {
5175 if !visible.contains(&variable) {
5176 visible.push(variable);
5177 }
5178 }
5179 let with_values =
5180 push_values_into_union(place_values_at_lca_with_live(flattened, &visible));
5181 let unpin = |expression: &Expression| pins.unpin(expression);
5186 let forced = crate::optional_to_join::replace_filter_forced_joins(with_values, &unpin);
5187 let grounded = push_groundings_into_subselects(forced);
5188 if pins.is_empty() {
5189 grounded
5190 } else {
5191 let mut seen = vec![0u32; pins.len()];
5192 let mut anchors = vec![0u32; pins.len()];
5193 let optimized = restore_and_sink_conjuncts(grounded, &pins, &mut seen);
5194 let optimized = strip_pin_extends(optimized, &pins, &mut anchors);
5195 check_pin_survival(&optimized, &pins, &seen, &anchors)?;
5196 optimized
5197 }
5198 };
5199 Ok((variables, optimized, slice, distinct, order))
5200}
5201
5202fn optimize_preserving_graph(pattern: GraphPattern) -> GraphPattern {
5206 if !pattern_contains_graph(&pattern) {
5207 return sparopt_roundtrip(pattern);
5208 }
5209 match pattern {
5210 GraphPattern::Graph { name, inner } => GraphPattern::Graph {
5211 name,
5212 inner: Box::new(optimize_preserving_graph(*inner)),
5213 },
5214 GraphPattern::Join { left, right } => GraphPattern::Join {
5215 left: Box::new(optimize_preserving_graph(*left)),
5216 right: Box::new(optimize_preserving_graph(*right)),
5217 },
5218 GraphPattern::LeftJoin {
5219 left,
5220 right,
5221 expression,
5222 } => GraphPattern::LeftJoin {
5223 left: Box::new(optimize_preserving_graph(*left)),
5224 right: Box::new(optimize_preserving_graph(*right)),
5225 expression,
5226 },
5227 GraphPattern::Union { left, right } => GraphPattern::Union {
5228 left: Box::new(optimize_preserving_graph(*left)),
5229 right: Box::new(optimize_preserving_graph(*right)),
5230 },
5231 GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
5232 expr,
5233 inner: Box::new(optimize_preserving_graph(*inner)),
5234 },
5235 GraphPattern::Extend {
5236 inner,
5237 variable,
5238 expression,
5239 } => GraphPattern::Extend {
5240 inner: Box::new(optimize_preserving_graph(*inner)),
5241 variable,
5242 expression,
5243 },
5244 GraphPattern::Minus { left, right } => GraphPattern::Minus {
5245 left: Box::new(optimize_preserving_graph(*left)),
5246 right: Box::new(optimize_preserving_graph(*right)),
5247 },
5248 GraphPattern::Slice {
5249 inner,
5250 start,
5251 length,
5252 } => GraphPattern::Slice {
5253 inner: Box::new(optimize_preserving_graph(*inner)),
5254 start,
5255 length,
5256 },
5257 GraphPattern::Group {
5258 inner,
5259 variables,
5260 aggregates,
5261 } => GraphPattern::Group {
5262 inner: Box::new(optimize_preserving_graph(*inner)),
5263 variables,
5264 aggregates,
5265 },
5266 GraphPattern::Project { inner, variables } => GraphPattern::Project {
5267 inner: Box::new(optimize_preserving_graph(*inner)),
5268 variables,
5269 },
5270 GraphPattern::Distinct { inner } => GraphPattern::Distinct {
5271 inner: Box::new(optimize_preserving_graph(*inner)),
5272 },
5273 GraphPattern::Reduced { inner } => GraphPattern::Reduced {
5274 inner: Box::new(optimize_preserving_graph(*inner)),
5275 },
5276 GraphPattern::OrderBy { inner, expression } => GraphPattern::OrderBy {
5277 inner: Box::new(optimize_preserving_graph(*inner)),
5278 expression,
5279 },
5280 GraphPattern::Service {
5281 name,
5282 inner,
5283 silent,
5284 } => GraphPattern::Service {
5285 name,
5286 inner: Box::new(optimize_preserving_graph(*inner)),
5287 silent,
5288 },
5289 other => sparopt_roundtrip(other),
5290 }
5291}
5292
5293struct PinnedConjunct {
5297 ghost: Variable,
5300 expression: Expression,
5302}
5303
5304fn expression_contains_exists(expression: &Expression) -> bool {
5313 match expression {
5314 Expression::Exists(_) => true,
5315 Expression::NamedNode(_)
5316 | Expression::Literal(_)
5317 | Expression::Variable(_)
5318 | Expression::Bound(_) => false,
5319 Expression::Not(inner) | Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => {
5320 expression_contains_exists(inner)
5321 }
5322 Expression::And(left, right)
5323 | Expression::Or(left, right)
5324 | Expression::SameTerm(left, right)
5325 | Expression::Equal(left, right)
5326 | Expression::Greater(left, right)
5327 | Expression::GreaterOrEqual(left, right)
5328 | Expression::Less(left, right)
5329 | Expression::LessOrEqual(left, right)
5330 | Expression::Add(left, right)
5331 | Expression::Subtract(left, right)
5332 | Expression::Multiply(left, right)
5333 | Expression::Divide(left, right) => {
5334 expression_contains_exists(left) || expression_contains_exists(right)
5335 }
5336 Expression::FunctionCall(_, args) | Expression::Coalesce(args) => {
5337 args.iter().any(expression_contains_exists)
5338 }
5339 Expression::If(cond, then_branch, else_branch) => {
5340 expression_contains_exists(cond)
5341 || expression_contains_exists(then_branch)
5342 || expression_contains_exists(else_branch)
5343 }
5344 Expression::In(inner, args) => {
5345 expression_contains_exists(inner) || args.iter().any(expression_contains_exists)
5346 }
5347 }
5348}
5349
5350fn pins_candidate_conjunct(expression: &Expression) -> bool {
5354 if expression_contains_exists(expression) {
5355 return false;
5356 }
5357 crate::plugin::process_plugins()
5358 .planner_plugins()
5359 .any(|plugin| plugin.pins_through_optimizer(expression))
5360}
5361
5362fn pinned_ghost_variable() -> Variable {
5366 Variable::new_unchecked(format!("__waratah_pin_{}", mint_scope_token()))
5367}
5368
5369fn pinned_ghost_variable_of(conjunct: &Expression) -> Option<&Variable> {
5372 match conjunct {
5373 Expression::Variable(variable) => Some(variable),
5374 Expression::Not(inner) => match inner.as_ref() {
5375 Expression::Variable(variable) => Some(variable),
5376 _ => None,
5377 },
5378 _ => None,
5379 }
5380}
5381
5382struct PinnedConjuncts {
5392 pins: Vec<PinnedConjunct>,
5393}
5394
5395impl PinnedConjuncts {
5396 fn new(pins: Vec<PinnedConjunct>) -> Self {
5397 Self { pins }
5398 }
5399
5400 fn unpin(&self, expression: &Expression) -> Option<Expression> {
5403 pinned_ghost_variable_of(expression).and_then(|ghost| {
5404 self.pins
5405 .iter()
5406 .find(|pin| &pin.ghost == ghost)
5407 .map(|pin| pin.expression.clone())
5408 })
5409 }
5410
5411 fn variables(&self) -> Vec<Variable> {
5415 let mut mentions = Vec::new();
5416 for pin in &self.pins {
5417 collect_expression_mentions(&mut mentions, &pin.expression);
5418 }
5419 let mut out = Vec::new();
5420 for (variable, _) in mentions {
5421 if !out.contains(&variable) {
5422 out.push(variable);
5423 }
5424 }
5425 out
5426 }
5427}
5428
5429impl std::ops::Deref for PinnedConjuncts {
5430 type Target = [PinnedConjunct];
5431
5432 fn deref(&self) -> &Self::Target {
5433 &self.pins
5434 }
5435}
5436
5437fn pin_candidate_conjuncts(
5461 pattern: GraphPattern,
5462 pins: &dyn Fn(&Expression) -> bool,
5463 out: &mut Vec<PinnedConjunct>,
5464) -> GraphPattern {
5465 match pattern {
5466 GraphPattern::Filter { expr, inner } => {
5467 let mut inner = pin_candidate_conjuncts(*inner, pins, out);
5468 let mut remaining = Vec::new();
5469 let mut ghosts = Vec::new();
5470 for conjunct in flatten_and(&expr) {
5471 if pins(&conjunct) {
5472 let ghost = pinned_ghost_variable();
5473 out.push(PinnedConjunct {
5474 ghost: ghost.clone(),
5475 expression: conjunct,
5476 });
5477 ghosts.push(ghost);
5478 } else {
5479 remaining.push(conjunct);
5480 }
5481 }
5482 for ghost in &ghosts {
5491 inner = GraphPattern::Extend {
5492 inner: Box::new(inner),
5493 variable: ghost.clone(),
5494 expression: Expression::Not(Box::new(Expression::Variable(ghost.clone()))),
5495 };
5496 }
5497 for ghost in ghosts {
5498 remaining.push(Expression::Not(Box::new(Expression::Variable(ghost))));
5499 }
5500 GraphPattern::Filter {
5501 expr: and_fold(remaining).expect("a FILTER has at least one conjunct"),
5502 inner: Box::new(inner),
5503 }
5504 }
5505 other => map_algebra_children(other, &mut |child| {
5506 pin_candidate_conjuncts(child, pins, out)
5507 }),
5508 }
5509}
5510
5511fn restore_and_sink_conjuncts(
5520 pattern: GraphPattern,
5521 pins: &[PinnedConjunct],
5522 seen: &mut [u32],
5523) -> GraphPattern {
5524 match pattern {
5525 GraphPattern::Filter { expr, inner } => {
5526 let inner = restore_and_sink_conjuncts(*inner, pins, seen);
5527 let mut remaining = Vec::new();
5528 let mut restored = Vec::new();
5529 for conjunct in flatten_and(&expr) {
5530 let index = pinned_ghost_variable_of(&conjunct)
5531 .and_then(|ghost| pins.iter().position(|pin| &pin.ghost == ghost));
5532 match index {
5533 Some(index) => {
5534 seen[index] += 1;
5535 restored.push(index);
5536 }
5537 None => remaining.push(conjunct),
5538 }
5539 }
5540 let mut inner = inner;
5541 for index in restored {
5542 inner = sink_pinned_conjunct(inner, pins[index].expression.clone());
5543 }
5544 match and_fold(remaining) {
5545 Some(expr) => GraphPattern::Filter {
5546 expr,
5547 inner: Box::new(inner),
5548 },
5549 None => inner,
5550 }
5551 }
5552 other => map_algebra_children(other, &mut |child| {
5553 restore_and_sink_conjuncts(child, pins, seen)
5554 }),
5555 }
5556}
5557
5558fn strip_pin_extends(
5564 pattern: GraphPattern,
5565 pins: &[PinnedConjunct],
5566 stripped: &mut [u32],
5567) -> GraphPattern {
5568 match pattern {
5569 GraphPattern::Extend {
5570 inner,
5571 variable,
5572 expression,
5573 } => {
5574 if let Some(index) = pins.iter().position(|pin| pin.ghost == variable) {
5575 stripped[index] += 1;
5576 strip_pin_extends(*inner, pins, stripped)
5577 } else {
5578 GraphPattern::Extend {
5579 inner: Box::new(strip_pin_extends(*inner, pins, stripped)),
5580 variable,
5581 expression,
5582 }
5583 }
5584 }
5585 other => map_algebra_children(other, &mut |child| strip_pin_extends(child, pins, stripped)),
5586 }
5587}
5588
5589fn pattern_is_surely_empty(pattern: &GraphPattern) -> bool {
5596 match pattern {
5597 GraphPattern::Values { bindings, .. } => bindings.is_empty(),
5598 GraphPattern::Join { left, right } => {
5599 pattern_is_surely_empty(left) || pattern_is_surely_empty(right)
5600 }
5601 GraphPattern::Union { left, right } => {
5602 pattern_is_surely_empty(left) && pattern_is_surely_empty(right)
5603 }
5604 GraphPattern::LeftJoin { left, .. } | GraphPattern::Minus { left, .. } => {
5605 pattern_is_surely_empty(left)
5606 }
5607 GraphPattern::Filter { inner, .. }
5608 | GraphPattern::Extend { inner, .. }
5609 | GraphPattern::Project { inner, .. }
5610 | GraphPattern::Distinct { inner }
5611 | GraphPattern::Reduced { inner }
5612 | GraphPattern::OrderBy { inner, .. }
5613 | GraphPattern::Graph { inner, .. } => pattern_is_surely_empty(inner),
5614 GraphPattern::Slice { inner, length, .. } => {
5615 *length == Some(0) || pattern_is_surely_empty(inner)
5616 }
5617 GraphPattern::Group {
5619 inner, variables, ..
5620 } => !variables.is_empty() && pattern_is_surely_empty(inner),
5621 GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Service { .. } => {
5622 false
5623 }
5624 }
5625}
5626
5627fn check_pin_survival(
5637 optimized: &GraphPattern,
5638 pins: &[PinnedConjunct],
5639 seen: &[u32],
5640 anchors: &[u32],
5641) -> Result<(), ComputeError> {
5642 for ((pin, conjuncts), anchors) in pins.iter().zip(seen.iter()).zip(anchors.iter()) {
5643 if *conjuncts == 1 && *anchors == 1 {
5644 continue;
5645 }
5646 if *conjuncts == 0 && *anchors == 0 && pattern_is_surely_empty(optimized) {
5647 continue;
5648 }
5649 return Err(ComputeError::Internal(format!(
5650 "pinned FILTER conjunct ?{} survived the algebra optimizer as {conjuncts} filter \
5651 occurrence(s) and {anchors} anchor(s), expected exactly one of each: the pin \
5652 substitutes a negation of a variable bound nowhere, and a rule that prunes or \
5653 duplicates either form invalidates the substitution",
5654 pin.ghost.as_str()
5655 )));
5656 }
5657 Ok(())
5658}
5659
5660fn sink_pinned_conjunct(pattern: GraphPattern, expression: Expression) -> GraphPattern {
5669 let mut variables = variables_in_expression(&expression);
5670 variables.sort();
5671 variables.dedup();
5672 let mut sites = Vec::new();
5680 let mut every_variable_bound = !variables.is_empty();
5681 for variable in &variables {
5682 let before = sites.len();
5683 collect_binding_sites(
5684 &pattern,
5685 std::slice::from_ref(variable),
5686 &mut Vec::new(),
5687 &mut sites,
5688 );
5689 if sites.len() == before {
5690 every_variable_bound = false;
5691 break;
5692 }
5693 }
5694 let target = every_variable_bound
5695 .then(|| common_path_prefix(&sites))
5696 .flatten();
5697 let Some(target) = target
5698 .filter(|target| !target.is_empty() && sink_path_is_safe(&pattern, target, &variables))
5699 else {
5700 return GraphPattern::Filter {
5701 expr: expression,
5702 inner: Box::new(pattern),
5703 };
5704 };
5705 insert_filter_at(pattern, &target, expression)
5706}
5707
5708fn collect_binding_sites(
5719 pattern: &GraphPattern,
5720 variables: &[Variable],
5721 path: &mut Vec<usize>,
5722 out: &mut Vec<Vec<usize>>,
5723) {
5724 match pattern {
5725 GraphPattern::Bgp { patterns } => {
5726 if patterns.iter().any(|triple| {
5727 term_pattern_binds(&triple.subject, variables)
5728 || named_node_pattern_binds(&triple.predicate, variables)
5729 || term_pattern_binds(&triple.object, variables)
5730 }) {
5731 out.push(path.clone());
5732 }
5733 }
5734 GraphPattern::Path {
5735 subject, object, ..
5736 } => {
5737 if term_pattern_binds(subject, variables) || term_pattern_binds(object, variables) {
5738 out.push(path.clone());
5739 }
5740 }
5741 GraphPattern::Values {
5742 variables: columns, ..
5743 } => {
5744 if columns.iter().any(|column| variables.contains(column)) {
5745 out.push(path.clone());
5746 }
5747 }
5748 GraphPattern::Extend {
5749 inner, variable, ..
5750 } => {
5751 if variables.contains(variable) {
5752 out.push(path.clone());
5754 } else {
5755 path.push(0);
5756 collect_binding_sites(inner, variables, path, out);
5757 path.pop();
5758 }
5759 }
5760 GraphPattern::Group {
5761 variables: keys,
5762 aggregates,
5763 ..
5764 } => {
5765 if keys.iter().any(|key| variables.contains(key))
5769 || aggregates
5770 .iter()
5771 .any(|(variable, _)| variables.contains(variable))
5772 {
5773 out.push(path.clone());
5774 }
5775 }
5776 GraphPattern::Project {
5777 inner,
5778 variables: projected,
5779 } => {
5780 if variables
5781 .iter()
5782 .all(|variable| projected.contains(variable))
5783 {
5784 path.push(0);
5785 collect_binding_sites(inner, variables, path, out);
5786 path.pop();
5787 }
5788 }
5789 GraphPattern::Filter { inner, .. }
5790 | GraphPattern::OrderBy { inner, .. }
5791 | GraphPattern::Distinct { inner }
5792 | GraphPattern::Reduced { inner }
5793 | GraphPattern::Slice { inner, .. } => {
5794 path.push(0);
5795 collect_binding_sites(inner, variables, path, out);
5796 path.pop();
5797 }
5798 GraphPattern::Join { left, right } | GraphPattern::Union { left, right } => {
5799 path.push(0);
5800 collect_binding_sites(left, variables, path, out);
5801 path.pop();
5802 path.push(1);
5803 collect_binding_sites(right, variables, path, out);
5804 path.pop();
5805 }
5806 GraphPattern::LeftJoin { left, right, .. } => {
5812 path.push(0);
5813 collect_binding_sites(left, variables, path, out);
5814 path.pop();
5815 path.push(1);
5816 collect_binding_sites(right, variables, path, out);
5817 path.pop();
5818 }
5819 GraphPattern::Minus { left, .. } => {
5821 path.push(0);
5822 collect_binding_sites(left, variables, path, out);
5823 path.pop();
5824 }
5825 GraphPattern::Graph { inner, .. } | GraphPattern::Service { inner, .. } => {
5830 path.push(0);
5831 collect_binding_sites(inner, variables, path, out);
5832 path.pop();
5833 }
5834 }
5835}
5836
5837fn term_pattern_binds(term: &TermPattern, variables: &[Variable]) -> bool {
5838 matches!(term, TermPattern::Variable(variable) if variables.contains(variable))
5839}
5840
5841fn named_node_pattern_binds(term: &NamedNodePattern, variables: &[Variable]) -> bool {
5842 matches!(term, NamedNodePattern::Variable(variable) if variables.contains(variable))
5843}
5844
5845fn common_path_prefix(sites: &[Vec<usize>]) -> Option<Vec<usize>> {
5848 let first = sites.first()?;
5849 let mut prefix = Vec::new();
5850 'depth: for (depth, index) in first.iter().enumerate() {
5851 for site in &sites[1..] {
5852 if site.get(depth) != Some(index) {
5853 break 'depth;
5854 }
5855 }
5856 prefix.push(*index);
5857 }
5858 Some(prefix)
5859}
5860
5861fn sink_path_is_safe(pattern: &GraphPattern, target: &[usize], variables: &[Variable]) -> bool {
5872 let mut node = pattern;
5873 for index in target {
5874 let may_cross = match node {
5875 GraphPattern::Slice { .. } | GraphPattern::Union { .. } => false,
5876 GraphPattern::Graph { .. } | GraphPattern::Service { .. } => false,
5877 GraphPattern::LeftJoin { .. } | GraphPattern::Minus { .. } => *index == 0,
5878 GraphPattern::Project {
5879 variables: projected,
5880 ..
5881 } => variables
5882 .iter()
5883 .all(|variable| projected.contains(variable)),
5884 _ => true,
5885 };
5886 if !may_cross {
5887 return false;
5888 }
5889 node = algebra_child(node, *index);
5890 }
5891 true
5892}
5893
5894fn safe_join_target(pattern: &GraphPattern, target: &[usize]) -> Vec<usize> {
5908 let mut node = pattern;
5909 let mut safe = Vec::new();
5910 for index in target {
5911 let may_cross = match node {
5912 GraphPattern::Slice { .. } | GraphPattern::Union { .. } => false,
5913 GraphPattern::Graph { .. } | GraphPattern::Service { .. } => false,
5914 GraphPattern::LeftJoin { .. } | GraphPattern::Minus { .. } => *index == 0,
5915 GraphPattern::Distinct { .. }
5919 | GraphPattern::Reduced { .. }
5920 | GraphPattern::Group { .. } => false,
5921 GraphPattern::Project { .. } => false,
5925 _ => true,
5926 };
5927 if !may_cross {
5928 break;
5929 }
5930 safe.push(*index);
5931 node = algebra_child(node, *index);
5932 }
5933 safe
5934}
5935
5936fn insert_filter_at(
5939 pattern: GraphPattern,
5940 target: &[usize],
5941 expression: Expression,
5942) -> GraphPattern {
5943 let Some((&index, rest)) = target.split_first() else {
5944 return GraphPattern::Filter {
5945 expr: expression,
5946 inner: Box::new(pattern),
5947 };
5948 };
5949 replace_algebra_child(pattern, index, &mut |child| {
5950 insert_filter_at(child, rest, expression.clone())
5951 })
5952}
5953
5954fn algebra_child(pattern: &GraphPattern, index: usize) -> &GraphPattern {
5957 match pattern {
5958 GraphPattern::Join { left, right }
5959 | GraphPattern::LeftJoin { left, right, .. }
5960 | GraphPattern::Union { left, right }
5961 | GraphPattern::Minus { left, right } => match index {
5962 0 => left,
5963 _ => right,
5964 },
5965 GraphPattern::Filter { inner, .. }
5966 | GraphPattern::Graph { inner, .. }
5967 | GraphPattern::Extend { inner, .. }
5968 | GraphPattern::OrderBy { inner, .. }
5969 | GraphPattern::Project { inner, .. }
5970 | GraphPattern::Distinct { inner }
5971 | GraphPattern::Reduced { inner }
5972 | GraphPattern::Slice { inner, .. }
5973 | GraphPattern::Group { inner, .. }
5974 | GraphPattern::Service { inner, .. } => inner,
5975 GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Values { .. } => {
5976 unreachable!("leaf patterns have no children")
5977 }
5978 }
5979}
5980
5981fn replace_algebra_child(
5982 pattern: GraphPattern,
5983 index: usize,
5984 f: &mut dyn FnMut(GraphPattern) -> GraphPattern,
5985) -> GraphPattern {
5986 match pattern {
5987 GraphPattern::Join { left, right } => GraphPattern::Join {
5988 left: Box::new(if index == 0 { f(*left) } else { *left }),
5989 right: Box::new(if index == 0 { *right } else { f(*right) }),
5990 },
5991 GraphPattern::LeftJoin {
5992 left,
5993 right,
5994 expression,
5995 } => GraphPattern::LeftJoin {
5996 left: Box::new(if index == 0 { f(*left) } else { *left }),
5997 right: Box::new(if index == 0 { *right } else { f(*right) }),
5998 expression,
5999 },
6000 GraphPattern::Union { left, right } => GraphPattern::Union {
6001 left: Box::new(if index == 0 { f(*left) } else { *left }),
6002 right: Box::new(if index == 0 { *right } else { f(*right) }),
6003 },
6004 GraphPattern::Minus { left, right } => GraphPattern::Minus {
6005 left: Box::new(if index == 0 { f(*left) } else { *left }),
6006 right: Box::new(if index == 0 { *right } else { f(*right) }),
6007 },
6008 GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
6009 expr,
6010 inner: Box::new(f(*inner)),
6011 },
6012 GraphPattern::Graph { name, inner } => GraphPattern::Graph {
6013 name,
6014 inner: Box::new(f(*inner)),
6015 },
6016 GraphPattern::Extend {
6017 inner,
6018 variable,
6019 expression,
6020 } => GraphPattern::Extend {
6021 inner: Box::new(f(*inner)),
6022 variable,
6023 expression,
6024 },
6025 GraphPattern::OrderBy { inner, expression } => GraphPattern::OrderBy {
6026 inner: Box::new(f(*inner)),
6027 expression,
6028 },
6029 GraphPattern::Project { inner, variables } => GraphPattern::Project {
6030 inner: Box::new(f(*inner)),
6031 variables,
6032 },
6033 GraphPattern::Distinct { inner } => GraphPattern::Distinct {
6034 inner: Box::new(f(*inner)),
6035 },
6036 GraphPattern::Reduced { inner } => GraphPattern::Reduced {
6037 inner: Box::new(f(*inner)),
6038 },
6039 GraphPattern::Slice {
6040 inner,
6041 start,
6042 length,
6043 } => GraphPattern::Slice {
6044 inner: Box::new(f(*inner)),
6045 start,
6046 length,
6047 },
6048 GraphPattern::Group {
6049 inner,
6050 variables,
6051 aggregates,
6052 } => GraphPattern::Group {
6053 inner: Box::new(f(*inner)),
6054 variables,
6055 aggregates,
6056 },
6057 GraphPattern::Service {
6058 name,
6059 inner,
6060 silent,
6061 } => GraphPattern::Service {
6062 name,
6063 inner: Box::new(f(*inner)),
6064 silent,
6065 },
6066 GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Values { .. } => {
6067 unreachable!("leaf patterns have no children")
6068 }
6069 }
6070}
6071
6072fn map_algebra_children(
6075 pattern: GraphPattern,
6076 f: &mut dyn FnMut(GraphPattern) -> GraphPattern,
6077) -> GraphPattern {
6078 match pattern {
6079 GraphPattern::Bgp { patterns } => GraphPattern::Bgp { patterns },
6080 GraphPattern::Path {
6081 subject,
6082 path,
6083 object,
6084 } => GraphPattern::Path {
6085 subject,
6086 path,
6087 object,
6088 },
6089 GraphPattern::Values {
6090 variables,
6091 bindings,
6092 } => GraphPattern::Values {
6093 variables,
6094 bindings,
6095 },
6096 GraphPattern::Join { left, right } => GraphPattern::Join {
6097 left: Box::new(f(*left)),
6098 right: Box::new(f(*right)),
6099 },
6100 GraphPattern::LeftJoin {
6101 left,
6102 right,
6103 expression,
6104 } => GraphPattern::LeftJoin {
6105 left: Box::new(f(*left)),
6106 right: Box::new(f(*right)),
6107 expression,
6108 },
6109 GraphPattern::Union { left, right } => GraphPattern::Union {
6110 left: Box::new(f(*left)),
6111 right: Box::new(f(*right)),
6112 },
6113 GraphPattern::Minus { left, right } => GraphPattern::Minus {
6114 left: Box::new(f(*left)),
6115 right: Box::new(f(*right)),
6116 },
6117 GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
6118 expr,
6119 inner: Box::new(f(*inner)),
6120 },
6121 GraphPattern::Graph { name, inner } => GraphPattern::Graph {
6122 name,
6123 inner: Box::new(f(*inner)),
6124 },
6125 GraphPattern::Extend {
6126 inner,
6127 variable,
6128 expression,
6129 } => GraphPattern::Extend {
6130 inner: Box::new(f(*inner)),
6131 variable,
6132 expression,
6133 },
6134 GraphPattern::OrderBy { inner, expression } => GraphPattern::OrderBy {
6135 inner: Box::new(f(*inner)),
6136 expression,
6137 },
6138 GraphPattern::Project { inner, variables } => GraphPattern::Project {
6139 inner: Box::new(f(*inner)),
6140 variables,
6141 },
6142 GraphPattern::Distinct { inner } => GraphPattern::Distinct {
6143 inner: Box::new(f(*inner)),
6144 },
6145 GraphPattern::Reduced { inner } => GraphPattern::Reduced {
6146 inner: Box::new(f(*inner)),
6147 },
6148 GraphPattern::Slice {
6149 inner,
6150 start,
6151 length,
6152 } => GraphPattern::Slice {
6153 inner: Box::new(f(*inner)),
6154 start,
6155 length,
6156 },
6157 GraphPattern::Group {
6158 inner,
6159 variables,
6160 aggregates,
6161 } => GraphPattern::Group {
6162 inner: Box::new(f(*inner)),
6163 variables,
6164 aggregates,
6165 },
6166 GraphPattern::Service {
6167 name,
6168 inner,
6169 silent,
6170 } => GraphPattern::Service {
6171 name,
6172 inner: Box::new(f(*inner)),
6173 silent,
6174 },
6175 }
6176}
6177
6178fn pattern_contains_graph(pattern: &GraphPattern) -> bool {
6179 match pattern {
6180 GraphPattern::Graph { .. } => true,
6181 GraphPattern::Join { left, right }
6182 | GraphPattern::Union { left, right }
6183 | GraphPattern::Minus { left, right } => {
6184 pattern_contains_graph(left) || pattern_contains_graph(right)
6185 }
6186 GraphPattern::LeftJoin { left, right, .. } => {
6187 pattern_contains_graph(left) || pattern_contains_graph(right)
6188 }
6189 GraphPattern::Filter { inner, .. }
6190 | GraphPattern::Extend { inner, .. }
6191 | GraphPattern::Distinct { inner }
6192 | GraphPattern::Reduced { inner }
6193 | GraphPattern::Slice { inner, .. }
6194 | GraphPattern::Group { inner, .. }
6195 | GraphPattern::OrderBy { inner, .. }
6196 | GraphPattern::Project { inner, .. }
6197 | GraphPattern::Service { inner, .. } => pattern_contains_graph(inner),
6198 _ => false,
6199 }
6200}
6201
6202fn sparopt_roundtrip(pattern: GraphPattern) -> GraphPattern {
6203 let sparopt_in = sparopt::algebra::GraphPattern::from(&pattern);
6204 let sparopt_out = sparopt::Optimizer::optimize_graph_pattern(sparopt_in);
6205 GraphPattern::from(&sparopt_out)
6206}
6207
6208#[derive(Debug, Clone, Default, PartialEq, Eq)]
6213struct IncomingBound {
6214 entries: Vec<(Variable, Option<u64>)>,
6215}
6216
6217impl IncomingBound {
6218 fn contains(&self, variable: &Variable) -> bool {
6219 self.entries.iter().any(|(known, _)| known == variable)
6220 }
6221
6222 fn known_domain(&self, variable: &Variable) -> Option<u64> {
6224 self.entries
6225 .iter()
6226 .find(|(known, _)| known == variable)
6227 .and_then(|(_, domain)| *domain)
6228 }
6229
6230 fn insert(&mut self, variable: Variable, domain: Option<u64>) {
6231 if let Some((_, existing)) = self
6232 .entries
6233 .iter_mut()
6234 .find(|(known, _)| *known == variable)
6235 {
6236 *existing = match (*existing, domain) {
6237 (Some(a), Some(b)) => Some(a.min(b)),
6238 (a, b) => a.or(b),
6239 };
6240 } else {
6241 self.entries.push((variable, domain));
6242 }
6243 }
6244
6245 fn merge(&mut self, extra: &IncomingBound) {
6246 for (variable, domain) in &extra.entries {
6247 self.insert(variable.clone(), *domain);
6248 }
6249 }
6250}
6251
6252type PeeledExists = (Vec<(bool, GraphPattern)>, Option<Expression>);
6255
6256fn peel_exists_conjuncts(expr: &Expression) -> Result<PeeledExists, ComputeError> {
6257 let mut exists = Vec::new();
6258 let mut rest = Vec::new();
6259 for conjunct in flatten_and(expr) {
6260 match exists_conjunct(&conjunct) {
6261 Some((negated, body)) => exists.push((negated, body)),
6262 None => rest.push(conjunct),
6263 }
6264 }
6265 Ok((exists, and_fold(rest)))
6266}
6267
6268fn exists_conjunct(expr: &Expression) -> Option<(bool, GraphPattern)> {
6269 match expr {
6270 Expression::Exists(inner) => Some((false, (**inner).clone())),
6271 Expression::Not(inner) => match inner.as_ref() {
6272 Expression::Exists(body) => Some((true, (**body).clone())),
6273 _ => None,
6274 },
6275 _ => None,
6276 }
6277}
6278
6279fn lower_exists_clause(
6280 negated: bool,
6281 body: GraphPattern,
6282 outer: &PlanNode,
6283 incoming: &IncomingBound,
6284 profile: Option<&StatsProfile>,
6285 ctx: &QueryContext,
6286 scope: &GraphScope,
6287) -> Result<ExistsClause, ComputeError> {
6288 let outer_vars = outer.output_vars();
6289 if exists_has_correlated_subselect(&body, &outer_vars) {
6290 return Err(ComputeError::UnsupportedSparql(
6291 "EXISTS body sub-SELECT that references outer variables is not supported".into(),
6292 ));
6293 }
6294 let outer_live = outer_vars.all();
6308 let prepared = crate::optional_to_join::replace_filter_forced_joins(
6309 push_values_into_union(place_values_at_lca_with_live(
6310 crate::alt_to_union::flatten_alternative_paths(optimize_preserving_graph(body)),
6311 &outer_live,
6312 )),
6313 &|_| None,
6314 );
6315 let lowered = lower_pattern(&prepared, profile, incoming, ctx, scope)?;
6316 reject_exists_correlated_group(&lowered, &outer_vars)?;
6317 let correlation = exists_correlation(outer, &lowered);
6318 Ok(ExistsClause {
6319 negated,
6320 body: Box::new(lowered),
6321 correlation,
6322 kind: ExistsKind::NestedProbe,
6323 })
6324}
6325
6326fn exists_correlation(outer: &PlanNode, body: &PlanNode) -> Vec<Variable> {
6327 let outer_vars = outer.output_vars();
6328 let mut correlation = Vec::new();
6329 for variable in plan_referenced_variables(body) {
6330 if outer_vars.contains(&variable) && !correlation.contains(&variable) {
6331 correlation.push(variable);
6332 }
6333 }
6334 correlation
6335}
6336
6337fn plan_referenced_variables(node: &PlanNode) -> Vec<Variable> {
6338 let mut out = node.inner_variables();
6339 collect_plan_expr_vars(node, &mut out);
6340 out
6341}
6342
6343fn push_var(out: &mut Vec<Variable>, variable: Variable) {
6344 if !out.contains(&variable) {
6345 out.push(variable);
6346 }
6347}
6348
6349fn collect_plan_expr_vars(node: &PlanNode, out: &mut Vec<Variable>) {
6350 match node {
6351 PlanNode::CustomNode(op) => {
6352 for child in &op.children {
6353 collect_plan_expr_vars(child, out);
6354 }
6355 }
6356 PlanNode::Filter {
6357 inner,
6358 early,
6359 residual,
6360 exists,
6361 ..
6362 } => {
6363 for expr in early.iter().chain(residual.iter()) {
6364 for variable in variables_in_expression(expr) {
6365 push_var(out, variable);
6366 }
6367 }
6368 collect_plan_expr_vars(inner, out);
6369 for clause in exists {
6370 for variable in &clause.correlation {
6371 push_var(out, variable.clone());
6372 }
6373 collect_plan_expr_vars(&clause.body, out);
6374 }
6375 }
6376 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
6377 collect_plan_expr_vars(left, out);
6378 collect_plan_expr_vars(right, out);
6379 }
6380 PlanNode::LeftJoin {
6381 left,
6382 right,
6383 early_filter,
6384 residual_filter,
6385 ..
6386 } => {
6387 collect_plan_expr_vars(left, out);
6388 collect_plan_expr_vars(right, out);
6389 for expr in early_filter.iter().chain(residual_filter.iter()) {
6390 for variable in variables_in_expression(expr) {
6391 push_var(out, variable);
6392 }
6393 }
6394 }
6395 PlanNode::Extend {
6396 inner, expression, ..
6397 } => {
6398 for variable in variables_in_expression(expression) {
6399 push_var(out, variable);
6400 }
6401 collect_plan_expr_vars(inner, out);
6402 }
6403 PlanNode::Sort { inner, keys } => {
6404 for key in keys {
6405 for variable in variables_in_expression(&key.expression) {
6406 push_var(out, variable);
6407 }
6408 }
6409 collect_plan_expr_vars(inner, out);
6410 }
6411 PlanNode::Group {
6412 inner, aggregates, ..
6413 } => {
6414 for (_, agg) in aggregates {
6415 if let AggregateExpression::FunctionCall { expr, .. } = agg {
6416 for variable in variables_in_expression(expr) {
6417 push_var(out, variable);
6418 }
6419 }
6420 }
6421 collect_plan_expr_vars(inner, out);
6422 }
6423 PlanNode::Slice { inner, .. }
6424 | PlanNode::Distinct { inner, .. }
6425 | PlanNode::JoinGraphVar { inner, .. } => collect_plan_expr_vars(inner, out),
6426 PlanNode::SubSelect(sub) => collect_plan_expr_vars(&sub.inner, out),
6427 PlanNode::Scan(_)
6428 | PlanNode::Path(_)
6429 | PlanNode::Values(_)
6430 | PlanNode::NamedGraphs { .. }
6431 | PlanNode::NamedGraphExists { .. }
6432 | PlanNode::DomainCounts { .. }
6433 | PlanNode::HeadCounts { .. }
6434 | PlanNode::PatternCount { .. }
6435 | PlanNode::Unit => {}
6436 }
6437}
6438
6439fn is_simple_bgp_exists_body(node: &PlanNode) -> bool {
6440 match node {
6441 PlanNode::Scan(_)
6442 | PlanNode::Values(_)
6443 | PlanNode::Unit
6444 | PlanNode::NamedGraphExists { .. } => true,
6445 PlanNode::CustomNode(_) => false,
6447 PlanNode::Join { left, right, .. } => {
6448 is_simple_bgp_exists_body(left) && is_simple_bgp_exists_body(right)
6449 }
6450 PlanNode::Filter { inner, exists, .. } => {
6451 exists.is_empty() && is_simple_bgp_exists_body(inner)
6452 }
6453 PlanNode::Extend { inner, .. } => is_simple_bgp_exists_body(inner),
6454 PlanNode::Path(_)
6455 | PlanNode::LeftJoin { .. }
6456 | PlanNode::Union { .. }
6457 | PlanNode::SubSelect(_)
6458 | PlanNode::Group { .. }
6459 | PlanNode::Slice { .. }
6460 | PlanNode::Distinct { .. }
6461 | PlanNode::Sort { .. }
6462 | PlanNode::NamedGraphs { .. }
6463 | PlanNode::DomainCounts { .. }
6464 | PlanNode::HeadCounts { .. }
6465 | PlanNode::PatternCount { .. }
6466 | PlanNode::JoinGraphVar { .. } => false,
6467 }
6468}
6469
6470pub(crate) fn exists_scan_keys(body: &PlanNode, correlation: &[Variable]) -> Vec<Variable> {
6472 let produced = body.inner_variables();
6473 correlation
6474 .iter()
6475 .filter(|variable| produced.contains(variable))
6476 .cloned()
6477 .collect()
6478}
6479
6480fn exists_expr_keys(body: &PlanNode, correlation: &[Variable]) -> Vec<Variable> {
6483 let mut expr = Vec::new();
6484 collect_plan_expr_vars(body, &mut expr);
6485 correlation
6486 .iter()
6487 .filter(|variable| expr.contains(variable))
6488 .cloned()
6489 .collect()
6490}
6491
6492pub(crate) fn exists_expr_only_keys(body: &PlanNode, correlation: &[Variable]) -> Vec<Variable> {
6496 let scan = exists_scan_keys(body, correlation);
6497 exists_expr_keys(body, correlation)
6498 .into_iter()
6499 .filter(|variable| !scan.contains(variable))
6500 .collect()
6501}
6502
6503fn classify_exists_kind(outer: &PlanNode, body: &PlanNode, correlation: &[Variable]) -> ExistsKind {
6504 if correlation.is_empty() {
6505 return ExistsKind::Uncorrelated;
6506 }
6507 let outer_vars = outer.output_vars();
6508 let always_bound = correlation
6509 .iter()
6510 .all(|variable| outer_vars.is_always_bound(variable));
6511 let expr_only = exists_expr_only_keys(body, correlation);
6512 if always_bound && is_simple_bgp_exists_body(body) && expr_only.is_empty() {
6513 ExistsKind::SemiJoin
6514 } else {
6515 ExistsKind::NestedProbe
6516 }
6517}
6518
6519fn classify_exists_in_plan(node: &mut PlanNode) -> Result<(), ComputeError> {
6522 match node {
6523 PlanNode::CustomNode(op) => {
6524 for child in &mut op.children {
6525 classify_exists_in_plan(child)?;
6526 }
6527 }
6528 PlanNode::Filter { inner, exists, .. } => {
6529 classify_exists_in_plan(inner)?;
6530 for clause in exists.iter_mut() {
6531 classify_exists_in_plan(&mut clause.body)?;
6532 clause.correlation = exists_correlation(inner, &clause.body);
6533 clause.kind = classify_exists_kind(inner, &clause.body, &clause.correlation);
6534 if clause.kind == ExistsKind::NestedProbe {
6535 let prefix = mint_scope_prefix();
6536 let projected = clause.correlation.clone();
6537 rename_subselect_scope(&mut clause.body, &projected, &prefix)?;
6538 }
6539 }
6540 }
6541 PlanNode::Join { left, right, .. }
6542 | PlanNode::LeftJoin { left, right, .. }
6543 | PlanNode::Union { left, right } => {
6544 classify_exists_in_plan(left)?;
6545 classify_exists_in_plan(right)?;
6546 }
6547 PlanNode::Extend { inner, .. }
6548 | PlanNode::Slice { inner, .. }
6549 | PlanNode::Distinct { inner, .. }
6550 | PlanNode::Sort { inner, .. }
6551 | PlanNode::Group { inner, .. }
6552 | PlanNode::JoinGraphVar { inner, .. } => classify_exists_in_plan(inner)?,
6553 PlanNode::SubSelect(sub) => classify_exists_in_plan(&mut sub.inner)?,
6554 PlanNode::Scan(_)
6555 | PlanNode::Path(_)
6556 | PlanNode::Values(_)
6557 | PlanNode::NamedGraphs { .. }
6558 | PlanNode::NamedGraphExists { .. }
6559 | PlanNode::DomainCounts { .. }
6560 | PlanNode::HeadCounts { .. }
6561 | PlanNode::PatternCount { .. }
6562 | PlanNode::Unit => {}
6563 }
6564 Ok(())
6565}
6566
6567fn exists_has_correlated_subselect(pattern: &GraphPattern, outer: &OutputVars) -> bool {
6571 if let Some(spine) = subselect_spine(pattern) {
6572 if algebra_references_outer(spine.body, outer) {
6573 return true;
6574 }
6575 for key in &spine.order {
6576 if variables_in_expression(&key.expression)
6577 .iter()
6578 .any(|variable| outer.contains(variable))
6579 {
6580 return true;
6581 }
6582 }
6583 return exists_has_correlated_subselect(spine.body, outer);
6584 }
6585 match pattern {
6586 GraphPattern::Join { left, right }
6587 | GraphPattern::Union { left, right }
6588 | GraphPattern::Minus { left, right }
6589 | GraphPattern::LeftJoin { left, right, .. } => {
6590 exists_has_correlated_subselect(left, outer)
6591 || exists_has_correlated_subselect(right, outer)
6592 }
6593 GraphPattern::Filter { inner, .. }
6594 | GraphPattern::Extend { inner, .. }
6595 | GraphPattern::Group { inner, .. }
6596 | GraphPattern::Graph { inner, .. }
6597 | GraphPattern::Service { inner, .. }
6598 | GraphPattern::Project { inner, .. } => exists_has_correlated_subselect(inner, outer),
6599 _ => false,
6600 }
6601}
6602
6603fn algebra_references_outer(pattern: &GraphPattern, outer: &OutputVars) -> bool {
6604 match pattern {
6605 GraphPattern::Bgp { patterns } => patterns.iter().any(|triple| {
6606 term_pattern_is_outer(&triple.subject, outer)
6607 || named_node_pattern_is_outer(&triple.predicate, outer)
6608 || term_pattern_is_outer(&triple.object, outer)
6609 }),
6610 GraphPattern::Path {
6611 subject, object, ..
6612 } => term_pattern_is_outer(subject, outer) || term_pattern_is_outer(object, outer),
6613 GraphPattern::Join { left, right }
6614 | GraphPattern::Union { left, right }
6615 | GraphPattern::Minus { left, right } => {
6616 algebra_references_outer(left, outer) || algebra_references_outer(right, outer)
6617 }
6618 GraphPattern::LeftJoin {
6619 left,
6620 right,
6621 expression,
6622 } => {
6623 algebra_references_outer(left, outer)
6624 || algebra_references_outer(right, outer)
6625 || expression
6626 .as_ref()
6627 .is_some_and(|expr| expr_references_outer(expr, outer))
6628 }
6629 GraphPattern::Filter { expr, inner } => {
6630 expr_references_outer(expr, outer) || algebra_references_outer(inner, outer)
6631 }
6632 GraphPattern::Graph { name, inner } => {
6633 named_node_pattern_is_outer(name, outer) || algebra_references_outer(inner, outer)
6634 }
6635 GraphPattern::Extend {
6636 inner,
6637 variable,
6638 expression,
6639 } => {
6640 outer.contains(variable)
6641 || expr_references_outer(expression, outer)
6642 || algebra_references_outer(inner, outer)
6643 }
6644 GraphPattern::Values { variables, .. } => variables.iter().any(|v| outer.contains(v)),
6645 GraphPattern::OrderBy { inner, expression } => {
6646 expression
6647 .iter()
6648 .any(|oe| expr_references_outer(order_expression_expr(oe), outer))
6649 || algebra_references_outer(inner, outer)
6650 }
6651 GraphPattern::Slice { inner, .. }
6652 | GraphPattern::Distinct { inner }
6653 | GraphPattern::Reduced { inner }
6654 | GraphPattern::Service { inner, .. }
6655 | GraphPattern::Project { inner, .. } => algebra_references_outer(inner, outer),
6656 GraphPattern::Group {
6657 inner,
6658 variables,
6659 aggregates,
6660 } => {
6661 variables.iter().any(|v| outer.contains(v))
6662 || aggregates.iter().any(|(result, agg)| {
6663 outer.contains(result)
6664 || matches!(
6665 agg,
6666 AggregateExpression::FunctionCall { expr, .. }
6667 if expr_references_outer(expr, outer)
6668 )
6669 })
6670 || algebra_references_outer(inner, outer)
6671 }
6672 }
6673}
6674
6675fn order_expression_expr(oe: &OrderExpression) -> &Expression {
6676 match oe {
6677 OrderExpression::Asc(expression) | OrderExpression::Desc(expression) => expression,
6678 }
6679}
6680
6681fn expr_references_outer(expression: &Expression, outer: &OutputVars) -> bool {
6682 variables_in_expression(expression)
6683 .iter()
6684 .any(|variable| outer.contains(variable))
6685}
6686
6687fn term_pattern_is_outer(term: &TermPattern, outer: &OutputVars) -> bool {
6688 matches!(term, TermPattern::Variable(v) if outer.contains(v))
6689}
6690
6691fn named_node_pattern_is_outer(name: &NamedNodePattern, outer: &OutputVars) -> bool {
6692 matches!(name, NamedNodePattern::Variable(v) if outer.contains(v))
6693}
6694
6695fn reject_exists_correlated_group(node: &PlanNode, outer: &OutputVars) -> Result<(), ComputeError> {
6696 match node {
6697 PlanNode::CustomNode(_) => Ok(()),
6699 PlanNode::Group {
6700 inner,
6701 variables,
6702 aggregates,
6703 ..
6704 } => {
6705 let mut refs = inner.inner_variables();
6706 collect_plan_expr_vars(node, &mut refs);
6707 for variable in variables {
6708 push_var(&mut refs, variable.clone());
6709 }
6710 for (result, _) in aggregates {
6711 push_var(&mut refs, result.clone());
6712 }
6713 if refs.iter().any(|variable| outer.contains(variable)) {
6714 return Err(ComputeError::UnsupportedSparql(
6715 "EXISTS body GROUP BY that references outer variables is not supported".into(),
6716 ));
6717 }
6718 reject_exists_correlated_group(inner, outer)
6719 }
6720 PlanNode::Filter { inner, exists, .. } => {
6721 reject_exists_correlated_group(inner, outer)?;
6722 for clause in exists {
6723 reject_exists_correlated_group(&clause.body, outer)?;
6724 }
6725 Ok(())
6726 }
6727 PlanNode::Join { left, right, .. }
6728 | PlanNode::LeftJoin { left, right, .. }
6729 | PlanNode::Union { left, right } => {
6730 reject_exists_correlated_group(left, outer)?;
6731 reject_exists_correlated_group(right, outer)
6732 }
6733 PlanNode::Extend { inner, .. }
6734 | PlanNode::Slice { inner, .. }
6735 | PlanNode::Distinct { inner, .. }
6736 | PlanNode::Sort { inner, .. }
6737 | PlanNode::JoinGraphVar { inner, .. } => reject_exists_correlated_group(inner, outer),
6738 PlanNode::SubSelect(sub) => reject_exists_correlated_group(&sub.inner, outer),
6739 PlanNode::Scan(_)
6740 | PlanNode::Path(_)
6741 | PlanNode::Values(_)
6742 | PlanNode::NamedGraphs { .. }
6743 | PlanNode::NamedGraphExists { .. }
6744 | PlanNode::DomainCounts { .. }
6745 | PlanNode::HeadCounts { .. }
6746 | PlanNode::PatternCount { .. }
6747 | PlanNode::Unit => Ok(()),
6748 }
6749}
6750
6751pub(crate) fn inject_exists_values(node: &mut PlanNode, values: &ValuesOp) {
6756 if values.variables.is_empty() {
6757 return;
6758 }
6759 match node {
6760 PlanNode::CustomNode(op) => {
6761 for child in &mut op.children {
6762 inject_exists_values(child, values);
6763 }
6764 }
6765 PlanNode::Filter {
6766 inner,
6767 early,
6768 residual,
6769 exists,
6770 ..
6771 } => {
6772 inject_exists_values(inner, values);
6773 let needs = early
6774 .iter()
6775 .chain(residual.iter())
6776 .any(|expr| expr_uses_values(expr, values));
6777 if needs && !node_produces_values(inner, values) {
6778 **inner = join_values_cartesian(values.clone(), (**inner).clone());
6779 }
6780 for clause in exists {
6781 inject_exists_values(&mut clause.body, values);
6782 }
6783 }
6784 PlanNode::Extend {
6785 inner, expression, ..
6786 } => {
6787 inject_exists_values(inner, values);
6788 if expr_uses_values(expression, values) && !node_produces_values(inner, values) {
6789 **inner = join_values_cartesian(values.clone(), (**inner).clone());
6790 }
6791 }
6792 PlanNode::LeftJoin {
6793 left,
6794 right,
6795 early_filter,
6796 residual_filter,
6797 ..
6798 } => {
6799 inject_exists_values(left, values);
6800 inject_exists_values(right, values);
6801 let needs = early_filter
6802 .iter()
6803 .chain(residual_filter.iter())
6804 .any(|expr| expr_uses_values(expr, values));
6805 if needs && !node_produces_values(left, values) {
6806 **left = join_values_cartesian(values.clone(), (**left).clone());
6807 }
6808 }
6809 PlanNode::Sort { inner, keys } => {
6810 inject_exists_values(inner, values);
6811 let needs = keys
6812 .iter()
6813 .any(|key| expr_uses_values(&key.expression, values));
6814 if needs && !node_produces_values(inner, values) {
6815 **inner = join_values_cartesian(values.clone(), (**inner).clone());
6816 }
6817 }
6818 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
6819 inject_exists_values(left, values);
6820 inject_exists_values(right, values);
6821 }
6822 PlanNode::Slice { inner, .. }
6823 | PlanNode::Distinct { inner, .. }
6824 | PlanNode::Group { inner, .. }
6825 | PlanNode::JoinGraphVar { inner, .. } => inject_exists_values(inner, values),
6826 PlanNode::SubSelect(_)
6827 | PlanNode::Scan(_)
6828 | PlanNode::Path(_)
6829 | PlanNode::Values(_)
6830 | PlanNode::NamedGraphs { .. }
6831 | PlanNode::NamedGraphExists { .. }
6832 | PlanNode::DomainCounts { .. }
6833 | PlanNode::HeadCounts { .. }
6834 | PlanNode::PatternCount { .. }
6835 | PlanNode::Unit => {}
6836 }
6837}
6838
6839fn expr_uses_values(expression: &Expression, values: &ValuesOp) -> bool {
6840 variables_in_expression(expression)
6841 .iter()
6842 .any(|variable| values.variables.contains(variable))
6843}
6844
6845fn node_produces_values(node: &PlanNode, values: &ValuesOp) -> bool {
6846 let produced = node.output_vars();
6847 values
6848 .variables
6849 .iter()
6850 .all(|variable| produced.contains(variable))
6851}
6852
6853fn join_values_cartesian(values: ValuesOp, inner: PlanNode) -> PlanNode {
6854 let left = PlanNode::Values(values);
6855 let hash_keys = hash_keys_for(&left.output_vars(), &inner.output_vars());
6856 let rhs_hostable_keys = stamp_rhs_hostable_keys(&inner);
6857 PlanNode::Join {
6858 left: Box::new(left),
6859 right: Box::new(inner),
6860 hash_keys,
6861 probe_key_domains: Vec::new(),
6863 probe_key_overlap_milli: Vec::new(),
6864 rhs_hostable_keys,
6865 meta: JoinMeta {
6866 semi_gate: None,
6867 star_arms: None,
6868 strategy: JoinStrategy::Broadcast,
6869 produced_row_count_estimate: 1,
6870 own_push_removed_row_count_estimate: 1,
6871 },
6872 }
6873}
6874
6875fn lower_pattern(
6876 pattern: &GraphPattern,
6877 profile: Option<&StatsProfile>,
6878 incoming: &IncomingBound,
6879 ctx: &QueryContext,
6880 scope: &GraphScope,
6881) -> Result<PlanNode, ComputeError> {
6882 if let Some(spine) = subselect_spine(pattern) {
6888 return lower_subselect(
6889 spine.body,
6890 spine.variables,
6891 spine.distinct,
6892 spine.slice,
6893 spine.order,
6894 profile,
6895 ctx,
6896 scope,
6897 );
6898 }
6899 let mut leaves = Vec::new();
6900 if collect_flat_leaves(pattern, &mut leaves) {
6901 return lower_pipeline(leaves, profile, incoming, ctx, scope);
6902 }
6903 match pattern {
6904 GraphPattern::Filter { expr, inner } => {
6905 let inner = lower_pattern(inner, profile, incoming, ctx, scope)?;
6906 if matches!(inner, PlanNode::Group { .. }) {
6909 let (early, residual) = crate::expr::split_filter(expr)?;
6910 return Ok(PlanNode::Filter {
6911 inner: Box::new(inner),
6912 early,
6913 residual,
6914 exists: Vec::new(),
6915 one_to_one: false,
6916 });
6917 }
6918 let (exists_raw, rest) = peel_exists_conjuncts(expr)?;
6919 let (early, residual) = match rest {
6920 Some(expr) => crate::expr::split_filter(&expr)?,
6921 None => (None, None),
6922 };
6923 let incoming_body = incoming_from_plan_left(incoming, &inner, profile);
6924 let mut exists = Vec::with_capacity(exists_raw.len());
6925 for (negated, body) in exists_raw {
6926 exists.push(lower_exists_clause(
6927 negated,
6928 body,
6929 &inner,
6930 &incoming_body,
6931 profile,
6932 ctx,
6933 scope,
6934 )?);
6935 }
6936 Ok(PlanNode::Filter {
6937 inner: Box::new(inner),
6938 early,
6939 residual,
6940 exists,
6941 one_to_one: false,
6942 })
6943 }
6944 GraphPattern::LeftJoin {
6945 left,
6946 right,
6947 expression,
6948 } => {
6949 let left = lower_pattern(left, profile, incoming, ctx, scope)?;
6950 let right_incoming = incoming_from_plan_left(incoming, &left, profile);
6951 let mut right = lower_pattern(right, profile, &right_incoming, ctx, scope)?;
6952 let hash_keys = hash_keys_for(&left.output_vars(), &right.output_vars());
6953 ground_and_recost_broadcasted_arm(&left, &mut right, &hash_keys, profile);
6954 if !hash_keys.is_empty() {
6955 compose_graph_from_sibling(&left, &mut right, &hash_keys, profile, true);
6956 }
6957 let (early_filter, residual_filter) = match expression.as_ref() {
6958 Some(expr) => crate::expr::split_filter(expr)?,
6959 None => (None, None),
6960 };
6961 let meta = stamp_left_join_meta(
6962 left.produced_row_count_estimate(),
6963 &left,
6964 &right,
6965 &hash_keys,
6966 profile,
6967 );
6968 let probe_key_domains = stamp_probe_key_domains(profile, &right, &hash_keys);
6969 let probe_key_overlap_milli =
6970 stamp_probe_key_overlaps(profile, &left, &right, &hash_keys);
6971 Ok(PlanNode::LeftJoin {
6972 left: Box::new(left),
6973 right: Box::new(right),
6974 hash_keys,
6975 early_filter,
6976 residual_filter,
6977 probe_key_domains,
6978 probe_key_overlap_milli,
6979 meta,
6980 })
6981 }
6982 GraphPattern::Union { left, right } => {
6983 let left = lower_pattern(left, profile, incoming, ctx, scope)?;
6984 let right = lower_pattern(right, profile, incoming, ctx, scope)?;
6985 Ok(PlanNode::Union {
6986 left: Box::new(left),
6987 right: Box::new(right),
6988 })
6989 }
6990 GraphPattern::Extend {
6991 inner,
6992 variable,
6993 expression,
6994 } => {
6995 let inner = lower_pattern(inner, profile, incoming, ctx, scope)?;
6996 if inner.output_vars().contains(variable) {
6997 return Err(ComputeError::UnsupportedSparql(format!(
6998 "BIND variable {variable} is already in-scope"
6999 )));
7000 }
7001 let _ = crate::expr::split_filter(expression)?;
7002 Ok(PlanNode::Extend {
7003 inner: Box::new(inner),
7004 variable: variable.clone(),
7005 expression: expression.clone(),
7006 const_strings: Vec::new(),
7009 const_blobs: Vec::new(),
7010 })
7011 }
7012 GraphPattern::Join { left, right } => {
7013 let left = lower_pattern(left, profile, incoming, ctx, scope)?;
7014 let right = lower_pattern(right, profile, incoming, ctx, scope)?;
7015 Ok(join_nodes(left, right, profile))
7016 }
7017 GraphPattern::Slice {
7018 inner,
7019 start,
7020 length,
7021 } => Ok(PlanNode::Slice {
7022 inner: Box::new(lower_pattern(inner, profile, incoming, ctx, scope)?),
7023 start: *start as u64,
7024 length: length.map(|n| n as u64),
7025 }),
7026 GraphPattern::Distinct { inner } => {
7027 let inner = lower_pattern(inner, profile, incoming, ctx, scope)?;
7028 let columns = inner.variables();
7029 Ok(PlanNode::Distinct {
7030 inner: Box::new(inner),
7031 columns,
7032 })
7033 }
7034 GraphPattern::Group {
7035 inner,
7036 variables,
7037 aggregates,
7038 } => {
7039 reject_unsupported_aggregates(aggregates)?;
7040 let lowered = lower_pattern(inner, profile, incoming, ctx, scope)?;
7041 Ok(PlanNode::Group {
7042 inner: Box::new(lowered),
7043 variables: variables.clone(),
7044 aggregates: aggregates.clone(),
7045 const_strings: Vec::new(),
7047 const_blobs: Vec::new(),
7048 })
7049 }
7050 GraphPattern::Project { inner, variables } => lower_subselect(
7052 inner,
7053 variables,
7054 false,
7055 None,
7056 Vec::new(),
7057 profile,
7058 ctx,
7059 scope,
7060 ),
7061 GraphPattern::Path {
7062 subject,
7063 path,
7064 object,
7065 } => lower_path(subject, path, object, profile, incoming, ctx, scope),
7066 GraphPattern::Graph { name, inner } => {
7067 let inner_scope = graph_scope_for_name(name, ctx.dataset())?;
7068 if matches!(inner_scope, GraphScope::Empty) {
7069 let inner = lower_pattern(inner, profile, incoming, ctx, &GraphScope::Empty)?;
7070 return Ok(empty_plan_like(&inner, &inner_scope));
7071 }
7072 let (lower_scope, join_graph) = graph_lower_scope(inner, inner_scope);
7073 let lowered = lower_pattern(inner, profile, incoming, ctx, &lower_scope)?;
7074 if let Some(exists) = named_graph_exists_for_unit(&lowered, &lower_scope, ctx.dataset())
7075 {
7076 return Ok(exists);
7077 }
7078 let lowered = attach_graph_domain(lowered, &lower_scope, profile, ctx.dataset())?;
7079 Ok(match join_graph {
7080 Some((graph_var, active_var)) => PlanNode::JoinGraphVar {
7081 inner: Box::new(lowered),
7082 graph_var,
7083 active_var,
7084 },
7085 None => lowered,
7086 })
7087 }
7088 GraphPattern::OrderBy { inner, expression } => {
7089 let keys: Vec<SortKey> = expression
7090 .iter()
7091 .map(|oe| match oe {
7092 OrderExpression::Asc(expression) => SortKey {
7093 expression: expression.clone(),
7094 descending: false,
7095 },
7096 OrderExpression::Desc(expression) => SortKey {
7097 expression: expression.clone(),
7098 descending: true,
7099 },
7100 })
7101 .collect();
7102 Ok(PlanNode::Sort {
7103 inner: Box::new(lower_pattern(inner, profile, incoming, ctx, scope)?),
7104 keys,
7105 })
7106 }
7107 other => Err(ComputeError::UnsupportedSparql(format!(
7108 "{} is not supported (BGP, JOIN, FILTER, OPTIONAL, UNION, VALUES, BIND, GROUP BY, GRAPH, sub-SELECT, property paths, LIMIT / OFFSET, ORDER BY only)",
7109 shape_name(other)
7110 ))),
7111 }
7112}
7113
7114struct SubSelectSpine<'a> {
7121 body: &'a GraphPattern,
7122 variables: &'a [Variable],
7123 distinct: bool,
7124 slice: Option<(usize, Option<usize>)>,
7125 order: Vec<SortKey>,
7126}
7127
7128fn subselect_spine(pattern: &GraphPattern) -> Option<SubSelectSpine<'_>> {
7129 let mut cur = pattern;
7130 let mut distinct = false;
7131 let mut slice = None;
7132 let mut order = Vec::new();
7133 loop {
7134 match cur {
7135 GraphPattern::Slice {
7136 inner,
7137 start,
7138 length,
7139 } => {
7140 slice = Some((*start, *length));
7141 cur = inner;
7142 }
7143 GraphPattern::OrderBy { inner, expression } => {
7144 order = expression
7145 .iter()
7146 .map(|oe| match oe {
7147 OrderExpression::Asc(expression) => SortKey {
7148 expression: expression.clone(),
7149 descending: false,
7150 },
7151 OrderExpression::Desc(expression) => SortKey {
7152 expression: expression.clone(),
7153 descending: true,
7154 },
7155 })
7156 .collect();
7157 cur = inner;
7158 }
7159 GraphPattern::Distinct { inner } => {
7160 distinct = true;
7161 cur = inner;
7162 }
7163 GraphPattern::Reduced { inner } => {
7164 cur = inner;
7165 }
7166 GraphPattern::Project { inner, variables } => {
7167 return Some(SubSelectSpine {
7168 body: inner,
7169 variables,
7170 distinct,
7171 slice,
7172 order,
7173 });
7174 }
7175 _ => return None,
7176 }
7177 }
7178}
7179
7180#[allow(clippy::too_many_arguments)]
7195fn lower_subselect(
7196 inner: &GraphPattern,
7197 variables: &[Variable],
7198 distinct: bool,
7199 slice: Option<(usize, Option<usize>)>,
7200 order: Vec<SortKey>,
7201 profile: Option<&StatsProfile>,
7202 ctx: &QueryContext,
7203 scope: &GraphScope,
7204) -> Result<PlanNode, ComputeError> {
7205 let mut body = lower_pattern(inner, profile, &IncomingBound::default(), ctx, scope)?;
7206 let prefix = mint_scope_prefix();
7207 rename_subselect_scope(&mut body, variables, &prefix)?;
7208 if distinct {
7213 body = PlanNode::Distinct {
7214 inner: Box::new(body),
7215 columns: variables.to_vec(),
7216 };
7217 }
7218 if !order.is_empty() {
7219 body = PlanNode::Sort {
7220 inner: Box::new(body),
7221 keys: order,
7222 };
7223 }
7224 if let Some((start, length)) = slice {
7225 body = PlanNode::Slice {
7226 inner: Box::new(body),
7227 start: start as u64,
7228 length: length.map(|n| n as u64),
7229 };
7230 }
7231 Ok(PlanNode::SubSelect(SubSelectOp {
7232 inner: Box::new(body),
7233 variables: variables.to_vec(),
7234 }))
7235}
7236
7237fn mint_scope_prefix() -> String {
7245 format!("sq_{}_", mint_scope_token())
7246}
7247
7248pub fn mint_scope_token() -> String {
7257 use std::hash::{BuildHasher, Hasher};
7258 const ALPHABET: &[u8; 62] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
7259 let mut token = String::with_capacity(16);
7260 while token.len() < 16 {
7261 let bits = std::collections::hash_map::RandomState::new()
7264 .build_hasher()
7265 .finish();
7266 for byte in bits.to_le_bytes() {
7267 token.push(ALPHABET[byte as usize % ALPHABET.len()] as char);
7268 if token.len() == 16 {
7269 break;
7270 }
7271 }
7272 }
7273 token
7274}
7275
7276fn scope_rename(variable: &Variable, projection: &[Variable], prefix: &str) -> Option<Variable> {
7283 if projection.contains(variable) {
7284 return None;
7285 }
7286 Some(Variable::new_unchecked(format!(
7287 "{prefix}{}",
7288 variable.as_str()
7289 )))
7290}
7291
7292fn rename_opt_var(slot: &mut Option<Variable>, projection: &[Variable], prefix: &str) {
7293 if let Some(variable) = slot
7294 && let Some(fresh) = scope_rename(variable, projection, prefix)
7295 {
7296 *variable = fresh;
7297 }
7298}
7299
7300fn rename_subselect_scope(
7311 node: &mut PlanNode,
7312 projection: &[Variable],
7313 prefix: &str,
7314) -> Result<(), ComputeError> {
7315 match node {
7316 PlanNode::CustomNode(op) => {
7317 for variable in &mut op.variables {
7318 if let Some(fresh) = scope_rename(variable, projection, prefix) {
7319 *variable = fresh;
7320 }
7321 }
7322 for child in &mut op.children {
7323 rename_subselect_scope(child, projection, prefix)?;
7324 }
7325 }
7326 PlanNode::Scan(scan) => {
7327 rename_opt_var(&mut scan.subject, projection, prefix);
7328 rename_opt_var(&mut scan.predicate, projection, prefix);
7329 rename_opt_var(&mut scan.object, projection, prefix);
7330 rename_opt_var(&mut scan.graph, projection, prefix);
7331 for (variable, _) in &mut scan.grounded {
7332 if let Some(fresh) = scope_rename(variable, projection, prefix) {
7333 *variable = fresh;
7334 }
7335 }
7336 if let Some((variable, _)) = &mut scan.broadcasted
7337 && let Some(fresh) = scope_rename(variable, projection, prefix)
7338 {
7339 *variable = fresh;
7340 }
7341 }
7342 PlanNode::Path(path) => {
7343 rename_opt_var(&mut path.subject, projection, prefix);
7344 rename_opt_var(&mut path.object, projection, prefix);
7345 rename_opt_var(&mut path.graph, projection, prefix);
7346 }
7347 PlanNode::Join {
7348 left,
7349 right,
7350 hash_keys,
7351 ..
7352 } => {
7353 rename_subselect_scope(left, projection, prefix)?;
7354 rename_subselect_scope(right, projection, prefix)?;
7355 for key in &mut *hash_keys {
7356 if let Some(fresh) = scope_rename(key, projection, prefix) {
7357 *key = fresh;
7358 }
7359 }
7360 }
7361 PlanNode::LeftJoin {
7362 left,
7363 right,
7364 hash_keys,
7365 early_filter,
7366 residual_filter,
7367 ..
7368 } => {
7369 rename_subselect_scope(left, projection, prefix)?;
7370 rename_subselect_scope(right, projection, prefix)?;
7371 for key in &mut *hash_keys {
7372 if let Some(fresh) = scope_rename(key, projection, prefix) {
7373 *key = fresh;
7374 }
7375 }
7376 if let Some(expr) = early_filter {
7377 rename_expression_scope(expr, projection, prefix)?;
7378 }
7379 if let Some(expr) = residual_filter {
7380 rename_expression_scope(expr, projection, prefix)?;
7381 }
7382 }
7383 PlanNode::Filter {
7384 inner,
7385 early,
7386 residual,
7387 exists,
7388 ..
7389 } => {
7390 rename_subselect_scope(inner, projection, prefix)?;
7391 if let Some(expr) = early {
7392 rename_expression_scope(expr, projection, prefix)?;
7393 }
7394 if let Some(expr) = residual {
7395 rename_expression_scope(expr, projection, prefix)?;
7396 }
7397 for clause in exists {
7398 for variable in &mut clause.correlation {
7399 if let Some(fresh) = scope_rename(variable, projection, prefix) {
7400 *variable = fresh;
7401 }
7402 }
7403 rename_subselect_scope(&mut clause.body, projection, prefix)?;
7404 }
7405 }
7406 PlanNode::Union { left, right } => {
7407 rename_subselect_scope(left, projection, prefix)?;
7408 rename_subselect_scope(right, projection, prefix)?;
7409 }
7410 PlanNode::Unit | PlanNode::NamedGraphExists { .. } => {}
7411 PlanNode::Values(values) => {
7412 for variable in &mut values.variables {
7413 if let Some(fresh) = scope_rename(variable, projection, prefix) {
7414 *variable = fresh;
7415 }
7416 }
7417 }
7418 PlanNode::NamedGraphs { variable, .. } => {
7419 if let Some(fresh) = scope_rename(variable, projection, prefix) {
7420 *variable = fresh;
7421 }
7422 }
7423 PlanNode::Extend {
7424 inner,
7425 variable,
7426 expression,
7427 ..
7428 } => {
7429 rename_subselect_scope(inner, projection, prefix)?;
7430 if let Some(fresh) = scope_rename(variable, projection, prefix) {
7431 *variable = fresh;
7432 }
7433 rename_expression_scope(expression, projection, prefix)?;
7434 }
7435 PlanNode::Slice { inner, .. } => rename_subselect_scope(inner, projection, prefix)?,
7436 PlanNode::JoinGraphVar {
7437 inner,
7438 graph_var,
7439 active_var,
7440 ..
7441 } => {
7442 rename_subselect_scope(inner, projection, prefix)?;
7443 if let Some(fresh) = scope_rename(graph_var, projection, prefix) {
7444 *graph_var = fresh;
7445 }
7446 if let Some(fresh) = scope_rename(active_var, projection, prefix) {
7447 *active_var = fresh;
7448 }
7449 }
7450 PlanNode::Distinct { inner, columns } => {
7451 rename_subselect_scope(inner, projection, prefix)?;
7452 for column in &mut *columns {
7453 if let Some(fresh) = scope_rename(column, projection, prefix) {
7454 *column = fresh;
7455 }
7456 }
7457 }
7458 PlanNode::Sort { inner, keys } => {
7459 rename_subselect_scope(inner, projection, prefix)?;
7460 for key in keys {
7461 rename_expression_scope(&mut key.expression, projection, prefix)?;
7462 }
7463 }
7464 PlanNode::Group {
7465 inner,
7466 variables,
7467 aggregates,
7468 ..
7469 } => {
7470 rename_subselect_scope(inner, projection, prefix)?;
7471 for key in &mut *variables {
7472 if let Some(fresh) = scope_rename(key, projection, prefix) {
7473 *key = fresh;
7474 }
7475 }
7476 for (result, agg) in &mut *aggregates {
7477 if let Some(fresh) = scope_rename(result, projection, prefix) {
7478 *result = fresh;
7479 }
7480 if let AggregateExpression::FunctionCall { expr, .. } = agg {
7481 rename_expression_scope(expr, projection, prefix)?;
7482 }
7483 }
7484 }
7485 PlanNode::SubSelect(sub) => {
7490 for variable in &mut sub.variables {
7491 if let Some(fresh) = scope_rename(variable, projection, prefix) {
7492 let old = std::mem::replace(variable, fresh.clone());
7493 rename_variable_in_subtree(&mut sub.inner, &old, &fresh)?;
7494 }
7495 }
7496 }
7497 PlanNode::DomainCounts {
7500 head,
7501 count,
7502 dead,
7503 constraint_var,
7504 ..
7505 } => {
7506 if let Some(fresh) = scope_rename(head, projection, prefix) {
7507 *head = fresh;
7508 }
7509 if let Some(fresh) = scope_rename(count, projection, prefix) {
7510 *count = fresh;
7511 }
7512 if let Some(dead) = dead
7513 && let Some(fresh) = scope_rename(dead, projection, prefix)
7514 {
7515 *dead = fresh;
7516 }
7517 if let Some(cv) = constraint_var
7518 && let Some(fresh) = scope_rename(cv, projection, prefix)
7519 {
7520 *constraint_var = Some(fresh);
7521 }
7522 }
7523 PlanNode::HeadCounts {
7524 counted,
7525 group,
7526 count,
7527 ..
7528 } => {
7529 if let Some(fresh) = scope_rename(counted, projection, prefix) {
7530 *counted = fresh;
7531 }
7532 if let Some(group) = group
7533 && let Some(fresh) = scope_rename(group, projection, prefix)
7534 {
7535 *group = fresh;
7536 }
7537 if let Some(fresh) = scope_rename(count, projection, prefix) {
7538 *count = fresh;
7539 }
7540 }
7541 PlanNode::PatternCount {
7542 subject,
7543 predicate,
7544 object,
7545 count,
7546 counted,
7547 ..
7548 } => {
7549 rename_opt_var(subject, projection, prefix);
7550 rename_opt_var(predicate, projection, prefix);
7551 rename_opt_var(object, projection, prefix);
7552 if let Some(fresh) = scope_rename(count, projection, prefix) {
7553 *count = fresh;
7554 }
7555 if let Some(counted) = counted
7556 && let Some(fresh) = scope_rename(counted, projection, prefix)
7557 {
7558 *counted = fresh;
7559 }
7560 }
7561 }
7562 Ok(())
7563}
7564
7565fn rename_variable_in_subtree(
7578 node: &mut PlanNode,
7579 old: &Variable,
7580 fresh: &Variable,
7581) -> Result<(), ComputeError> {
7582 let rename_expr =
7583 |expression: &mut Expression| rename_expression_variable(expression, old, fresh);
7584 match node {
7585 PlanNode::CustomNode(op) => {
7586 for variable in &mut op.variables {
7587 if variable == old {
7588 *variable = fresh.clone();
7589 }
7590 }
7591 for child in &mut op.children {
7592 rename_variable_in_subtree(child, old, fresh)?;
7593 }
7594 }
7595 PlanNode::Scan(scan) => {
7596 for slot in [
7597 &mut scan.subject,
7598 &mut scan.predicate,
7599 &mut scan.object,
7600 &mut scan.graph,
7601 ] {
7602 if slot.as_ref() == Some(old) {
7603 *slot = Some(fresh.clone());
7604 }
7605 }
7606 for (variable, _) in &mut scan.grounded {
7607 if variable == old {
7608 *variable = fresh.clone();
7609 }
7610 }
7611 if let Some((variable, _)) = &mut scan.broadcasted
7612 && variable == old
7613 {
7614 *variable = fresh.clone();
7615 }
7616 }
7617 PlanNode::Path(path) => {
7618 for slot in [&mut path.subject, &mut path.object, &mut path.graph] {
7619 if slot.as_ref() == Some(old) {
7620 *slot = Some(fresh.clone());
7621 }
7622 }
7623 }
7624 PlanNode::Join {
7625 left,
7626 right,
7627 hash_keys,
7628 ..
7629 } => {
7630 rename_variable_in_subtree(left, old, fresh)?;
7631 rename_variable_in_subtree(right, old, fresh)?;
7632 for key in &mut *hash_keys {
7633 if key == old {
7634 *key = fresh.clone();
7635 }
7636 }
7637 }
7638 PlanNode::LeftJoin {
7639 left,
7640 right,
7641 hash_keys,
7642 early_filter,
7643 residual_filter,
7644 ..
7645 } => {
7646 rename_variable_in_subtree(left, old, fresh)?;
7647 rename_variable_in_subtree(right, old, fresh)?;
7648 for key in &mut *hash_keys {
7649 if key == old {
7650 *key = fresh.clone();
7651 }
7652 }
7653 if let Some(expr) = early_filter {
7654 rename_expr(expr)?;
7655 }
7656 if let Some(expr) = residual_filter {
7657 rename_expr(expr)?;
7658 }
7659 }
7660 PlanNode::Filter {
7661 inner,
7662 early,
7663 residual,
7664 exists,
7665 ..
7666 } => {
7667 rename_variable_in_subtree(inner, old, fresh)?;
7668 if let Some(expr) = early {
7669 rename_expr(expr)?;
7670 }
7671 if let Some(expr) = residual {
7672 rename_expr(expr)?;
7673 }
7674 for clause in exists {
7675 for variable in &mut clause.correlation {
7676 if variable == old {
7677 *variable = fresh.clone();
7678 }
7679 }
7680 rename_variable_in_subtree(&mut clause.body, old, fresh)?;
7681 }
7682 }
7683 PlanNode::Union { left, right } => {
7684 rename_variable_in_subtree(left, old, fresh)?;
7685 rename_variable_in_subtree(right, old, fresh)?;
7686 }
7687 PlanNode::Unit | PlanNode::NamedGraphExists { .. } => {}
7688 PlanNode::Values(values) => {
7689 for variable in &mut values.variables {
7690 if variable == old {
7691 *variable = fresh.clone();
7692 }
7693 }
7694 }
7695 PlanNode::NamedGraphs { variable, .. } => {
7696 if variable == old {
7697 *variable = fresh.clone();
7698 }
7699 }
7700 PlanNode::Extend {
7701 inner,
7702 variable,
7703 expression,
7704 ..
7705 } => {
7706 rename_variable_in_subtree(inner, old, fresh)?;
7707 if variable == old {
7708 *variable = fresh.clone();
7709 }
7710 rename_expr(expression)?;
7711 }
7712 PlanNode::Slice { inner, .. } => rename_variable_in_subtree(inner, old, fresh)?,
7713 PlanNode::JoinGraphVar {
7714 inner,
7715 graph_var,
7716 active_var,
7717 ..
7718 } => {
7719 rename_variable_in_subtree(inner, old, fresh)?;
7720 if graph_var == old {
7721 *graph_var = fresh.clone();
7722 }
7723 if active_var == old {
7724 *active_var = fresh.clone();
7725 }
7726 }
7727 PlanNode::Distinct { inner, columns } => {
7728 rename_variable_in_subtree(inner, old, fresh)?;
7729 for column in &mut *columns {
7730 if column == old {
7731 *column = fresh.clone();
7732 }
7733 }
7734 }
7735 PlanNode::Sort { inner, keys } => {
7736 rename_variable_in_subtree(inner, old, fresh)?;
7737 for key in keys {
7738 rename_expr(&mut key.expression)?;
7739 }
7740 }
7741 PlanNode::Group {
7742 inner,
7743 variables,
7744 aggregates,
7745 ..
7746 } => {
7747 rename_variable_in_subtree(inner, old, fresh)?;
7748 for key in &mut *variables {
7749 if key == old {
7750 *key = fresh.clone();
7751 }
7752 }
7753 for (result, agg) in &mut *aggregates {
7754 if result == old {
7755 *result = fresh.clone();
7756 }
7757 if let AggregateExpression::FunctionCall { expr, .. } = agg {
7758 rename_expr(expr)?;
7759 }
7760 }
7761 }
7762 PlanNode::SubSelect(sub) => {
7763 let projects_old = sub.variables.iter().any(|variable| variable == old);
7764 for variable in &mut sub.variables {
7765 if variable == old {
7766 *variable = fresh.clone();
7767 }
7768 }
7769 if projects_old {
7770 rename_variable_in_subtree(&mut sub.inner, old, fresh)?;
7771 }
7772 }
7773 PlanNode::DomainCounts {
7774 head, count, dead, ..
7775 } => {
7776 if head == old {
7777 *head = fresh.clone();
7778 }
7779 if count == old {
7780 *count = fresh.clone();
7781 }
7782 if let Some(slot) = dead
7783 && slot == old
7784 {
7785 *slot = fresh.clone();
7786 }
7787 }
7788 PlanNode::HeadCounts {
7789 counted,
7790 group,
7791 count,
7792 ..
7793 } => {
7794 if counted == old {
7795 *counted = fresh.clone();
7796 }
7797 if let Some(group) = group
7798 && group == old
7799 {
7800 *group = fresh.clone();
7801 }
7802 if count == old {
7803 *count = fresh.clone();
7804 }
7805 }
7806 PlanNode::PatternCount {
7807 subject,
7808 predicate,
7809 object,
7810 count,
7811 counted,
7812 ..
7813 } => {
7814 for slot in [subject, predicate, object] {
7815 if slot.as_ref() == Some(old) {
7816 *slot = Some(fresh.clone());
7817 }
7818 }
7819 if count == old {
7820 *count = fresh.clone();
7821 }
7822 if let Some(counted) = counted
7823 && counted == old
7824 {
7825 *counted = fresh.clone();
7826 }
7827 }
7828 }
7829 Ok(())
7830}
7831
7832fn rename_expression_scope(
7835 expression: &mut Expression,
7836 projection: &[Variable],
7837 prefix: &str,
7838) -> Result<(), ComputeError> {
7839 rewrite_expression_vars(expression, &|variable| {
7840 scope_rename(variable, projection, prefix)
7841 })
7842}
7843
7844fn rename_expression_variable(
7847 expression: &mut Expression,
7848 old: &Variable,
7849 fresh: &Variable,
7850) -> Result<(), ComputeError> {
7851 rewrite_expression_vars(expression, &|variable| {
7852 (variable == old).then(|| fresh.clone())
7853 })
7854}
7855
7856fn rewrite_expression_vars(
7860 expression: &mut Expression,
7861 rename: &dyn Fn(&Variable) -> Option<Variable>,
7862) -> Result<(), ComputeError> {
7863 match expression {
7864 Expression::NamedNode(_) | Expression::Literal(_) => {}
7865 Expression::Variable(variable) => {
7866 if let Some(fresh) = rename(variable) {
7867 *variable = fresh;
7868 }
7869 }
7870 Expression::Bound(variable) => {
7871 if let Some(fresh) = rename(variable) {
7872 *variable = fresh;
7873 }
7874 }
7875 Expression::Or(a, b)
7876 | Expression::And(a, b)
7877 | Expression::Equal(a, b)
7878 | Expression::SameTerm(a, b)
7879 | Expression::Greater(a, b)
7880 | Expression::GreaterOrEqual(a, b)
7881 | Expression::Less(a, b)
7882 | Expression::LessOrEqual(a, b)
7883 | Expression::Add(a, b)
7884 | Expression::Subtract(a, b)
7885 | Expression::Multiply(a, b)
7886 | Expression::Divide(a, b) => {
7887 rewrite_expression_vars(a, rename)?;
7888 rewrite_expression_vars(b, rename)?;
7889 }
7890 Expression::In(left, args) => {
7891 rewrite_expression_vars(left, rename)?;
7892 for arg in args {
7893 rewrite_expression_vars(arg, rename)?;
7894 }
7895 }
7896 Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) | Expression::Not(inner) => {
7897 rewrite_expression_vars(inner, rename)?;
7898 }
7899 Expression::Exists(_) => {
7900 return Err(ComputeError::UnsupportedSparql(
7901 "EXISTS inside a sub-SELECT is not supported".into(),
7902 ));
7903 }
7904 Expression::If(condition, then_branch, else_branch) => {
7905 rewrite_expression_vars(condition, rename)?;
7906 rewrite_expression_vars(then_branch, rename)?;
7907 rewrite_expression_vars(else_branch, rename)?;
7908 }
7909 Expression::Coalesce(args) | Expression::FunctionCall(_, args) => {
7910 for arg in args {
7911 rewrite_expression_vars(arg, rename)?;
7912 }
7913 }
7914 }
7915 Ok(())
7916}
7917
7918fn graph_scope_for_name(
7919 name: &NamedNodePattern,
7920 dataset: &QueryDataset,
7921) -> Result<GraphScope, ComputeError> {
7922 Ok(match name {
7923 NamedNodePattern::NamedNode(node) => {
7924 GraphScope::named_iri(EncodedTerm::from(node), dataset)
7925 }
7926 NamedNodePattern::Variable(variable) => GraphScope::named_var(variable.clone(), dataset),
7927 })
7928}
7929
7930fn graph_lower_scope(
7933 inner: &GraphPattern,
7934 scope: GraphScope,
7935) -> (GraphScope, Option<(Variable, Variable)>) {
7936 let GraphScope::NamedVar { variable, window } = &scope else {
7937 return (scope, None);
7938 };
7939 if !pattern_mentions_graph_var(inner, variable) {
7940 return (scope, None);
7941 }
7942 let active_var = mint_graph_active_var(variable);
7943 (
7944 GraphScope::NamedVar {
7945 variable: active_var.clone(),
7946 window: window.clone(),
7947 },
7948 Some((variable.clone(), active_var)),
7949 )
7950}
7951
7952fn named_graph_exists_for_unit(
7955 inner: &PlanNode,
7956 scope: &GraphScope,
7957 dataset: &QueryDataset,
7958) -> Option<PlanNode> {
7959 if !matches!(inner, PlanNode::Unit) {
7960 return None;
7961 }
7962 if !matches!(dataset.named, NamedGraphWindow::EngineAllNamed) {
7963 return None;
7964 }
7965 match scope {
7966 GraphScope::NamedIri(graph) => Some(PlanNode::NamedGraphExists {
7967 graph: graph.clone(),
7968 }),
7969 _ => None,
7970 }
7971}
7972
7973fn pattern_mentions_graph_var(pattern: &GraphPattern, var: &Variable) -> bool {
7976 match pattern {
7977 GraphPattern::Bgp { patterns } => patterns.iter().any(|triple| {
7978 term_pattern_mentions(&triple.subject, var)
7979 || named_node_pattern_mentions(&triple.predicate, var)
7980 || term_pattern_mentions(&triple.object, var)
7981 }),
7982 GraphPattern::Path {
7983 subject, object, ..
7984 } => term_pattern_mentions(subject, var) || term_pattern_mentions(object, var),
7985 GraphPattern::Join { left, right }
7986 | GraphPattern::Union { left, right }
7987 | GraphPattern::Minus { left, right } => {
7988 pattern_mentions_graph_var(left, var) || pattern_mentions_graph_var(right, var)
7989 }
7990 GraphPattern::LeftJoin {
7991 left,
7992 right,
7993 expression,
7994 } => {
7995 pattern_mentions_graph_var(left, var)
7996 || pattern_mentions_graph_var(right, var)
7997 || expression
7998 .as_ref()
7999 .is_some_and(|expr| variables_in_expression(expr).contains(var))
8000 }
8001 GraphPattern::Filter { expr, inner } => {
8002 variables_in_expression(expr).contains(var) || pattern_mentions_graph_var(inner, var)
8003 }
8004 GraphPattern::Graph { inner, .. }
8005 | GraphPattern::Service { inner, .. }
8006 | GraphPattern::Slice { inner, .. }
8007 | GraphPattern::Distinct { inner }
8008 | GraphPattern::Reduced { inner }
8009 | GraphPattern::Project { inner, .. }
8010 | GraphPattern::OrderBy { inner, .. } => pattern_mentions_graph_var(inner, var),
8011 GraphPattern::Extend {
8012 inner,
8013 variable,
8014 expression,
8015 } => {
8016 variable == var
8017 || variables_in_expression(expression).contains(var)
8018 || pattern_mentions_graph_var(inner, var)
8019 }
8020 GraphPattern::Values { variables, .. } => variables.contains(var),
8021 GraphPattern::Group {
8022 inner, variables, ..
8023 } => variables.contains(var) || pattern_mentions_graph_var(inner, var),
8024 }
8025}
8026
8027fn term_pattern_mentions(term: &TermPattern, var: &Variable) -> bool {
8028 matches!(term, TermPattern::Variable(v) if v == var)
8029}
8030
8031fn named_node_pattern_mentions(name: &NamedNodePattern, var: &Variable) -> bool {
8032 matches!(name, NamedNodePattern::Variable(v) if v == var)
8033}
8034
8035fn mint_graph_active_var(variable: &Variable) -> Variable {
8038 let sq = mint_scope_prefix();
8039 Variable::new_unchecked(format!(
8040 "gact_{}{}",
8041 sq.strip_prefix("sq_").unwrap_or(&sq),
8042 variable.as_str()
8043 ))
8044}
8045
8046fn empty_plan_like(inner: &PlanNode, scope: &GraphScope) -> PlanNode {
8047 let mut variables = inner.variables();
8048 if let GraphScope::NamedVar { variable, .. } = scope
8049 && !variables.contains(variable)
8050 {
8051 variables.push(variable.clone());
8052 }
8053 PlanNode::Values(ValuesOp {
8054 variables,
8055 rows: Vec::new(),
8056 strings: Vec::new(),
8057 blobs: Vec::new(),
8058 })
8059}
8060
8061fn attach_graph_domain(
8073 inner: PlanNode,
8074 scope: &GraphScope,
8075 profile: Option<&StatsProfile>,
8076 dataset: &QueryDataset,
8077) -> Result<PlanNode, ComputeError> {
8078 let GraphScope::NamedVar { variable, window } = scope else {
8079 return Ok(inner);
8080 };
8081 let inner = if let PlanNode::Filter {
8085 inner: filter_inner,
8086 early,
8087 residual,
8088 exists,
8089 one_to_one,
8090 } = inner
8091 {
8092 if !filter_inner.output_vars().contains(variable) {
8093 let attached = attach_graph_domain(*filter_inner, scope, profile, dataset)?;
8094 return Ok(PlanNode::Filter {
8095 inner: Box::new(attached),
8096 early,
8097 residual,
8098 exists,
8099 one_to_one,
8100 });
8101 }
8102 PlanNode::Filter {
8103 inner: filter_inner,
8104 early,
8105 residual,
8106 exists,
8107 one_to_one,
8108 }
8109 } else {
8110 inner
8111 };
8112 let domain = graph_domain(variable, window, dataset, profile)?;
8113 if matches!(inner, PlanNode::Unit) {
8114 return Ok(domain);
8115 }
8116 let vars = inner.output_vars();
8117 if vars.is_always_bound(variable) {
8118 return Ok(inner);
8119 }
8120 if !vars.contains(variable) {
8121 return Ok(join_nodes(domain, inner, profile));
8122 }
8123 let (mut right, early_filter, residual_filter) = flatten_unit_left_join(inner);
8128 let hash_keys = vec![variable.clone()];
8129 ground_and_recost_broadcasted_arm(&domain, &mut right, &hash_keys, profile);
8130 compose_graph_from_sibling(&domain, &mut right, &hash_keys, profile, true);
8131 let meta = stamp_left_join_meta(
8132 domain.produced_row_count_estimate(),
8133 &domain,
8134 &right,
8135 &hash_keys,
8136 profile,
8137 );
8138 let probe_key_domains = stamp_probe_key_domains(profile, &right, &hash_keys);
8139 let probe_key_overlap_milli = stamp_probe_key_overlaps(profile, &domain, &right, &hash_keys);
8140 Ok(PlanNode::LeftJoin {
8141 left: Box::new(domain),
8142 right: Box::new(right),
8143 hash_keys,
8144 early_filter,
8145 residual_filter,
8146 probe_key_domains,
8147 probe_key_overlap_milli,
8148 meta,
8149 })
8150}
8151
8152fn flatten_unit_left_join(inner: PlanNode) -> (PlanNode, Option<Expression>, Option<Expression>) {
8155 match inner {
8156 PlanNode::LeftJoin {
8157 left,
8158 right,
8159 early_filter,
8160 residual_filter,
8161 ..
8162 } if matches!(left.as_ref(), PlanNode::Unit) => (*right, early_filter, residual_filter),
8163 other => (other, None, None),
8164 }
8165}
8166
8167fn graph_domain(
8168 variable: &Variable,
8169 window: &NamedVarWindow,
8170 dataset: &QueryDataset,
8171 profile: Option<&StatsProfile>,
8172) -> Result<PlanNode, ComputeError> {
8173 match window {
8174 NamedVarWindow::Collect => Ok(PlanNode::NamedGraphs {
8175 variable: variable.clone(),
8176 produced_row_count_estimate: named_graphs_estimated_rows(profile),
8177 }),
8178 NamedVarWindow::Ground(term) => {
8179 graph_domain_values(variable, std::slice::from_ref(term), &dataset.named_strings)
8180 }
8181 NamedVarWindow::Allow(filter) => {
8182 graph_domain_values(variable, filter.terms(), &dataset.named_strings)
8183 }
8184 }
8185}
8186
8187fn graph_domain_values(
8188 variable: &Variable,
8189 terms: &[EncodedTerm],
8190 named_strings: &[(StrHash, String)],
8191) -> Result<PlanNode, ComputeError> {
8192 if terms.len() > GRAPH_FILTER_TERM_CAP as usize {
8193 return Err(ComputeError::UnsupportedSparql(format!(
8194 "FROM NAMED / named-graph-uri list exceeds {GRAPH_FILTER_TERM_CAP} graphs"
8195 )));
8196 }
8197 Ok(PlanNode::Values(ValuesOp {
8198 variables: vec![variable.clone()],
8199 rows: terms.iter().cloned().map(|term| vec![Some(term)]).collect(),
8200 strings: named_strings.to_vec(),
8201 blobs: Vec::new(),
8202 }))
8203}
8204
8205fn empty_pipeline_values(leaves: &[FlatLeaf], scope: &GraphScope) -> PlanNode {
8206 let mut variables = Vec::new();
8207 for leaf in leaves {
8208 match leaf {
8209 FlatLeaf::Triple(pattern)
8210 | FlatLeaf::FilteredTriple {
8211 triple: pattern, ..
8212 } => {
8213 if let TermPattern::Variable(v) = &pattern.subject
8214 && !variables.contains(v)
8215 {
8216 variables.push(v.clone());
8217 }
8218 if let NamedNodePattern::Variable(v) = &pattern.predicate
8219 && !variables.contains(v)
8220 {
8221 variables.push(v.clone());
8222 }
8223 if let TermPattern::Variable(v) = &pattern.object
8224 && !variables.contains(v)
8225 {
8226 variables.push(v.clone());
8227 }
8228 }
8229 FlatLeaf::Values {
8230 variables: vars, ..
8231 } => {
8232 for v in vars {
8233 if !variables.contains(v) {
8234 variables.push(v.clone());
8235 }
8236 }
8237 }
8238 FlatLeaf::Path {
8239 subject, object, ..
8240 } => {
8241 for term in [subject, object] {
8242 if let TermPattern::Variable(v) = term
8243 && !variables.contains(v)
8244 {
8245 variables.push(v.clone());
8246 }
8247 }
8248 }
8249 }
8250 }
8251 if let GraphScope::NamedVar { variable, .. } = scope
8252 && !variables.contains(variable)
8253 {
8254 variables.push(variable.clone());
8255 }
8256 PlanNode::Values(ValuesOp {
8257 variables,
8258 rows: Vec::new(),
8259 strings: Vec::new(),
8260 blobs: Vec::new(),
8261 })
8262}
8263
8264enum FlatLeaf {
8266 Triple(TriplePattern),
8267 FilteredTriple {
8273 triple: TriplePattern,
8274 expression: Expression,
8275 },
8276 Values {
8277 variables: Vec<Variable>,
8278 bindings: Vec<Vec<Option<GroundTerm>>>,
8279 },
8280 Path {
8281 subject: TermPattern,
8282 path: PropertyPathExpression,
8283 object: TermPattern,
8284 },
8285}
8286
8287fn collect_flat_leaves(pattern: &GraphPattern, out: &mut Vec<FlatLeaf>) -> bool {
8290 match pattern {
8291 GraphPattern::Bgp { patterns } => {
8292 out.extend(patterns.iter().cloned().map(FlatLeaf::Triple));
8293 true
8294 }
8295 GraphPattern::Filter { expr, inner } => match inner.as_ref() {
8296 GraphPattern::Bgp { patterns }
8300 if patterns.len() == 1 && !expression_contains_exists(expr) =>
8301 {
8302 out.push(FlatLeaf::FilteredTriple {
8303 triple: patterns[0].clone(),
8304 expression: expr.clone(),
8305 });
8306 true
8307 }
8308 _ => false,
8309 },
8310 GraphPattern::Values {
8311 variables,
8312 bindings,
8313 } => {
8314 out.push(FlatLeaf::Values {
8315 variables: variables.clone(),
8316 bindings: bindings.clone(),
8317 });
8318 true
8319 }
8320 GraphPattern::Path {
8321 subject,
8322 path,
8323 object,
8324 } => {
8325 out.push(FlatLeaf::Path {
8326 subject: subject.clone(),
8327 path: path.clone(),
8328 object: object.clone(),
8329 });
8330 true
8331 }
8332 GraphPattern::Join { left, right } => {
8333 collect_flat_leaves(left, out) && collect_flat_leaves(right, out)
8334 }
8335 _ => false,
8336 }
8337}
8338
8339fn order_pipeline_leaves(
8340 leaves: Vec<FlatLeaf>,
8341 profile: Option<&StatsProfile>,
8342 incoming: &IncomingBound,
8343 ctx: &QueryContext,
8344 scope: &GraphScope,
8345) -> Result<Vec<FlatLeaf>, ComputeError> {
8346 let mut keyed = Vec::with_capacity(leaves.len());
8347 for leaf in leaves {
8348 let (rows, bound, incoming_slots) = leaf_sort_key(&leaf, profile, incoming, ctx, scope)?;
8349 keyed.push((leaf, rows, bound, incoming_slots));
8350 }
8351 keyed.sort_by(|a, b| {
8352 a.1.cmp(&b.1)
8353 .then_with(|| b.2.cmp(&a.2))
8354 .then_with(|| b.3.cmp(&a.3))
8355 });
8356 Ok(keyed.into_iter().map(|(leaf, _, _, _)| leaf).collect())
8357}
8358
8359fn leaf_sort_key(
8360 leaf: &FlatLeaf,
8361 profile: Option<&StatsProfile>,
8362 incoming: &IncomingBound,
8363 ctx: &QueryContext,
8364 scope: &GraphScope,
8365) -> Result<(u64, usize, usize), ComputeError> {
8366 Ok(match leaf {
8367 FlatLeaf::Triple(pattern)
8368 | FlatLeaf::FilteredTriple {
8369 triple: pattern, ..
8370 } => {
8371 let scan = plan_scan_op(pattern, profile, incoming, ctx, scope)?;
8372 let extra = extra_bound_slots_for(
8373 &scan.subject,
8374 &scan.predicate,
8375 &scan.object,
8376 &scan.graph,
8377 incoming,
8378 );
8379 (
8380 scan.produced_row_count_estimate,
8381 bound_slots(&scan.pattern) + extra.count(),
8382 extra.count(),
8383 )
8384 }
8385 FlatLeaf::Values { bindings, .. } => (bindings.len() as u64, 3, 0),
8386 FlatLeaf::Path {
8387 subject,
8388 path,
8389 object,
8390 } => {
8391 let path_node = lower_path(subject, path, object, profile, incoming, ctx, scope)?;
8392 let PlanNode::Path(op) = path_node else {
8393 unreachable!("lower_path returns Path");
8394 };
8395 let incoming_ends = usize::from(term_incoming_bound(subject, incoming))
8396 + usize::from(term_incoming_bound(object, incoming));
8397 (
8398 op.produced_row_count_estimate,
8399 op.bound_ends() + incoming_ends,
8400 incoming_ends,
8401 )
8402 }
8403 })
8404}
8405
8406fn lower_pipeline(
8407 leaves: Vec<FlatLeaf>,
8408 profile: Option<&StatsProfile>,
8409 incoming: &IncomingBound,
8410 ctx: &QueryContext,
8411 scope: &GraphScope,
8412) -> Result<PlanNode, ComputeError> {
8413 if matches!(scope, GraphScope::Empty) {
8416 return Ok(empty_pipeline_values(&leaves, scope));
8417 }
8418 if leaves.is_empty() {
8419 return Ok(PlanNode::Unit);
8420 }
8421 let default_empty = matches!(scope, GraphScope::Default)
8422 && matches!(ctx.dataset().default, DefaultGraphWindow::Empty);
8423 let ordered = order_pipeline_leaves(leaves, profile, incoming, ctx, scope)?;
8424 let mut nodes = Vec::with_capacity(ordered.len());
8425 for leaf in ordered {
8426 nodes.push(lower_leaf(
8427 leaf,
8428 profile,
8429 incoming,
8430 ctx,
8431 scope,
8432 default_empty,
8433 )?);
8434 }
8435 nodes.retain(|node| !matches!(node, PlanNode::Unit));
8438 if nodes.is_empty() {
8439 return Ok(PlanNode::Unit);
8440 }
8441 let mut node = nodes.remove(0);
8442 for right in nodes {
8443 node = join_nodes(node, right, profile);
8444 }
8445 Ok(node)
8446}
8447
8448fn pair_first_drives(
8457 profile: Option<&StatsProfile>,
8458 first: &PlanNode,
8459 second: &PlanNode,
8460 hash_keys: &[Variable],
8461 first_cost: SeatCost,
8462 second_cost: SeatCost,
8463) -> bool {
8464 if seat_beats(second_cost, first_cost) {
8465 return false;
8466 }
8467 if seat_beats(first_cost, second_cost) {
8468 return true;
8469 }
8470 let first_rows = driver_whole_read_rows(first, hash_keys, profile);
8473 let second_rows = driver_whole_read_rows(second, hash_keys, profile);
8474 let first_domain =
8475 join_key_domain_for_allow_list(profile, first, second, hash_keys, first_rows);
8476 let second_domain =
8477 join_key_domain_for_allow_list(profile, second, first, hash_keys, second_rows);
8478 (driver_cost(first_rows, first_domain), first_rows)
8479 <= (driver_cost(second_rows, second_domain), second_rows)
8480}
8481
8482fn pair_start_matches_seed_start(
8488 pair_first: usize,
8489 seed_idx: usize,
8490 first_candidate_tag: Option<&str>,
8491 other_tag: &str,
8492) -> bool {
8493 first_candidate_tag == Some(other_tag) && pair_first == seed_idx
8494}
8495
8496fn associate_cost_based(
8584 nodes: Vec<JoinableSpineNode>,
8585 profile: Option<&StatsProfile>,
8586 ctx: Option<&crate::context::QueryContext>,
8587) -> PlanNode {
8588 if nodes.len() < 2 {
8589 return nodes
8590 .into_iter()
8591 .next()
8592 .map(JoinableSpineNode::into_plan)
8593 .unwrap_or(PlanNode::Unit);
8594 }
8595 let seat_by_totals = ctx.is_some_and(crate::context::QueryContext::seat_by_total_cost);
8596 let tags: Vec<String> = nodes
8599 .iter()
8600 .map(|node| crate::explain::plan_node_tag(node.as_plan()))
8601 .collect();
8602 let produced = |idx: usize| nodes[idx].as_plan().produced_row_count_estimate();
8603 let values_first = |idx: usize| u8::from(!matches!(nodes[idx].as_plan(), PlanNode::Values(_)));
8607 let min_idx = (0..nodes.len())
8608 .min_by(|&i, &j| {
8609 produced(i)
8610 .cmp(&produced(j))
8611 .then_with(|| values_first(i).cmp(&values_first(j)))
8612 .then_with(|| tags[i].cmp(&tags[j]))
8613 })
8614 .expect("nodes is non-empty");
8615 let mut min_remaining = Vec::with_capacity(nodes.len() - 1);
8616 for (idx, node) in nodes.iter().enumerate() {
8617 if idx != min_idx {
8618 min_remaining.push(node.clone());
8619 }
8620 }
8621 let (plan_a, total_a, first_candidate_a) = associate_from_seed(
8622 nodes[min_idx].clone().into_plan(),
8623 min_remaining,
8624 profile,
8625 ctx,
8626 seat_by_totals,
8627 );
8628 if !seat_by_totals {
8639 return plan_a;
8640 }
8641 let pair_order = |i: usize, j: usize| {
8642 if tags[i] <= tags[j] { (i, j) } else { (j, i) }
8643 };
8644 let pair_tags_less = |i: usize, j: usize, oi: usize, oj: usize| {
8645 let (a, b) = pair_order(i, j);
8646 let (c, d) = pair_order(oi, oj);
8647 (tags[a].as_str(), tags[b].as_str()) < (tags[c].as_str(), tags[d].as_str())
8648 };
8649 let mut pair_produced: Vec<(usize, usize, u64)> =
8652 Vec::with_capacity(nodes.len() * (nodes.len() - 1) / 2);
8653 let mut bar = u64::MAX;
8654 for i in 0..nodes.len() {
8655 for j in (i + 1)..nodes.len() {
8656 let (a, b) = pair_order(i, j);
8657 let keys = hash_keys_for(
8658 &nodes[a].as_plan().output_vars(),
8659 &nodes[b].as_plan().output_vars(),
8660 );
8661 let rows =
8662 finalize_inner_join_meta(nodes[a].as_plan(), nodes[b].as_plan(), &keys, profile).1;
8663 pair_produced.push((i, j, rows));
8664 bar = bar.min(rows);
8665 }
8666 }
8667 let guard = bar.saturating_mul(SEAT_ASSOC_EXPLOSION_GUARD);
8668 let mut best_pair: Option<(usize, usize, SeatCost, bool)> = None;
8673 for (i, j, pair_rows) in pair_produced {
8674 if pair_rows > guard {
8675 continue;
8676 }
8677 let (a, b) = pair_order(i, j);
8678 let keys = hash_keys_for(
8679 &nodes[a].as_plan().output_vars(),
8680 &nodes[b].as_plan().output_vars(),
8681 );
8682 let a_drives = seat_cost_total(
8683 profile,
8684 nodes[a].as_plan(),
8685 nodes[b].as_plan(),
8686 &keys,
8687 ctx,
8688 None,
8689 );
8690 let b_drives = seat_cost_total(
8691 profile,
8692 nodes[b].as_plan(),
8693 nodes[a].as_plan(),
8694 &keys,
8695 ctx,
8696 None,
8697 );
8698 let first_drives = pair_first_drives(
8699 profile,
8700 nodes[a].as_plan(),
8701 nodes[b].as_plan(),
8702 &keys,
8703 a_drives,
8704 b_drives,
8705 );
8706 let first_drives = if (a == min_idx || b == min_idx)
8713 && !seat_beats(a_drives, b_drives)
8714 && !seat_beats(b_drives, a_drives)
8715 {
8716 a == min_idx
8717 } else {
8718 first_drives
8719 };
8720 let cost = if first_drives { a_drives } else { b_drives };
8721 let better = match best_pair {
8722 None => true,
8723 Some((bi, bj, incumbent, _)) => {
8724 if seat_beats(cost, incumbent) {
8725 true
8726 } else if seat_beats(incumbent, cost) {
8727 false
8728 } else {
8729 pair_tags_less(i, j, bi, bj)
8730 }
8731 }
8732 };
8733 if better {
8734 best_pair = Some((i, j, cost, first_drives));
8735 }
8736 }
8737 let (pi, pj, pair_cost, pair_first_drives) =
8738 best_pair.expect("two operands always have a pair");
8739 let (pair_first, pair_second) = {
8743 let (first, second) = pair_order(pi, pj);
8744 let table_first = match (
8745 matches!(nodes[first].as_plan(), PlanNode::Values(_)),
8746 matches!(nodes[second].as_plan(), PlanNode::Values(_)),
8747 ) {
8748 (true, false) => Some(true),
8749 (false, true) => Some(false),
8750 _ => None,
8751 };
8752 if table_first.unwrap_or(pair_first_drives) {
8753 (first, second)
8754 } else {
8755 (second, first)
8756 }
8757 };
8758 let pair_other = if pi == min_idx {
8761 Some(pj)
8762 } else if pj == min_idx {
8763 Some(pi)
8764 } else {
8765 None
8766 };
8767 let pair_is_run_a_first = pair_other.is_some_and(|other| {
8774 pair_start_matches_seed_start(
8775 pair_first,
8776 min_idx,
8777 first_candidate_a.as_deref(),
8778 tags[other].as_str(),
8779 )
8780 });
8781 let (plan_b, total_b) = if pair_is_run_a_first {
8782 (plan_a.clone(), total_a)
8783 } else {
8784 let mut pair_remaining = Vec::with_capacity(nodes.len().saturating_sub(2));
8785 for (idx, node) in nodes.iter().enumerate() {
8786 if idx != pi && idx != pj {
8787 pair_remaining.push(node.clone());
8788 }
8789 }
8790 let pair_join = join_nodes(
8791 nodes[pair_first].as_plan().clone(),
8792 nodes[pair_second].as_plan().clone(),
8793 profile,
8794 );
8795 let (plan, mut total, _) =
8796 associate_from_seed(pair_join, pair_remaining, profile, ctx, true);
8797 total.rows = total.rows.saturating_add(pair_cost.rows);
8798 total.seeks = total.seeks.saturating_add(pair_cost.seeks);
8799 (plan, total)
8800 };
8801 if seat_beats(total_b, total_a) {
8811 plan_b
8812 } else if seat_beats(total_a, total_b) {
8813 plan_a
8814 } else {
8815 plan_b
8817 }
8818}
8819
8820fn values_drives_over(acc: &PlanNode, candidate: &PlanNode) -> bool {
8826 matches!(candidate, PlanNode::Values(_)) && !matches!(acc, PlanNode::Values(_))
8827}
8828
8829fn pick_attachment(
8842 acc: &PlanNode,
8843 remaining: &[JoinableSpineNode],
8844 profile: Option<&StatsProfile>,
8845 ctx: Option<&crate::context::QueryContext>,
8846 seat_by_totals: bool,
8847) -> (usize, u64, SeatCost) {
8848 let acc_out = acc.output_vars();
8849 let mut priced: Vec<(usize, u64, SeatCost)> = Vec::with_capacity(remaining.len());
8850 for (idx, candidate) in remaining.iter().enumerate() {
8851 let keys = hash_keys_for(&acc_out, &candidate.as_plan().output_vars());
8852 let produced = finalize_inner_join_meta(acc, candidate.as_plan(), &keys, profile).1;
8853 let acc_drives = seat_cost_total(profile, acc, candidate.as_plan(), &keys, ctx, None);
8854 let candidate_drives = seat_cost_total(profile, candidate.as_plan(), acc, &keys, ctx, None);
8855 let cost = if seat_beats(candidate_drives, acc_drives) {
8856 candidate_drives
8857 } else {
8858 acc_drives
8859 };
8860 priced.push((idx, produced, cost));
8861 }
8862 if let Some(ctx) = ctx
8865 && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
8866 {
8867 let entries = priced
8868 .iter()
8869 .map(|(idx, produced, cost)| {
8870 format!(
8871 "#{} {} produced={} seat={}:{}s",
8872 idx,
8873 crate::explain::plan_node_tag(remaining[*idx].as_plan()),
8874 produced,
8875 cost.rows,
8876 cost.seeks,
8877 )
8878 })
8879 .collect::<Vec<_>>()
8880 .join(" | ");
8881 ctx.log(
8882 crate::context::LogLevel::Debug,
8883 &format!(
8884 "assoc-prices: acc={} candidates=[{entries}]",
8885 crate::explain::plan_node_tag(acc),
8886 ),
8887 );
8888 }
8889 let produced_pick = priced
8890 .iter()
8891 .min_by_key(|(_, produced, _)| *produced)
8892 .expect("remaining is non-empty");
8893 let bar = produced_pick.1;
8894 let guard = bar.saturating_mul(SEAT_ASSOC_EXPLOSION_GUARD);
8895 let mut cost_pick: Option<&(usize, u64, SeatCost)> = None;
8896 let mut eligible = 0usize;
8897 for entry in &priced {
8898 if entry.1 > guard {
8899 continue;
8900 }
8901 eligible += 1;
8902 if cost_pick.is_none_or(|incumbent| seat_beats(entry.2, incumbent.2)) {
8903 cost_pick = Some(entry);
8904 }
8905 }
8906 let cost_pick = cost_pick.expect("the produced-bar candidate always clears its own guard");
8907 let pick = if seat_by_totals {
8908 cost_pick
8909 } else {
8910 produced_pick
8911 };
8912 if cost_pick.0 != produced_pick.0
8913 && let Some(ctx) = ctx
8914 && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
8915 {
8916 ctx.log(
8917 crate::context::LogLevel::Debug,
8918 &format!(
8919 "{}: applied=idx{} produced_only=idx{} candidates={} \
8920 eligible={} produced_bar={} pick(produced={} seat={}:{}) \
8921 produced_pick(produced={} seat={}:{})",
8922 if seat_by_totals {
8923 "join-seat-assoc"
8924 } else {
8925 "join-seat-assoc-shadow"
8926 },
8927 cost_pick.0,
8928 produced_pick.0,
8929 priced.len(),
8930 eligible,
8931 bar,
8932 cost_pick.1,
8933 cost_pick.2.rows,
8934 cost_pick.2.seeks,
8935 produced_pick.1,
8936 produced_pick.2.rows,
8937 produced_pick.2.seeks,
8938 ),
8939 );
8940 }
8941 (pick.0, pick.1, pick.2)
8942}
8943
8944fn associate_from_seed(
8950 mut acc: PlanNode,
8951 mut remaining: Vec<JoinableSpineNode>,
8952 profile: Option<&StatsProfile>,
8953 ctx: Option<&crate::context::QueryContext>,
8954 seat_by_totals: bool,
8955) -> (PlanNode, SeatCost, Option<String>) {
8956 remaining.sort_by(|a, b| {
8957 crate::explain::plan_node_tag(a.as_plan()).cmp(&crate::explain::plan_node_tag(b.as_plan()))
8958 });
8959 let mut total = SeatCost { rows: 0, seeks: 0 };
8960 let mut first_candidate: Option<String> = None;
8961 while !remaining.is_empty() {
8962 let (pick_idx, _pick_produced, pick_cost) =
8963 pick_attachment(&acc, &remaining, profile, ctx, seat_by_totals);
8964 let candidate = remaining.remove(pick_idx);
8965 if first_candidate.is_none() {
8966 first_candidate = Some(crate::explain::plan_node_tag(candidate.as_plan()));
8967 }
8968 total.rows = total.rows.saturating_add(pick_cost.rows);
8969 total.seeks = total.seeks.saturating_add(pick_cost.seeks);
8970 let values_drives = values_drives_over(&acc, candidate.as_plan());
8974 let candidate = candidate.into_plan();
8975 acc = if values_drives {
8976 join_nodes(candidate, acc, profile)
8977 } else {
8978 join_nodes(acc, candidate, profile)
8979 };
8980 }
8981 (acc, total, first_candidate)
8982}
8983
8984fn custom_cluster_pool_eligible(op: &CustomOp) -> bool {
8999 op.cost.is_some() && op.pinned.is_empty()
9000}
9001
9002fn join_spine_has_frozen_custom_cluster(node: &PlanNode) -> bool {
9011 match node {
9012 PlanNode::Join { left, right, .. } => {
9013 join_spine_has_frozen_custom_cluster(left)
9014 || join_spine_has_frozen_custom_cluster(right)
9015 }
9016 PlanNode::CustomNode(op) => !custom_cluster_pool_eligible(op),
9017 _ => false,
9018 }
9019}
9020
9021#[derive(Debug, Clone)]
9035enum JoinableSpineNode {
9036 Bare(PlanNode),
9037 TransparentJoin(PlanNode),
9038 Opaque(PlanNode),
9039}
9040
9041impl JoinableSpineNode {
9042 fn as_plan(&self) -> &PlanNode {
9043 match self {
9044 Self::Bare(node) | Self::TransparentJoin(node) | Self::Opaque(node) => node,
9045 }
9046 }
9047
9048 fn into_plan(self) -> PlanNode {
9049 match self {
9050 Self::Bare(node) | Self::TransparentJoin(node) | Self::Opaque(node) => node,
9051 }
9052 }
9053
9054 fn is_unit(&self) -> bool {
9055 matches!(self.as_plan(), PlanNode::Unit)
9056 }
9057}
9058
9059fn is_custom_cluster_pair(left: &PlanNode, right: &PlanNode) -> bool {
9062 matches!(left, PlanNode::CustomNode(_)) || matches!(right, PlanNode::CustomNode(_))
9063}
9064
9065fn is_values_join(node: &PlanNode) -> bool {
9067 matches!(
9068 node,
9069 PlanNode::Join { left, right, .. }
9070 if matches!(**left, PlanNode::Values(_)) || matches!(**right, PlanNode::Values(_))
9071 )
9072}
9073
9074fn is_transparent_pair(left: &PlanNode, right: &PlanNode) -> bool {
9081 matches!(left, PlanNode::Values(_))
9082 && !matches!(
9083 right,
9084 PlanNode::Values(_) | PlanNode::Filter { .. } | PlanNode::SubSelect(_)
9085 )
9086 && !is_values_join(right)
9087 && !flatten_would_dissolve(right)
9088 && !hash_keys_for(&left.output_vars(), &right.output_vars()).is_empty()
9092}
9093
9094fn flatten_would_dissolve(node: &PlanNode) -> bool {
9098 let PlanNode::Join { left, right, .. } = node else {
9099 return false;
9100 };
9101 !is_custom_cluster_pair(left, right) && !is_transparent_pair(left, right)
9102}
9103
9104fn flatten_join_spine(node: PlanNode, out: &mut Vec<JoinableSpineNode>) {
9123 if let PlanNode::Join { left, right, .. } = &node {
9124 if is_custom_cluster_pair(left, right) {
9125 out.push(JoinableSpineNode::Opaque(node));
9126 return;
9127 }
9128 if is_transparent_pair(left, right) {
9129 out.push(JoinableSpineNode::TransparentJoin(node));
9130 return;
9131 }
9132 let PlanNode::Join { left, right, .. } = node else {
9133 unreachable!("the match above established a Join");
9134 };
9135 flatten_join_spine(*left, out);
9136 flatten_join_spine(*right, out);
9137 return;
9138 }
9139 match node {
9140 PlanNode::Filter { .. } | PlanNode::SubSelect(_) => {
9141 out.push(JoinableSpineNode::Opaque(node));
9142 }
9143 other => out.push(JoinableSpineNode::Bare(other)),
9144 }
9145}
9146
9147fn reassociate_operand(
9156 operand: &mut PlanNode,
9157 profile: Option<&StatsProfile>,
9158 ctx: Option<&crate::context::QueryContext>,
9159) {
9160 match operand {
9161 PlanNode::Join { left, right, .. } => {
9162 reassociate_inner_joins(left, profile, ctx);
9163 reassociate_inner_joins(right, profile, ctx);
9164 }
9165 _ => reassociate_inner_joins(operand, profile, ctx),
9166 }
9167}
9168
9169fn reassociate_spine_operand(
9171 operand: &mut JoinableSpineNode,
9172 profile: Option<&StatsProfile>,
9173 ctx: Option<&crate::context::QueryContext>,
9174) {
9175 match operand {
9176 JoinableSpineNode::Bare(node) => reassociate_inner_joins(node, profile, ctx),
9179 JoinableSpineNode::TransparentJoin(node) => {
9181 if let PlanNode::Join { left, right, .. } = node {
9182 let inner = if matches!(**left, PlanNode::Values(_)) {
9183 right.as_mut()
9184 } else {
9185 left.as_mut()
9186 };
9187 reassociate_operand(inner, profile, ctx);
9188 }
9189 }
9190 JoinableSpineNode::Opaque(node) => reassociate_operand(node, profile, ctx),
9191 }
9192}
9193
9194fn reassociate_inner_joins(
9230 node: &mut PlanNode,
9231 profile: Option<&StatsProfile>,
9232 ctx: Option<&crate::context::QueryContext>,
9233) {
9234 match node {
9235 PlanNode::Join { .. } if !join_spine_has_frozen_custom_cluster(node) => {
9236 let taken = std::mem::replace(node, PlanNode::Unit);
9237 let mut operands: Vec<JoinableSpineNode> = Vec::new();
9238 flatten_join_spine(taken, &mut operands);
9239 operands.retain(|operand| !operand.is_unit());
9240 for operand in &mut operands {
9247 reassociate_spine_operand(operand, profile, ctx);
9248 }
9249 *node = match operands.len() {
9250 0 => PlanNode::Unit,
9251 1 => operands.remove(0).into_plan(),
9252 _ => associate_cost_based(operands, profile, ctx),
9253 };
9254 }
9255 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
9256 reassociate_inner_joins(left, profile, ctx);
9257 reassociate_inner_joins(right, profile, ctx);
9258 }
9259 PlanNode::LeftJoin { left, right, .. } => {
9260 reassociate_inner_joins(left, profile, ctx);
9261 reassociate_inner_joins(right, profile, ctx);
9262 }
9263 PlanNode::CustomNode(op) => {
9264 for child in &mut op.children {
9265 reassociate_inner_joins(child, profile, ctx);
9266 }
9267 }
9268 PlanNode::SubSelect(sub) => reassociate_inner_joins(&mut sub.inner, profile, ctx),
9269 PlanNode::Filter { inner, exists, .. } => {
9270 for clause in exists {
9271 reassociate_inner_joins(&mut clause.body, profile, ctx);
9272 }
9273 reassociate_inner_joins(inner, profile, ctx);
9274 }
9275 PlanNode::Extend { inner, .. }
9276 | PlanNode::Slice { inner, .. }
9277 | PlanNode::Distinct { inner, .. }
9278 | PlanNode::Sort { inner, .. }
9279 | PlanNode::Group { inner, .. }
9280 | PlanNode::JoinGraphVar { inner, .. } => reassociate_inner_joins(inner, profile, ctx),
9281 PlanNode::Scan(_)
9282 | PlanNode::Path(_)
9283 | PlanNode::Values(_)
9284 | PlanNode::NamedGraphs { .. }
9285 | PlanNode::NamedGraphExists { .. }
9286 | PlanNode::DomainCounts { .. }
9287 | PlanNode::HeadCounts { .. }
9288 | PlanNode::PatternCount { .. }
9289 | PlanNode::Unit => {}
9290 }
9291}
9292
9293fn lower_leaf(
9294 leaf: FlatLeaf,
9295 profile: Option<&StatsProfile>,
9296 incoming: &IncomingBound,
9297 ctx: &QueryContext,
9298 scope: &GraphScope,
9299 default_empty: bool,
9300) -> Result<PlanNode, ComputeError> {
9301 if default_empty
9305 && matches!(
9306 leaf,
9307 FlatLeaf::Triple(_) | FlatLeaf::FilteredTriple { .. } | FlatLeaf::Path { .. }
9308 )
9309 {
9310 return Ok(empty_pipeline_values(std::slice::from_ref(&leaf), scope));
9311 }
9312 match leaf {
9313 FlatLeaf::Triple(pattern) => Ok(PlanNode::Scan(plan_scan_op(
9314 &pattern, profile, incoming, ctx, scope,
9315 )?)),
9316 FlatLeaf::FilteredTriple { triple, expression } => {
9317 let scan = PlanNode::Scan(plan_scan_op(&triple, profile, incoming, ctx, scope)?);
9318 let (early, residual) = crate::expr::split_filter(&expression)?;
9319 Ok(PlanNode::Filter {
9320 inner: Box::new(scan),
9321 early,
9322 residual,
9323 exists: Vec::new(),
9324 one_to_one: false,
9325 })
9326 }
9327 FlatLeaf::Path {
9328 subject,
9329 path,
9330 object,
9331 } => lower_path(&subject, &path, &object, profile, incoming, ctx, scope),
9332 FlatLeaf::Values {
9333 variables,
9334 bindings,
9335 } => lower_values(variables, bindings),
9336 }
9337}
9338
9339fn lower_values(
9340 variables: Vec<Variable>,
9341 bindings: Vec<Vec<Option<GroundTerm>>>,
9342) -> Result<PlanNode, ComputeError> {
9343 if is_unit_values(&variables, &bindings) {
9347 return Ok(PlanNode::Unit);
9348 }
9349 let mut strings = Vec::new();
9350 let mut blobs = Vec::new();
9351 let mut rows = Vec::with_capacity(bindings.len());
9352 for binding in bindings {
9353 if binding.len() != variables.len() {
9354 return Err(ComputeError::UnsupportedSparql(
9355 "VALUES row width does not match the variable list".into(),
9356 ));
9357 }
9358 let mut row = Vec::with_capacity(binding.len());
9359 for cell in binding {
9360 match cell {
9361 None => row.push(None),
9362 Some(ground) => {
9363 let term = ground_term_to_term(ground)?;
9364 let (encoded, (cell_strings, cell_blobs)) =
9372 crate::query::caches::mint_const_entries(&term);
9373 strings.extend(cell_strings);
9374 blobs.extend(cell_blobs);
9375 row.push(Some(encoded));
9376 }
9377 }
9378 }
9379 rows.push(row);
9380 }
9381 Ok(PlanNode::Values(ValuesOp {
9382 variables,
9383 rows,
9384 strings,
9385 blobs,
9386 }))
9387}
9388
9389fn is_unit_values(variables: &[Variable], bindings: &[Vec<Option<GroundTerm>>]) -> bool {
9390 variables.is_empty() && bindings.len() == 1 && bindings[0].iter().all(Option::is_none)
9391}
9392
9393fn ground_term_to_term(ground: GroundTerm) -> Result<Term, ComputeError> {
9394 match ground {
9395 GroundTerm::NamedNode(node) => Ok(Term::NamedNode(node)),
9396 GroundTerm::Literal(literal) => Ok(Term::Literal(literal)),
9397 }
9398}
9399
9400fn join_nodes(left: PlanNode, right: PlanNode, profile: Option<&StatsProfile>) -> PlanNode {
9401 let (left, right) = replace_named_graphs_with_exists(left, right);
9409 let left_out = left.output_vars();
9410 let right_out = right.output_vars();
9411 let mut hash_keys = hash_keys_for(&left_out, &right_out);
9412 let (left, mut right) = maybe_swap_scan_union(left, right, &hash_keys, profile);
9413 if zero_row_arm(&left)
9419 || zero_row_arm(&right)
9420 || (!hash_keys.is_empty() && conflicting_ground_keys(&left, &right, &hash_keys).is_some())
9421 {
9422 return provably_empty_join(&left, &right);
9423 }
9424 let (strategy, mut produced_row_count_estimate, mut own_push_removed_row_count_estimate) =
9425 finalize_inner_join_meta(&left, &right, &hash_keys, profile);
9426 let mut probe_key_domains = stamp_probe_key_domains(profile, &right, &hash_keys);
9427 let mut probe_key_overlap_milli = stamp_probe_key_overlaps(profile, &left, &right, &hash_keys);
9428 reorder_hash_keys_by_probe_return(
9435 &mut hash_keys,
9436 &mut probe_key_domains,
9437 &mut probe_key_overlap_milli,
9438 &left,
9439 &right,
9440 profile,
9441 );
9442 if strategy == JoinStrategy::Broadcast && !hash_keys.is_empty() {
9447 ground_and_recost_broadcasted_arm(&left, &mut right, &hash_keys, profile);
9448 let (_, produced, own_push_removed) =
9454 finalize_inner_join_meta(&left, &right, &hash_keys, profile);
9455 produced_row_count_estimate = produced;
9456 own_push_removed_row_count_estimate = own_push_removed;
9457 }
9458 let (mut left, mut right) = (left, right);
9459 if !hash_keys.is_empty() {
9460 compose_graph_from_sibling(&left, &mut right, &hash_keys, profile, true);
9461 compose_graph_from_sibling(&right, &mut left, &hash_keys, profile, true);
9462 }
9463 let rhs_hostable_keys = stamp_rhs_hostable_keys(&right);
9468 PlanNode::Join {
9469 left: Box::new(left),
9470 right: Box::new(right),
9471 hash_keys,
9472 probe_key_domains,
9473 probe_key_overlap_milli,
9474 rhs_hostable_keys,
9475 meta: JoinMeta {
9476 semi_gate: None,
9477 star_arms: None,
9478 strategy,
9479 produced_row_count_estimate,
9480 own_push_removed_row_count_estimate,
9487 },
9488 }
9489}
9490
9491fn replace_named_graphs_with_exists(left: PlanNode, right: PlanNode) -> (PlanNode, PlanNode) {
9495 if let PlanNode::NamedGraphs { variable, .. } = &left
9496 && let Some(term) = unique_ground_term(&right, variable)
9497 {
9498 return (PlanNode::NamedGraphExists { graph: term }, right);
9499 }
9500 if let PlanNode::NamedGraphs { variable, .. } = &right
9501 && let Some(term) = unique_ground_term(&left, variable)
9502 {
9503 return (left, PlanNode::NamedGraphExists { graph: term });
9504 }
9505 (left, right)
9506}
9507
9508fn left_join_unmatched_rows(
9517 left_rows: u64,
9518 left: &PlanNode,
9519 right: &PlanNode,
9520 hash_keys: &[Variable],
9521 profile: Option<&StatsProfile>,
9522) -> u64 {
9523 let mut numer: u128 = 1;
9524 let mut denom: u128 = 1;
9525 for key in hash_keys {
9526 let (Some(dom_l), Some(dom_r)) = (
9527 join_key_domain_for_node(profile, left, key),
9528 join_key_domain_for_node(profile, right, key),
9529 ) else {
9530 continue;
9531 };
9532 if dom_r >= dom_l {
9533 return 0;
9536 }
9537 numer = numer.saturating_mul(u128::from(dom_l - dom_r));
9538 denom = denom.saturating_mul(u128::from(dom_l));
9539 if numer == 0 || denom == u128::MAX {
9540 return 0;
9541 }
9542 }
9543 let left_rows = u128::from(left_rows.max(1));
9544 u64::try_from(left_rows * numer / denom).unwrap_or(u64::MAX)
9545}
9546
9547fn estimate_left_join_rows_product(
9556 left_rows: u64,
9557 left: &PlanNode,
9558 right: &PlanNode,
9559 hash_keys: &[Variable],
9560 right_rows: u64,
9561 profile: Option<&StatsProfile>,
9562) -> u64 {
9563 if hash_keys.is_empty() {
9564 return left_rows.saturating_mul(right_rows.max(1));
9565 }
9566 let probe_key_domains = hash_keys
9567 .iter()
9568 .map(|key| {
9569 (
9570 join_key_domain_for_node(profile, left, key),
9571 join_key_domain_for_node(profile, right, key),
9572 )
9573 })
9574 .collect::<Vec<_>>();
9575 let matched = estimate_join_rows_multi(left_rows, right_rows, &probe_key_domains);
9576 left_join_unmatched_rows(left_rows, left, right, hash_keys, profile)
9577 .saturating_add(matched)
9578 .max(left_rows)
9579}
9580
9581fn estimate_left_join_rows(
9589 left_rows: u64,
9590 left: &PlanNode,
9591 right: &PlanNode,
9592 hash_keys: &[Variable],
9593 profile: Option<&StatsProfile>,
9594) -> u64 {
9595 let left_rows = left_rows.max(1);
9596 let right_rows = path_probe_row_bound(
9597 right,
9598 left,
9599 hash_keys,
9600 right.produced_row_count_estimate(),
9601 profile,
9602 );
9603 estimate_left_join_rows_product(left_rows, left, right, hash_keys, right_rows, profile)
9604}
9605
9606fn estimate_left_join_rows_own_push_removed(
9620 left_rows: u64,
9621 left: &PlanNode,
9622 right: &PlanNode,
9623 hash_keys: &[Variable],
9624 profile: Option<&StatsProfile>,
9625) -> u64 {
9626 let left_rows = left_rows.max(1);
9627 let right_rows =
9628 path_arm_own_push_removed_price(right, right.produced_row_count_estimate(), profile);
9629 estimate_left_join_rows_product(left_rows, left, right, hash_keys, right_rows, profile)
9630}
9631
9632fn estimate_left_join_rows_pushed(
9637 left_rows: u64,
9638 left: &PlanNode,
9639 right: &PlanNode,
9640 hash_keys: &[Variable],
9641 profile: Option<&StatsProfile>,
9642) -> u64 {
9643 let left_rows = left_rows.max(1);
9644 let right_rows = path_probe_row_bound(
9649 right,
9650 left,
9651 hash_keys,
9652 right.produced_row_count_estimate(),
9653 profile,
9654 );
9655 if hash_keys.is_empty() {
9656 return left_rows.saturating_mul(right_rows.max(1));
9657 }
9658 left_join_unmatched_rows(left_rows, left, right, hash_keys, profile)
9659 .saturating_add(right_rows)
9660 .max(left_rows)
9661}
9662
9663fn stamp_left_join_meta(
9671 left_rows: u64,
9672 left: &PlanNode,
9673 right: &PlanNode,
9674 hash_keys: &[Variable],
9675 profile: Option<&StatsProfile>,
9676) -> LeftJoinMeta {
9677 let produced = estimate_left_join_rows(left_rows, left, right, hash_keys, profile);
9678 let own_push_removed =
9679 estimate_left_join_rows_own_push_removed(left_rows, left, right, hash_keys, profile);
9680 LeftJoinMeta {
9681 produced_row_count_estimate: produced,
9682 own_push_removed_row_count_estimate: own_push_removed,
9683 }
9684}
9685
9686fn path_pushed_val_count(
9719 path: &PathOp,
9720 driver: &PlanNode,
9721 hash_keys: &[Variable],
9722 profile: Option<&StatsProfile>,
9723) -> Option<u64> {
9724 hash_keys
9725 .iter()
9726 .filter(|key| path.end_of(key).is_some())
9727 .map(|key| {
9728 join_key_domain_for_node(profile, driver, key)
9729 .map(|d| d.min(driver.produced_row_count_estimate()))
9730 .unwrap_or_else(|| driver.produced_row_count_estimate())
9731 })
9732 .min()
9733 .map(|pushed| pushed.max(1))
9734}
9735
9736fn path_probe_row_bound(
9753 arm: &PlanNode,
9754 other: &PlanNode,
9755 hash_keys: &[Variable],
9756 rows: u64,
9757 profile: Option<&StatsProfile>,
9758) -> u64 {
9759 let Some(path) = arm.as_dependent_path() else {
9760 return rows;
9761 };
9762 let Some(pushed) = path_pushed_val_count(path, other, hash_keys, profile) else {
9763 return rows;
9764 };
9765 rows.min(pushed)
9766}
9767
9768fn path_arm_own_push_removed_price(
9780 arm: &PlanNode,
9781 rows: u64,
9782 profile: Option<&StatsProfile>,
9783) -> u64 {
9784 match arm.as_dependent_path() {
9785 Some(path) => estimate_path_size(
9786 path.subject_term.is_some(),
9787 &path.path,
9788 path.object_term.is_some(),
9789 ),
9790 None => match arm.as_scan() {
9791 Some(scan) if scan.broadcasted.is_some() => estimate_unclamped_scan_rows(profile, scan),
9802 _ => rows,
9803 },
9804 }
9805}
9806
9807fn scan_key_vocabulary(
9827 node: &PlanNode,
9828 key: &Variable,
9829) -> Option<(EncodedTriplePattern, JoinKeySlot)> {
9830 let scan = node.as_scan()?;
9831 let slot = if scan.subject.as_ref() == Some(key) {
9832 JoinKeySlot::Subject
9833 } else if scan.object.as_ref() == Some(key) {
9834 JoinKeySlot::Object
9835 } else {
9836 return None;
9837 };
9838 let ground = match slot {
9839 JoinKeySlot::Subject => scan.pattern.subject.is_some(),
9840 JoinKeySlot::Object => scan.pattern.object.is_some(),
9841 };
9842 if ground {
9843 return None;
9844 }
9845 Some((scan.pattern.clone(), slot))
9846}
9847
9848fn resolve_key_overlap_milli(
9855 profile: Option<&StatsProfile>,
9856 driver: &PlanNode,
9857 probe: &PlanNode,
9858 key: &Variable,
9859) -> u64 {
9860 let Some(profile) = profile.filter(|p| !p.is_empty()) else {
9861 return VOCABULARY_OVERLAP_FULL_MILLI;
9862 };
9863 let Some((driver_pattern, driver_slot)) = scan_key_vocabulary(driver, key) else {
9864 return VOCABULARY_OVERLAP_FULL_MILLI;
9865 };
9866 let Some((probe_pattern, probe_slot)) = scan_key_vocabulary(probe, key) else {
9867 return VOCABULARY_OVERLAP_FULL_MILLI;
9868 };
9869 estimate_vocabulary_overlap(
9870 profile,
9871 &driver_pattern,
9872 driver_slot,
9873 &probe_pattern,
9874 probe_slot,
9875 )
9876 .unwrap_or(VOCABULARY_OVERLAP_FULL_MILLI)
9877}
9878
9879fn stamp_probe_key_overlaps(
9884 profile: Option<&StatsProfile>,
9885 driver: &PlanNode,
9886 probe: &PlanNode,
9887 hash_keys: &[Variable],
9888) -> Vec<u64> {
9889 hash_keys
9890 .iter()
9891 .map(|key| resolve_key_overlap_milli(profile, driver, probe, key))
9892 .collect()
9893}
9894fn stamp_probe_key_domains(
9895 profile: Option<&StatsProfile>,
9896 probe: &PlanNode,
9897 hash_keys: &[Variable],
9898) -> Vec<u64> {
9899 hash_keys
9900 .iter()
9901 .map(|key| join_key_domain_for_node(profile, probe, key).unwrap_or(0))
9902 .collect()
9903}
9904
9905fn finalize_inner_join_meta(
9906 left: &PlanNode,
9907 right: &PlanNode,
9908 hash_keys: &[Variable],
9909 profile: Option<&StatsProfile>,
9910) -> (JoinStrategy, u64, u64) {
9911 let left_rows = left.produced_row_count_estimate();
9912 let right_rows = path_probe_row_bound(
9916 right,
9917 left,
9918 hash_keys,
9919 right.produced_row_count_estimate(),
9920 profile,
9921 );
9922 let right_rows_raw =
9929 path_arm_own_push_removed_price(right, right.produced_row_count_estimate(), profile);
9930 let left_rows_raw = left_rows;
9931 let left_domain = join_key_domain_for_allow_list(profile, left, right, hash_keys, left_rows);
9932 let right_domain = join_key_domain_for_allow_list(profile, right, left, hash_keys, right_rows);
9933 let mut strategy = JoinStrategy::from_cardinalities_and_domains(
9934 left_rows,
9935 right_rows,
9936 left_domain,
9937 right_domain,
9938 );
9939 if let Some(path) = right.as_dependent_path()
9942 && !hash_keys.is_empty()
9943 && hash_keys.iter().any(|key| path.end_of(key).is_some())
9944 {
9945 strategy = JoinStrategy::Broadcast;
9946 }
9947 let (produced_row_count_estimate, own_push_removed_row_count_estimate) = if hash_keys.is_empty()
9957 {
9958 (
9959 left_rows.saturating_mul(right_rows).max(1),
9960 left_rows_raw.saturating_mul(right_rows_raw).max(1),
9961 )
9962 } else {
9963 let probe_key_domains = hash_keys
9964 .iter()
9965 .map(|key| {
9966 (
9967 join_key_domain_for_node(profile, left, key),
9968 join_key_domain_for_node(profile, right, key),
9969 )
9970 })
9971 .collect::<Vec<_>>();
9972 (
9973 estimate_join_rows_multi(left_rows, right_rows, &probe_key_domains),
9974 estimate_join_rows_multi(left_rows_raw, right_rows_raw, &probe_key_domains),
9975 )
9976 };
9977 (
9978 strategy,
9979 produced_row_count_estimate,
9980 own_push_removed_row_count_estimate,
9981 )
9982}
9983
9984fn maybe_swap_scan_union(
9990 mut left: PlanNode,
9991 mut right: PlanNode,
9992 hash_keys: &[Variable],
9993 profile: Option<&StatsProfile>,
9994) -> (PlanNode, PlanNode) {
9995 if hash_keys.is_empty() {
9996 return (left, right);
9997 }
9998 let scan_union = left.as_broadcast_scan().is_some() && right.as_union().is_some();
9999 let union_scan = left.as_union().is_some() && right.as_broadcast_scan().is_some();
10000 if !scan_union && !union_scan {
10001 return (left, right);
10002 }
10003 let left_rows = left.produced_row_count_estimate();
10004 let right_rows = right.produced_row_count_estimate();
10005 let left_domain = join_key_domain_for_allow_list(profile, &left, &right, hash_keys, left_rows);
10006 let right_domain =
10007 join_key_domain_for_allow_list(profile, &right, &left, hash_keys, right_rows);
10008 let left_cost = driver_cost(left_rows, left_domain);
10009 let right_cost = driver_cost(right_rows, right_domain);
10010 if right_cost < left_cost {
10011 std::mem::swap(&mut left, &mut right);
10012 }
10013 (left, right)
10014}
10015
10016fn driver_cost(rows: u64, domain: Option<u64>) -> u64 {
10017 match domain {
10018 Some(d) => d.min(rows).max(1),
10019 None => rows.max(1),
10020 }
10021}
10022
10023fn driver_whole_read_rows(
10046 arm: &PlanNode,
10047 hash_keys: &[Variable],
10048 profile: Option<&StatsProfile>,
10049) -> u64 {
10050 match arm {
10051 PlanNode::Scan(scan) => match &scan.broadcasted {
10052 None => scan.produced_row_count_estimate,
10053 Some((variable, _)) if hash_keys.contains(variable) => {
10054 estimate_unclamped_scan_rows(profile, scan)
10055 }
10056 Some(_) => scan.produced_row_count_estimate,
10057 },
10058 other => other.produced_row_count_estimate(),
10059 }
10060}
10061
10062fn seat_driver_work_rows(
10076 driver: &PlanNode,
10077 hash_keys: &[Variable],
10078 profile: Option<&StatsProfile>,
10079) -> u64 {
10080 match driver {
10081 PlanNode::CustomNode(op) => op
10082 .sweep_cost()
10083 .unwrap_or_else(|| driver_whole_read_rows(driver, hash_keys, profile)),
10084 _ => driver_whole_read_rows(driver, hash_keys, profile),
10085 }
10086}
10087
10088#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10095pub(crate) struct SeatCost {
10096 rows: u64,
10097 seeks: u64,
10098}
10099
10100thread_local! {
10110 static SEAT_CALLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
10111 static WALK_VISITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
10112}
10113
10114fn seat_calls_bump() {
10115 SEAT_CALLS.with(|counter| counter.set(counter.get() + 1));
10116}
10117
10118fn walk_visits_bump() {
10119 WALK_VISITS.with(|counter| counter.set(counter.get() + 1));
10120}
10121
10122thread_local! {
10123 static PLANNER_PARSE_US: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
10130}
10131
10132const SEAT_NOISE_BAND_PCT: u64 = 2;
10137
10138const SEAT_ASSOC_EXPLOSION_GUARD: u64 = 4;
10150
10151fn seat_beats(challenger: SeatCost, incumbent: SeatCost) -> bool {
10152 if challenger.rows > incumbent.rows {
10153 return false;
10154 }
10155 let band = incumbent.rows.saturating_mul(SEAT_NOISE_BAND_PCT) / 100;
10156 if challenger.rows.saturating_add(band) < incumbent.rows {
10157 return true;
10158 }
10159 challenger.seeks < incumbent.seeks
10160}
10161
10162pub(crate) fn clustered_page_distinct(driver_rows: u64, domain: u64, page_rows: u64) -> u64 {
10173 if driver_rows == 0 {
10174 return 0;
10175 }
10176 let d = domain.max(1);
10177 let dense = page_rows.saturating_mul(d) / driver_rows;
10178 dense.min(page_rows).min(driver_rows).clamp(1, d)
10179}
10180
10181fn mixed_page_distinct(domain: u64, page_rows: u64, driver_rows: u64) -> u64 {
10188 let d = domain.max(1) as f64;
10189 let p = page_rows.max(1) as f64;
10190 let mixed = d * (1.0 - (-(p / d)).exp());
10191 ((mixed.ceil() as u64)
10192 .clamp(1, page_rows.max(1))
10193 .min(driver_rows.max(1)))
10194 .min(domain.max(1))
10195}
10196
10197fn seat_page_rows(
10204 driver: &PlanNode,
10205 probe: &PlanNode,
10206 ctx: Option<&crate::context::QueryContext>,
10207) -> u64 {
10208 match driver {
10209 PlanNode::Scan(_) => {
10210 let base = ctx.map_or(PUSHDOWN_TERMS_LIMIT as usize, |c| {
10211 c.join_chunk_rows(1, PUSHDOWN_TERMS_LIMIT as usize)
10212 });
10213 crate::join_chunks::driver_chunk_rows(base)
10214 }
10215 _ => {
10216 let width =
10217 crate::join_chunks::join_page_width(driver.output_vars().all().as_slice(), probe)
10218 .max(1);
10219 ctx.map_or(PUSHDOWN_TERMS_LIMIT, |c| {
10220 c.join_chunk_rows(width, PUSHDOWN_TERMS_LIMIT as usize) as u64
10221 })
10222 }
10223 }
10224}
10225
10226fn first_broadcast_key(
10262 keys: &[(bool, u64, u64, u64)],
10263 coverage_drop_allowed: bool,
10264) -> Option<(u64, u64, u64)> {
10265 keys.iter()
10266 .find(|&&(covered, ..)| !(covered && coverage_drop_allowed))
10267 .map(|&(_, page_val_count, probe_domain, overlap_milli)| {
10268 (page_val_count, probe_domain, overlap_milli)
10269 })
10270}
10271
10272fn probe_broadcast_price(
10273 whole_read_rows: u64,
10274 keys: &[(bool, u64, u64, u64)],
10275 coverage_drop_allowed: bool,
10276) -> (u64, u64) {
10277 let Some((page_val_count, probe_domain, overlap_milli)) =
10280 first_broadcast_key(keys, coverage_drop_allowed)
10281 else {
10282 return (0, whole_read_rows);
10290 };
10291 let matched = if probe_domain == 0 {
10312 whole_read_rows
10313 } else {
10314 let scaled_list = u128::from(page_val_count) * u128::from(overlap_milli);
10318 let denominator = u128::from(probe_domain) * u128::from(VOCABULARY_OVERLAP_FULL_MILLI);
10319 let quotient = (u128::from(whole_read_rows) * scaled_list.min(denominator)) / denominator;
10324 u64::try_from(quotient).unwrap_or(whole_read_rows)
10325 };
10326 (page_val_count, matched)
10327}
10328
10329pub(crate) fn fetch_once_stampable(scan: &ScanOp) -> bool {
10343 scan.domain_scan.is_none()
10344 && scan.head_scan.is_none()
10345 && (scan.domain_counts.is_none() || bound_constraint_count_scan(scan))
10346 && scan.head_scan_counts.is_none()
10347}
10348
10349pub(crate) fn bound_constraint_count_scan(scan: &ScanOp) -> bool {
10365 scan.domain_counts.is_some_and(|kind| {
10366 scan.domain_count_mode() == waratah_storage::DomainCountMode::Rows
10367 && count_scan_covers_one_predicate(scan, kind)
10368 })
10369}
10370
10371pub(crate) fn count_scan_covers_one_predicate(scan: &ScanOp, kind: DomainScanKind) -> bool {
10374 kind.constraint_slot() == PatternSlot::Predicate && scan.pattern.predicate.is_some()
10375}
10376#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10409pub(crate) enum FetchOnceVerdict {
10410 FetchOnce,
10411 PerPage,
10412}
10413
10414#[allow(clippy::too_many_arguments)]
10415fn fetch_once_verdict(
10416 pages: u64,
10417 seeks_per_page: u64,
10418 matched_per_page: u64,
10419 whole_read_rows: u64,
10420 whole_read_rows_known: bool,
10421 driver_domains_known: bool,
10422 matched_is_bound: bool,
10423 seek_equiv_milli: u128,
10424 matched_row_equiv_milli: u128,
10425 matched_bound_equiv_milli: u128,
10426 seek_concurrency_milli: u128,
10427 margin_milli: u128,
10428) -> FetchOnceVerdict {
10429 if whole_read_rows == 0 || pages == 0 {
10432 return FetchOnceVerdict::PerPage;
10433 }
10434 if !driver_domains_known {
10444 return FetchOnceVerdict::PerPage;
10445 }
10446 if !whole_read_rows_known {
10453 return FetchOnceVerdict::PerPage;
10454 }
10455 let price = fetch_once_price_milli(
10460 pages,
10461 seeks_per_page,
10462 matched_per_page,
10463 matched_is_bound,
10464 seek_equiv_milli,
10465 matched_row_equiv_milli,
10466 matched_bound_equiv_milli,
10467 seek_concurrency_milli,
10468 );
10469 let threshold = margin_milli.saturating_mul(whole_read_rows as u128);
10470 if price >= threshold {
10471 FetchOnceVerdict::FetchOnce
10472 } else {
10473 FetchOnceVerdict::PerPage
10474 }
10475}
10476
10477#[allow(clippy::too_many_arguments)]
10502fn fetch_once_price_milli(
10503 pages: u64,
10504 seeks_per_page: u64,
10505 matched_per_page: u64,
10506 matched_is_bound: bool,
10507 seek_equiv_milli: u128,
10508 matched_row_equiv_milli: u128,
10509 matched_bound_equiv_milli: u128,
10510 seek_concurrency_milli: u128,
10511) -> u128 {
10512 let matched_equiv_milli = if matched_is_bound {
10513 matched_bound_equiv_milli
10514 } else {
10515 matched_row_equiv_milli
10516 };
10517 (pages as u128).saturating_mul(
10518 (seeks_per_page as u128)
10519 .saturating_mul(seek_equiv_milli)
10520 .saturating_mul(1000)
10521 .saturating_div(seek_concurrency_milli.max(1))
10522 .saturating_add((matched_per_page as u128).saturating_mul(matched_equiv_milli)),
10523 )
10524}
10525
10526#[allow(clippy::too_many_arguments)]
10530fn fetch_once_verdict_now(
10531 pages: u64,
10532 seeks_per_page: u64,
10533 matched_per_page: u64,
10534 whole_read_rows: u64,
10535 whole_read_rows_known: bool,
10536 driver_domains_known: bool,
10537 matched_is_bound: bool,
10538 seek_concurrency_milli: u128,
10539) -> FetchOnceVerdict {
10540 fetch_once_verdict(
10541 pages,
10542 seeks_per_page,
10543 matched_per_page,
10544 whole_read_rows,
10545 whole_read_rows_known,
10546 driver_domains_known,
10547 matched_is_bound,
10548 crate::query::tunables::fetch_once_seek_equiv_milli(),
10549 crate::query::tunables::fetch_once_matched_row_equiv_milli(),
10550 crate::query::tunables::fetch_once_matched_bound_equiv_milli(),
10551 seek_concurrency_milli,
10552 crate::query::tunables::fetch_once_margin_milli(),
10553 )
10554}
10555
10556fn probe_seek_concurrency_milli(
10612 batched: bool,
10613 pages: u64,
10614 seeks_per_page: u64,
10615 fetch_concurrency: u64,
10616) -> u128 {
10617 if !batched {
10618 return 1000;
10619 }
10620 if fetch_concurrency < 2 {
10625 return 1000;
10626 }
10627 let total_seeks = pages.saturating_mul(seeks_per_page);
10628 let chunks = total_seeks.div_ceil(waratah_stats::PUSHDOWN_TERMS_LIMIT);
10629 if chunks == 0 {
10635 return 1000;
10636 }
10637 let funded_milli = fetch_concurrency
10646 .saturating_mul(1000)
10647 .min(chunks.saturating_mul(1000));
10648 funded_milli.min(crate::query::tunables::probe_seek_concurrency_realized_milli(funded_milli))
10649 as u128
10650}
10651
10652#[allow(clippy::too_many_arguments)]
10662fn seat_cost_arithmetic(
10663 driver_rows: u64,
10664 whole_read_rows: u64,
10665 probe_memoizable: bool,
10666 pages: u64,
10667 keys: &[(bool, u64, u64, u64)],
10668 coverage_drop_allowed: bool,
10669 probe_stampable: bool,
10670 whole_read_rows_known: bool,
10671 driver_domains_known: bool,
10672 probe_count_walk: bool,
10673 subtree_page: Option<SeatCost>,
10674) -> SeatCost {
10675 if driver_rows == 0 {
10676 return SeatCost { rows: 0, seeks: 0 };
10677 }
10678 if keys.is_empty() {
10679 if let Some(road) = subtree_page {
10686 return SeatCost {
10687 rows: driver_rows.saturating_add(pages.saturating_mul(road.rows)),
10688 seeks: pages.saturating_mul(road.seeks),
10689 };
10690 }
10691 return SeatCost {
10692 rows: driver_rows.saturating_add(whole_read_rows),
10693 seeks: 0,
10694 };
10695 }
10696 if keys.iter().all(|&(covered, _, _, _)| covered) && coverage_drop_allowed {
10697 let extra = u64::from(probe_memoizable) * whole_read_rows;
10708 return SeatCost {
10709 rows: driver_rows
10710 .saturating_add(whole_read_rows)
10711 .saturating_add(extra),
10712 seeks: 0,
10713 };
10714 }
10715 let (seeks_per_page, matched_per_page) = match subtree_page {
10716 Some(page) => (page.seeks, page.rows),
10722 None => probe_broadcast_price(whole_read_rows, keys, coverage_drop_allowed),
10723 };
10724 if probe_count_walk && pages > 1 {
10733 return SeatCost {
10734 rows: driver_rows.saturating_add(whole_read_rows),
10735 seeks: 0,
10736 };
10737 }
10738 let matched_is_bound = subtree_page.is_none()
10759 && first_broadcast_key(keys, coverage_drop_allowed)
10760 .is_some_and(|(_, probe_domain, _)| probe_domain == 0);
10761 if probe_stampable
10762 && fetch_once_verdict_now(
10763 pages,
10764 seeks_per_page,
10765 matched_per_page,
10766 whole_read_rows,
10767 whole_read_rows_known,
10768 driver_domains_known,
10769 matched_is_bound,
10770 1000,
10777 ) == FetchOnceVerdict::FetchOnce
10778 {
10779 return SeatCost {
10780 rows: driver_rows.saturating_add(whole_read_rows),
10781 seeks: 0,
10782 };
10783 }
10784 SeatCost {
10785 rows: driver_rows.saturating_add(pages.saturating_mul(matched_per_page)),
10789 seeks: pages.saturating_mul(seeks_per_page),
10790 }
10791}
10792
10793struct SeatProbeShape {
10823 pages: u64,
10824 keys: Vec<(bool, u64, u64, u64)>,
10829 broadcast_key: Option<Variable>,
10836 coverage_drop_allowed: bool,
10837 driver_domains_known: bool,
10843}
10844
10845fn seat_probe_shape(
10846 profile: Option<&StatsProfile>,
10847 driver: &PlanNode,
10848 probe: &PlanNode,
10849 hash_keys: &[Variable],
10850 ctx: Option<&crate::context::QueryContext>,
10851 driver_row_bound: Option<u64>,
10852) -> SeatProbeShape {
10853 let mut driver_rows = driver_whole_read_rows(driver, hash_keys, profile);
10864 if let Some(bound) = driver_row_bound {
10865 driver_rows = driver_rows.min(bound);
10871 }
10872 let page_rows = seat_page_rows(driver, probe, ctx);
10873 let pages = driver_rows.div_ceil(page_rows.max(1));
10874 let scan_driver = driver.as_scan().is_some();
10875 let probe_rows = probe.produced_row_count_estimate();
10882
10883 let mut keys: Vec<(bool, u64, u64, u64, Option<u128>, Variable)> =
10893 Vec::with_capacity(hash_keys.len());
10894 let mut driver_domains_known = true;
10895 for key in hash_keys {
10896 let driver_domain = join_key_domain_for_node(profile, driver, key);
10897 let probe_domain_opt = join_key_domain_for_node(profile, probe, key);
10898 let probe_domain = probe_domain_opt.unwrap_or(0);
10899 let reorder_cost = if !probe_scan_has_key(probe, key) {
10900 None
10901 } else {
10902 match (driver_domain, probe_domain_opt) {
10903 (Some(driver_domain), probe_domain) => {
10904 Some((driver_domain as u128).saturating_mul(match probe_domain {
10905 Some(domain) => (probe_rows as u128) / domain.max(1) as u128,
10906 None => 1,
10907 }))
10908 }
10909 (None, _) => None,
10910 }
10911 };
10912 let (cover_len, page_val_count) = match driver_domain {
10913 None => {
10920 driver_domains_known = false;
10921 (1, page_rows.min(driver_rows.max(1)))
10922 }
10923 Some(d) => {
10924 let clustered = clustered_page_distinct(driver_rows, d, page_rows);
10925 if scan_driver {
10926 (clustered, clustered)
10927 } else {
10928 let mixed = mixed_page_distinct(d, page_rows, driver_rows);
10929 (clustered.min(mixed), clustered.max(mixed))
10930 }
10931 }
10932 };
10933 let overlap_milli = resolve_key_overlap_milli(profile, driver, probe, key);
10938 let covered = crate::query::pushdown::push_list_covers_domain(
10939 usize::try_from(cover_len).unwrap_or(usize::MAX),
10940 probe_domain,
10941 overlap_milli,
10942 );
10943 keys.push((
10944 covered,
10945 page_val_count,
10946 probe_domain,
10947 overlap_milli,
10948 reorder_cost,
10949 key.clone(),
10950 ));
10951 }
10952 keys.sort_by_key(|&(_, _, _, _, cost, _)| cost.unwrap_or(u128::MAX));
10955
10956 let coverage_drop_allowed =
10959 crate::query::pushdown::source_coverage_drop(driver, probe, page_rows);
10960 let broadcast_key = keys
10968 .iter()
10969 .find(|&&(covered, _, _, _, _, _)| !(covered && coverage_drop_allowed))
10970 .map(|(_, _, _, _, _, key)| key.clone());
10971 let keys: Vec<(bool, u64, u64, u64)> = keys
10972 .into_iter()
10973 .map(|(c, d, p, r, _, _)| (c, d, p, r))
10974 .collect();
10975 SeatProbeShape {
10976 pages,
10977 keys,
10978 broadcast_key,
10979 coverage_drop_allowed,
10980 driver_domains_known,
10981 }
10982}
10983
10984fn probe_side_mirror_road(
11049 profile: Option<&StatsProfile>,
11050 probe: &PlanNode,
11051 hash_keys: &[Variable],
11052 shape_keys: &[(bool, u64, u64, u64)],
11053 coverage_drop_allowed: bool,
11054 containing: Option<&ContainingPush>,
11055) -> Option<SeatCost> {
11056 let scan = probe.as_scan()?;
11057 let push = containing?;
11058 if !probe_scan_has_key(probe, &push.key) {
11059 return None;
11060 }
11061 let ancestor_slot = scan.first_slot_of(&push.key)?;
11062 let whole_read = estimate_unclamped_scan_rows(profile, scan);
11063 let domain = join_key_domain_for_node(profile, probe, &push.key).unwrap_or(0);
11064 let pushed_road = probe_broadcast_price(
11069 whole_read,
11070 &[(
11071 false,
11072 push.pushed_val_count,
11073 domain,
11074 VOCABULARY_OVERLAP_FULL_MILLI,
11075 )],
11076 false,
11077 );
11078 let survivor_slot =
11095 hash_keys
11096 .iter()
11097 .zip(shape_keys)
11098 .find_map(|(key, &(covered, list, _, _))| {
11099 if list == 0 || list > PUSHDOWN_TERMS_LIMIT || (coverage_drop_allowed && covered) {
11100 return None;
11101 }
11102 scan.first_slot_of(key)
11103 });
11104 match survivor_slot {
11105 Some(slot) if slot == ancestor_slot => {
11111 let own_road = probe_broadcast_price(whole_read, shape_keys, coverage_drop_allowed);
11112 ((pushed_road.1, pushed_road.0) < (own_road.1, own_road.0)).then_some(SeatCost {
11114 rows: pushed_road.1,
11115 seeks: pushed_road.0,
11116 })
11117 }
11118 _ => Some(SeatCost {
11123 rows: pushed_road.1,
11124 seeks: pushed_road.0,
11125 }),
11126 }
11127}
11128
11129fn seat_cost_total(
11130 profile: Option<&StatsProfile>,
11131 driver: &PlanNode,
11132 probe: &PlanNode,
11133 hash_keys: &[Variable],
11134 ctx: Option<&crate::context::QueryContext>,
11135 containing: Option<&ContainingPush>,
11136) -> SeatCost {
11137 seat_calls_bump();
11138 let driver_keyed = match (driver, containing) {
11173 (PlanNode::CustomNode(op), Some(push)) if op.variables.contains(&push.key) => {
11174 let pushed_column = op
11175 .variables
11176 .iter()
11177 .position(|variable| variable == &push.key);
11178 op.keyed_cost(push.pushed_val_count, pushed_column)
11179 }
11180 _ => None,
11181 };
11182 let (driver_rows, driver_seeks) = match driver {
11183 PlanNode::Scan(_) | PlanNode::CustomNode(_) if driver_keyed.is_some() => {
11184 (driver_keyed.unwrap(), 0)
11185 }
11186 PlanNode::Scan(_) | PlanNode::CustomNode(_) => {
11187 (seat_driver_work_rows(driver, hash_keys, profile), 0)
11188 }
11189 _ if containing.is_none() => {
11190 let once = driver_once_cost(profile, driver, ctx);
11191 (once.rows, once.seeks)
11192 }
11193 _ => (seat_driver_work_rows(driver, hash_keys, profile), 0),
11194 };
11195 let probe_scan = probe.as_scan().filter(|scan| fetch_once_stampable(scan));
11196 let probe_count_walk = probe.as_scan().is_some_and(bound_constraint_count_scan);
11203 let probe_rows = match probe_scan {
11212 Some(scan) => estimate_unclamped_scan_rows(profile, scan),
11213 None => match probe {
11218 PlanNode::CustomNode(op) => op.sweep_cost().unwrap_or(op.produced_row_count_estimate),
11219 _ => probe.produced_row_count_estimate(),
11220 },
11221 };
11222 if driver_rows == 0 {
11223 return SeatCost { rows: 0, seeks: 0 };
11224 }
11225 if hash_keys.is_empty() {
11226 return SeatCost {
11235 rows: driver_rows.saturating_add(probe_rows),
11236 seeks: driver_seeks,
11237 };
11238 }
11239 let driver_bound = containing
11250 .filter(|push| probe_scan_has_key(driver, &push.key))
11251 .and_then(|push| {
11252 containing_push_driver_bound(profile, driver, &push.key, push.pushed_val_count)
11253 });
11254 let driver_rows = if driver_keyed.is_some() {
11259 driver_rows
11260 } else {
11261 driver_rows.min(driver_bound.unwrap_or(u64::MAX))
11262 };
11263 let shape = seat_probe_shape(profile, driver, probe, hash_keys, ctx, driver_bound);
11264 if let PlanNode::CustomNode(op) = probe
11277 && op.cost.is_some()
11278 {
11279 if shape.keys.iter().all(|&(covered, _, _, _)| covered) && shape.coverage_drop_allowed {
11287 return SeatCost {
11288 rows: driver_rows.saturating_add(probe_rows),
11289 seeks: driver_seeks,
11290 };
11291 }
11292 let cost = op.cost.expect("the branch requires a stamped op");
11299 let (list, _, _) =
11300 first_broadcast_key(&shape.keys, shape.coverage_drop_allowed).unwrap_or((0, 0, 0));
11301 let pushed_column = shape
11306 .broadcast_key
11307 .as_ref()
11308 .and_then(|key| op.variables.iter().position(|variable| variable == key));
11309 let (per_page, pays_drain) = op
11310 .probe_page_cost(list, pushed_column)
11311 .unwrap_or((0, false));
11312 let drain = if !pays_drain {
11313 0
11314 } else if op.probe_drain_amortized() {
11315 cost.drain_rows
11316 } else {
11317 shape.pages.saturating_mul(cost.drain_rows)
11318 };
11319 return SeatCost {
11320 rows: driver_rows
11321 .saturating_add(drain)
11322 .saturating_add(shape.pages.saturating_mul(per_page)),
11323 seeks: driver_seeks,
11324 };
11325 }
11326 let probe_memoizable = probe.as_scan().is_some_and(scan_memo_eligible)
11327 && probe_rows <= SCAN_MEMO_MAX_ENTRY_ROWS as u64;
11328 let whole_read_rows_known = probe
11335 .as_scan()
11336 .is_some_and(|scan| whole_read_rows_known(profile, scan));
11337 let walk_page = if probe.as_scan().is_none()
11346 && !matches!(probe, PlanNode::CustomNode(_) | PlanNode::Path(_))
11347 {
11348 let push = containing
11349 .cloned()
11350 .or_else(|| child_push_from_shape(profile, driver, probe, ctx, &shape));
11351 push.map(|push| {
11352 let mut budget = SUBTREE_WALK_NODE_BUDGET;
11353 subtree_page_cost(profile, probe, &push, ctx, &mut budget)
11354 })
11355 } else {
11356 None
11357 };
11358 let mirror_road = probe_side_mirror_road(
11372 profile,
11373 probe,
11374 hash_keys,
11375 &shape.keys,
11376 shape.coverage_drop_allowed,
11377 containing,
11378 );
11379 let mut subtree_page = walk_page;
11383 if subtree_page.is_none() {
11384 subtree_page = mirror_road;
11385 }
11386 let build_stamp_writable = probe_scan.is_some()
11397 && hash_keys.iter().any(|key| {
11398 probe
11399 .as_scan()
11400 .is_some_and(|s| s.first_slot_of(key).is_some())
11401 });
11402 let mut cost = seat_cost_arithmetic(
11403 driver_rows,
11404 probe_rows,
11405 probe_memoizable,
11406 shape.pages,
11407 &shape.keys,
11408 shape.coverage_drop_allowed,
11409 build_stamp_writable,
11410 whole_read_rows_known,
11411 shape.driver_domains_known,
11412 probe_count_walk,
11413 subtree_page,
11414 );
11415 if let Some(road) = mirror_road {
11429 let all_covered = shape.keys.iter().all(|&(covered, _, _, _)| covered);
11430 if all_covered && shape.coverage_drop_allowed {
11431 cost = SeatCost {
11432 rows: driver_rows.saturating_add(shape.pages.saturating_mul(road.rows)),
11433 seeks: shape.pages.saturating_mul(road.seeks),
11434 };
11435 }
11436 } else if let Some(walk) = walk_page {
11437 let all_covered = shape.keys.iter().all(|&(covered, _, _, _)| covered);
11479 if all_covered
11480 && shape.coverage_drop_allowed
11481 && let Some(push) = containing
11482 {
11483 cost = if hash_keys.contains(&push.key) {
11484 SeatCost {
11485 rows: driver_rows.saturating_add(shape.pages.saturating_mul(walk.rows)),
11486 seeks: shape.pages.saturating_mul(walk.seeks),
11487 }
11488 } else {
11489 SeatCost {
11490 rows: driver_rows.saturating_add(walk.rows),
11491 seeks: walk.seeks,
11492 }
11493 };
11494 }
11495 }
11496 cost.seeks = cost.seeks.saturating_add(driver_seeks);
11501 cost
11502}
11503
11504const SUBTREE_WALK_NODE_BUDGET: u64 = 64;
11511
11512fn subtree_has_join(node: &PlanNode) -> bool {
11521 match node {
11522 PlanNode::Join { .. } | PlanNode::LeftJoin { .. } => true,
11523 PlanNode::Union { left, right } => subtree_has_join(left) || subtree_has_join(right),
11524 PlanNode::Filter { inner, .. }
11525 | PlanNode::Extend { inner, .. }
11526 | PlanNode::Slice { inner, .. }
11527 | PlanNode::Distinct { inner, .. }
11528 | PlanNode::Sort { inner, .. }
11529 | PlanNode::Group { inner, .. }
11530 | PlanNode::JoinGraphVar { inner, .. } => subtree_has_join(inner),
11531 _ => false,
11534 }
11535}
11536
11537fn subtree_page_cost(
11570 profile: Option<&StatsProfile>,
11571 node: &PlanNode,
11572 push: &ContainingPush,
11573 ctx: Option<&crate::context::QueryContext>,
11574 budget: &mut u64,
11575) -> SeatCost {
11576 let mut filter_cost_milli = 0;
11577 subtree_page_cost_with_filter(profile, node, push, ctx, budget, &mut filter_cost_milli)
11578}
11579
11580#[allow(clippy::too_many_arguments)]
11587fn subtree_page_cost_with_filter(
11588 profile: Option<&StatsProfile>,
11589 node: &PlanNode,
11590 push: &ContainingPush,
11591 ctx: Option<&crate::context::QueryContext>,
11592 budget: &mut u64,
11593 filter_cost_milli: &mut u64,
11594) -> SeatCost {
11595 let coarse = || SeatCost {
11596 rows: node.produced_row_count_estimate(),
11597 seeks: 0,
11598 };
11599 if *budget == 0 {
11600 return coarse();
11601 }
11602 *budget -= 1;
11603 walk_visits_bump();
11604 match node {
11605 PlanNode::Join {
11606 left,
11607 right,
11608 hash_keys,
11609 ..
11610 } => {
11611 let cost = seat_cost_total(profile, left, right, hash_keys, ctx, Some(push));
11612 let driver_extra = if subtree_has_join(left) {
11613 subtree_page_cost_with_filter(profile, left, push, ctx, budget, filter_cost_milli)
11614 } else {
11615 SeatCost { rows: 0, seeks: 0 }
11616 };
11617 SeatCost {
11618 rows: cost.rows.saturating_add(driver_extra.rows),
11619 seeks: cost.seeks.saturating_add(driver_extra.seeks),
11620 }
11621 }
11622 PlanNode::LeftJoin { left, right, .. } | PlanNode::Union { left, right } => {
11626 let left_extra =
11627 subtree_page_cost_with_filter(profile, left, push, ctx, budget, filter_cost_milli);
11628 let right_extra =
11629 subtree_page_cost_with_filter(profile, right, push, ctx, budget, filter_cost_milli);
11630 SeatCost {
11631 rows: left_extra.rows.saturating_add(right_extra.rows),
11632 seeks: left_extra.seeks.saturating_add(right_extra.seeks),
11633 }
11634 }
11635 PlanNode::Scan(scan) => {
11636 let whole_read = estimate_unclamped_scan_rows(profile, scan);
11637 let domain = join_key_domain_for_node(profile, node, &push.key).unwrap_or(0);
11638 let (seeks, matched) = probe_broadcast_price(
11642 whole_read,
11643 &[(
11644 false,
11645 push.pushed_val_count,
11646 domain,
11647 VOCABULARY_OVERLAP_FULL_MILLI,
11648 )],
11649 false,
11650 );
11651 SeatCost {
11652 rows: matched,
11653 seeks,
11654 }
11655 }
11656 PlanNode::Filter {
11657 inner,
11658 early,
11659 residual,
11660 exists,
11661 ..
11662 } => {
11663 let extra =
11664 subtree_page_cost_with_filter(profile, inner, push, ctx, budget, filter_cost_milli);
11665 let exists_rows: u64 = exists
11668 .iter()
11669 .map(|clause| clause.body.produced_row_count_estimate())
11670 .sum();
11671 let scalar_cost_milli = extra
11674 .rows
11675 .saturating_mul(filter_row_cost_milli(early.as_ref(), residual.as_ref()));
11676 *filter_cost_milli = filter_cost_milli.saturating_add(scalar_cost_milli);
11677 SeatCost {
11678 rows: extra
11679 .rows
11680 .saturating_add(exists_rows)
11681 .saturating_add(scalar_cost_milli / 1000),
11682 seeks: extra.seeks,
11683 }
11684 }
11685 PlanNode::Extend { inner, .. }
11686 | PlanNode::Slice { inner, .. }
11687 | PlanNode::Distinct { inner, .. }
11688 | PlanNode::Sort { inner, .. }
11689 | PlanNode::Group { inner, .. }
11690 | PlanNode::JoinGraphVar { inner, .. } => {
11691 subtree_page_cost_with_filter(profile, inner, push, ctx, budget, filter_cost_milli)
11692 }
11693 PlanNode::CustomNode(_)
11697 | PlanNode::Path(_)
11698 | PlanNode::SubSelect(_)
11699 | PlanNode::Values(_)
11700 | PlanNode::NamedGraphs { .. }
11701 | PlanNode::NamedGraphExists { .. }
11702 | PlanNode::DomainCounts { .. }
11703 | PlanNode::HeadCounts { .. }
11704 | PlanNode::PatternCount { .. }
11705 | PlanNode::Unit => coarse(),
11706 }
11707}
11708
11709fn driver_once_cost(
11757 profile: Option<&StatsProfile>,
11758 node: &PlanNode,
11759 ctx: Option<&crate::context::QueryContext>,
11760) -> SeatCost {
11761 let mut budget = SUBTREE_WALK_NODE_BUDGET;
11762 driver_once_work(profile, node, ctx, &mut budget)
11763}
11764
11765fn driver_once_work(
11769 profile: Option<&StatsProfile>,
11770 node: &PlanNode,
11771 ctx: Option<&crate::context::QueryContext>,
11772 budget: &mut u64,
11773) -> SeatCost {
11774 let coarse = || SeatCost {
11775 rows: node.produced_row_count_estimate(),
11776 seeks: 0,
11777 };
11778 if *budget == 0 {
11779 return coarse();
11780 }
11781 *budget -= 1;
11782 walk_visits_bump();
11783 match node {
11784 PlanNode::Scan(scan) => SeatCost {
11785 rows: estimate_unclamped_scan_rows(profile, scan),
11786 seeks: 0,
11787 },
11788 PlanNode::CustomNode(op) => SeatCost {
11789 rows: op
11790 .sweep_cost()
11791 .unwrap_or_else(|| node.produced_row_count_estimate()),
11792 seeks: 0,
11793 },
11794 PlanNode::Join {
11810 left,
11811 right,
11812 hash_keys,
11813 ..
11814 }
11815 | PlanNode::LeftJoin {
11816 left,
11817 right,
11818 hash_keys,
11819 ..
11820 } => seat_cost_total(profile, left, right, hash_keys, ctx, None),
11821 PlanNode::Union { left, right } => once_work_sum(profile, left, right, ctx, budget),
11822 PlanNode::Filter {
11823 inner,
11824 early,
11825 residual,
11826 ..
11827 } => {
11828 let inner_cost = driver_once_work(profile, inner, ctx, budget);
11829 let filter_rows = inner
11830 .produced_row_count_estimate()
11831 .saturating_mul(filter_row_cost_milli(early.as_ref(), residual.as_ref()))
11832 .saturating_div(1000);
11833 SeatCost {
11834 rows: inner_cost.rows.saturating_add(filter_rows),
11835 seeks: inner_cost.seeks,
11836 }
11837 }
11838 PlanNode::Extend { inner, .. }
11839 | PlanNode::Slice { inner, .. }
11840 | PlanNode::Distinct { inner, .. }
11841 | PlanNode::Sort { inner, .. }
11842 | PlanNode::Group { inner, .. }
11843 | PlanNode::JoinGraphVar { inner, .. } => driver_once_work(profile, inner, ctx, budget),
11844 _ => coarse(),
11845 }
11846}
11847
11848fn once_work_sum(
11851 profile: Option<&StatsProfile>,
11852 left: &PlanNode,
11853 right: &PlanNode,
11854 ctx: Option<&crate::context::QueryContext>,
11855 budget: &mut u64,
11856) -> SeatCost {
11857 let l = driver_once_work(profile, left, ctx, budget);
11858 let r = driver_once_work(profile, right, ctx, budget);
11859 SeatCost {
11860 rows: l.rows.saturating_add(r.rows),
11861 seeks: l.seeks.saturating_add(r.seeks),
11862 }
11863}
11864
11865fn join_key_domain_for_allow_list(
11890 profile: Option<&StatsProfile>,
11891 producer: &PlanNode,
11892 probe: &PlanNode,
11893 hash_keys: &[Variable],
11894 producer_rows: u64,
11895) -> Option<u64> {
11896 let mut survivors: Vec<u64> = Vec::new();
11897 let mut hosted_keys = 0usize;
11898 let mut noop_keys = 0usize;
11899 for key in hash_keys {
11900 if !probe_scan_has_key(probe, key) {
11901 continue;
11902 }
11903 hosted_keys += 1;
11904 if let (Some(producer_term), Some(probe_term)) =
11905 (arm_ground_term(producer, key), arm_ground_term(probe, key))
11906 {
11907 if producer_term == probe_term {
11908 noop_keys += 1;
11909 }
11910 continue;
11914 }
11915 let Some(raw) = join_key_domain_for_node(profile, producer, key) else {
11916 continue;
11917 };
11918 let capped = raw.min(producer_rows).max(1);
11919 if capped > PUSHDOWN_TERMS_LIMIT {
11920 continue;
11921 }
11922 survivors.push(capped);
11923 }
11924 if let Some(smallest) = survivors.iter().min() {
11926 return Some(*smallest);
11927 }
11928 if noop_keys > 0 && noop_keys == hosted_keys {
11929 let mut best: Option<u64> = None;
11935 for key in hash_keys {
11936 if !probe_scan_has_key(probe, key) {
11937 continue;
11938 }
11939 let Some(raw) = join_key_domain_for_node(profile, producer, key) else {
11940 continue;
11941 };
11942 let capped = raw.min(producer_rows).max(1);
11943 if capped > PUSHDOWN_TERMS_LIMIT {
11944 continue;
11945 }
11946 best = Some(best.map_or(capped, |b| b.min(capped)));
11947 }
11948 return best;
11949 }
11950 None
11951}
11952
11953fn probe_scan_has_key(node: &PlanNode, variable: &Variable) -> bool {
11958 match node {
11959 PlanNode::Scan(scan) => {
11960 !scan.slot_of(variable).is_empty() || scan.graph.as_ref() == Some(variable)
11961 }
11962 PlanNode::CustomNode(op) => op.variables.contains(variable),
11965 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
11966 probe_scan_has_key(left, variable) || probe_scan_has_key(right, variable)
11967 }
11968 PlanNode::Filter { inner, .. }
11969 | PlanNode::Extend { inner, .. }
11970 | PlanNode::Slice { inner, .. }
11971 | PlanNode::Distinct { inner, .. }
11972 | PlanNode::Sort { inner, .. }
11973 | PlanNode::Group { inner, .. }
11974 | PlanNode::JoinGraphVar { inner, .. } => probe_scan_has_key(inner, variable),
11975 PlanNode::Path(path) => path.graph.as_ref() == Some(variable),
11976 PlanNode::SubSelect(_) => false,
11979 PlanNode::LeftJoin { left, right, .. } => {
11989 probe_scan_has_key(left, variable) || probe_scan_has_key(right, variable)
11990 }
11991 PlanNode::Values(_)
11995 | PlanNode::NamedGraphs { .. }
11996 | PlanNode::NamedGraphExists { .. }
11997 | PlanNode::DomainCounts { .. }
11998 | PlanNode::HeadCounts { .. }
11999 | PlanNode::PatternCount { .. }
12000 | PlanNode::Unit => false,
12001 }
12002}
12003
12004pub fn subtree_hostable_variables(node: &PlanNode) -> Vec<Variable> {
12016 fn walk(node: &PlanNode, out: &mut Vec<Variable>) {
12017 match node {
12018 PlanNode::Scan(scan) => {
12019 for variable in scan.variables() {
12020 if !out.contains(&variable) {
12021 out.push(variable);
12022 }
12023 }
12024 }
12025 PlanNode::CustomNode(op) => {
12026 for variable in &op.variables {
12027 if !out.contains(variable) {
12028 out.push(variable.clone());
12029 }
12030 }
12031 }
12032 PlanNode::Join { left, right, .. }
12033 | PlanNode::Union { left, right }
12034 | PlanNode::LeftJoin { left, right, .. } => {
12035 walk(left, out);
12036 walk(right, out);
12037 }
12038 PlanNode::Filter { inner, .. }
12039 | PlanNode::Extend { inner, .. }
12040 | PlanNode::Slice { inner, .. }
12041 | PlanNode::Distinct { inner, .. }
12042 | PlanNode::Sort { inner, .. }
12043 | PlanNode::Group { inner, .. }
12044 | PlanNode::JoinGraphVar { inner, .. } => walk(inner, out),
12045 PlanNode::Path(path) => {
12046 if let Some(variable) = &path.graph
12047 && !out.contains(variable)
12048 {
12049 out.push(variable.clone());
12050 }
12051 }
12052 PlanNode::SubSelect(_)
12053 | PlanNode::Values(_)
12054 | PlanNode::NamedGraphs { .. }
12055 | PlanNode::NamedGraphExists { .. }
12056 | PlanNode::DomainCounts { .. }
12057 | PlanNode::HeadCounts { .. }
12058 | PlanNode::PatternCount { .. }
12059 | PlanNode::Unit => {}
12060 }
12061 }
12062 let mut out = Vec::new();
12063 walk(node, &mut out);
12064 out
12065}
12066
12067fn stamp_rhs_hostable_keys(right: &PlanNode) -> Arc<[Variable]> {
12077 Arc::from(subtree_hostable_variables(right))
12078}
12079
12080fn shape_name(pattern: &GraphPattern) -> &'static str {
12081 match pattern {
12082 GraphPattern::Bgp { .. } => "a basic graph pattern",
12083 GraphPattern::Path { .. } => "a property path",
12084 GraphPattern::Join { .. } => "a join",
12085 GraphPattern::LeftJoin { .. } => "OPTIONAL",
12086 GraphPattern::Filter { .. } => "FILTER",
12087 GraphPattern::Union { .. } => "UNION",
12088 GraphPattern::Graph { .. } => "GRAPH",
12089 GraphPattern::Extend { .. } => "BIND",
12090 GraphPattern::Minus { .. } => "MINUS",
12091 GraphPattern::Values { .. } => "VALUES",
12092 GraphPattern::OrderBy { .. } => "ORDER BY",
12093 GraphPattern::Project { .. } => "a sub-SELECT",
12094 GraphPattern::Distinct { .. } => "DISTINCT",
12095 GraphPattern::Reduced { .. } => "REDUCED",
12096 GraphPattern::Slice { .. } => "LIMIT / OFFSET",
12097 GraphPattern::Group { .. } => "GROUP BY",
12098 GraphPattern::Service { .. } => "SERVICE",
12099 }
12100}
12101
12102fn extra_bound_slots_for(
12103 subject: &Option<Variable>,
12104 predicate: &Option<Variable>,
12105 object: &Option<Variable>,
12106 graph: &Option<Variable>,
12107 incoming: &IncomingBound,
12108) -> ExtraBoundSlots {
12109 ExtraBoundSlots {
12110 subject: subject.as_ref().is_some_and(|v| incoming.contains(v)),
12111 predicate: predicate.as_ref().is_some_and(|v| incoming.contains(v)),
12112 object: object.as_ref().is_some_and(|v| incoming.contains(v)),
12113 graph: graph.as_ref().is_some_and(|v| incoming.contains(v)),
12114 }
12115}
12116
12117fn one_end_incoming_var<'a>(
12122 extra: ExtraBoundSlots,
12123 subject: &'a Option<Variable>,
12124 predicate: &'a Option<Variable>,
12125 object: &'a Option<Variable>,
12126) -> Option<&'a Variable> {
12127 if extra.subject != extra.object {
12128 if extra.subject {
12129 subject.as_ref()
12130 } else {
12131 object.as_ref()
12132 }
12133 } else if extra.predicate {
12134 predicate.as_ref()
12135 } else {
12136 None
12137 }
12138}
12139
12140fn term_incoming_bound(pattern: &TermPattern, incoming: &IncomingBound) -> bool {
12141 match pattern {
12142 TermPattern::Variable(variable) => incoming.contains(variable),
12143 _ => false,
12144 }
12145}
12146
12147fn incoming_plus(incoming: &IncomingBound, extra: &IncomingBound) -> IncomingBound {
12148 let mut out = incoming.clone();
12149 out.merge(extra);
12150 out
12151}
12152
12153fn incoming_from_plan_left(
12154 incoming: &IncomingBound,
12155 left: &PlanNode,
12156 profile: Option<&StatsProfile>,
12157) -> IncomingBound {
12158 let rows = left.produced_row_count_estimate();
12159 let mut extra = IncomingBound::default();
12160 for variable in &left.output_vars().always_bound {
12161 let domain = join_key_domain_for_node(profile, left, variable)
12162 .map(|d| d.min(rows))
12163 .unwrap_or(rows);
12164 extra.insert(variable.clone(), Some(domain));
12165 }
12166 incoming_plus(incoming, &extra)
12167}
12168
12169fn plan_scan_op(
12170 pattern: &TriplePattern,
12171 profile: Option<&StatsProfile>,
12172 incoming: &IncomingBound,
12173 ctx: &QueryContext,
12174 scope: &GraphScope,
12175) -> Result<ScanOp, ComputeError> {
12176 let (subject_term, subject) = term_slot(&pattern.subject)?;
12177 let (predicate_term, predicate) = named_node_slot(&pattern.predicate);
12178 let (object_term, object) = term_slot(&pattern.object)?;
12179 let applied = apply_graph_scope(scope, ctx.dataset());
12180
12181 let encoded = EncodedTriplePattern {
12182 subject: subject_term,
12183 predicate: predicate_term,
12184 object: object_term,
12185 graph_name: applied.graph_name,
12186 };
12187 let extra = extra_bound_slots_for(&subject, &predicate, &object, &applied.graph, incoming);
12188 let produced_row_count_estimate = match profile {
12189 Some(p) if !p.is_empty() => {
12190 let per_key = estimate_pattern_with_bound_slots(p, &encoded, extra).max(1);
12191 scale_incoming_scan_estimate(
12192 p,
12193 &encoded,
12194 incoming,
12195 one_end_incoming_var(extra, &subject, &predicate, &object),
12196 per_key,
12197 )
12198 }
12199 _ => (4 - (bound_slots(&encoded) + extra.count()) as u64).max(1) * 1_000_000,
12200 };
12201
12202 let join_domains = JoinDomainStamps::classify(profile, &encoded);
12203
12204 Ok(ScanOp {
12205 fetch_once: None,
12206 ancestor_push_return_bound: None,
12207 pattern: encoded,
12208 subject,
12209 predicate,
12210 object,
12211 graph: applied.graph,
12212 produced_row_count_estimate,
12213 broadcasted: None,
12214 graph_filter: applied.graph_filter,
12215 grounded: Vec::new(),
12216 merge_default_graph: applied.merge_default_graph,
12217 marks: Vec::new(),
12218 domain_scan: None,
12219 head_scan: None,
12220 head_scan_counts: None,
12221 domain_counts: None,
12222 iri_only: Vec::new(),
12223 eager: Vec::new(),
12224 join_domains,
12225 })
12226}
12227
12228#[derive(Clone)]
12234pub struct AppliedGraph {
12235 pub graph_name: Option<EncodedTerm>,
12238 pub graph: Option<Variable>,
12240 pub graph_filter: Option<GraphFilter>,
12242 pub merge_default_graph: bool,
12244}
12245
12246pub fn applied_default_graph(dataset: &QueryDataset) -> AppliedGraph {
12251 apply_graph_scope(&GraphScope::Default, dataset)
12252}
12253
12254fn apply_graph_scope(scope: &GraphScope, dataset: &QueryDataset) -> AppliedGraph {
12255 let mut applied = match scope {
12256 GraphScope::Default => match &dataset.default {
12257 DefaultGraphWindow::RdfDefault => AppliedGraph {
12258 graph_name: Some(EncodedTerm::DefaultGraph),
12259 graph: None,
12260 graph_filter: None,
12261 merge_default_graph: false,
12262 },
12263 DefaultGraphWindow::AllGraphs => AppliedGraph {
12264 graph_name: None,
12265 graph: None,
12266 graph_filter: None,
12267 merge_default_graph: false,
12268 },
12269 DefaultGraphWindow::Empty => AppliedGraph {
12270 graph_name: Some(EncodedTerm::DefaultGraph),
12271 graph: None,
12272 graph_filter: None,
12273 merge_default_graph: false,
12274 },
12275 DefaultGraphWindow::Ground(term) => AppliedGraph {
12276 graph_name: Some(term.clone()),
12277 graph: None,
12278 graph_filter: None,
12279 merge_default_graph: false,
12280 },
12281 DefaultGraphWindow::Allow(filter) => AppliedGraph {
12282 graph_name: None,
12283 graph: None,
12284 graph_filter: Some(filter.clone()),
12285 merge_default_graph: false,
12286 },
12287 },
12288 GraphScope::NamedIri(term) => AppliedGraph {
12289 graph_name: Some(term.clone()),
12290 graph: None,
12291 graph_filter: None,
12292 merge_default_graph: false,
12293 },
12294 GraphScope::NamedVar { variable, window } => match window {
12295 NamedVarWindow::Collect => AppliedGraph {
12296 graph_name: None,
12297 graph: Some(variable.clone()),
12298 graph_filter: Some(GraphFilter::exclude_default()),
12299 merge_default_graph: false,
12300 },
12301 NamedVarWindow::Allow(filter) => AppliedGraph {
12302 graph_name: None,
12303 graph: Some(variable.clone()),
12304 graph_filter: Some(filter.clone()),
12305 merge_default_graph: false,
12306 },
12307 NamedVarWindow::Ground(term) => AppliedGraph {
12308 graph_name: Some(term.clone()),
12309 graph: Some(variable.clone()),
12310 graph_filter: None,
12311 merge_default_graph: false,
12312 },
12313 },
12314 GraphScope::Empty => AppliedGraph {
12315 graph_name: Some(EncodedTerm::DefaultGraph),
12316 graph: None,
12317 graph_filter: None,
12318 merge_default_graph: false,
12319 },
12320 };
12321 applied.merge_default_graph =
12323 matches!(scope, GraphScope::Default) && dataset.default.merge_default_graph();
12324 applied
12325}
12326
12327fn scale_incoming_scan_estimate(
12334 profile: &StatsProfile,
12335 encoded: &EncodedTriplePattern,
12336 incoming: &IncomingBound,
12337 var: Option<&Variable>,
12338 per_key: u64,
12339) -> u64 {
12340 let Some(domain) = var.and_then(|v| incoming.known_domain(v)) else {
12341 return per_key;
12342 };
12343 if domain > PUSHDOWN_TERMS_LIMIT {
12344 return estimate_pattern(profile, encoded).max(1);
12345 }
12346 let unbound = estimate_pattern(profile, encoded).max(1);
12347 unbound.min(per_key.saturating_mul(domain))
12348}
12349
12350fn lower_path(
12351 subject: &TermPattern,
12352 path: &PropertyPathExpression,
12353 object: &TermPattern,
12354 _profile: Option<&StatsProfile>,
12355 incoming: &IncomingBound,
12356 ctx: &QueryContext,
12357 scope: &GraphScope,
12358) -> Result<PlanNode, ComputeError> {
12359 let mut strings = path_end_strings(subject);
12360 strings.extend(path_end_strings(object));
12361 let (subject_term, subject_var) = term_slot(subject)?;
12362 let (object_term, object_var) = term_slot(object)?;
12363 let path = encode_property_path(path);
12364 let applied = apply_graph_scope(scope, ctx.dataset());
12365 let start_bound = subject_term.is_some() || term_incoming_bound(subject, incoming);
12366 let end_bound = object_term.is_some() || term_incoming_bound(object, incoming);
12367 let produced_row_count_estimate = estimate_path_size(start_bound, &path, end_bound);
12368 Ok(PlanNode::Path(PathOp {
12369 subject_term,
12370 subject: subject_var,
12371 path,
12372 object_term,
12373 object: object_var,
12374 produced_row_count_estimate,
12375 strings,
12376 graph: applied.graph,
12377 graph_name: applied.graph_name,
12378 graph_filter: applied.graph_filter,
12379 merge_default_graph: applied.merge_default_graph,
12380 }))
12381}
12382
12383fn path_end_strings(pattern: &TermPattern) -> Vec<(StrHash, String)> {
12384 match pattern {
12390 TermPattern::NamedNode(node) => {
12391 crate::query::caches::mint_const_entries(&Term::NamedNode(node.clone()))
12392 .1
12393 .0
12394 }
12395 TermPattern::Literal(literal) => {
12396 crate::query::caches::mint_const_entries(&Term::Literal(literal.clone()))
12397 .1
12398 .0
12399 }
12400 TermPattern::Variable(_) | TermPattern::BlankNode(_) => Vec::new(),
12401 }
12402}
12403
12404fn encode_property_path(path: &PropertyPathExpression) -> PropertyPath {
12405 match path {
12406 PropertyPathExpression::NamedNode(node) => PropertyPath::Predicate(EncodedTerm::from(node)),
12407 PropertyPathExpression::Reverse(inner) => {
12408 PropertyPath::Reverse(Box::new(encode_property_path(inner)))
12409 }
12410 PropertyPathExpression::Sequence(a, b) => PropertyPath::Sequence(
12411 Box::new(encode_property_path(a)),
12412 Box::new(encode_property_path(b)),
12413 ),
12414 PropertyPathExpression::Alternative(a, b) => PropertyPath::Alternative(
12415 Box::new(encode_property_path(a)),
12416 Box::new(encode_property_path(b)),
12417 ),
12418 PropertyPathExpression::ZeroOrMore(inner) => {
12419 PropertyPath::ZeroOrMore(Box::new(encode_property_path(inner)))
12420 }
12421 PropertyPathExpression::OneOrMore(inner) => {
12422 PropertyPath::OneOrMore(Box::new(encode_property_path(inner)))
12423 }
12424 PropertyPathExpression::ZeroOrOne(inner) => {
12425 PropertyPath::ZeroOrOne(Box::new(encode_property_path(inner)))
12426 }
12427 PropertyPathExpression::NegatedPropertySet(nodes) => {
12428 PropertyPath::NegatedPropertySet(nodes.iter().map(EncodedTerm::from).collect())
12429 }
12430 }
12431}
12432
12433const OPEN_STAR_ROW_ESTIMATE: u64 = u64::MAX / 4;
12437
12438pub(crate) fn estimate_path_size(start_bound: bool, path: &PropertyPath, end_bound: bool) -> u64 {
12439 if !start_bound && !end_bound && path.contains_star_or_plus() {
12440 return OPEN_STAR_ROW_ESTIMATE;
12441 }
12442 match path {
12443 PropertyPath::Predicate(predicate) => {
12444 let base = estimate_path_triple(start_bound, true, end_bound);
12445 if *predicate == RDF_TYPE {
12450 base.saturating_add(1)
12451 } else {
12452 base
12453 }
12454 }
12455 PropertyPath::Reverse(inner) => estimate_path_size(end_bound, inner, start_bound),
12456 PropertyPath::Sequence(a, b) => {
12457 let forward = estimate_path_size(start_bound, a, false)
12458 .saturating_mul(estimate_path_size(true, b, end_bound));
12459 let backward = estimate_path_size(start_bound, a, true)
12460 .saturating_mul(estimate_path_size(false, b, end_bound));
12461 forward.min(backward)
12462 }
12463 PropertyPath::Alternative(a, b) => estimate_path_size(start_bound, a, end_bound)
12464 .saturating_add(estimate_path_size(start_bound, b, end_bound)),
12465 PropertyPath::ZeroOrMore(inner) => {
12466 if start_bound && end_bound {
12467 1
12468 } else if start_bound || end_bound {
12469 estimate_path_size(start_bound, inner, end_bound).saturating_mul(1000)
12470 } else {
12471 OPEN_STAR_ROW_ESTIMATE
12472 }
12473 }
12474 PropertyPath::OneOrMore(inner) => {
12475 if start_bound && end_bound {
12476 1
12477 } else if start_bound || end_bound {
12478 estimate_path_size(start_bound, inner, end_bound).saturating_mul(1000)
12479 } else {
12480 OPEN_STAR_ROW_ESTIMATE
12481 }
12482 }
12483 PropertyPath::ZeroOrOne(inner) => {
12484 if start_bound && end_bound {
12485 1
12486 } else if start_bound || end_bound {
12487 estimate_path_size(start_bound, inner, end_bound)
12488 } else {
12489 1_000_000_000
12490 }
12491 }
12492 PropertyPath::NegatedPropertySet(_) => estimate_path_triple(start_bound, false, end_bound),
12493 }
12494}
12495
12496fn estimate_path_triple(subject_bound: bool, predicate_bound: bool, object_bound: bool) -> u64 {
12504 match (subject_bound, predicate_bound, object_bound) {
12505 (true, true, true) => 1,
12506 (true, true, false) => 10,
12507 (true, false, true) => 2,
12508 (false, true, true) => 1_000,
12509 (true, false, false) => 100,
12510 (false, false, false) => 1_000_000_000,
12511 (false, true, false) => 1_000_000,
12512 (false, false, true) => 10_000,
12513 }
12514}
12515
12516fn recost_path(path: &mut PathOp) {
12517 path.produced_row_count_estimate = estimate_path_size(
12518 path.subject_term.is_some(),
12519 &path.path,
12520 path.object_term.is_some(),
12521 );
12522}
12523
12524pub(crate) fn join_key_domain_for(
12525 profile: Option<&StatsProfile>,
12526 scan: &ScanOp,
12527 hash_keys: &[Variable],
12528) -> Option<u64> {
12529 let var = hash_keys.first()?;
12530 if !scan.is_live(var) {
12531 return None;
12532 }
12533 let slot = if scan.subject.as_ref() == Some(var) {
12534 JoinKeySlot::Subject
12535 } else if scan.object.as_ref() == Some(var) {
12536 JoinKeySlot::Object
12537 } else {
12538 return None;
12539 };
12540 let ground = match slot {
12541 JoinKeySlot::Subject => scan.pattern.subject.is_some(),
12542 JoinKeySlot::Object => scan.pattern.object.is_some(),
12543 };
12544 if ground {
12547 return Some(1);
12548 }
12549 let profile = profile.filter(|p| !p.is_empty())?;
12550 if let JoinDomainStamp::Known(domain) = scan.join_domains.get(slot) {
12555 return Some(domain);
12556 }
12557 estimate_join_key_domain(profile, &scan.pattern, slot)
12558}
12559
12560pub(crate) const TERM_DICT_RESERVE_FLOOR: u64 = 10_000;
12564
12565pub(crate) const TERM_DICT_RESERVE_MAX: u64 = 1_000_000;
12571
12572pub(crate) fn term_dict_reserve_amount(estimate: u64) -> Option<u64> {
12576 let amount = estimate.min(TERM_DICT_RESERVE_MAX);
12577 (amount >= TERM_DICT_RESERVE_FLOOR).then_some(amount)
12578}
12579
12580fn estimated_distinct_terms(
12586 node: &PlanNode,
12587 profile: &StatsProfile,
12588 maxima: &mut Vec<(Variable, u64)>,
12589) {
12590 match node {
12591 PlanNode::Scan(scan) => {
12592 let slots = [
12593 (&scan.subject, scan.pattern.subject.is_none()),
12594 (&scan.object, scan.pattern.object.is_none()),
12595 ];
12596 for (slot, unbound) in slots {
12597 let Some(variable) = slot else { continue };
12598 if !unbound || !scan.is_live(variable) {
12599 continue;
12600 }
12601 let domain =
12602 join_key_domain_for(Some(profile), scan, std::slice::from_ref(variable))
12603 .unwrap_or(0);
12604 if domain == 0 {
12605 continue;
12606 }
12607 match maxima.iter_mut().find(|(v, _)| v == variable) {
12608 Some(entry) => entry.1 = entry.1.max(domain),
12609 None => maxima.push((variable.clone(), domain)),
12610 }
12611 }
12612 }
12613 PlanNode::Join { left, right, .. }
12614 | PlanNode::LeftJoin { left, right, .. }
12615 | PlanNode::Union { left, right } => {
12616 estimated_distinct_terms(left, profile, maxima);
12617 estimated_distinct_terms(right, profile, maxima);
12618 }
12619 PlanNode::NamedGraphs {
12620 variable,
12621 produced_row_count_estimate,
12622 } => {
12623 if *produced_row_count_estimate > 0 {
12625 match maxima.iter_mut().find(|(v, _)| v == variable) {
12626 Some(entry) => entry.1 = entry.1.max(*produced_row_count_estimate),
12627 None => maxima.push((variable.clone(), *produced_row_count_estimate)),
12628 }
12629 }
12630 }
12631 PlanNode::Filter { inner, .. }
12632 | PlanNode::JoinGraphVar { inner, .. }
12633 | PlanNode::Extend { inner, .. }
12634 | PlanNode::Slice { inner, .. }
12635 | PlanNode::Distinct { inner, .. }
12636 | PlanNode::Sort { inner, .. }
12637 | PlanNode::Group { inner, .. } => estimated_distinct_terms(inner, profile, maxima),
12638 PlanNode::SubSelect(sub) => estimated_distinct_terms(&sub.inner, profile, maxima),
12639 PlanNode::CustomNode(_)
12640 | PlanNode::Path(_)
12641 | PlanNode::Values(_)
12642 | PlanNode::NamedGraphExists { .. }
12643 | PlanNode::DomainCounts { .. }
12644 | PlanNode::HeadCounts { .. }
12645 | PlanNode::PatternCount { .. }
12646 | PlanNode::Unit => {}
12647 }
12648}
12649
12650pub(crate) fn reserve_term_dict_from_plan(
12658 plan: &LogicalPlan,
12659 profile: Option<&StatsProfile>,
12660 ctx: &QueryContext,
12661) {
12662 let Some(profile) = profile else {
12664 return;
12665 };
12666 let mut maxima = Vec::new();
12667 estimated_distinct_terms(&plan.root, profile, &mut maxima);
12668 let estimate: u64 = maxima.iter().map(|(_, domain)| domain).sum();
12669 if let Some(amount) = term_dict_reserve_amount(estimate) {
12671 ctx.term_dict().reserve(amount as usize);
12672 }
12673}
12674
12675type UnionDomainCacheKey = (u64, Vec<(StrHash, u8)>);
12686
12687thread_local! {
12688 static UNION_DOMAIN_CACHE: std::cell::RefCell<FxHashMap<UnionDomainCacheKey, u64>> =
12689 std::cell::RefCell::new(FxHashMap::default());
12690}
12691
12692fn clear_union_domain_cache() {
12693 UNION_DOMAIN_CACHE.with(|cache| cache.borrow_mut().clear());
12694}
12695
12696#[derive(Default)]
12706struct UnionVocabulary<'a> {
12707 sketches: Vec<&'a waratah_stats::HyperLogLog>,
12709 fingerprint: Vec<(StrHash, u8)>,
12711 sketch_sum: u64,
12715 exact_add: u64,
12717 exact_once: u64,
12720}
12721
12722impl UnionVocabulary<'_> {
12723 fn size_proxy(&self) -> u64 {
12726 self.sketch_sum
12727 .saturating_add(self.exact_add)
12728 .saturating_add(self.exact_once)
12729 }
12730}
12731
12732enum UnionVocabularyWalk<'a> {
12735 Value(UnionVocabulary<'a>),
12736 Absent,
12738 Unknown,
12741}
12742
12743fn union_vocabulary_for<'a>(
12751 profile: &'a StatsProfile,
12752 node: &PlanNode,
12753 variable: &Variable,
12754) -> UnionVocabularyWalk<'a> {
12755 match node {
12756 PlanNode::Scan(scan) => {
12757 let Some((pattern, slot)) = scan_key_vocabulary(node, variable) else {
12758 return if scan.subject.as_ref() == Some(variable)
12761 || scan.object.as_ref() == Some(variable)
12762 {
12763 UnionVocabularyWalk::Unknown
12764 } else {
12765 UnionVocabularyWalk::Absent
12766 };
12767 };
12768 let Some(predicate) = pattern.predicate.as_ref().and_then(named_node_hash) else {
12769 return UnionVocabularyWalk::Unknown;
12770 };
12771 if pattern.predicate.as_ref() == Some(&RDF_TYPE) {
12772 if slot == JoinKeySlot::Subject
12773 && let Some(object) = pattern.object.as_ref()
12774 && let Some(class) = named_node_hash(object)
12775 && let Some(&count) = profile.class_counts.get(&class)
12776 && count > 0
12777 {
12778 return UnionVocabularyWalk::Value(UnionVocabulary {
12779 exact_add: count,
12780 ..UnionVocabulary::default()
12781 });
12782 }
12783 if slot == JoinKeySlot::Object && !profile.class_counts.is_empty() {
12784 return UnionVocabularyWalk::Value(UnionVocabulary {
12785 exact_once: profile.class_counts.len() as u64,
12786 ..UnionVocabulary::default()
12787 });
12788 }
12789 }
12790 let sketch = match slot {
12791 JoinKeySlot::Subject => profile.subjects_per_predicate.get(&predicate),
12792 JoinKeySlot::Object => profile.objects_per_predicate.get(&predicate),
12793 };
12794 match sketch {
12795 Some(sketch) => {
12796 let cardinality = match slot {
12797 JoinKeySlot::Subject => profile.subject_domain(&predicate),
12798 JoinKeySlot::Object => profile.object_domain(&predicate),
12799 }
12800 .unwrap_or_else(|| sketch.cardinality());
12801 UnionVocabularyWalk::Value(UnionVocabulary {
12802 sketches: vec![sketch],
12803 fingerprint: vec![(predicate, slot as u8)],
12804 sketch_sum: cardinality,
12805 ..UnionVocabulary::default()
12806 })
12807 }
12808 None => UnionVocabularyWalk::Unknown,
12809 }
12810 }
12811 PlanNode::Extend { inner, .. }
12812 | PlanNode::Filter { inner, .. }
12813 | PlanNode::Slice { inner, .. }
12814 | PlanNode::Distinct { inner, .. }
12815 | PlanNode::Sort { inner, .. }
12816 | PlanNode::Group { inner, .. }
12817 | PlanNode::JoinGraphVar { inner, .. } => union_vocabulary_for(profile, inner, variable),
12818 PlanNode::Join { left, right, .. } => {
12819 let picked = match (
12820 union_vocabulary_for(profile, left, variable),
12821 union_vocabulary_for(profile, right, variable),
12822 ) {
12823 (UnionVocabularyWalk::Value(a), UnionVocabularyWalk::Value(b)) => {
12824 if a.size_proxy() <= b.size_proxy() {
12825 UnionVocabularyWalk::Value(a)
12826 } else {
12827 UnionVocabularyWalk::Value(b)
12828 }
12829 }
12830 (UnionVocabularyWalk::Value(value), _) | (_, UnionVocabularyWalk::Value(value)) => {
12833 UnionVocabularyWalk::Value(value)
12834 }
12835 (UnionVocabularyWalk::Absent, UnionVocabularyWalk::Absent) => {
12836 UnionVocabularyWalk::Absent
12837 }
12838 _ => UnionVocabularyWalk::Unknown,
12839 };
12840 clamp_join_vocabulary_to_rows(picked, node.produced_row_count_estimate())
12841 }
12842 PlanNode::Union { left, right } => {
12843 match (
12844 union_vocabulary_for(profile, left, variable),
12845 union_vocabulary_for(profile, right, variable),
12846 ) {
12847 (UnionVocabularyWalk::Value(mut left), UnionVocabularyWalk::Value(right)) => {
12848 left.sketches.extend(right.sketches);
12849 left.fingerprint.extend(right.fingerprint);
12850 left.sketch_sum = left.sketch_sum.saturating_add(right.sketch_sum);
12851 left.exact_add = left.exact_add.saturating_add(right.exact_add);
12852 left.exact_once = left.exact_once.max(right.exact_once);
12853 UnionVocabularyWalk::Value(left)
12854 }
12855 _ => UnionVocabularyWalk::Unknown,
12860 }
12861 }
12862 _ => UnionVocabularyWalk::Unknown,
12863 }
12864}
12865
12866fn clamp_join_vocabulary_to_rows<'a>(
12880 walked: UnionVocabularyWalk<'a>,
12881 rows: u64,
12882) -> UnionVocabularyWalk<'a> {
12883 let UnionVocabularyWalk::Value(vocabulary) = walked else {
12884 return walked;
12885 };
12886 let rows = rows.max(1);
12887 if vocabulary.size_proxy() > rows.saturating_mul(2) {
12888 UnionVocabularyWalk::Value(UnionVocabulary {
12889 exact_add: rows,
12890 ..UnionVocabulary::default()
12891 })
12892 } else {
12893 UnionVocabularyWalk::Value(vocabulary)
12894 }
12895}
12896
12897fn union_domain_from_vocabularies(
12903 profile: Option<&StatsProfile>,
12904 node: &PlanNode,
12905 variable: &Variable,
12906) -> Option<u64> {
12907 let profile = profile.filter(|profile| !profile.is_empty())?;
12908 let UnionVocabularyWalk::Value(vocabulary) = union_vocabulary_for(profile, node, variable)
12909 else {
12910 return None;
12911 };
12912 let merged = if vocabulary.sketches.is_empty() {
12913 0
12914 } else {
12915 let mut fingerprint = vocabulary.fingerprint.clone();
12916 fingerprint.sort_unstable();
12917 let key = (profile.total_puts, fingerprint);
12918 match UNION_DOMAIN_CACHE.with(|cache| cache.borrow().get(&key).copied()) {
12919 Some(cardinality) => cardinality,
12920 None => {
12921 let mut merged = vocabulary.sketches[0].clone();
12922 for sketch in &vocabulary.sketches[1..] {
12923 merged.merge(sketch).ok()?;
12924 }
12925 let cardinality = merged.cardinality();
12926 UNION_DOMAIN_CACHE.with(|cache| {
12927 cache.borrow_mut().insert(key, cardinality);
12928 });
12929 cardinality
12930 }
12931 }
12932 };
12933 Some(
12934 merged
12935 .saturating_add(vocabulary.exact_add)
12936 .saturating_add(vocabulary.exact_once)
12937 .max(1),
12938 )
12939}
12940
12941pub(crate) fn join_key_domain_for_node(
12948 profile: Option<&StatsProfile>,
12949 node: &PlanNode,
12950 variable: &Variable,
12951) -> Option<u64> {
12952 match node {
12953 PlanNode::Scan(scan) => join_key_domain_for(profile, scan, std::slice::from_ref(variable)),
12954 PlanNode::Path(_) => None,
12955 PlanNode::CustomNode(op) => op
12958 .variables
12959 .contains(variable)
12960 .then_some(op.produced_row_count_estimate),
12961 PlanNode::Values(values) => values.distinct_key_count(variable),
12962 PlanNode::DomainCounts {
12965 head,
12966 produced_row_count_estimate,
12967 ..
12968 } if head == variable => Some(*produced_row_count_estimate),
12969 PlanNode::DomainCounts { .. } => None,
12970 PlanNode::HeadCounts { .. } | PlanNode::PatternCount { .. } => None,
12971 PlanNode::Join { left, right, .. } => {
12972 match (
12977 join_key_domain_for_node(profile, left, variable),
12978 join_key_domain_for_node(profile, right, variable),
12979 ) {
12980 (Some(a), Some(b)) => Some(a.min(b)),
12981 (a, b) => a.or(b),
12982 }
12983 }
12984 PlanNode::LeftJoin { left, .. } => join_key_domain_for_node(profile, left, variable),
12986 PlanNode::Union { left, right } => {
12987 if let Some(domain) = union_domain_from_vocabularies(profile, node, variable) {
12994 return Some(domain);
12995 }
12996 let left_domain = join_key_domain_for_node(profile, left, variable);
13012 let right_domain = join_key_domain_for_node(profile, right, variable);
13013 match (left_domain, right_domain) {
13014 (Some(a), Some(b)) => Some(a.saturating_add(b)),
13015 (Some(a), None) if probe_scan_has_key(right, variable) => {
13016 Some(a.saturating_add(right.produced_row_count_estimate()))
13017 }
13018 (None, Some(b)) if probe_scan_has_key(left, variable) => {
13019 Some(b.saturating_add(left.produced_row_count_estimate()))
13020 }
13021 _ => None,
13022 }
13023 }
13024 PlanNode::Filter {
13025 inner,
13026 early,
13027 residual,
13028 exists,
13029 ..
13030 } => {
13031 let inner_domain = join_key_domain_for_node(profile, inner, variable)?;
13039 match filter_selectivity_milli(early.as_ref(), residual.as_ref(), exists) {
13040 Some(selectivity) => Some(filter_domain_bound(
13041 inner_domain,
13042 inner.produced_row_count_estimate(),
13043 selectivity,
13044 )),
13045 None => Some(inner_domain),
13046 }
13047 }
13048 PlanNode::Extend { inner, .. }
13049 | PlanNode::Slice { inner, .. }
13050 | PlanNode::Distinct { inner, .. }
13051 | PlanNode::Sort { inner, .. }
13052 | PlanNode::Group { inner, .. }
13053 | PlanNode::JoinGraphVar { inner, .. } => {
13054 join_key_domain_for_node(profile, inner, variable)
13055 }
13056 PlanNode::SubSelect(_) => None,
13059 PlanNode::NamedGraphs {
13060 produced_row_count_estimate,
13061 ..
13062 } => Some(*produced_row_count_estimate),
13063 PlanNode::Unit | PlanNode::NamedGraphExists { .. } => None,
13064 }
13065}
13066
13067fn reorder_hash_keys_by_probe_return(
13092 hash_keys: &mut [Variable],
13093 probe_key_domains: &mut [u64],
13094 probe_key_overlap_milli: &mut [u64],
13095 left: &PlanNode,
13096 right: &PlanNode,
13097 profile: Option<&StatsProfile>,
13098) {
13099 if hash_keys.len() < 2 {
13100 return;
13101 }
13102 debug_assert!(
13107 probe_key_domains.is_empty() || probe_key_domains.len() == hash_keys.len(),
13108 "domain stamps must be empty or key-aligned"
13109 );
13110 debug_assert!(
13111 probe_key_overlap_milli.is_empty() || probe_key_overlap_milli.len() == hash_keys.len(),
13112 "overlap stamps must be empty or key-aligned"
13113 );
13114 let probe_rows = right.produced_row_count_estimate() as u128;
13115 let cost = |key: &Variable| -> Option<u128> {
13116 if !probe_scan_has_key(right, key) {
13117 return None;
13118 }
13119 let driver_domain = join_key_domain_for_node(profile, left, key)? as u128;
13120 let fan_out = match join_key_domain_for_node(profile, right, key) {
13121 Some(domain) => probe_rows / domain.max(1) as u128,
13122 None => 1,
13123 };
13124 Some(driver_domain * fan_out)
13125 };
13126 let mut paired: Vec<(Variable, u64, u64, Option<u128>)> = hash_keys
13130 .iter()
13131 .enumerate()
13132 .map(|(i, key)| {
13133 (
13134 key.clone(),
13135 probe_key_domains.get(i).copied().unwrap_or(0),
13136 probe_key_overlap_milli.get(i).copied().unwrap_or(0),
13137 cost(key),
13138 )
13139 })
13140 .collect();
13141 paired.sort_by_key(|(_, _, _, order)| (*order).unwrap_or(u128::MAX));
13146 for (i, (key, domain, overlap, _)) in paired.into_iter().enumerate() {
13147 hash_keys[i] = key;
13148 if i < probe_key_domains.len() {
13149 probe_key_domains[i] = domain;
13150 }
13151 if i < probe_key_overlap_milli.len() {
13152 probe_key_overlap_milli[i] = overlap;
13153 }
13154 }
13155}
13156
13157pub(crate) fn bind_pattern_slot(
13159 mut pattern: EncodedTriplePattern,
13160 slot: PatternSlot,
13161 term: &EncodedTerm,
13162) -> EncodedTriplePattern {
13163 match slot {
13164 PatternSlot::Subject => pattern.subject = Some(term.clone()),
13165 PatternSlot::Predicate => pattern.predicate = Some(term.clone()),
13166 PatternSlot::Object => pattern.object = Some(term.clone()),
13167 }
13168 pattern
13169}
13170
13171fn pattern_slot_term(pattern: &EncodedTriplePattern, slot: PatternSlot) -> Option<&EncodedTerm> {
13172 match slot {
13173 PatternSlot::Subject => pattern.subject.as_ref(),
13174 PatternSlot::Predicate => pattern.predicate.as_ref(),
13175 PatternSlot::Object => pattern.object.as_ref(),
13176 }
13177}
13178
13179fn fold_identity_filters(node: &mut PlanNode, profile: Option<&StatsProfile>) {
13189 if matches!(node, PlanNode::Filter { .. }) {
13190 let PlanNode::Filter {
13191 inner,
13192 mut early,
13193 mut residual,
13194 mut exists,
13195 ..
13196 } = std::mem::replace(node, PlanNode::Unit)
13197 else {
13198 unreachable!("Filter arm");
13199 };
13200 let mut inner = *inner;
13201 fold_identity_filters(&mut inner, profile);
13202 for clause in &mut exists {
13203 fold_identity_filters(&mut clause.body, profile);
13204 }
13205 if let Some(expr) = early.take() {
13206 let inner_vars = inner.output_vars();
13207 let mut kept = Vec::new();
13208 for conjunct in flatten_and(&expr) {
13209 match identity_safe_equality(&conjunct, &inner) {
13210 Some(IdentityFold::Bind(eq)) => {
13211 let grounding = ground_identity_term(
13212 &mut inner,
13213 &eq.variable,
13214 &eq.term,
13215 profile,
13216 &eq.strings,
13217 );
13218 for clause in &mut exists {
13219 let _ = ground_identity_term(
13220 &mut clause.body,
13221 &eq.variable,
13222 &eq.term,
13223 profile,
13224 &eq.strings,
13225 );
13226 }
13227 if grounding.producers_constrained
13232 && inner_vars.is_always_bound(&eq.variable)
13233 {
13234 continue;
13235 }
13236 kept.push(conjunct);
13243 }
13244 Some(IdentityFold::AlwaysTrue { a, b }) => {
13245 if inner_vars.is_always_bound(&a) && inner_vars.is_always_bound(&b) {
13246 continue;
13247 }
13248 kept.push(conjunct);
13249 }
13250 None => kept.push(conjunct),
13251 }
13252 }
13253 let mut grounded_kept = Vec::with_capacity(kept.len());
13260 for mut conjunct in kept {
13261 substitute_ground_variables(&mut conjunct, &inner, &inner_vars);
13262 grounded_kept.push(conjunct);
13263 }
13264 early = and_fold(grounded_kept);
13265 if let Some(expr) = early.as_ref()
13270 && let Some((variable, extra)) = collect_not_same_term_graph(expr)
13271 {
13272 let applied = apply_graph_exclusions(&mut inner, &variable, &extra);
13273 if applied && inner_vars.is_always_bound(&variable) {
13274 early = None;
13275 }
13276 }
13277 }
13278 for clause in &mut exists {
13279 for variable in &clause.correlation {
13280 if let Some(term) = unique_ground_term(&inner, variable) {
13281 let _ = ground_identity_term(&mut clause.body, variable, &term, profile, &[]);
13282 }
13283 }
13284 }
13285 let inner_vars = inner.output_vars();
13293 if let Some(expr) = residual.take() {
13294 let conjuncts = flatten_and(&expr);
13295 let mut kept = Vec::with_capacity(conjuncts.len());
13296 for mut conjunct in conjuncts {
13297 ground_residual_conjunct(
13298 &mut conjunct,
13299 &inner,
13300 &inner_vars,
13301 &producer_keeps_variable,
13302 );
13303 kept.push(conjunct);
13304 }
13305 residual = and_fold(kept);
13306 }
13307 if early.is_none() && residual.is_none() && exists.is_empty() {
13311 *node = inner;
13312 } else {
13313 *node = PlanNode::Filter {
13315 inner: Box::new(inner),
13316 early,
13317 residual,
13318 exists,
13319 one_to_one: false,
13320 };
13321 }
13322 return;
13323 }
13324 match node {
13327 PlanNode::CustomNode(op) => {
13328 for child in &mut op.children {
13329 fold_identity_filters(child, profile);
13330 }
13331 }
13332 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
13333 fold_identity_filters(left, profile);
13334 fold_identity_filters(right, profile);
13335 }
13336 PlanNode::LeftJoin {
13337 left,
13338 right,
13339 early_filter,
13340 residual_filter: _,
13341 ..
13342 } => {
13343 fold_identity_filters(left, profile);
13344 fold_identity_filters(right, profile);
13345 fold_left_join_early_into_right(right, early_filter, profile);
13346 }
13347 PlanNode::SubSelect(sub) => fold_identity_filters(&mut sub.inner, profile),
13351 PlanNode::Extend { inner, .. }
13352 | PlanNode::Slice { inner, .. }
13353 | PlanNode::Distinct { inner, .. }
13354 | PlanNode::Sort { inner, .. }
13355 | PlanNode::Group { inner, .. }
13356 | PlanNode::JoinGraphVar { inner, .. } => {
13357 fold_identity_filters(inner, profile);
13358 }
13359 PlanNode::Filter { .. } => unreachable!("Filter handled above"),
13360 PlanNode::Scan(_)
13361 | PlanNode::Path(_)
13362 | PlanNode::Values(_)
13363 | PlanNode::NamedGraphs { .. }
13364 | PlanNode::NamedGraphExists { .. }
13365 | PlanNode::DomainCounts { .. }
13366 | PlanNode::HeadCounts { .. }
13367 | PlanNode::PatternCount { .. }
13368 | PlanNode::Unit => {}
13369 }
13370}
13371
13372fn fold_left_join_early_into_right(
13373 right: &mut PlanNode,
13374 early_filter: &mut Option<Expression>,
13375 profile: Option<&StatsProfile>,
13376) {
13377 let Some(expr) = early_filter.take() else {
13378 return;
13379 };
13380 let right_vars = right.output_vars().all();
13381 let mut kept = Vec::new();
13382 for conjunct in flatten_and(&expr) {
13383 let all_on_right = variables_in_expression(&conjunct)
13384 .iter()
13385 .all(|v| right_vars.contains(v));
13386 let folded = all_on_right
13390 && match identity_safe_equality(&conjunct, right) {
13391 Some(IdentityFold::Bind(eq)) => {
13392 ground_identity_term(right, &eq.variable, &eq.term, profile, &eq.strings)
13393 .producers_constrained
13394 }
13395 Some(IdentityFold::AlwaysTrue { .. }) => true,
13396 None => false,
13397 };
13398 if !folded {
13399 kept.push(conjunct);
13400 }
13401 }
13402 *early_filter = and_fold(kept);
13403}
13404
13405struct IdentityEquality {
13406 variable: Variable,
13407 term: EncodedTerm,
13408 strings: Vec<(StrHash, String)>,
13409}
13410
13411enum IdentityFold {
13412 Bind(IdentityEquality),
13413 AlwaysTrue { a: Variable, b: Variable },
13414}
13415
13416fn identity_safe_equality(expr: &Expression, node: &PlanNode) -> Option<IdentityFold> {
13417 let (a, b, equal_not_same_term) = match expr {
13418 Expression::SameTerm(a, b) => (a.as_ref(), b.as_ref(), false),
13419 Expression::Equal(a, b) => (a.as_ref(), b.as_ref(), true),
13420 _ => return None,
13421 };
13422 match (a, b) {
13423 (Expression::Variable(va), Expression::Variable(vb)) => {
13424 identity_safe_var_var(va, vb, equal_not_same_term, node)
13425 }
13426 (Expression::Variable(v), c) | (c, Expression::Variable(v)) => {
13427 let (term, strings) = encoded_ground_expr(c)?;
13428 identity_bind_if_safe(v, term, strings, equal_not_same_term)
13429 }
13430 _ => None,
13431 }
13432}
13433
13434fn identity_safe_var_var(
13435 va: &Variable,
13436 vb: &Variable,
13437 equal_not_same_term: bool,
13438 node: &PlanNode,
13439) -> Option<IdentityFold> {
13440 let ground_a = unique_ground_with_strings(node, va);
13441 let ground_b = unique_ground_with_strings(node, vb);
13442 match (ground_a, ground_b) {
13443 (Some((term, strings)), None) => {
13444 identity_bind_if_safe(vb, term, strings, equal_not_same_term)
13445 }
13446 (None, Some((term, strings))) => {
13447 identity_bind_if_safe(va, term, strings, equal_not_same_term)
13448 }
13449 (Some((ta, _)), Some((tb, _))) if ta == tb => {
13450 if equal_not_same_term && !sparql_equal_is_encoded_identity(&ta) {
13451 return None;
13452 }
13453 Some(IdentityFold::AlwaysTrue {
13454 a: va.clone(),
13455 b: vb.clone(),
13456 })
13457 }
13458 (Some(_), Some(_)) => None,
13459 (None, None) => {
13460 None
13465 }
13466 }
13467}
13468
13469fn identity_bind_if_safe(
13470 variable: &Variable,
13471 term: EncodedTerm,
13472 strings: Vec<(StrHash, String)>,
13473 equal_not_same_term: bool,
13474) -> Option<IdentityFold> {
13475 if equal_not_same_term && !sparql_equal_is_encoded_identity(&term) {
13476 return None;
13477 }
13478 Some(IdentityFold::Bind(IdentityEquality {
13479 variable: variable.clone(),
13480 term,
13481 strings,
13482 }))
13483}
13484
13485fn encoded_ground_expr(expr: &Expression) -> Option<(EncodedTerm, Vec<(StrHash, String)>)> {
13486 match expr {
13491 Expression::NamedNode(node) => {
13492 let (encoded, (strings, _payloads)) =
13493 crate::query::caches::mint_const_entries(&Term::NamedNode(node.clone()));
13494 Some((encoded, strings))
13495 }
13496 Expression::Literal(literal) => {
13497 let (encoded, (strings, _payloads)) =
13498 crate::query::caches::mint_const_entries(&Term::Literal(literal.clone()));
13499 Some((encoded, strings))
13500 }
13501 _ => None,
13502 }
13503}
13504
13505fn sparql_equal_is_encoded_identity(term: &EncodedTerm) -> bool {
13506 matches!(
13507 term,
13508 EncodedTerm::NamedNode { .. }
13509 | EncodedTerm::SmallStringLiteral(_)
13510 | EncodedTerm::BigStringLiteral { .. }
13511 | EncodedTerm::SmallSmallLangStringLiteral { .. }
13512 | EncodedTerm::SmallBigLangStringLiteral { .. }
13513 | EncodedTerm::BigSmallLangStringLiteral { .. }
13514 | EncodedTerm::BigBigLangStringLiteral { .. }
13515 | EncodedTerm::BooleanLiteral(_)
13516 )
13517}
13518
13519struct IdentityGrounding {
13526 #[allow(dead_code)]
13530 rewrote_scan: bool,
13531 producers_constrained: bool,
13532}
13533
13534struct IdentityWalk {
13536 rewrote_scan: bool,
13537 saw_producer: bool,
13538 all_ok: bool,
13539}
13540
13541impl IdentityWalk {
13542 fn vacuous() -> Self {
13543 Self {
13544 rewrote_scan: false,
13545 saw_producer: false,
13546 all_ok: true,
13547 }
13548 }
13549
13550 fn producer(rewrote_scan: bool, constrained: bool) -> Self {
13551 Self {
13552 rewrote_scan,
13553 saw_producer: true,
13554 all_ok: constrained,
13555 }
13556 }
13557
13558 fn combine(self, other: Self) -> Self {
13559 Self {
13560 rewrote_scan: self.rewrote_scan || other.rewrote_scan,
13561 saw_producer: self.saw_producer || other.saw_producer,
13562 all_ok: self.all_ok && other.all_ok,
13563 }
13564 }
13565
13566 fn finish(self) -> IdentityGrounding {
13567 IdentityGrounding {
13568 rewrote_scan: self.rewrote_scan,
13569 producers_constrained: self.saw_producer && self.all_ok,
13570 }
13571 }
13572}
13573
13574fn ground_identity_term(
13577 node: &mut PlanNode,
13578 variable: &Variable,
13579 term: &EncodedTerm,
13580 profile: Option<&StatsProfile>,
13581 strings: &[(StrHash, String)],
13582) -> IdentityGrounding {
13583 ground_identity_walk(node, variable, term, profile, strings).finish()
13584}
13585
13586fn ground_identity_walk(
13587 node: &mut PlanNode,
13588 variable: &Variable,
13589 term: &EncodedTerm,
13590 profile: Option<&StatsProfile>,
13591 strings: &[(StrHash, String)],
13592) -> IdentityWalk {
13593 match node {
13594 PlanNode::CustomNode(op) => {
13598 if op.variables.contains(variable) {
13599 IdentityWalk::producer(false, false)
13600 } else {
13601 IdentityWalk::vacuous()
13602 }
13603 }
13604 PlanNode::Scan(scan) => {
13605 if scan.slot_of(variable).is_empty() && scan.graph.as_ref() != Some(variable) {
13606 return IdentityWalk::vacuous();
13607 }
13608 let ok = bind_scan_equality(scan, variable, term, profile);
13609 IdentityWalk::producer(ok, ok)
13610 }
13611 PlanNode::Path(path) => {
13612 if path.end_of(variable).is_none() && path.graph.as_ref() != Some(variable) {
13613 return IdentityWalk::vacuous();
13614 }
13615 let ok = bind_path_equality(path, variable, term, strings);
13616 IdentityWalk::producer(ok, ok)
13617 }
13618 PlanNode::Values(values) => {
13619 if !values.variables.contains(variable) {
13620 return IdentityWalk::vacuous();
13621 }
13622 let ok = values.unique_term(variable).as_ref() == Some(term);
13623 IdentityWalk::producer(false, ok)
13624 }
13625 PlanNode::Join { left, right, .. }
13626 | PlanNode::Union { left, right }
13627 | PlanNode::LeftJoin { left, right, .. } => {
13628 let a = ground_identity_walk(left, variable, term, profile, strings);
13632 let b = ground_identity_walk(right, variable, term, profile, strings);
13633 a.combine(b)
13634 }
13635 PlanNode::Extend {
13636 inner,
13637 variable: bound,
13638 expression,
13639 ..
13640 } => {
13641 let inner_walk = ground_identity_walk(inner, variable, term, profile, strings);
13642 if bound != variable {
13643 return inner_walk;
13644 }
13645 let expr_ok = extend_expression_is_term(inner, expression, term);
13646 IdentityWalk::producer(false, expr_ok).combine(inner_walk)
13647 }
13648 PlanNode::Filter { inner, exists, .. } => {
13649 for clause in exists {
13653 let _ = ground_identity_walk(&mut clause.body, variable, term, profile, strings);
13654 }
13655 ground_identity_walk(inner, variable, term, profile, strings)
13656 }
13657 PlanNode::Slice { inner, .. }
13658 | PlanNode::Distinct { inner, .. }
13659 | PlanNode::Sort { inner, .. }
13660 | PlanNode::Group { inner, .. }
13661 | PlanNode::JoinGraphVar { inner, .. } => {
13662 ground_identity_walk(inner, variable, term, profile, strings)
13663 }
13664 PlanNode::NamedGraphs {
13665 variable: bound, ..
13666 } => {
13667 if bound != variable {
13668 return IdentityWalk::vacuous();
13669 }
13670 IdentityWalk::producer(false, false)
13671 }
13672 PlanNode::DomainCounts { head, count, .. } => {
13675 if head == variable || count == variable {
13676 IdentityWalk::producer(false, false)
13677 } else {
13678 IdentityWalk::vacuous()
13679 }
13680 }
13681 PlanNode::HeadCounts {
13682 counted,
13683 group,
13684 count,
13685 ..
13686 } => {
13687 if counted == variable || group.as_ref() == Some(variable) || count == variable {
13688 IdentityWalk::producer(false, false)
13689 } else {
13690 IdentityWalk::vacuous()
13691 }
13692 }
13693 PlanNode::PatternCount {
13694 count,
13695 counted,
13696 subject,
13697 predicate,
13698 object,
13699 ..
13700 } => {
13701 let on_scan = [subject, predicate, object, counted]
13702 .into_iter()
13703 .flatten()
13704 .any(|v| v == variable);
13705 if count == variable || on_scan {
13706 IdentityWalk::producer(false, false)
13707 } else {
13708 IdentityWalk::vacuous()
13709 }
13710 }
13711 PlanNode::SubSelect(sub) => {
13715 if sub.variables.contains(variable) {
13716 IdentityWalk::producer(false, false)
13717 } else {
13718 IdentityWalk::vacuous()
13719 }
13720 }
13721 PlanNode::Unit | PlanNode::NamedGraphExists { .. } => IdentityWalk::vacuous(),
13722 }
13723}
13724
13725fn extend_expression_is_term(
13726 inner: &PlanNode,
13727 expression: &Expression,
13728 term: &EncodedTerm,
13729) -> bool {
13730 match expression {
13731 Expression::NamedNode(node) => EncodedTerm::from(node) == *term,
13732 Expression::Literal(literal) => crate::plugin::encode_user_literal(literal) == *term,
13733 Expression::Variable(source) => unique_ground_term(inner, source).as_ref() == Some(term),
13734 _ => false,
13735 }
13736}
13737
13738fn bind_scan_equality(
13739 scan: &mut ScanOp,
13740 variable: &Variable,
13741 term: &EncodedTerm,
13742 profile: Option<&StatsProfile>,
13743) -> bool {
13744 let mut hit = false;
13745 if scan.graph.as_ref() == Some(variable) {
13746 if !push_graph_terms(
13747 &mut scan.pattern.graph_name,
13748 &mut scan.graph_filter,
13749 std::slice::from_ref(term),
13750 ) {
13751 return false;
13752 }
13753 hit = true;
13754 }
13755 let slots = scan.slot_of(variable);
13756 if slots.is_empty() && !hit {
13757 return false;
13758 }
13759 for slot in slots {
13760 if let Some(existing) = pattern_slot_term(&scan.pattern, slot) {
13761 if existing != term {
13762 return false;
13763 }
13764 scan.record_grounded(variable, slot, profile);
13765 hit = true;
13766 continue;
13767 }
13768 scan.pattern = bind_pattern_slot(scan.pattern.clone(), slot, term);
13769 scan.record_grounded(variable, slot, profile);
13770 hit = true;
13771 }
13772 if hit {
13773 scan.produced_row_count_estimate = estimate_bound_scan(profile, &scan.pattern, 1);
13774 }
13775 hit
13776}
13777
13778fn bind_path_equality(
13779 path: &mut PathOp,
13780 variable: &Variable,
13781 term: &EncodedTerm,
13782 strings: &[(StrHash, String)],
13783) -> bool {
13784 let mut hit = false;
13785 if path.graph.as_ref() == Some(variable) {
13786 if !push_graph_terms(
13787 &mut path.graph_name,
13788 &mut path.graph_filter,
13789 std::slice::from_ref(term),
13790 ) {
13791 return false;
13792 }
13793 hit = true;
13794 }
13795 let Some(end) = path.end_of(variable) else {
13796 if hit {
13797 path.strings.extend(strings.iter().cloned());
13798 recost_path(path);
13799 }
13800 return hit;
13801 };
13802 if matches!(end, PathEnd::Start | PathEnd::Both) {
13803 if let Some(existing) = &path.subject_term {
13804 if existing != term {
13805 return false;
13806 }
13807 hit = true;
13808 } else {
13809 path.subject_term = Some(term.clone());
13810 hit = true;
13811 }
13812 }
13813 if matches!(end, PathEnd::End | PathEnd::Both) {
13814 if let Some(existing) = &path.object_term {
13815 if existing != term {
13816 return false;
13817 }
13818 hit = true;
13819 } else {
13820 path.object_term = Some(term.clone());
13821 hit = true;
13822 }
13823 }
13824 if hit {
13825 path.strings.extend(strings.iter().cloned());
13826 recost_path(path);
13827 }
13828 hit
13829}
13830
13831fn compose_graph_from_sibling(
13836 source: &PlanNode,
13837 target: &mut PlanNode,
13838 hash_keys: &[Variable],
13839 profile: Option<&StatsProfile>,
13840 ground_unique: bool,
13841) {
13842 match target {
13843 PlanNode::Scan(scan) => {
13844 let Some(variable) = scan.graph.clone() else {
13845 return;
13846 };
13847 if !hash_keys.iter().any(|key| key == &variable) {
13848 return;
13849 }
13850 if ground_unique && let Some(term) = unique_ground_term(source, &variable) {
13851 let _ = push_graph_terms(
13852 &mut scan.pattern.graph_name,
13853 &mut scan.graph_filter,
13854 std::slice::from_ref(&term),
13855 );
13856 scan.produced_row_count_estimate = estimate_bound_scan(profile, &scan.pattern, 1);
13857 } else if let Some(terms) = allow_list_from_node(source, &variable) {
13858 let _ = push_graph_terms(
13859 &mut scan.pattern.graph_name,
13860 &mut scan.graph_filter,
13861 terms.as_ref(),
13862 );
13863 scan.produced_row_count_estimate =
13864 join_key_domain_for_node(profile, source, &variable)
13865 .unwrap_or_else(|| source.produced_row_count_estimate())
13866 .max(1);
13867 }
13868 }
13869 PlanNode::Path(path) => {
13870 let Some(variable) = path.graph.clone() else {
13871 return;
13872 };
13873 if !hash_keys.iter().any(|key| key == &variable) {
13874 return;
13875 }
13876 if ground_unique
13877 && let Some((term, strings)) = unique_ground_with_strings(source, &variable)
13878 {
13879 let _ = bind_path_equality(path, &variable, &term, &strings);
13880 } else if let Some(terms) = allow_list_from_node(source, &variable) {
13881 let _ =
13882 push_graph_terms(&mut path.graph_name, &mut path.graph_filter, terms.as_ref());
13883 path.produced_row_count_estimate =
13884 join_key_domain_for_node(profile, source, &variable)
13885 .unwrap_or_else(|| source.produced_row_count_estimate())
13886 .max(1);
13887 }
13888 }
13889 PlanNode::Union { left: a, right: b }
13890 | PlanNode::Join {
13891 left: a, right: b, ..
13892 } => {
13893 compose_graph_from_sibling(source, a, hash_keys, profile, ground_unique);
13894 compose_graph_from_sibling(source, b, hash_keys, profile, ground_unique);
13895 }
13896 PlanNode::LeftJoin {
13897 left: nested_left,
13898 right: nested_right,
13899 ..
13900 } => {
13901 compose_graph_from_sibling(source, nested_left, hash_keys, profile, ground_unique);
13902 compose_graph_from_sibling(source, nested_right, hash_keys, profile, ground_unique);
13903 }
13904 PlanNode::Filter { inner, .. }
13905 | PlanNode::Extend { inner, .. }
13906 | PlanNode::Slice { inner, .. }
13907 | PlanNode::Distinct { inner, .. }
13908 | PlanNode::Sort { inner, .. }
13909 | PlanNode::Group { inner, .. }
13910 | PlanNode::JoinGraphVar { inner, .. } => {
13911 compose_graph_from_sibling(source, inner, hash_keys, profile, ground_unique);
13912 }
13913 _ => {}
13914 }
13915}
13916
13917fn ground_and_recost_broadcasted_arm(
13940 left: &PlanNode,
13941 right: &mut PlanNode,
13942 hash_keys: &[Variable],
13943 profile: Option<&StatsProfile>,
13944) {
13945 match right {
13946 PlanNode::Scan(scan) => {
13947 for variable in hash_keys {
13948 if scan.graph.as_ref() == Some(variable)
13949 && let Some(term) = unique_ground_term(left, variable)
13950 {
13951 let _ = push_graph_terms(
13952 &mut scan.pattern.graph_name,
13953 &mut scan.graph_filter,
13954 std::slice::from_ref(&term),
13955 );
13956 scan.produced_row_count_estimate =
13957 estimate_bound_scan(profile, &scan.pattern, 1);
13958 }
13959 let slots = scan.slot_of(variable);
13960 if slots.is_empty() {
13961 continue;
13962 }
13963 if let Some(term) = unique_ground_term(left, variable) {
13964 for slot in slots {
13965 scan.pattern = bind_pattern_slot(scan.pattern.clone(), slot, &term);
13966 scan.record_grounded(variable, slot, profile);
13967 }
13968 scan.produced_row_count_estimate =
13969 estimate_bound_scan(profile, &scan.pattern, 1);
13970 scan.domain_scan = None;
13975 scan.head_scan = None;
13976 scan.iri_only.retain(|v| v != variable);
13979 }
13980 }
13981 }
13982 PlanNode::Path(path) => {
13983 for variable in hash_keys {
13984 if path.end_of(variable).is_none() && path.graph.as_ref() != Some(variable) {
13985 continue;
13986 }
13987 if path.graph.as_ref() == Some(variable)
13988 && let Some((term, strings)) = unique_ground_with_strings(left, variable)
13989 {
13990 let _ = bind_path_equality(path, variable, &term, &strings);
13991 }
13992 if path.end_of(variable).is_none() {
13993 continue;
13994 }
13995 if let Some((term, strings)) = unique_ground_with_strings(left, variable) {
13996 let _ = bind_path_equality(path, variable, &term, &strings);
13997 }
13998 }
13999 }
14000 PlanNode::Union { left: a, right: b }
14001 | PlanNode::Join {
14002 left: a, right: b, ..
14003 } => {
14004 ground_and_recost_broadcasted_arm(left, a, hash_keys, profile);
14005 ground_and_recost_broadcasted_arm(left, b, hash_keys, profile);
14006 }
14007 PlanNode::LeftJoin {
14008 left: nested_left,
14009 right: nested_right,
14010 hash_keys: nested_keys,
14011 ..
14012 } => {
14013 ground_and_recost_broadcasted_arm(left, nested_left, hash_keys, profile);
14014 ground_and_recost_broadcasted_arm(nested_left, nested_right, nested_keys, profile);
14015 }
14016 PlanNode::CustomNode(op) => {
14017 for variable in hash_keys {
14018 if !op.variables.contains(variable)
14022 || op.pinned.iter().any(|(pinned, _)| pinned == variable)
14023 {
14024 continue;
14025 }
14026 if let Some(term) = unique_ground_term(left, variable) {
14027 op.pinned.push((variable.clone(), term));
14033 if op.variables.len() == 1 {
14042 op.produced_row_count_estimate = 1;
14043 }
14044 }
14045 }
14046 }
14047 PlanNode::Extend { inner, .. }
14048 | PlanNode::Filter { inner, .. }
14049 | PlanNode::Slice { inner, .. }
14050 | PlanNode::Distinct { inner, .. }
14051 | PlanNode::Sort { inner, .. }
14052 | PlanNode::Group { inner, .. }
14053 | PlanNode::JoinGraphVar { inner, .. } => {
14054 ground_and_recost_broadcasted_arm(left, inner, hash_keys, profile);
14055 }
14056 _ => {}
14057 }
14058}
14059
14060fn restamp_broadcast_marks(node: &mut PlanNode, profile: Option<&StatsProfile>) {
14088 match node {
14089 PlanNode::Join {
14090 left,
14091 right,
14092 hash_keys,
14093 probe_key_domains: _,
14094 probe_key_overlap_milli: _,
14095 rhs_hostable_keys: _,
14096 meta,
14097 } => {
14098 if meta.strategy == JoinStrategy::Broadcast && !hash_keys.is_empty() {
14099 claim_broadcast_probe(left, right, hash_keys, profile);
14100 }
14101 restamp_broadcast_marks(left, profile);
14102 restamp_broadcast_marks(right, profile);
14103 }
14104 PlanNode::LeftJoin {
14105 left,
14106 right,
14107 hash_keys,
14108 ..
14109 } => {
14110 claim_broadcast_probe(left, right, hash_keys, profile);
14111 restamp_broadcast_marks(left, profile);
14112 restamp_broadcast_marks(right, profile);
14113 }
14114 PlanNode::Union { left, right } => {
14115 restamp_broadcast_marks(left, profile);
14116 restamp_broadcast_marks(right, profile);
14117 }
14118 PlanNode::CustomNode(op) => {
14119 for child in &mut op.children {
14120 restamp_broadcast_marks(child, profile);
14121 }
14122 }
14123 PlanNode::Filter { inner, exists, .. } => {
14124 restamp_broadcast_marks(inner, profile);
14125 for clause in exists {
14126 restamp_broadcast_marks(&mut clause.body, profile);
14127 }
14128 }
14129 PlanNode::Extend { inner, .. }
14130 | PlanNode::Slice { inner, .. }
14131 | PlanNode::Distinct { inner, .. }
14132 | PlanNode::Sort { inner, .. }
14133 | PlanNode::Group { inner, .. }
14134 | PlanNode::JoinGraphVar { inner, .. } => {
14135 restamp_broadcast_marks(inner, profile);
14136 }
14137 PlanNode::SubSelect(sub) => restamp_broadcast_marks(&mut sub.inner, profile),
14140 _ => {}
14141 }
14142}
14143
14144fn claim_broadcast_probe(
14148 left: &PlanNode,
14149 right: &mut PlanNode,
14150 hash_keys: &[Variable],
14151 profile: Option<&StatsProfile>,
14152) {
14153 match right {
14154 PlanNode::Scan(scan) => {
14155 let Some(variable) = hash_keys.first() else {
14156 return;
14157 };
14158 if scan.broadcasted.is_some() {
14160 return;
14161 }
14162 if scan.grounded.iter().any(|(v, _)| v == variable) {
14166 return;
14167 }
14168 let slots = scan.slot_of(variable);
14169 if slots.is_empty() {
14170 return;
14171 }
14172 if pattern_is_point_lookup(&scan.pattern) {
14173 return;
14174 }
14175 let estimated_pushed_val_count = pushed_val_count(profile, left, variable);
14179 scan.broadcasted = Some((variable.clone(), slots[0]));
14180 let price = estimate_unclamped_scan_rows(profile, scan);
14181 let bound = pushed_scan_return_bound(
14182 estimated_pushed_val_count,
14183 price,
14184 scan,
14185 variable,
14186 profile,
14187 );
14188 scan.produced_row_count_estimate = scan.produced_row_count_estimate.min(bound);
14189 scan.ancestor_push_return_bound = Some(bound);
14196 }
14197 PlanNode::Union { left: a, right: b }
14198 | PlanNode::Join {
14199 left: a, right: b, ..
14200 } => {
14201 claim_broadcast_probe(left, a, hash_keys, profile);
14202 claim_broadcast_probe(left, b, hash_keys, profile);
14203 }
14204 PlanNode::LeftJoin {
14205 left: nested_left,
14206 right: nested_right,
14207 hash_keys: nested_keys,
14208 ..
14209 } => {
14210 claim_broadcast_probe(left, nested_left, hash_keys, profile);
14211 claim_broadcast_probe(nested_left, nested_right, nested_keys, profile);
14212 }
14213 PlanNode::Extend { inner, .. }
14214 | PlanNode::Filter { inner, .. }
14215 | PlanNode::Slice { inner, .. }
14216 | PlanNode::Distinct { inner, .. }
14217 | PlanNode::Sort { inner, .. }
14218 | PlanNode::Group { inner, .. }
14219 | PlanNode::JoinGraphVar { inner, .. } => {
14220 claim_broadcast_probe(left, inner, hash_keys, profile);
14221 }
14222 _ => {}
14226 }
14227}
14228
14229fn restamp_fetch_once(
14277 node: &mut PlanNode,
14278 profile: Option<&StatsProfile>,
14279 ctx: Option<&crate::context::QueryContext>,
14280 sliced: bool,
14281) {
14282 clear_fetch_once_marks(node);
14283 stamp_fetch_once(node, profile, ctx, None, None, sliced);
14284}
14285
14286pub(crate) fn stamp_star_join_shapes(node: &mut PlanNode) {
14316 if let PlanNode::Join {
14317 left,
14318 right,
14319 hash_keys,
14320 probe_key_domains,
14321 probe_key_overlap_milli,
14322 rhs_hostable_keys: _,
14323 meta,
14324 } = node
14325 {
14326 let arms = crate::concurrent_star::detect(
14332 left,
14333 right,
14334 hash_keys,
14335 probe_key_domains,
14336 probe_key_overlap_milli,
14337 meta.strategy,
14338 false,
14339 crate::concurrent_star::eager_star_page_rows(),
14340 )
14341 .map(|star| star.probes.len() as u8);
14342 meta.star_arms = arms;
14343 stamp_star_join_shapes(left);
14344 stamp_star_join_shapes(right);
14345 return;
14346 }
14347 match node {
14353 PlanNode::Join { .. } => unreachable!("handled above"),
14354 PlanNode::LeftJoin { left, right, .. } | PlanNode::Union { left, right } => {
14355 stamp_star_join_shapes(left);
14356 stamp_star_join_shapes(right);
14357 }
14358 PlanNode::CustomNode(op) => {
14359 for child in &mut op.children {
14360 stamp_star_join_shapes(child);
14361 }
14362 }
14363 PlanNode::Filter { inner, exists, .. } => {
14364 stamp_star_join_shapes(inner);
14365 for clause in exists {
14366 stamp_star_join_shapes(&mut clause.body);
14367 }
14368 }
14369 PlanNode::Extend { inner, .. }
14370 | PlanNode::Slice { inner, .. }
14371 | PlanNode::Distinct { inner, .. }
14372 | PlanNode::Sort { inner, .. }
14373 | PlanNode::Group { inner, .. }
14374 | PlanNode::JoinGraphVar { inner, .. } => stamp_star_join_shapes(inner),
14375 PlanNode::SubSelect(sub) => stamp_star_join_shapes(&mut sub.inner),
14376 _ => {}
14377 }
14378}
14379
14380#[derive(Clone, Debug)]
14408struct ContainingPush {
14409 key: Variable,
14410 pushed_val_count: u64,
14411}
14412
14413fn containing_push_basis(driver: &PlanNode, profile: Option<&StatsProfile>) -> u64 {
14447 match driver {
14448 PlanNode::Scan(scan) => match &scan.broadcasted {
14449 Some(_) => estimate_unclamped_scan_rows(profile, scan),
14450 None => scan.produced_row_count_estimate,
14451 },
14452 PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
14453 containing_push_basis(left, profile)
14454 .saturating_mul(containing_push_basis(right, profile))
14455 }
14456 PlanNode::Union { left, right } => containing_push_basis(left, profile)
14457 .saturating_add(containing_push_basis(right, profile)),
14458 PlanNode::Filter { inner, .. }
14459 | PlanNode::Extend { inner, .. }
14460 | PlanNode::Slice { inner, .. }
14461 | PlanNode::Distinct { inner, .. }
14462 | PlanNode::Sort { inner, .. }
14463 | PlanNode::Group { inner, .. }
14464 | PlanNode::JoinGraphVar { inner, .. } => containing_push_basis(inner, profile),
14465 _ => driver.produced_row_count_estimate(),
14466 }
14467}
14468
14469fn containing_push_driver_bound(
14491 profile: Option<&StatsProfile>,
14492 driver: &PlanNode,
14493 pushed_key: &Variable,
14494 pushed_val_count: u64,
14495) -> Option<u64> {
14496 let domain = join_key_domain_for_node(profile, driver, pushed_key);
14497 let basis = containing_push_basis(driver, profile);
14498 pushed_return_bound_core(pushed_val_count, basis, domain)
14499}
14500
14501fn child_push_from_shape(
14512 profile: Option<&StatsProfile>,
14513 driver: &PlanNode,
14514 probe: &PlanNode,
14515 ctx: Option<&crate::context::QueryContext>,
14516 shape: &SeatProbeShape,
14517) -> Option<ContainingPush> {
14518 if shape.pages == 0
14519 || (shape.coverage_drop_allowed && shape.keys.iter().all(|(covered, _, _, _)| *covered))
14520 {
14521 return None;
14522 }
14523 let key = shape.broadcast_key.clone()?;
14524 let page_rows = seat_page_rows(driver, probe, ctx);
14531 let pushed_val_count = pushed_val_count(profile, driver, &key).min(page_rows);
14539 (pushed_val_count > 0).then_some(ContainingPush {
14540 key,
14541 pushed_val_count,
14542 })
14543}
14544
14545fn stamp_fetch_once(
14563 node: &mut PlanNode,
14564 profile: Option<&StatsProfile>,
14565 ctx: Option<&crate::context::QueryContext>,
14566 containing: Option<&ContainingPush>,
14567 star_ctx: Option<u8>,
14568 sliced: bool,
14569) {
14570 match node {
14571 PlanNode::Join {
14572 left,
14573 right,
14574 hash_keys,
14575 meta,
14576 ..
14577 } => {
14578 let engine_on = crate::context::parallel_probe_engine_enabled();
14598 let star_arms = if engine_on {
14599 meta.star_arms.or(star_ctx)
14600 } else {
14601 None
14602 };
14603 let batchable = engine_on
14604 && !sliced
14605 && crate::query::parallel_probe::scan_hosts_broadcast_key(right, hash_keys);
14606 let batch_arms = if sliced {
14613 None
14614 } else if batchable {
14615 star_arms.or(Some(1))
14616 } else {
14617 star_arms
14618 };
14619 let driver_bound = containing
14633 .filter(|push| probe_scan_has_key(left, &push.key))
14634 .and_then(|push| {
14635 containing_push_driver_bound(profile, left, &push.key, push.pushed_val_count)
14636 });
14637 if !hash_keys.is_empty()
14638 && let Some(scan) = right.as_scan()
14639 && fetch_once_stampable(scan)
14640 && hash_keys
14654 .iter()
14655 .any(|key| scan.first_slot_of(key).is_some())
14656 {
14657 let produced = scan.produced_row_count_estimate;
14669 let whole_read_rows = estimate_unclamped_scan_rows(profile, scan);
14670 let shape = seat_probe_shape(profile, left, right, hash_keys, ctx, driver_bound);
14671 if shape.coverage_drop_allowed
14688 && shape.keys.iter().all(|(covered, _, _, _)| *covered)
14689 {
14690 if let Some(ctx) = ctx {
14691 ctx.log(
14692 crate::LogLevel::Debug,
14693 &format!(
14694 "fetch-once-stamp: {} pages={} produced(clamped)={} whole_read_rows={} -> skipped (all-dropped probe: the probe executes once via the built slot; no build decision)",
14695 crate::explain::scan_pattern_tag(scan),
14696 shape.pages,
14697 produced,
14698 whole_read_rows
14699 ),
14700 );
14701 }
14702 } else {
14703 let mirror_road = probe_side_mirror_road(
14713 profile,
14714 right,
14715 hash_keys,
14716 &shape.keys,
14717 shape.coverage_drop_allowed,
14718 containing,
14719 );
14720 let (seeks_per_page, matched_per_page) = match mirror_road {
14721 Some(road) => (road.seeks, road.rows),
14722 None => probe_broadcast_price(
14723 whole_read_rows,
14724 &shape.keys,
14725 shape.coverage_drop_allowed,
14726 ),
14727 };
14728 let matched_is_bound = mirror_road.is_none()
14734 && first_broadcast_key(&shape.keys, shape.coverage_drop_allowed)
14735 .is_some_and(|(_, probe_domain, _)| probe_domain == 0);
14736 let count_walk_build_once =
14737 bound_constraint_count_scan(scan) && shape.pages > 1;
14738 let verdict = if count_walk_build_once {
14739 FetchOnceVerdict::FetchOnce
14752 } else if crate::query::tunables::calibration_force_probe() {
14753 FetchOnceVerdict::PerPage
14765 } else {
14766 fetch_once_verdict_now(
14767 shape.pages,
14768 seeks_per_page,
14769 matched_per_page,
14770 whole_read_rows,
14771 whole_read_rows_known(profile, scan),
14772 shape.driver_domains_known,
14773 matched_is_bound,
14774 probe_seek_concurrency_milli(
14775 batch_arms.is_some(),
14776 shape.pages,
14777 seeks_per_page,
14778 crate::context::query_fetch_concurrency() as u64,
14779 ),
14780 )
14781 };
14782 let push_bound_tag = driver_bound
14790 .map(|bound| format!(" push_bound={bound}"))
14791 .unwrap_or_default();
14792 if let Some(ctx) = ctx {
14793 ctx.log(
14794 crate::LogLevel::Debug,
14795 &format!(
14796 "fetch-once-stamp: {} pages={}{} seeks/page={} matched/page={} produced(clamped)={} whole_read_rows={} matched_bound={} arm_known={} domains_known={} -> {:?}{}",
14797 crate::explain::scan_pattern_tag(scan),
14798 shape.pages,
14799 push_bound_tag,
14800 seeks_per_page,
14801 matched_per_page,
14802 produced,
14803 whole_read_rows,
14804 matched_is_bound,
14805 whole_read_rows_known(profile, scan),
14806 shape.driver_domains_known,
14807 verdict,
14808 if count_walk_build_once {
14809 " (bound-constraint count walk: one walk, built once)"
14810 } else {
14811 ""
14812 }
14813 ),
14814 );
14815 }
14816 if verdict == FetchOnceVerdict::FetchOnce {
14822 right.as_scan_mut().expect("as_scan held").fetch_once =
14823 Some(whole_read_rows);
14824 }
14825 }
14826 }
14827 let child_containing = containing.cloned().or_else(|| {
14842 if hash_keys.is_empty() || right.as_scan().is_some() {
14843 return None;
14844 }
14845 let shape = seat_probe_shape(profile, left, right, hash_keys, ctx, driver_bound);
14846 child_push_from_shape(profile, left, right, ctx, &shape)
14847 });
14848 stamp_fetch_once(left, profile, ctx, containing, star_arms, sliced);
14849 stamp_fetch_once(right, profile, ctx, child_containing.as_ref(), None, sliced);
14850 }
14851 PlanNode::LeftJoin { left, right, .. } => {
14852 stamp_fetch_once(left, profile, ctx, containing, None, sliced);
14864 stamp_fetch_once(right, profile, ctx, containing, None, sliced);
14865 }
14866 PlanNode::Union { left, right } => {
14867 stamp_fetch_once(left, profile, ctx, containing, None, sliced);
14868 stamp_fetch_once(right, profile, ctx, containing, None, sliced);
14869 }
14870 PlanNode::CustomNode(op) => {
14871 for child in &mut op.children {
14876 stamp_fetch_once(child, profile, ctx, None, None, sliced);
14877 }
14878 }
14879 PlanNode::Filter { inner, exists, .. } => {
14880 stamp_fetch_once(inner, profile, ctx, containing, None, sliced);
14881 for clause in exists {
14884 stamp_fetch_once(&mut clause.body, profile, ctx, None, None, sliced);
14885 }
14886 }
14887 PlanNode::Slice { inner, .. } => {
14891 stamp_fetch_once(inner, profile, ctx, containing, None, true);
14892 }
14893 PlanNode::Extend { inner, .. }
14894 | PlanNode::Distinct { inner, .. }
14895 | PlanNode::Sort { inner, .. }
14896 | PlanNode::Group { inner, .. }
14897 | PlanNode::JoinGraphVar { inner, .. } => {
14898 stamp_fetch_once(inner, profile, ctx, containing, None, sliced);
14899 }
14900 PlanNode::SubSelect(sub) => {
14907 stamp_fetch_once(&mut sub.inner, profile, ctx, None, None, sliced);
14908 }
14909 _ => {}
14910 }
14911}
14912
14913fn count_stamps_after_restamp(node: &PlanNode) -> usize {
14917 match node {
14918 PlanNode::Scan(scan) => usize::from(scan.fetch_once.is_some()),
14919 PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
14920 count_stamps_after_restamp(left) + count_stamps_after_restamp(right)
14921 }
14922 PlanNode::Union { left, right } => {
14923 count_stamps_after_restamp(left) + count_stamps_after_restamp(right)
14924 }
14925 PlanNode::CustomNode(op) => op.children.iter().map(count_stamps_after_restamp).sum(),
14926 PlanNode::Filter { inner, exists, .. } => {
14927 count_stamps_after_restamp(inner)
14928 + exists
14929 .iter()
14930 .map(|clause| count_stamps_after_restamp(&clause.body))
14931 .sum::<usize>()
14932 }
14933 PlanNode::Extend { inner, .. }
14934 | PlanNode::Slice { inner, .. }
14935 | PlanNode::Distinct { inner, .. }
14936 | PlanNode::Sort { inner, .. }
14937 | PlanNode::Group { inner, .. }
14938 | PlanNode::JoinGraphVar { inner, .. } => count_stamps_after_restamp(inner),
14939 PlanNode::SubSelect(sub) => count_stamps_after_restamp(&sub.inner),
14940 _ => 0,
14941 }
14942}
14943
14944fn clear_fetch_once_marks(node: &mut PlanNode) {
14945 match node {
14946 PlanNode::Scan(scan) => scan.fetch_once = None,
14947 PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
14948 clear_fetch_once_marks(left);
14949 clear_fetch_once_marks(right);
14950 }
14951 PlanNode::Union { left, right } => {
14952 clear_fetch_once_marks(left);
14953 clear_fetch_once_marks(right);
14954 }
14955 PlanNode::CustomNode(op) => {
14956 for child in &mut op.children {
14957 clear_fetch_once_marks(child);
14958 }
14959 }
14960 PlanNode::Filter { inner, exists, .. } => {
14961 clear_fetch_once_marks(inner);
14962 for clause in exists {
14963 clear_fetch_once_marks(&mut clause.body);
14964 }
14965 }
14966 PlanNode::Extend { inner, .. }
14967 | PlanNode::Slice { inner, .. }
14968 | PlanNode::Distinct { inner, .. }
14969 | PlanNode::Sort { inner, .. }
14970 | PlanNode::Group { inner, .. }
14971 | PlanNode::JoinGraphVar { inner, .. } => clear_fetch_once_marks(inner),
14972 PlanNode::SubSelect(sub) => clear_fetch_once_marks(&mut sub.inner),
14973 _ => {}
14974 }
14975}
14976
14977fn unpushed_row_count_estimate(
14995 profile: Option<&StatsProfile>,
14996 node: &PlanNode,
14997 budget: &mut u64,
14998) -> Option<u64> {
14999 if *budget == 0 {
15000 return None;
15001 }
15002 *budget -= 1;
15003 match node {
15004 PlanNode::Scan(scan) => {
15005 if !whole_read_rows_known(profile, scan) {
15006 return None;
15007 }
15008 Some(estimate_unclamped_scan_rows(profile, scan))
15009 }
15010 PlanNode::Path(path) => Some(estimate_path_size(
15011 path.subject_term.is_some(),
15012 &path.path,
15013 path.object_term.is_some(),
15014 )),
15015 PlanNode::Union { left, right } => Some(
15016 unpushed_row_count_estimate(profile, left, budget)?
15017 .saturating_add(unpushed_row_count_estimate(profile, right, budget)?),
15018 ),
15019 PlanNode::Join {
15020 left,
15021 right,
15022 hash_keys,
15023 ..
15024 } => {
15025 let left_rows = unpushed_row_count_estimate(profile, left, budget)?;
15026 let right_rows = unpushed_row_count_estimate(profile, right, budget)?;
15027 if hash_keys.is_empty() {
15028 return Some(left_rows.saturating_mul(right_rows).max(1));
15029 }
15030 let domains = hash_keys
15031 .iter()
15032 .map(|key| {
15033 (
15034 join_key_domain_for_node(profile, left, key),
15035 join_key_domain_for_node(profile, right, key),
15036 )
15037 })
15038 .collect::<Vec<_>>();
15039 Some(estimate_join_rows_multi(left_rows, right_rows, &domains))
15040 }
15041 PlanNode::LeftJoin {
15042 left,
15043 right,
15044 hash_keys,
15045 ..
15046 } => {
15047 let left_rows = unpushed_row_count_estimate(profile, left, budget)?;
15048 let right_rows = unpushed_row_count_estimate(profile, right, budget)?;
15049 Some(estimate_left_join_rows_product(
15050 left_rows, left, right, hash_keys, right_rows, profile,
15051 ))
15052 }
15053 PlanNode::Filter {
15054 inner,
15055 early,
15056 residual,
15057 exists,
15058 ..
15059 } => {
15060 let inner_rows = unpushed_row_count_estimate(profile, inner, budget)?;
15061 Some(apply_filter_selectivity(
15062 inner_rows,
15063 early.as_ref(),
15064 residual.as_ref(),
15065 exists,
15066 ))
15067 }
15068 PlanNode::Extend { inner, .. }
15069 | PlanNode::Slice { inner, .. }
15070 | PlanNode::Distinct { inner, .. }
15071 | PlanNode::Sort { inner, .. }
15072 | PlanNode::Group { inner, .. }
15073 | PlanNode::JoinGraphVar { inner, .. } => {
15074 unpushed_row_count_estimate(profile, inner, budget)
15075 }
15076 _ => Some(node.produced_row_count_estimate()),
15077 }
15078}
15079
15080fn unpushed_read_rows(
15092 profile: Option<&StatsProfile>,
15093 node: &PlanNode,
15094 budget: &mut u64,
15095) -> Option<u64> {
15096 if *budget == 0 {
15097 return None;
15098 }
15099 *budget -= 1;
15100 match node {
15101 PlanNode::Scan(scan) => {
15102 if !whole_read_rows_known(profile, scan) {
15103 return None;
15104 }
15105 Some(estimate_unclamped_scan_rows(profile, scan))
15106 }
15107 PlanNode::Path(path) => Some(estimate_path_size(
15108 path.subject_term.is_some(),
15109 &path.path,
15110 path.object_term.is_some(),
15111 )),
15112 PlanNode::Union { left, right } => Some(
15113 unpushed_read_rows(profile, left, budget)?
15114 .saturating_add(unpushed_read_rows(profile, right, budget)?),
15115 ),
15116 PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => Some(
15117 unpushed_read_rows(profile, left, budget)?
15118 .saturating_add(unpushed_read_rows(profile, right, budget)?),
15119 ),
15120 PlanNode::Filter { inner, exists, .. } if exists.is_empty() => {
15121 unpushed_read_rows(profile, inner, budget)
15122 }
15123 PlanNode::Filter { .. } => None,
15124 PlanNode::Extend { inner, .. }
15125 | PlanNode::Slice { inner, .. }
15126 | PlanNode::Distinct { inner, .. }
15127 | PlanNode::Sort { inner, .. }
15128 | PlanNode::Group { inner, .. }
15129 | PlanNode::JoinGraphVar { inner, .. } => unpushed_read_rows(profile, inner, budget),
15130 PlanNode::CustomNode(op) => Some(op.sweep_cost().unwrap_or(op.produced_row_count_estimate)),
15131 PlanNode::SubSelect(sub) => unpushed_read_rows(profile, &sub.inner, budget),
15132 PlanNode::Values(_) | PlanNode::Unit => Some(0),
15133 _ => None,
15134 }
15135}
15136
15137#[derive(Debug, Clone)]
15144pub(crate) struct AncestorPushKey {
15145 key: Variable,
15146 list: u64,
15147}
15148
15149fn add_ancestor_push(pushes: &mut Vec<AncestorPushKey>, key: &Variable, list: u64) {
15153 if list == 0 {
15154 return;
15155 }
15156 if let Some(existing) = pushes.iter_mut().find(|push| &push.key == key) {
15157 existing.list = existing.list.min(list);
15158 } else {
15159 pushes.push(AncestorPushKey {
15160 key: key.clone(),
15161 list,
15162 });
15163 }
15164}
15165
15166#[derive(Debug, Clone, Copy)]
15168enum SemiBuildPushSource<'a> {
15169 AncestorPushesOnly,
15173 #[allow(dead_code)]
15177 AncestorPushesAndDriverDomain { key: &'a Variable, domain: u64 },
15178}
15179
15180impl SemiBuildPushSource<'_> {
15181 fn label(&self) -> &'static str {
15182 match self {
15183 Self::AncestorPushesOnly => "ancestor-pushes-only",
15184 Self::AncestorPushesAndDriverDomain { .. } => "ancestor-pushes-and-driver-domain",
15185 }
15186 }
15187}
15188
15189#[derive(Debug, Clone, Copy)]
15194struct SemiBuildDrainEstimate {
15195 read_rows: u64,
15198 pushed_terms: u64,
15201 chunk_fetches: u64,
15204 filter_eval_milli: u64,
15208}
15209
15210fn estimate_semi_build_drain(
15242 profile: Option<&StatsProfile>,
15243 node: &PlanNode,
15244 source: SemiBuildPushSource<'_>,
15245 ancestors: &[AncestorPushKey],
15246 budget: &mut u64,
15247) -> Option<SemiBuildDrainEstimate> {
15248 if *budget == 0 {
15249 return None;
15250 }
15251 *budget -= 1;
15252 match node {
15253 PlanNode::Scan(scan) => {
15254 if scan.has_specialized_rpc() || !whole_read_rows_known(profile, scan) {
15255 return None;
15256 }
15257 let whole = estimate_unclamped_scan_rows(profile, scan);
15258 let driver = match source {
15266 SemiBuildPushSource::AncestorPushesAndDriverDomain { key, domain }
15267 if !scan.slot_of(key).is_empty() || scan.graph.as_ref() == Some(key) =>
15268 {
15269 Some((key, domain))
15270 }
15271 _ => None,
15272 };
15273 let effective = ancestors
15274 .iter()
15275 .find(|ancestor| {
15276 !scan.slot_of(&ancestor.key).is_empty()
15277 || scan.graph.as_ref() == Some(&ancestor.key)
15278 })
15279 .map(|ancestor| {
15280 let domain =
15281 join_key_domain_for(profile, scan, std::slice::from_ref(&ancestor.key))
15282 .unwrap_or(0);
15283 let list = match driver {
15284 Some((driver_key, driver_domain)) if ancestor.key == *driver_key => {
15285 ancestor.list.min(driver_domain)
15286 }
15287 _ => ancestor.list,
15288 };
15289 (list, domain)
15290 })
15291 .or_else(|| {
15292 driver.map(|(driver_key, driver_domain)| {
15293 let domain =
15294 join_key_domain_for(profile, scan, std::slice::from_ref(driver_key))
15295 .unwrap_or(0);
15296 (driver_domain, domain)
15297 })
15298 });
15299 let Some((list, domain)) = effective else {
15300 return Some(SemiBuildDrainEstimate {
15301 read_rows: whole,
15302 pushed_terms: 0,
15303 chunk_fetches: 0,
15304 filter_eval_milli: 0,
15305 });
15306 };
15307 let matched = if domain > 0 && list < domain {
15308 u64::try_from(
15309 u128::from(whole)
15310 .saturating_mul(u128::from(list))
15311 .saturating_div(u128::from(domain)),
15312 )
15313 .unwrap_or(whole)
15314 } else {
15315 whole
15316 };
15317 Some(SemiBuildDrainEstimate {
15318 read_rows: matched,
15319 pushed_terms: list,
15320 chunk_fetches: list.div_ceil(PUSHDOWN_TERMS_LIMIT),
15321 filter_eval_milli: 0,
15322 })
15323 }
15324 PlanNode::Filter {
15325 inner,
15326 early,
15327 residual,
15328 exists,
15329 ..
15330 } if exists.is_empty() => {
15331 let inner = estimate_semi_build_drain(profile, inner, source, ancestors, budget)?;
15332 let filter_eval_milli = inner
15333 .read_rows
15334 .saturating_mul(filter_row_cost_milli(early.as_ref(), residual.as_ref()));
15335 Some(SemiBuildDrainEstimate {
15336 filter_eval_milli: inner.filter_eval_milli.saturating_add(filter_eval_milli),
15337 ..inner
15338 })
15339 }
15340 PlanNode::Filter { .. } => None,
15343 PlanNode::Union { left, right } => {
15344 let left = estimate_semi_build_drain(profile, left, source, ancestors, budget)?;
15345 let right = estimate_semi_build_drain(profile, right, source, ancestors, budget)?;
15346 Some(SemiBuildDrainEstimate {
15347 read_rows: left.read_rows.saturating_add(right.read_rows),
15348 pushed_terms: left.pushed_terms.saturating_add(right.pushed_terms),
15349 chunk_fetches: left.chunk_fetches.saturating_add(right.chunk_fetches),
15350 filter_eval_milli: left
15351 .filter_eval_milli
15352 .saturating_add(right.filter_eval_milli),
15353 })
15354 }
15355 PlanNode::Extend { inner, .. }
15356 | PlanNode::Slice { inner, .. }
15357 | PlanNode::Distinct { inner, .. }
15358 | PlanNode::Sort { inner, .. }
15359 | PlanNode::Group { inner, .. }
15360 | PlanNode::JoinGraphVar { inner, .. } => {
15361 estimate_semi_build_drain(profile, inner, source, ancestors, budget)
15362 }
15363 _ => None,
15364 }
15365}
15366
15367fn subtree_has_specialized_scan(node: &PlanNode) -> bool {
15371 match node {
15372 PlanNode::Scan(scan) => scan.has_specialized_rpc(),
15373 PlanNode::Join { left, right, .. }
15374 | PlanNode::LeftJoin { left, right, .. }
15375 | PlanNode::Union { left, right, .. } => {
15376 subtree_has_specialized_scan(left) || subtree_has_specialized_scan(right)
15377 }
15378 PlanNode::Filter { inner, exists, .. } => {
15379 subtree_has_specialized_scan(inner)
15380 || exists
15381 .iter()
15382 .any(|clause| subtree_has_specialized_scan(&clause.body))
15383 }
15384 PlanNode::CustomNode(op) => op.children.iter().any(subtree_has_specialized_scan),
15385 PlanNode::Extend { inner, .. }
15386 | PlanNode::Slice { inner, .. }
15387 | PlanNode::Distinct { inner, .. }
15388 | PlanNode::Sort { inner, .. }
15389 | PlanNode::Group { inner, .. }
15390 | PlanNode::JoinGraphVar { inner, .. } => subtree_has_specialized_scan(inner),
15391 PlanNode::SubSelect(sub) => subtree_has_specialized_scan(&sub.inner),
15392 _ => false,
15393 }
15394}
15395
15396#[derive(Debug, Clone, Copy)]
15409struct SemiBuildPrice {
15410 pages: u64,
15413 driver_rows: u64,
15414 page_rows: u64,
15415 seeks_per_page: u64,
15416 matched_per_page: u64,
15417 per_page_filter_cost_milli: u64,
15419 per_page_price_milli: u128,
15420 build_read_rows: u64,
15422 build_source: &'static str,
15423 build_seek_terms: u64,
15424 build_rpcs: u64,
15425 build_output_rows: u64,
15426 build_keys: u64,
15430 build_price_milli: u128,
15431 build_bar_milli: u128,
15432 build_filter_cost_milli: u64,
15434 unpushed_read_rows: Option<u64>,
15438 unpushed_output_rows: Option<u64>,
15439 ancestor_keys: usize,
15441 driver_domain: u64,
15443 probe_domain_known: bool,
15444}
15445
15446fn option_rows(rows: Option<u64>) -> String {
15448 rows.map_or_else(|| "unknown".to_owned(), |rows| rows.to_string())
15449}
15450
15451impl SemiBuildPrice {
15452 fn summary(&self) -> String {
15453 format!(
15454 "pages={} driver_rows={} page_rows={} per_page_seeks={} per_page_matched={} \
15455 per_page_filter_cost={} per_page_price={} build_read={} build_source={} \
15456 build_seeks={} build_rpcs={} \
15457 build_output={} build_keys={} filter_cost={} build_price={} build_bar={} \
15458 unpushed_read={} unpushed_out={} ancestors={} \
15459 driver_domain={} probe_domain_known={}",
15460 self.pages,
15461 self.driver_rows,
15462 self.page_rows,
15463 self.seeks_per_page,
15464 self.matched_per_page,
15465 self.per_page_filter_cost_milli / 1000,
15466 self.per_page_price_milli / 1000,
15467 self.build_read_rows,
15468 self.build_source,
15469 self.build_seek_terms,
15470 self.build_rpcs,
15471 self.build_output_rows,
15472 self.build_keys,
15473 self.build_filter_cost_milli / 1000,
15474 self.build_price_milli / 1000,
15475 self.build_bar_milli / 1000,
15476 option_rows(self.unpushed_read_rows),
15477 option_rows(self.unpushed_output_rows),
15478 self.ancestor_keys,
15479 self.driver_domain,
15480 self.probe_domain_known,
15481 )
15482 }
15483}
15484
15485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15487enum SemiBuildVerdict {
15488 Build,
15489 PerPage,
15490}
15491
15492fn semi_build_verdict(price: &SemiBuildPrice) -> SemiBuildVerdict {
15500 if price.pages == 0 || price.build_read_rows == 0 {
15501 return SemiBuildVerdict::PerPage;
15502 }
15503 if price.per_page_price_milli >= price.build_bar_milli {
15504 SemiBuildVerdict::Build
15505 } else {
15506 SemiBuildVerdict::PerPage
15507 }
15508}
15509
15510#[derive(Debug, Clone)]
15514enum SemiRefusal {
15515 StarArm,
15516 SlicedSubtree,
15517 MultiKey(usize),
15518 KeyNotBoundLeft(Variable),
15519 KeyNotBoundRight(Variable),
15520 SpecializedScan,
15521 Payload,
15522 CountStar,
15523 RowMultiplicity,
15524 BuildEstimateUnknown,
15525 DriverDomainUnknown,
15526 PerPage(Box<SemiBuildPrice>),
15527}
15528
15529impl SemiRefusal {
15530 fn describe(&self) -> String {
15531 match self {
15532 Self::StarArm => "star arm".to_owned(),
15533 Self::SlicedSubtree => "the Slice path runs through OpenNode".to_owned(),
15534 Self::MultiKey(count) => format!("{count} join keys (first cut admits one)"),
15535 Self::KeyNotBoundLeft(key) => {
15536 format!("key {key} is not always bound on the left")
15537 }
15538 Self::KeyNotBoundRight(key) => {
15539 format!("key {key} is not always bound on the right")
15540 }
15541 Self::SpecializedScan => "specialized scan in the right subtree".to_owned(),
15542 Self::Payload => "right payload above the join".to_owned(),
15543 Self::CountStar => "plain COUNT(*) above the join".to_owned(),
15544 Self::RowMultiplicity => "row multiplicity is observed above the join".to_owned(),
15545 Self::BuildEstimateUnknown => "build read estimate unknown".to_owned(),
15546 Self::DriverDomainUnknown => "driver key domain unknown".to_owned(),
15547 Self::PerPage(price) => format!("per-page road is cheaper ({})", price.summary()),
15548 }
15549 }
15550}
15551
15552#[allow(clippy::too_many_arguments)]
15576fn semi_join_admission(
15577 left: &PlanNode,
15578 right: &PlanNode,
15579 hash_keys: &[Variable],
15580 meta: &JoinMeta,
15581 facts: &SemiGateFacts,
15582 ancestors: &[AncestorPushKey],
15583 sliced: bool,
15584 profile: Option<&StatsProfile>,
15585 ctx: Option<&crate::context::QueryContext>,
15586) -> Result<SemiBuildPrice, SemiRefusal> {
15587 if meta.star_arms.is_some() {
15588 return Err(SemiRefusal::StarArm);
15593 }
15594 if sliced {
15595 return Err(SemiRefusal::SlicedSubtree);
15596 }
15597 if hash_keys.len() != 1 {
15598 return Err(SemiRefusal::MultiKey(hash_keys.len()));
15599 }
15600 let key = &hash_keys[0];
15601 if !left.output_vars().is_always_bound(key) {
15602 return Err(SemiRefusal::KeyNotBoundLeft(key.clone()));
15603 }
15604 if !right.output_vars().is_always_bound(key) {
15605 return Err(SemiRefusal::KeyNotBoundRight(key.clone()));
15606 }
15607 if subtree_has_specialized_scan(right) {
15608 return Err(SemiRefusal::SpecializedScan);
15609 }
15610 if facts.count_star {
15611 return Err(SemiRefusal::CountStar);
15612 }
15613 if facts.right_payload {
15614 return Err(SemiRefusal::Payload);
15615 }
15616 if facts.row_multiplicity_observed {
15617 return Err(SemiRefusal::RowMultiplicity);
15618 }
15619 let driver_domain =
15620 join_key_domain_for_node(profile, left, key).ok_or(SemiRefusal::DriverDomainUnknown)?;
15621 let driver_rows = driver_whole_read_rows(left, hash_keys, profile);
15622 let page_rows = seat_page_rows(left, right, ctx).max(1);
15623 let pages = driver_rows.div_ceil(page_rows);
15624 let clustered = clustered_page_distinct(driver_rows, driver_domain, page_rows);
15629 let mixed = mixed_page_distinct(driver_domain, page_rows, driver_rows);
15630 let page_val_count = if left.as_scan().is_some() {
15631 clustered
15632 } else {
15633 clustered.max(mixed)
15634 };
15635 let probe_domain = join_key_domain_for_node(profile, right, key);
15636 let probe_domain_known = probe_domain.is_some();
15637 let mut page_budget = SUBTREE_WALK_NODE_BUDGET;
15638 let mut page_filter_cost_milli = 0u64;
15639 let page = subtree_page_cost_with_filter(
15640 profile,
15641 right,
15642 &ContainingPush {
15643 key: key.clone(),
15644 pushed_val_count: page_val_count,
15645 },
15646 ctx,
15647 &mut page_budget,
15648 &mut page_filter_cost_milli,
15649 );
15650 let matched_per_page = page.rows.saturating_sub(page_filter_cost_milli / 1000);
15654 let page_batched = crate::context::parallel_probe_engine_enabled()
15658 && !sliced
15659 && crate::query::parallel_probe::scan_hosts_broadcast_key(right, hash_keys);
15660 let page_seek_concurrency = probe_seek_concurrency_milli(
15661 page_batched,
15662 pages,
15663 page.seeks,
15664 crate::context::query_fetch_concurrency() as u64,
15665 );
15666 let matched_is_bound = !probe_domain_known;
15670 let per_page_price_milli = fetch_once_price_milli(
15671 pages,
15672 page.seeks,
15673 matched_per_page,
15674 matched_is_bound,
15675 crate::query::tunables::fetch_once_seek_equiv_milli(),
15676 crate::query::tunables::fetch_once_matched_row_equiv_milli(),
15677 crate::query::tunables::fetch_once_matched_bound_equiv_milli(),
15678 page_seek_concurrency,
15679 )
15680 .saturating_add(u128::from(pages).saturating_mul(u128::from(page_filter_cost_milli)));
15681 let mut build_budget = SUBTREE_WALK_NODE_BUDGET;
15686 let build_source = SemiBuildPushSource::AncestorPushesOnly;
15687 let build =
15688 estimate_semi_build_drain(profile, right, build_source, ancestors, &mut build_budget)
15689 .ok_or(SemiRefusal::BuildEstimateUnknown)?;
15690 let build_seek_concurrency =
15691 if crate::context::parallel_probe_engine_enabled() && build.chunk_fetches >= 2 {
15692 let funded = (crate::context::query_fetch_concurrency() as u64)
15693 .saturating_mul(1000)
15694 .min(build.chunk_fetches.saturating_mul(1000));
15695 crate::query::tunables::probe_seek_concurrency_realized_milli(funded) as u128
15696 } else {
15697 1000
15698 };
15699 let build_pass_milli = fetch_once_price_milli(
15703 1,
15704 build.pushed_terms,
15705 build.read_rows,
15706 false,
15707 crate::query::tunables::fetch_once_seek_equiv_milli(),
15708 crate::query::tunables::fetch_once_matched_row_equiv_milli(),
15709 crate::query::tunables::fetch_once_matched_bound_equiv_milli(),
15710 build_seek_concurrency,
15711 )
15712 .saturating_add(u128::from(build.filter_eval_milli));
15713 let build_output_rows = right
15719 .produced_row_count_estimate()
15720 .min(build.read_rows)
15721 .max(1);
15722 let build_keys = join_key_domain_for_node(profile, right, key)
15723 .unwrap_or(build_output_rows)
15724 .min(build_output_rows)
15725 .max(1);
15726 let build_price_milli =
15727 build_pass_milli.saturating_add(u128::from(build_output_rows).saturating_mul(u128::from(
15728 crate::query::tunables::SEMI_KEY_SET_ROW_EQUIV_MILLI,
15729 )));
15730 let build_bar_milli = build_price_milli
15731 .saturating_mul(u128::from(crate::query::tunables::SEMI_BUILD_MARGIN_MILLI))
15732 .saturating_div(1000);
15733 let mut unpushed_read_budget = SUBTREE_WALK_NODE_BUDGET;
15736 let unpushed_read_rows = unpushed_read_rows(profile, right, &mut unpushed_read_budget);
15737 let mut unpushed_output_budget = SUBTREE_WALK_NODE_BUDGET;
15738 let unpushed_output_rows =
15739 unpushed_row_count_estimate(profile, right, &mut unpushed_output_budget);
15740 debug_assert!(
15741 unpushed_read_rows.is_none_or(|unpushed| build.read_rows <= unpushed),
15742 "the domain-pushed build read must not exceed the fully unpushed read: \
15743 build={} unpushed={:?}",
15744 build.read_rows,
15745 unpushed_read_rows,
15746 );
15747 let ancestor_keys = ancestors
15748 .iter()
15749 .filter(|push| probe_scan_has_key(right, &push.key))
15750 .count();
15751 let price = SemiBuildPrice {
15752 pages,
15753 driver_rows,
15754 page_rows,
15755 seeks_per_page: page.seeks,
15756 matched_per_page,
15757 per_page_filter_cost_milli: page_filter_cost_milli,
15758 per_page_price_milli,
15759 build_read_rows: build.read_rows,
15760 build_source: build_source.label(),
15761 build_seek_terms: build.pushed_terms,
15762 build_rpcs: build.chunk_fetches,
15763 build_output_rows,
15764 build_keys,
15765 build_price_milli,
15766 build_bar_milli,
15767 build_filter_cost_milli: build.filter_eval_milli,
15768 unpushed_read_rows,
15769 unpushed_output_rows,
15770 ancestor_keys,
15771 driver_domain,
15772 probe_domain_known,
15773 };
15774 match semi_build_verdict(&price) {
15775 SemiBuildVerdict::Build => Ok(price),
15776 SemiBuildVerdict::PerPage => Err(SemiRefusal::PerPage(Box::new(price))),
15777 }
15778}
15779
15780pub(crate) fn semi_gate_candidate(hash_keys: &[Variable], meta: &JoinMeta) -> bool {
15786 !hash_keys.is_empty() && !matches!(meta.strategy, JoinStrategy::Semi | JoinStrategy::SemiScan)
15787}
15788
15789pub(crate) fn record_semi_gate_facts(
15796 right: &PlanNode,
15797 hash_keys: &[Variable],
15798 semi: &JoinSemiContext,
15799 ctx: Option<&crate::context::QueryContext>,
15800) -> SemiGateFacts {
15801 let right_produced = right.inner_variables();
15806 let mut payload: Vec<&Variable> = Vec::new();
15807 for name in semi.right_required.keys() {
15812 if hash_keys.contains(name) || !semi.above_required.contains(name) {
15813 continue;
15814 }
15815 if !payload.contains(&name) {
15816 payload.push(name);
15817 }
15818 }
15819 for name in &semi.counted_distinct {
15823 if hash_keys.contains(name) || !right_produced.contains(name) {
15824 continue;
15825 }
15826 if !payload.contains(&name) {
15827 payload.push(name);
15828 }
15829 }
15830 if !payload.is_empty()
15831 && let Some(ctx) = ctx
15832 && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
15833 {
15834 let names = payload
15835 .iter()
15836 .map(|name| name.to_string())
15837 .collect::<Vec<_>>()
15838 .join(",");
15839 ctx.log(
15840 crate::context::LogLevel::Debug,
15841 &format!(
15842 "semi-payload: {} keys={hash_keys:?} payload=[{names}]",
15843 crate::explain::plan_node_tag(right)
15844 ),
15845 );
15846 }
15847 SemiGateFacts {
15848 right_payload: !payload.is_empty(),
15849 row_multiplicity_observed: semi.row_multiplicity_observed,
15850 count_star: semi.count_star,
15851 }
15852}
15853
15854#[allow(clippy::too_many_arguments)]
15860fn admit_semi_join(
15861 left: &PlanNode,
15862 right: &PlanNode,
15863 hash_keys: &[Variable],
15864 meta: &JoinMeta,
15865 facts: &SemiGateFacts,
15866 ancestors: &[AncestorPushKey],
15867 sliced: bool,
15868 profile: Option<&StatsProfile>,
15869 ctx: Option<&crate::context::QueryContext>,
15870) -> bool {
15871 let tag = crate::explain::plan_node_tag(right);
15872 match semi_join_admission(
15873 left, right, hash_keys, meta, facts, ancestors, sliced, profile, ctx,
15874 ) {
15875 Ok(price) => {
15876 if let Some(ctx) = ctx
15877 && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
15878 {
15879 ctx.log(
15880 crate::context::LogLevel::Debug,
15881 &format!(
15882 "semi-admit: {tag} keys={hash_keys:?} -> admit ({})",
15883 price.summary()
15884 ),
15885 );
15886 }
15887 true
15888 }
15889 Err(SemiRefusal::PerPage(price)) if ctx.is_some_and(|ctx| ctx.force_semi()) => {
15890 if let Some(ctx) = ctx
15894 && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
15895 {
15896 ctx.log(
15897 crate::context::LogLevel::Debug,
15898 &format!(
15899 "semi-admit: {tag} keys={hash_keys:?} -> forced semi ({})",
15900 price.summary()
15901 ),
15902 );
15903 }
15904 true
15905 }
15906 Err(refusal) => {
15907 if let Some(ctx) = ctx
15908 && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
15909 {
15910 ctx.log(
15911 crate::context::LogLevel::Debug,
15912 &format!(
15913 "semi-admit: {tag} keys={hash_keys:?} -> refuse: {}",
15914 refusal.describe()
15915 ),
15916 );
15917 }
15918 false
15919 }
15920 }
15921}
15922
15923fn semi_join_right_pushes(
15934 left: &PlanNode,
15935 hash_keys: &[Variable],
15936 meta: &JoinMeta,
15937 profile: Option<&StatsProfile>,
15938 ancestors: &[AncestorPushKey],
15939 hostable: &[Variable],
15940) -> Vec<AncestorPushKey> {
15941 let mut pushes = ancestors.to_vec();
15942 if !matches!(meta.strategy, JoinStrategy::Semi | JoinStrategy::SemiScan)
15943 && let Some(key) = hash_keys.iter().find(|key| hostable.contains(key))
15944 {
15945 let list = pushed_val_count(profile, left, key);
15946 add_ancestor_push(&mut pushes, key, list);
15947 }
15948 pushes
15949}
15950
15951fn stamp_semi_join_strategy(
16002 node: &mut PlanNode,
16003 profile: Option<&StatsProfile>,
16004 sliced: bool,
16005 ctx: Option<&crate::context::QueryContext>,
16006 ancestor_pushes: &[AncestorPushKey],
16007) {
16008 match node {
16009 PlanNode::Join {
16010 left,
16011 right,
16012 hash_keys,
16013 rhs_hostable_keys,
16014 meta,
16015 ..
16016 } => {
16017 let right_scan = right.as_scan();
16018 let stamped = right_scan.is_some_and(|scan| scan.fetch_once.is_some());
16019 let eligible = right_scan.is_some_and(|scan| semi_eligible_scan_right(scan, hash_keys));
16020 let promote = meta.star_arms.is_none() && stamped && eligible;
16021 let recorded = meta.semi_gate.take();
16025 let general = !promote
16026 && meta.star_arms.is_none()
16027 && recorded.is_some_and(|facts| {
16028 admit_semi_join(
16029 left,
16030 right,
16031 hash_keys,
16032 meta,
16033 &facts,
16034 ancestor_pushes,
16035 sliced,
16036 profile,
16037 ctx,
16038 )
16039 });
16040 if stamped
16041 && let Some(ctx) = ctx
16042 && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
16043 {
16044 let tag = right_scan.map_or_else(String::new, crate::explain::scan_pattern_tag);
16045 ctx.log(
16046 crate::context::LogLevel::Debug,
16047 &format!(
16048 "semi-scan: {tag} keys={hash_keys:?} eligible={eligible} star={} -> {}",
16049 meta.star_arms.is_some(),
16050 if promote { "Semi" } else { "unchanged" }
16051 ),
16052 );
16053 }
16054 if promote {
16055 meta.strategy = JoinStrategy::SemiScan;
16056 } else if general {
16057 meta.strategy = JoinStrategy::Semi;
16058 }
16059 let right_pushes = semi_join_right_pushes(
16064 left,
16065 hash_keys,
16066 meta,
16067 profile,
16068 ancestor_pushes,
16069 rhs_hostable_keys.as_ref(),
16070 );
16071 stamp_semi_join_strategy(left, profile, sliced, ctx, ancestor_pushes);
16072 stamp_semi_join_strategy(right, profile, sliced, ctx, &right_pushes);
16073 }
16074 PlanNode::LeftJoin { left, right, .. } => {
16075 stamp_semi_join_strategy(left, profile, sliced, ctx, ancestor_pushes);
16076 stamp_semi_join_strategy(right, profile, sliced, ctx, ancestor_pushes);
16077 }
16078 PlanNode::Union { left, right } => {
16079 stamp_semi_join_strategy(left, profile, sliced, ctx, ancestor_pushes);
16080 stamp_semi_join_strategy(right, profile, sliced, ctx, ancestor_pushes);
16081 }
16082 PlanNode::CustomNode(op) => {
16083 for child in &mut op.children {
16084 stamp_semi_join_strategy(child, profile, sliced, ctx, ancestor_pushes);
16085 }
16086 }
16087 PlanNode::Filter { inner, exists, .. } => {
16088 stamp_semi_join_strategy(inner, profile, sliced, ctx, ancestor_pushes);
16089 for clause in exists {
16090 stamp_semi_join_strategy(&mut clause.body, profile, true, ctx, &[]);
16093 }
16094 }
16095 PlanNode::Extend { inner, .. }
16096 | PlanNode::Distinct { inner, .. }
16097 | PlanNode::Sort { inner, .. }
16098 | PlanNode::Group { inner, .. }
16099 | PlanNode::JoinGraphVar { inner, .. } => {
16100 stamp_semi_join_strategy(inner, profile, sliced, ctx, ancestor_pushes)
16101 }
16102 PlanNode::Slice { inner, .. } => {
16103 stamp_semi_join_strategy(inner, profile, true, ctx, ancestor_pushes)
16107 }
16108 PlanNode::SubSelect(sub) => {
16109 stamp_semi_join_strategy(&mut sub.inner, profile, sliced, ctx, &[])
16112 }
16113 _ => {}
16114 }
16115}
16116
16117#[cfg(test)]
16121pub(crate) fn stamp_semi_join_strategy_for_test(
16122 root: &mut PlanNode,
16123 profile: Option<&StatsProfile>,
16124 sliced: bool,
16125 ctx: Option<&crate::context::QueryContext>,
16126) {
16127 stamp_semi_join_strategy(root, profile, sliced, ctx, &[]);
16128}
16129
16130fn semi_eligible_scan_right(scan: &ScanOp, hash_keys: &[Variable]) -> bool {
16162 if hash_keys.is_empty() || hash_keys.len() > 8 || scan.has_specialized_rpc() {
16163 return false;
16164 }
16165 let materialized = scan.materialized_variables();
16166 if !materialized
16167 .iter()
16168 .all(|variable| hash_keys.contains(variable))
16169 {
16170 return false;
16171 }
16172 scan_is_key_unique(scan, hash_keys)
16173}
16174
16175fn scan_is_key_unique(scan: &ScanOp, hash_keys: &[Variable]) -> bool {
16190 let [key] = hash_keys else {
16191 return false;
16192 };
16193 let fixed_by_filter = scan
16194 .graph_filter
16195 .as_ref()
16196 .is_some_and(|filter| !filter.is_exclude() && filter.len() == 1);
16197 let fixed_default = scan.graph.is_none() && scan.graph_filter.is_none();
16198 if scan.merge_default_graph || !(fixed_by_filter || fixed_default) {
16199 return false;
16200 }
16201 let mut key_slots = 0usize;
16202 for slot in [&scan.subject, &scan.predicate, &scan.object] {
16203 match slot {
16204 Some(variable) if variable == key => key_slots += 1,
16205 Some(_) => return false,
16206 None => {}
16207 }
16208 }
16209 key_slots == 1
16210}
16211
16212pub(crate) fn head_domain_estimate(
16220 profile: &StatsProfile,
16221 scan: &ScanOp,
16222 head_slot: PatternSlot,
16223) -> Option<u64> {
16224 match head_slot {
16225 PatternSlot::Predicate => {
16226 let predicates = profile.predicate_counts.len() as u64;
16227 (predicates > 0).then_some(predicates)
16228 }
16229 PatternSlot::Object | PatternSlot::Subject => {
16230 let predicate = named_node_hash(scan.pattern.predicate.as_ref()?)?;
16231 match head_slot {
16232 PatternSlot::Subject => profile.subject_domain(&predicate),
16233 _ => profile.object_domain(&predicate),
16234 }
16235 }
16236 }
16237}
16238
16239fn estimate_bound_scan(
16240 profile: Option<&StatsProfile>,
16241 pattern: &EncodedTriplePattern,
16242 fallback_rows: u64,
16243) -> u64 {
16244 if pattern_is_point_lookup(pattern) {
16245 return 1;
16246 }
16247 match profile {
16248 Some(p) if !p.is_empty() => estimate_pattern(p, pattern).max(1),
16249 _ => fallback_rows.max(1),
16250 }
16251}
16252
16253pub(crate) fn estimate_unclamped_scan_rows(profile: Option<&StatsProfile>, scan: &ScanOp) -> u64 {
16254 if let Some(kind) = scan.domain_scan {
16255 return scan_head_estimated_rows(profile, scan, kind.head_slot());
16256 }
16257 if let Some(kind) = scan.head_scan {
16258 return scan_head_estimated_rows(profile, scan, kind.head_slot());
16259 }
16260 if scan.will_collapse() {
16261 let keys = scan.collapse_keys();
16262 let rows = estimate_bound_scan(profile, &scan.pattern, scan.produced_row_count_estimate);
16263 let cost = match keys.as_slice() {
16272 [only] => join_key_domain_for(profile, scan, std::slice::from_ref(only))
16273 .map_or(rows, |domain| domain.min(rows)),
16274 _ => rows,
16275 };
16276 return cost.max(1);
16277 }
16278 estimate_bound_scan(profile, &scan.pattern, scan.produced_row_count_estimate)
16279}
16280
16281pub(crate) fn whole_read_rows_known(profile: Option<&StatsProfile>, scan: &ScanOp) -> bool {
16293 pattern_is_point_lookup(&scan.pattern)
16294 || profile.is_some_and(|p| !p.is_empty() && p.has_predicate_sketch(&scan.pattern))
16295}
16296
16297fn scan_head_estimated_rows(
16302 profile: Option<&StatsProfile>,
16303 scan: &ScanOp,
16304 head_slot: PatternSlot,
16305) -> u64 {
16306 if let Some(head) = scan_slot_variable(scan, head_slot)
16307 && let Some(domain) = join_key_domain_for(profile, scan, std::slice::from_ref(head))
16308 {
16309 return domain.max(1);
16310 }
16311 estimate_bound_scan(profile, &scan.pattern, scan.produced_row_count_estimate).max(1)
16312}
16313
16314pub(crate) fn scan_slot_variable(scan: &ScanOp, slot: PatternSlot) -> Option<&Variable> {
16317 match slot {
16318 PatternSlot::Subject => scan.subject.as_ref(),
16319 PatternSlot::Predicate => scan.predicate.as_ref(),
16320 PatternSlot::Object => scan.object.as_ref(),
16321 }
16322}
16323
16324fn collect_subtree_variables(node: &PlanNode, out: &mut Vec<Variable>) {
16332 fn push_var(out: &mut Vec<Variable>, variable: Variable) {
16333 if !out.contains(&variable) {
16334 out.push(variable);
16335 }
16336 }
16337 let vars = node.output_vars();
16338 for bound in vars.always_bound.iter().chain(vars.maybe_unbound.iter()) {
16339 push_var(out, bound.clone());
16340 }
16341 match node {
16342 PlanNode::Filter {
16343 inner,
16344 early,
16345 residual,
16346 exists,
16347 ..
16348 } => {
16349 for expression in early.iter().chain(residual.iter()) {
16350 out.extend(variables_in_expression(expression));
16351 }
16352 for clause in exists {
16353 collect_subtree_variables(&clause.body, out);
16354 }
16355 collect_subtree_variables(inner, out);
16356 }
16357 PlanNode::LeftJoin {
16358 left,
16359 right,
16360 early_filter,
16361 residual_filter,
16362 ..
16363 } => {
16364 for expression in early_filter.iter().chain(residual_filter.iter()) {
16365 out.extend(variables_in_expression(expression));
16366 }
16367 collect_subtree_variables(left, out);
16368 collect_subtree_variables(right, out);
16369 }
16370 PlanNode::Extend {
16371 inner, expression, ..
16372 } => {
16373 out.extend(variables_in_expression(expression));
16374 collect_subtree_variables(inner, out);
16375 }
16376 PlanNode::Sort { inner, keys } => {
16377 for key in keys {
16378 out.extend(variables_in_expression(&key.expression));
16379 }
16380 collect_subtree_variables(inner, out);
16381 }
16382 PlanNode::Group {
16383 inner,
16384 variables,
16385 aggregates,
16386 ..
16387 } => {
16388 for variable in variables {
16389 push_var(out, variable.clone());
16390 }
16391 for (variable, aggregate) in aggregates {
16392 push_var(out, variable.clone());
16393 match aggregate {
16394 AggregateExpression::CountSolutions { .. } => {}
16395 AggregateExpression::FunctionCall { expr, .. } => {
16396 out.extend(variables_in_expression(expr));
16397 }
16398 }
16399 }
16400 collect_subtree_variables(inner, out);
16401 }
16402 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
16403 collect_subtree_variables(left, out);
16404 collect_subtree_variables(right, out);
16405 }
16406 PlanNode::SubSelect(sub) => collect_subtree_variables(&sub.inner, out),
16407 PlanNode::CustomNode(op) => {
16408 for variable in &op.variables {
16409 push_var(out, variable.clone());
16410 }
16411 for child in &op.children {
16412 collect_subtree_variables(child, out);
16413 }
16414 }
16415 _ => {}
16416 }
16417}
16418
16419fn optional_pair_rotation_safe(
16437 core: &PlanNode,
16438 arm_a: &PlanNode,
16439 keys_a: &[Variable],
16440 arm_b: &PlanNode,
16441 keys_b: &[Variable],
16442 b_scope_expressions: [&Option<Expression>; 2],
16443) -> bool {
16444 let core_bound = &core.output_vars().always_bound;
16445 if !keys_a.iter().all(|key| core_bound.contains(key))
16446 || !keys_b.iter().all(|key| core_bound.contains(key))
16447 {
16448 return false;
16449 }
16450 let a_all = arm_a.output_vars().all();
16457 let a_first: Vec<&Variable> = a_all.iter().filter(|v| !core_bound.contains(*v)).collect();
16458 if a_first.is_empty() {
16459 return true;
16460 }
16461 let mut b_mentions: Vec<Variable> = Vec::new();
16462 for expression in b_scope_expressions.into_iter().flatten() {
16463 b_mentions.extend(variables_in_expression(expression));
16464 }
16465 collect_subtree_variables(arm_b, &mut b_mentions);
16466 a_first.iter().all(|v| !b_mentions.contains(*v))
16467}
16468
16469const LEFTJOIN_REORDER_MARGIN_PERCENT: u64 = 15;
16475
16476fn reorder_independent_optional_arms(node: &mut PlanNode, profile: Option<&StatsProfile>) -> bool {
16503 let (run_start, order);
16506 {
16507 struct ArmRef<'a> {
16508 right: &'a PlanNode,
16509 hash_keys: &'a [Variable],
16510 early_filter: &'a Option<Expression>,
16511 residual_filter: &'a Option<Expression>,
16512 }
16513 let mut arms_desc: Vec<ArmRef> = Vec::new();
16518 let mut spine: Vec<&PlanNode> = Vec::new();
16519 let mut cursor: &PlanNode = node;
16520 while let PlanNode::LeftJoin {
16521 left,
16522 right,
16523 hash_keys,
16524 early_filter,
16525 residual_filter,
16526 ..
16527 } = cursor
16528 {
16529 spine.push(cursor);
16530 arms_desc.push(ArmRef {
16531 right,
16532 hash_keys,
16533 early_filter,
16534 residual_filter,
16535 });
16536 cursor = left;
16537 }
16538 let core = cursor;
16539 spine.push(core);
16540 arms_desc.reverse();
16542 let arms = arms_desc;
16543 let k = arms.len();
16544 if k < 2 {
16545 return false;
16546 }
16547 let mut m = k;
16553 'extend: while m > 0 {
16554 let candidate = m - 1;
16555 for j in candidate + 1..k {
16556 if !optional_pair_rotation_safe(
16557 core,
16558 arms[candidate].right,
16559 arms[candidate].hash_keys,
16560 arms[j].right,
16561 arms[j].hash_keys,
16562 [arms[j].early_filter, arms[j].residual_filter],
16563 ) {
16564 break 'extend;
16565 }
16566 }
16567 m = candidate;
16568 }
16569 if k - m < 2 {
16570 return false;
16571 }
16572 let below = spine[k - m];
16575 let mut rows = below.produced_row_count_estimate();
16581 let mut current_sum = 0u64;
16582 for arm in &arms[m..] {
16583 let e = estimate_left_join_rows(rows, core, arm.right, arm.hash_keys, profile);
16584 current_sum = current_sum.saturating_add(e);
16585 rows = e;
16586 }
16587 let mut remaining: Vec<usize> = (m..k).collect();
16590 let mut greedy_order: Vec<usize> = Vec::new();
16591 let mut greedy_sum = 0u64;
16592 let mut rows = below.produced_row_count_estimate();
16593 while !remaining.is_empty() {
16594 let mut best: Option<(usize, u64)> = None;
16595 for &idx in &remaining {
16596 let e = estimate_left_join_rows(
16597 rows,
16598 core,
16599 arms[idx].right,
16600 arms[idx].hash_keys,
16601 profile,
16602 );
16603 if best.is_none_or(|(_, best_e)| e < best_e) {
16604 best = Some((idx, e));
16605 }
16606 }
16607 let (idx, e) = best.expect("remaining is non-empty");
16608 remaining.retain(|&r| r != idx);
16609 greedy_order.push(idx);
16610 greedy_sum = greedy_sum.saturating_add(e);
16611 rows = e;
16612 }
16613 if greedy_order == (m..k).collect::<Vec<_>>()
16614 || greedy_sum.saturating_mul(100)
16615 >= current_sum.saturating_mul(100 - LEFTJOIN_REORDER_MARGIN_PERCENT)
16616 {
16617 return false;
16618 }
16619 run_start = m;
16620 order = greedy_order;
16621 }
16622 let taken = std::mem::replace(node, PlanNode::Unit);
16628 let mut below = taken;
16629 type PeeledArm = (
16632 PlanNode,
16633 Vec<Variable>,
16634 Option<Expression>,
16635 Option<Expression>,
16636 );
16637 let mut peeled: Vec<PeeledArm> = Vec::new();
16638 for _ in 0..order.len() {
16639 let PlanNode::LeftJoin {
16640 left,
16641 right,
16642 hash_keys,
16643 early_filter,
16644 residual_filter,
16645 ..
16646 } = below
16647 else {
16648 unreachable!("spine shape checked above");
16649 };
16650 peeled.push((*right, hash_keys, early_filter, residual_filter));
16651 below = *left;
16652 }
16653 peeled.reverse(); let mut slots = peeled.into_iter().map(Some).collect::<Vec<_>>();
16655 let mut inner = below;
16656 for &idx in &order {
16657 let (mut arm, hash_keys, early_filter, residual_filter) = slots[idx - run_start]
16658 .take()
16659 .expect("each greedy index used once");
16660 clear_broadcast_marks(&mut arm);
16661 inner = PlanNode::LeftJoin {
16662 left: Box::new(inner),
16663 right: Box::new(arm),
16664 hash_keys,
16665 early_filter,
16666 residual_filter,
16667 probe_key_domains: Vec::new(),
16670 probe_key_overlap_milli: Vec::new(),
16671 meta: LeftJoinMeta {
16672 produced_row_count_estimate: 1,
16673 own_push_removed_row_count_estimate: 1,
16674 },
16675 };
16676 }
16677 *node = inner;
16678 true
16679}
16680
16681fn optional_delay_through_join_safe(
16699 l: &PlanNode,
16700 o: &PlanNode,
16701 o_filter_expressions: [&Option<Expression>; 2],
16702 keys_o: &[Variable],
16703 r: &PlanNode,
16704) -> bool {
16705 let l_bound = &l.output_vars().always_bound;
16706 if !keys_o.iter().all(|key| l_bound.contains(key)) {
16711 return false;
16712 }
16713 let mut o_scope: Vec<Variable> = Vec::new();
16716 for expression in o_filter_expressions.into_iter().flatten() {
16717 o_scope.extend(variables_in_expression(expression));
16718 }
16719 collect_subtree_variables(o, &mut o_scope);
16720 let mut r_mentions: Vec<Variable> = Vec::new();
16721 collect_subtree_variables(r, &mut r_mentions);
16722 o_scope
16723 .iter()
16724 .filter(|v| r_mentions.contains(*v))
16725 .all(|v| l_bound.contains(v))
16726}
16727
16728fn delay_optional_through_join(node: &mut PlanNode, profile: Option<&StatsProfile>) -> bool {
16753 let candidate;
16754 {
16755 let PlanNode::Join {
16756 left,
16757 right,
16758 hash_keys,
16759 ..
16760 } = node
16761 else {
16762 return false;
16763 };
16764 let (lj, r, lj_on_left) = match (left.as_ref(), right.as_ref()) {
16767 (PlanNode::LeftJoin { .. }, _) => (left.as_ref(), right.as_ref(), true),
16768 (_, PlanNode::LeftJoin { .. }) => (right.as_ref(), left.as_ref(), false),
16769 _ => return false,
16770 };
16771 let PlanNode::LeftJoin {
16772 left: l,
16773 right: o,
16774 hash_keys: keys_o,
16775 probe_key_domains: _,
16776 probe_key_overlap_milli: _,
16777 meta: lj_meta,
16778 early_filter,
16779 residual_filter,
16780 } = lj
16781 else {
16782 unreachable!("the LeftJoin arm matched above");
16783 };
16784 if hash_keys.is_empty() {
16789 return false;
16790 }
16791 if !optional_delay_through_join_safe(l, o, [early_filter, residual_filter], keys_o, r) {
16792 return false;
16793 }
16794 let current_final = finalize_inner_join_meta(lj, r, hash_keys, profile).1;
16799 let current_sum = lj_meta
16800 .produced_row_count_estimate
16801 .saturating_add(current_final);
16802 let mut l_clone = (**l).clone();
16836 clear_broadcast_marks(&mut l_clone);
16837 let mut r_clone = r.clone();
16838 clear_broadcast_marks(&mut r_clone);
16839 let join_lr = if lj_on_left {
16840 join_nodes(l_clone, r_clone, profile)
16841 } else {
16842 join_nodes(r_clone, l_clone, profile)
16843 };
16844 let swapped_first = join_lr.produced_row_count_estimate();
16845 let swapped_sum = swapped_first.saturating_add(estimate_left_join_rows(
16846 swapped_first,
16847 &join_lr,
16848 o,
16849 keys_o,
16850 profile,
16851 ));
16852 if swapped_sum.saturating_mul(100)
16853 >= current_sum.saturating_mul(100 - LEFTJOIN_REORDER_MARGIN_PERCENT)
16854 {
16855 return false;
16856 }
16857 fn same_var_set(a: &[Variable], b: &[Variable]) -> bool {
16863 a.len() == b.len() && a.iter().all(|v| b.contains(v))
16864 }
16865 let original_out = join_output_vars(&left.output_vars(), &right.output_vars());
16869 let delayed_out = left_join_output_vars(&join_lr.output_vars(), &o.output_vars());
16870 if !same_var_set(&original_out.always_bound, &delayed_out.always_bound)
16871 || !same_var_set(&original_out.maybe_unbound, &delayed_out.maybe_unbound)
16872 {
16873 return false;
16874 }
16875 candidate = join_lr;
16876 }
16877 let taken = std::mem::replace(node, PlanNode::Unit);
16885 let PlanNode::Join { left, right, .. } = taken else {
16886 unreachable!("shape checked above");
16887 };
16888 let lj = if matches!(*left, PlanNode::LeftJoin { .. }) {
16889 left
16890 } else {
16891 right
16892 };
16893 let PlanNode::LeftJoin {
16894 right: mut o,
16895 hash_keys: keys_o,
16896 early_filter,
16897 residual_filter,
16898 ..
16899 } = *lj
16900 else {
16901 unreachable!("shape checked above");
16902 };
16903 clear_broadcast_marks(&mut o);
16904 *node = PlanNode::LeftJoin {
16908 left: Box::new(candidate),
16909 right: o,
16910 hash_keys: keys_o,
16911 early_filter,
16912 residual_filter,
16913 probe_key_domains: Vec::new(),
16914 probe_key_overlap_milli: Vec::new(),
16915 meta: LeftJoinMeta {
16916 produced_row_count_estimate: 1,
16917 own_push_removed_row_count_estimate: 1,
16918 },
16919 };
16920 true
16921}
16922
16923#[cfg(test)]
16930fn refinalize_joins_without_ctx(node: &mut PlanNode, profile: Option<&StatsProfile>) {
16931 refinalize_joins(node, profile, None)
16932}
16933
16934fn refinalize_joins(
16938 node: &mut PlanNode,
16939 profile: Option<&StatsProfile>,
16940 ctx: Option<&crate::context::QueryContext>,
16941) {
16942 match node {
16943 PlanNode::CustomNode(op) => {
16946 for child in &mut op.children {
16947 refinalize_joins(child, profile, ctx);
16948 }
16949 }
16950 PlanNode::Scan(scan) => {
16951 let unclamped = estimate_unclamped_scan_rows(profile, scan);
16960 scan.produced_row_count_estimate =
16961 unclamped.min(scan.ancestor_push_return_bound.unwrap_or(u64::MAX));
16962 }
16963 PlanNode::Path(path) => recost_path(path),
16964 PlanNode::Join {
16965 left,
16966 right,
16967 hash_keys,
16968 probe_key_domains,
16969 probe_key_overlap_milli,
16970 rhs_hostable_keys,
16971 meta,
16972 } => {
16973 refinalize_joins(left, profile, ctx);
16974 refinalize_joins(right, profile, ctx);
16975 let taken_left = std::mem::replace(left.as_mut(), PlanNode::Unit);
16976 let taken_right = std::mem::replace(right.as_mut(), PlanNode::Unit);
16977 let (mut taken_left, mut taken_right) =
16978 maybe_swap_scan_union(taken_left, taken_right, hash_keys, profile);
16979 let left_rows = driver_whole_read_rows(&taken_left, hash_keys, profile);
16986 let right_rows = driver_whole_read_rows(&taken_right, hash_keys, profile);
16987 let left_domain = join_key_domain_for_allow_list(
16988 profile,
16989 &taken_left,
16990 &taken_right,
16991 hash_keys,
16992 left_rows,
16993 );
16994 let right_domain = join_key_domain_for_allow_list(
16995 profile,
16996 &taken_right,
16997 &taken_left,
16998 hash_keys,
16999 right_rows,
17000 );
17001 let mut swapped = false;
17002 let left_cost = driver_cost(left_rows, left_domain);
17006 let right_cost = driver_cost(right_rows, right_domain);
17007 let right_is_point = taken_right
17008 .as_scan()
17009 .is_some_and(|s| pattern_is_point_lookup(&s.pattern));
17010 let left_is_point = taken_left
17011 .as_scan()
17012 .is_some_and(|s| pattern_is_point_lookup(&s.pattern));
17013 let seat_by_totals =
17022 ctx.is_some_and(crate::context::QueryContext::seat_by_total_cost);
17023 let (left_seat, right_seat) = if !hash_keys.is_empty() {
17024 (
17025 seat_cost_total(profile, &taken_left, &taken_right, hash_keys, ctx, None),
17026 seat_cost_total(profile, &taken_right, &taken_left, hash_keys, ctx, None),
17027 )
17028 } else {
17029 (SeatCost { rows: 0, seeks: 0 }, SeatCost { rows: 0, seeks: 0 })
17030 };
17031 let totals_prefers_right = !hash_keys.is_empty() && seat_beats(right_seat, left_seat);
17032 let old_swaps = !hash_keys.is_empty()
17033 && ((right_cost, right_rows) < (left_cost, left_rows)
17034 || (right_is_point && !left_is_point));
17035 let totals_swaps = totals_prefers_right || (right_is_point && !left_is_point);
17036 if seat_by_totals
17037 && !hash_keys.is_empty()
17038 && totals_swaps != old_swaps
17039 && let Some(ctx) = ctx
17040 {
17041 ctx.log(
17042 crate::context::LogLevel::Debug,
17043 &format!(
17044 "join-seat-totals: keys={hash_keys:?} applied={} \
17045 old_would={} driver_costs(l={left_cost} r={right_cost}) \
17046 totals(left={}:{}s right={}:{}s) rows(l={left_rows} \
17047 r={right_rows})",
17048 if totals_swaps { "right" } else { "left" },
17049 if old_swaps { "right" } else { "left" },
17050 left_seat.rows,
17051 left_seat.seeks,
17052 right_seat.rows,
17053 right_seat.seeks,
17054 ),
17055 );
17056 }
17057 if !seat_by_totals
17058 && totals_prefers_right != old_swaps
17059 && let Some(ctx) = ctx
17060 {
17061 ctx.log(
17062 crate::context::LogLevel::Debug,
17063 &format!(
17064 "join-seat-shadow: keys={hash_keys:?} old={} new={} \
17065 driver_costs(l={left_cost} r={right_cost}) \
17066 totals(left={}:{}s right={}:{}s) rows(l={left_rows} \
17067 r={right_rows})",
17068 if old_swaps { "right" } else { "left" },
17069 if totals_prefers_right { "right" } else { "left" },
17070 left_seat.rows,
17071 left_seat.seeks,
17072 right_seat.rows,
17073 right_seat.seeks,
17074 ),
17075 );
17076 }
17077 let swaps = if seat_by_totals && !hash_keys.is_empty() {
17078 totals_swaps
17079 } else {
17080 old_swaps
17081 };
17082 if swaps {
17083 std::mem::swap(&mut taken_left, &mut taken_right);
17084 swapped = true;
17085 }
17086 if swapped {
17087 clear_broadcast_marks(&mut taken_left);
17089 }
17090 let (strategy, produced, own_push_removed) =
17091 finalize_inner_join_meta(&taken_left, &taken_right, hash_keys, profile);
17092 meta.strategy = strategy;
17093 meta.produced_row_count_estimate = produced;
17094 meta.own_push_removed_row_count_estimate = own_push_removed;
17100 reorder_hash_keys_by_probe_return(
17104 hash_keys,
17105 probe_key_domains,
17106 probe_key_overlap_milli,
17107 &taken_left,
17108 &taken_right,
17109 profile);
17110 *probe_key_domains = stamp_probe_key_domains(profile, &taken_right, hash_keys);
17113 *probe_key_overlap_milli =
17117 stamp_probe_key_overlaps(profile, &taken_left, &taken_right, hash_keys);
17118 if strategy == JoinStrategy::Broadcast && !hash_keys.is_empty() {
17124 ground_and_recost_broadcasted_arm(&taken_left, &mut taken_right, hash_keys, profile);
17125 }
17126 if !hash_keys.is_empty() {
17127 compose_graph_from_sibling(&taken_left, &mut taken_right, hash_keys, profile, true);
17128 compose_graph_from_sibling(&taken_right, &mut taken_left, hash_keys, profile, true);
17129 }
17130 clamp_broadcast_probe_estimates(&taken_left, &mut taken_right, hash_keys, profile);
17131 *rhs_hostable_keys = stamp_rhs_hostable_keys(&taken_right);
17144 if zero_row_arm(&taken_left)
17150 || zero_row_arm(&taken_right)
17151 || (!hash_keys.is_empty()
17152 && conflicting_ground_keys(&taken_left, &taken_right, hash_keys).is_some())
17153 {
17154 *node = provably_empty_join(&taken_left, &taken_right);
17155 return;
17156 }
17157 **left = taken_left;
17158 **right = taken_right;
17159 if delay_optional_through_join(node, profile) {
17167 refinalize_joins(node, profile, ctx);
17168 }
17169 }
17170 PlanNode::LeftJoin { .. } => {
17171 if let PlanNode::LeftJoin { left, right, .. } = node {
17172 refinalize_joins(left, profile, ctx);
17173 refinalize_joins(right, profile, ctx);
17174 }
17175 if reorder_independent_optional_arms(node, profile)
17180 && let PlanNode::LeftJoin { left, .. } = node
17181 {
17182 refinalize_joins(left, profile, ctx);
17183 }
17184 if let PlanNode::LeftJoin {
17191 left,
17192 right,
17193 hash_keys,
17194 probe_key_domains,
17195 probe_key_overlap_milli,
17196 meta,
17197 ..
17198 } = node
17199 {
17200 *meta = stamp_left_join_meta(
17201 left.produced_row_count_estimate(),
17202 left,
17203 right,
17204 hash_keys,
17205 profile,
17206 );
17207 *probe_key_domains = stamp_probe_key_domains(profile, right, hash_keys);
17208 *probe_key_overlap_milli =
17218 stamp_probe_key_overlaps(profile, left, right, hash_keys);
17219 clamp_broadcast_probe_estimates(left, right, hash_keys, profile);
17220 }
17221 }
17222 PlanNode::Union { left, right } => {
17223 refinalize_joins(left, profile, ctx);
17224 refinalize_joins(right, profile, ctx);
17225 }
17226 PlanNode::Filter { inner, exists, .. } => {
17227 refinalize_joins(inner, profile, ctx);
17228 for clause in exists {
17229 refinalize_joins(&mut clause.body, profile, ctx);
17230 }
17231 }
17232 PlanNode::Extend { inner, .. }
17233 | PlanNode::Slice { inner, .. }
17234 | PlanNode::Distinct { inner, .. }
17235 | PlanNode::Sort { inner, .. }
17236 | PlanNode::Group { inner, .. }
17237 | PlanNode::JoinGraphVar { inner, .. } => {
17238 refinalize_joins(inner, profile, ctx);
17239 }
17240 PlanNode::SubSelect(sub) => refinalize_joins(&mut sub.inner, profile, ctx),
17243 PlanNode::Values(_)
17244 | PlanNode::NamedGraphs { .. }
17245 | PlanNode::NamedGraphExists { .. }
17246 | PlanNode::DomainCounts { .. }
17248 | PlanNode::HeadCounts { .. }
17249 | PlanNode::PatternCount { .. }
17250 | PlanNode::Unit => {}
17251 }
17252}
17253
17254fn clear_broadcast_marks(node: &mut PlanNode) {
17261 match node {
17262 PlanNode::Scan(scan) => {
17263 scan.broadcasted = None;
17264 scan.ancestor_push_return_bound = None;
17270 scan.domain_scan = None;
17271 scan.domain_counts = None;
17274 }
17275 PlanNode::Join { left, right, .. }
17276 | PlanNode::Union { left, right }
17277 | PlanNode::LeftJoin { left, right, .. } => {
17278 clear_broadcast_marks(left);
17279 clear_broadcast_marks(right);
17280 }
17281 PlanNode::Filter { inner, .. }
17282 | PlanNode::Extend { inner, .. }
17283 | PlanNode::Slice { inner, .. }
17284 | PlanNode::Distinct { inner, .. }
17285 | PlanNode::Sort { inner, .. }
17286 | PlanNode::Group { inner, .. }
17287 | PlanNode::JoinGraphVar { inner, .. } => clear_broadcast_marks(inner),
17288 _ => {}
17289 }
17290}
17291
17292fn pushed_val_count(profile: Option<&StatsProfile>, pusher: &PlanNode, variable: &Variable) -> u64 {
17308 join_key_domain_for_node(profile, pusher, variable)
17309 .map(|domain| domain.min(pusher.produced_row_count_estimate()))
17310 .unwrap_or_else(|| pusher.produced_row_count_estimate())
17311 .max(1)
17312}
17313
17314fn pushed_return_bound_core(pushed_val_count: u64, basis: u64, domain: Option<u64>) -> Option<u64> {
17332 let basis = basis.max(1);
17333 let domain = domain?.max(1);
17334 let total = u128::from(pushed_val_count) * u128::from(basis);
17335 let bound = u64::try_from(total.div_ceil(u128::from(domain)))
17336 .unwrap_or(basis)
17337 .min(basis);
17338 Some(bound.max(1))
17339}
17340
17341fn pushed_scan_return_bound(
17357 pushed_val_count: u64,
17358 price: u64,
17359 scan: &ScanOp,
17360 variable: &Variable,
17361 profile: Option<&StatsProfile>,
17362) -> u64 {
17363 let domain = join_key_domain_for(profile, scan, std::slice::from_ref(variable));
17364 pushed_return_bound_core(pushed_val_count, price, domain)
17365 .unwrap_or_else(|| pushed_val_count.min(price.max(1)))
17366 .max(1)
17367}
17368
17369fn clamp_broadcast_probe_estimates(
17370 left: &PlanNode,
17371 right: &mut PlanNode,
17372 hash_keys: &[Variable],
17373 profile: Option<&StatsProfile>,
17374) {
17375 match right {
17376 PlanNode::Scan(scan) => {
17377 if pattern_is_point_lookup(&scan.pattern) {
17378 return;
17379 }
17380 let Some((variable, _)) = &scan.broadcasted else {
17381 return;
17382 };
17383 if !hash_keys.contains(variable) {
17389 return;
17390 }
17391 let pushed_val_count = pushed_val_count(profile, left, variable);
17395 let price = estimate_unclamped_scan_rows(profile, scan);
17396 let bound = pushed_scan_return_bound(pushed_val_count, price, scan, variable, profile);
17397 scan.produced_row_count_estimate = scan.produced_row_count_estimate.min(bound);
17398 scan.ancestor_push_return_bound = Some(bound);
17407 }
17408 PlanNode::Path(path) => {
17418 if path.subject_term.is_some() && path.object_term.is_some() {
17419 return;
17420 }
17421 let Some(pushed) = path_pushed_val_count(path, left, hash_keys, profile) else {
17422 return;
17423 };
17424 path.produced_row_count_estimate = path.produced_row_count_estimate.min(pushed);
17425 }
17426 PlanNode::Union { left: a, right: b }
17427 | PlanNode::Join {
17428 left: a, right: b, ..
17429 } => {
17430 clamp_broadcast_probe_estimates(left, a, hash_keys, profile);
17431 clamp_broadcast_probe_estimates(left, b, hash_keys, profile);
17432 }
17433 PlanNode::LeftJoin {
17434 left: nested_left,
17435 right: nested_right,
17436 hash_keys: nested_keys,
17437 ..
17438 } => {
17439 clamp_broadcast_probe_estimates(left, nested_left, hash_keys, profile);
17440 clamp_broadcast_probe_estimates(nested_left, nested_right, nested_keys, profile);
17441 }
17442 PlanNode::Filter { inner, .. }
17443 | PlanNode::Extend { inner, .. }
17444 | PlanNode::Slice { inner, .. }
17445 | PlanNode::Distinct { inner, .. }
17446 | PlanNode::Sort { inner, .. }
17447 | PlanNode::Group { inner, .. } => {
17448 clamp_broadcast_probe_estimates(left, inner, hash_keys, profile);
17449 }
17450 _ => {}
17451 }
17452}
17453
17454fn pushed_join_keys(node: &PlanNode, hash_keys: &[Variable]) -> Vec<Variable> {
17460 let mut pushed = Vec::new();
17461 match node {
17462 PlanNode::Scan(scan) => {
17463 if let Some((variable, _)) = &scan.broadcasted
17464 && hash_keys.contains(variable)
17465 && !pushed.iter().any(|v: &Variable| v == variable)
17466 {
17467 pushed.push(variable.clone());
17468 }
17469 }
17470 PlanNode::Union { left: a, right: b }
17471 | PlanNode::Join {
17472 left: a, right: b, ..
17473 } => {
17474 pushed.extend(pushed_join_keys(a, hash_keys));
17475 pushed.extend(pushed_join_keys(b, hash_keys));
17476 }
17477 PlanNode::LeftJoin {
17478 left: nested_left,
17479 right: nested_right,
17480 ..
17481 } => {
17482 pushed.extend(pushed_join_keys(nested_left, hash_keys));
17483 pushed.extend(pushed_join_keys(nested_right, hash_keys));
17484 }
17485 PlanNode::Filter { inner, .. }
17486 | PlanNode::Extend { inner, .. }
17487 | PlanNode::Slice { inner, .. }
17488 | PlanNode::Distinct { inner, .. }
17489 | PlanNode::Sort { inner, .. }
17490 | PlanNode::Group { inner, .. }
17491 | PlanNode::JoinGraphVar { inner, .. } => {
17492 pushed.extend(pushed_join_keys(inner, hash_keys));
17493 }
17494 _ => {}
17495 }
17496 pushed
17497}
17498
17499fn restamp_joins_produced_row_count_estimate(node: &mut PlanNode, profile: Option<&StatsProfile>) {
17518 match node {
17519 PlanNode::Join {
17520 left,
17521 right,
17522 hash_keys,
17523 meta,
17524 ..
17525 } => {
17526 restamp_joins_produced_row_count_estimate(left, profile);
17527 restamp_joins_produced_row_count_estimate(right, profile);
17528 let left_rows = left.produced_row_count_estimate();
17529 let right_rows = right.produced_row_count_estimate();
17530 meta.produced_row_count_estimate = if hash_keys.is_empty() {
17531 left_rows.saturating_mul(right_rows).max(1)
17532 } else {
17533 let pushed = pushed_join_keys(right, hash_keys);
17534 let probe_key_domains = hash_keys
17535 .iter()
17536 .map(|key| {
17537 if pushed.contains(key) {
17538 (
17539 join_key_domain_for_node(profile, left, key),
17540 None,
17544 )
17545 } else {
17546 (
17547 join_key_domain_for_node(profile, left, key),
17548 join_key_domain_for_node(profile, right, key),
17549 )
17550 }
17551 })
17552 .collect::<Vec<_>>();
17553 estimate_join_rows_multi(left_rows, right_rows, &probe_key_domains)
17554 };
17555 }
17556 PlanNode::Union { left, right } => {
17557 restamp_joins_produced_row_count_estimate(left, profile);
17558 restamp_joins_produced_row_count_estimate(right, profile);
17559 }
17560 PlanNode::LeftJoin {
17561 left,
17562 right,
17563 hash_keys,
17564 meta,
17565 ..
17566 } => {
17567 restamp_joins_produced_row_count_estimate(left, profile);
17568 restamp_joins_produced_row_count_estimate(right, profile);
17569 meta.produced_row_count_estimate = estimate_left_join_rows_pushed(
17574 left.produced_row_count_estimate(),
17575 left,
17576 right,
17577 hash_keys,
17578 profile,
17579 );
17580 }
17581 PlanNode::SubSelect(sub) => {
17582 restamp_joins_produced_row_count_estimate(&mut sub.inner, profile);
17583 }
17584 PlanNode::CustomNode(op) => {
17585 for child in &mut op.children {
17586 restamp_joins_produced_row_count_estimate(child, profile);
17587 }
17588 }
17589 PlanNode::Filter { inner, .. }
17590 | PlanNode::Extend { inner, .. }
17591 | PlanNode::Slice { inner, .. }
17592 | PlanNode::Distinct { inner, .. }
17593 | PlanNode::Sort { inner, .. }
17594 | PlanNode::Group { inner, .. }
17595 | PlanNode::JoinGraphVar { inner, .. } => {
17596 restamp_joins_produced_row_count_estimate(inner, profile);
17597 }
17598 _ => {}
17599 }
17600}
17601
17602fn allow_list_from_node(node: &PlanNode, variable: &Variable) -> Option<Arc<[EncodedTerm]>> {
17603 match node {
17604 PlanNode::Values(values) => {
17605 let terms = values.distinct_terms(variable)?;
17606 if terms.is_empty() || terms.len() > GRAPH_FILTER_TERM_CAP as usize {
17607 None
17608 } else {
17609 Some(Arc::from(terms))
17610 }
17611 }
17612 PlanNode::Join { left, right, .. } => {
17613 allow_list_from_node(left, variable).or_else(|| allow_list_from_node(right, variable))
17614 }
17615 PlanNode::Filter { inner, .. }
17616 | PlanNode::Extend { inner, .. }
17617 | PlanNode::Slice { inner, .. }
17618 | PlanNode::Distinct { inner, .. }
17619 | PlanNode::Sort { inner, .. }
17620 | PlanNode::Group { inner, .. } => allow_list_from_node(inner, variable),
17621 _ => None,
17622 }
17623}
17624
17625fn collect_not_same_term_graph(expr: &Expression) -> Option<(Variable, Vec<EncodedTerm>)> {
17626 let mut variable: Option<Variable> = None;
17627 let mut terms = Vec::new();
17628 for conjunct in flatten_and(expr) {
17629 let (found, term) = not_same_term_ground(&conjunct)?;
17630 match &variable {
17631 None => variable = Some(found),
17632 Some(existing) if existing != &found => return None,
17633 _ => {}
17634 }
17635 if !terms.iter().any(|existing| existing == &term) {
17636 terms.push(term);
17637 }
17638 }
17639 if terms.is_empty() || terms.len() > GRAPH_FILTER_TERM_CAP as usize {
17640 return None;
17641 }
17642 Some((variable?, terms))
17643}
17644
17645fn not_same_term_ground(expr: &Expression) -> Option<(Variable, EncodedTerm)> {
17646 let Expression::Not(inner) = expr else {
17647 return None;
17648 };
17649 let (a, b, equal_not_same_term) = match inner.as_ref() {
17650 Expression::SameTerm(a, b) => (a.as_ref(), b.as_ref(), false),
17651 Expression::Equal(a, b) => (a.as_ref(), b.as_ref(), true),
17652 _ => return None,
17653 };
17654 let (variable, constant) = match (a, b) {
17655 (Expression::Variable(v), c) | (c, Expression::Variable(v)) => (v, c),
17656 _ => return None,
17657 };
17658 let (term, _) = encoded_ground_expr(constant)?;
17659 if equal_not_same_term && !sparql_equal_is_encoded_identity(&term) {
17660 return None;
17661 }
17662 Some((variable.clone(), term))
17663}
17664
17665fn apply_graph_exclusions(node: &mut PlanNode, variable: &Variable, extra: &[EncodedTerm]) -> bool {
17669 matches!(
17670 apply_graph_exclusion_status(node, variable, extra),
17671 ExclusionStatus::Applied
17672 )
17673}
17674
17675#[derive(Clone, Copy, PartialEq, Eq)]
17680enum ExclusionStatus {
17681 Vacuous,
17682 Applied,
17683 Failed,
17684}
17685
17686fn merge_exclusion(left: ExclusionStatus, right: ExclusionStatus) -> ExclusionStatus {
17687 use ExclusionStatus::*;
17688 match (left, right) {
17689 (Failed, _) | (_, Failed) => Failed,
17690 (Applied, Vacuous) | (Vacuous, Applied) | (Applied, Applied) => Applied,
17691 (Vacuous, Vacuous) => Vacuous,
17692 }
17693}
17694
17695fn apply_graph_exclusion_status(
17696 node: &mut PlanNode,
17697 variable: &Variable,
17698 extra: &[EncodedTerm],
17699) -> ExclusionStatus {
17700 match node {
17701 PlanNode::SubSelect(sub) => {
17704 if sub.variables.contains(variable) {
17705 ExclusionStatus::Failed
17706 } else {
17707 ExclusionStatus::Vacuous
17708 }
17709 }
17710 PlanNode::CustomNode(op) => {
17713 if op.variables.contains(variable) {
17714 ExclusionStatus::Failed
17715 } else {
17716 ExclusionStatus::Vacuous
17717 }
17718 }
17719 PlanNode::Scan(scan) => {
17720 if scan.graph.as_ref() != Some(variable) {
17721 return ExclusionStatus::Vacuous;
17722 }
17723 if apply_scan_graph_exclusions(scan, extra) {
17724 ExclusionStatus::Applied
17725 } else {
17726 ExclusionStatus::Failed
17727 }
17728 }
17729 PlanNode::Path(path) => {
17730 if path.graph.as_ref() != Some(variable) {
17731 return ExclusionStatus::Vacuous;
17732 }
17733 if apply_path_graph_exclusions(path, extra) {
17734 ExclusionStatus::Applied
17735 } else {
17736 ExclusionStatus::Failed
17737 }
17738 }
17739 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => merge_exclusion(
17740 apply_graph_exclusion_status(left, variable, extra),
17741 apply_graph_exclusion_status(right, variable, extra),
17742 ),
17743 PlanNode::LeftJoin { left, right, .. } => merge_exclusion(
17744 apply_graph_exclusion_status(left, variable, extra),
17745 apply_graph_exclusion_status(right, variable, extra),
17746 ),
17747 PlanNode::Filter { inner, .. }
17748 | PlanNode::Extend { inner, .. }
17749 | PlanNode::Slice { inner, .. }
17750 | PlanNode::Distinct { inner, .. }
17751 | PlanNode::Sort { inner, .. }
17752 | PlanNode::Group { inner, .. }
17753 | PlanNode::JoinGraphVar { inner, .. } => {
17754 apply_graph_exclusion_status(inner, variable, extra)
17755 }
17756 PlanNode::Values(_)
17757 | PlanNode::NamedGraphs { .. }
17758 | PlanNode::NamedGraphExists { .. }
17759 | PlanNode::DomainCounts { .. }
17762 | PlanNode::HeadCounts { .. }
17763 | PlanNode::PatternCount { .. }
17764 | PlanNode::Unit => ExclusionStatus::Vacuous,
17765 }
17766}
17767
17768fn apply_scan_graph_exclusions(scan: &mut ScanOp, extra: &[EncodedTerm]) -> bool {
17769 apply_graph_filter_exclusions(&mut scan.pattern.graph_name, &mut scan.graph_filter, extra)
17770}
17771
17772fn apply_path_graph_exclusions(path: &mut PathOp, extra: &[EncodedTerm]) -> bool {
17773 apply_graph_filter_exclusions(&mut path.graph_name, &mut path.graph_filter, extra)
17774}
17775
17776fn apply_graph_filter_exclusions(
17784 graph_name: &mut Option<EncodedTerm>,
17785 graph_filter: &mut Option<GraphFilter>,
17786 extra: &[EncodedTerm],
17787) -> bool {
17788 match graph_filter.as_ref() {
17789 Some(filter) if filter.is_exclude() => match filter.union_exclude(extra) {
17790 Some(composed) => {
17791 apply_exclusion_composed(graph_name, graph_filter, composed);
17792 true
17793 }
17794 None => false,
17795 },
17796 Some(filter) => match filter.subtract_allow(extra) {
17797 Some(composed) => {
17798 apply_exclusion_composed(graph_name, graph_filter, composed);
17799 true
17800 }
17801 None => false,
17802 },
17803 None if graph_name.is_some() => !extra.iter().any(|term| graph_name.as_ref() == Some(term)),
17804 None => match GraphFilter::exclude_default().union_exclude(extra) {
17805 Some(ComposedGraph::Filter(filter)) => {
17806 *graph_filter = Some(filter);
17807 true
17808 }
17809 Some(_) => false,
17810 None => false,
17811 },
17812 }
17813}
17814
17815fn apply_exclusion_composed(
17816 graph_name: &mut Option<EncodedTerm>,
17817 graph_filter: &mut Option<GraphFilter>,
17818 composed: ComposedGraph,
17819) {
17820 match composed {
17821 ComposedGraph::Filter(filter) => {
17822 *graph_filter = Some(filter);
17823 }
17824 other => {
17825 let (name, filter) = other.into_slots();
17826 *graph_name = name;
17827 *graph_filter = filter;
17828 }
17829 }
17830}
17831
17832fn unique_ground_from_scan(scan: &ScanOp, variable: &Variable) -> Option<EncodedTerm> {
17833 if scan.graph.as_ref() == Some(variable) {
17834 return scan.pattern.graph_name.clone();
17835 }
17836 let slots = scan.slot_of(variable);
17837 if slots.is_empty() {
17838 return None;
17839 }
17840 let mut found: Option<EncodedTerm> = None;
17841 for slot in slots {
17842 let term = pattern_slot_term(&scan.pattern, slot)?.clone();
17843 match &found {
17844 None => found = Some(term),
17845 Some(existing) if existing != &term => return None,
17846 _ => {}
17847 }
17848 }
17849 found
17850}
17851
17852fn substitute_ground_variables(
17859 expression: &mut Expression,
17860 node: &PlanNode,
17861 inner_vars: &OutputVars,
17862) {
17863 match expression {
17864 Expression::Variable(variable) => {
17865 if inner_vars.is_always_bound(variable)
17866 && let Some(ground) = unique_ground_expression(node, variable)
17867 {
17868 *expression = ground;
17869 }
17870 }
17871 Expression::Not(inner) | Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => {
17872 substitute_ground_variables(inner, node, inner_vars);
17873 }
17874 Expression::And(left, right)
17875 | Expression::Or(left, right)
17876 | Expression::SameTerm(left, right)
17877 | Expression::Equal(left, right)
17878 | Expression::Greater(left, right)
17879 | Expression::Less(left, right)
17880 | Expression::GreaterOrEqual(left, right)
17881 | Expression::LessOrEqual(left, right)
17882 | Expression::Add(left, right)
17883 | Expression::Subtract(left, right)
17884 | Expression::Multiply(left, right)
17885 | Expression::Divide(left, right) => {
17886 substitute_ground_variables(left, node, inner_vars);
17887 substitute_ground_variables(right, node, inner_vars);
17888 }
17889 Expression::If(cond, then_branch, else_branch) => {
17890 substitute_ground_variables(cond, node, inner_vars);
17891 substitute_ground_variables(then_branch, node, inner_vars);
17892 substitute_ground_variables(else_branch, node, inner_vars);
17893 }
17894 Expression::Coalesce(args) | Expression::FunctionCall(_, args) => {
17895 for arg in args {
17896 substitute_ground_variables(arg, node, inner_vars);
17897 }
17898 }
17899 Expression::In(left, args) => {
17900 substitute_ground_variables(left, node, inner_vars);
17901 for arg in args {
17902 substitute_ground_variables(arg, node, inner_vars);
17903 }
17904 }
17905 Expression::NamedNode(_)
17907 | Expression::Literal(_)
17908 | Expression::Bound(_)
17909 | Expression::Exists(_) => {}
17910 }
17911}
17912
17913fn producer_keeps_variable(expression: &Expression) -> bool {
17923 crate::plugin::process_plugins()
17924 .planner_plugins()
17925 .any(|plugin| {
17926 plugin.pins_through_optimizer(expression)
17927 && plugin.keeps_variable_when_ground(expression)
17928 })
17929}
17930
17931fn ground_residual_conjunct(
17943 conjunct: &mut Expression,
17944 inner: &PlanNode,
17945 inner_vars: &OutputVars,
17946 keeps_variable: &dyn Fn(&Expression) -> bool,
17947) {
17948 let keeps = keeps_variable(conjunct);
17949 let mut grounded = conjunct.clone();
17950 substitute_ground_variables(&mut grounded, inner, inner_vars);
17951 if variables_in_expression(&grounded).is_empty() && keeps {
17952 return;
17953 }
17954 *conjunct = grounded;
17955}
17956
17957fn unique_ground_expression(node: &PlanNode, variable: &Variable) -> Option<Expression> {
17966 match node {
17967 PlanNode::Values(values) => values
17968 .unique_term(variable)
17969 .and_then(|term| const_term_to_expression(&term, &values.strings)),
17970 PlanNode::Extend {
17971 inner,
17972 variable: bound,
17973 expression,
17974 ..
17975 } => {
17976 if bound == variable {
17977 ground_extend_expression(expression, inner)
17978 } else {
17979 unique_ground_expression(inner, variable)
17980 }
17981 }
17982 PlanNode::Join { left, right, .. } => unique_ground_expression(left, variable)
17983 .or_else(|| unique_ground_expression(right, variable)),
17984 PlanNode::LeftJoin { left, .. } => unique_ground_expression(left, variable),
17985 PlanNode::Filter { inner, .. }
17986 | PlanNode::Slice { inner, .. }
17987 | PlanNode::Distinct { inner, .. }
17988 | PlanNode::Sort { inner, .. }
17989 | PlanNode::Group { inner, .. }
17990 | PlanNode::JoinGraphVar { inner, .. } => unique_ground_expression(inner, variable),
17991 PlanNode::Scan(_)
17993 | PlanNode::Path(_)
17994 | PlanNode::Unit
17995 | PlanNode::Union { .. }
17996 | PlanNode::NamedGraphs { .. }
17997 | PlanNode::NamedGraphExists { .. }
17998 | PlanNode::DomainCounts { .. }
17999 | PlanNode::HeadCounts { .. }
18000 | PlanNode::PatternCount { .. }
18001 | PlanNode::CustomNode(_)
18002 | PlanNode::SubSelect(_) => None,
18003 }
18004}
18005
18006fn const_term_to_expression(
18017 term: &EncodedTerm,
18018 strings: &[(StrHash, String)],
18019) -> Option<Expression> {
18020 if let Ok(decoded) = waratah_storage::decode_term(term, &StringsSliceResolver(strings)) {
18021 return term_to_expression(decoded);
18022 }
18023 let key = waratah_storage::geo_lexical_key(term)?;
18024 let datatype = match term {
18025 EncodedTerm::LiteralGeometry { geo_datatype, .. } => geo_datatype.iri().to_owned(),
18026 EncodedTerm::BlobLiteral { datatype_id, .. } => strings
18027 .iter()
18028 .find(|(id, _)| id == datatype_id)
18029 .map(|(_, iri)| iri.clone())?,
18030 _ => return None,
18031 };
18032 let lexical = strings
18039 .iter()
18040 .find(|(id, _)| *id == key)
18041 .map(|(_, raw)| raw.as_str())?;
18042 Some(Expression::Literal(oxrdf::Literal::new_typed_literal(
18043 lexical,
18044 oxrdf::NamedNode::new_unchecked(datatype),
18045 )))
18046}
18047
18048fn term_to_expression(term: Term) -> Option<Expression> {
18049 match term {
18050 Term::NamedNode(node) => Some(Expression::NamedNode(node)),
18051 Term::Literal(literal) => Some(Expression::Literal(literal)),
18052 Term::BlankNode(_) => None,
18053 }
18054}
18055
18056struct StringsSliceResolver<'a>(&'a [(StrHash, String)]);
18060
18061impl waratah_storage::StrResolver for StringsSliceResolver<'_> {
18062 fn resolve(&self, hash: StrHash) -> Option<&str> {
18063 self.0
18064 .iter()
18065 .find(|(id, _)| *id == hash)
18066 .map(|(_, raw)| raw.as_str())
18067 }
18068}
18069
18070fn ground_extend_expression(expression: &Expression, inner: &PlanNode) -> Option<Expression> {
18074 match expression {
18075 Expression::NamedNode(_) | Expression::Literal(_) => Some(expression.clone()),
18076 Expression::Variable(source) => unique_ground_expression(inner, source),
18077 _ => None,
18078 }
18079}
18080
18081pub fn ground_unique_probe_term(node: &PlanNode, variable: &Variable) -> Option<EncodedTerm> {
18087 unique_ground_term(node, variable)
18088}
18089
18090fn arm_ground_term(node: &PlanNode, variable: &Variable) -> Option<EncodedTerm> {
18102 match node {
18103 PlanNode::Scan(scan) => {
18104 let slot = scan.first_slot_of(variable)?;
18105 pattern_slot_term(&scan.pattern, slot).cloned()
18106 }
18107 _ => unique_ground_term(node, variable),
18108 }
18109}
18110
18111fn conflicting_ground_keys(
18118 left: &PlanNode,
18119 right: &PlanNode,
18120 hash_keys: &[Variable],
18121) -> Option<(Variable, EncodedTerm, EncodedTerm)> {
18122 for key in hash_keys {
18123 if let (Some(left_term), Some(right_term)) =
18124 (arm_ground_term(left, key), arm_ground_term(right, key))
18125 && left_term != right_term
18126 {
18127 return Some((key.clone(), left_term, right_term));
18128 }
18129 }
18130 None
18131}
18132
18133fn provably_empty_join(left: &PlanNode, right: &PlanNode) -> PlanNode {
18150 let mut variables = left.output_vars().all();
18151 for variable in right.output_vars().all() {
18152 if !variables.contains(&variable) {
18153 variables.push(variable);
18154 }
18155 }
18156 PlanNode::Values(ValuesOp {
18157 variables,
18158 rows: Vec::new(),
18159 strings: Vec::new(),
18160 blobs: Vec::new(),
18161 })
18162}
18163
18164fn zero_row_arm(node: &PlanNode) -> bool {
18167 matches!(node, PlanNode::Values(values) if values.rows.is_empty())
18168}
18169
18170fn unique_ground_term(node: &PlanNode, variable: &Variable) -> Option<EncodedTerm> {
18172 match node {
18173 PlanNode::Scan(scan) => unique_ground_from_scan(scan, variable),
18174 PlanNode::Values(values) => values.unique_term(variable),
18175 PlanNode::Extend {
18176 inner,
18177 variable: bound,
18178 expression,
18179 ..
18180 } => {
18181 if bound == variable {
18182 ground_bind_term(inner, expression)
18183 } else {
18184 unique_ground_term(inner, variable)
18185 }
18186 }
18187 PlanNode::Join { left, right, .. } => {
18188 unique_ground_term(left, variable).or_else(|| unique_ground_term(right, variable))
18189 }
18190 PlanNode::Filter { inner, .. }
18191 | PlanNode::Slice { inner, .. }
18192 | PlanNode::Distinct { inner, .. }
18193 | PlanNode::Sort { inner, .. }
18194 | PlanNode::Group { inner, .. }
18195 | PlanNode::JoinGraphVar { inner, .. } => unique_ground_term(inner, variable),
18196 PlanNode::LeftJoin { left, .. } => unique_ground_term(left, variable),
18197 PlanNode::Path(path) => {
18198 if path.graph.as_ref() == Some(variable) {
18199 return path.graph_name.clone();
18200 }
18201 match path.end_of(variable)? {
18202 PathEnd::Start | PathEnd::Both => path.subject_term.clone(),
18203 PathEnd::End => path.object_term.clone(),
18204 }
18205 }
18206 _ => None,
18207 }
18208}
18209
18210fn ground_bind_term(inner: &PlanNode, expression: &Expression) -> Option<EncodedTerm> {
18212 match expression {
18213 Expression::NamedNode(node) => Some(EncodedTerm::from(node)),
18214 Expression::Literal(literal) => Some(crate::plugin::encode_user_literal(literal)),
18223 Expression::Variable(source) => unique_ground_term(inner, source),
18224 _ => None,
18227 }
18228}
18229
18230fn unique_ground_with_strings(
18237 node: &PlanNode,
18238 variable: &Variable,
18239) -> Option<(EncodedTerm, Vec<(StrHash, String)>)> {
18240 match node {
18241 PlanNode::Scan(scan) => {
18242 let term = unique_ground_from_scan(scan, variable)?;
18243 Some((term, Vec::new()))
18244 }
18245 PlanNode::Values(values) => {
18246 let term = values.unique_term(variable)?;
18247 Some((term, values.strings.clone()))
18248 }
18249 PlanNode::Extend {
18250 inner,
18251 variable: bound,
18252 expression,
18253 ..
18254 } => {
18255 if bound == variable {
18256 ground_extend_with_strings(inner, expression)
18257 } else {
18258 unique_ground_with_strings(inner, variable)
18259 }
18260 }
18261 PlanNode::Join { left, right, .. } => unique_ground_with_strings(left, variable)
18262 .or_else(|| unique_ground_with_strings(right, variable)),
18263 PlanNode::Filter { inner, .. }
18264 | PlanNode::Slice { inner, .. }
18265 | PlanNode::Distinct { inner, .. }
18266 | PlanNode::Sort { inner, .. }
18267 | PlanNode::Group { inner, .. }
18268 | PlanNode::JoinGraphVar { inner, .. } => unique_ground_with_strings(inner, variable),
18269 PlanNode::LeftJoin { left, .. } => unique_ground_with_strings(left, variable),
18270 PlanNode::Path(path) => {
18271 if path.graph.as_ref() == Some(variable) {
18272 return path
18273 .graph_name
18274 .clone()
18275 .map(|term| (term, path.strings.clone()));
18276 }
18277 let term = match path.end_of(variable)? {
18278 PathEnd::Start | PathEnd::Both => path.subject_term.clone()?,
18279 PathEnd::End => path.object_term.clone()?,
18280 };
18281 Some((term, path.strings.clone()))
18282 }
18283 _ => None,
18284 }
18285}
18286
18287fn ground_extend_with_strings(
18288 inner: &PlanNode,
18289 expression: &Expression,
18290) -> Option<(EncodedTerm, Vec<(StrHash, String)>)> {
18291 match expression {
18292 Expression::NamedNode(_) | Expression::Literal(_) => encoded_ground_expr(expression),
18293 Expression::Variable(source) => unique_ground_with_strings(inner, source),
18294 _ => None,
18295 }
18296}
18297
18298fn is_join_identity_pattern(pattern: &GraphPattern) -> bool {
18299 match pattern {
18300 GraphPattern::Bgp { patterns } => patterns.is_empty(),
18301 GraphPattern::Values {
18302 variables,
18303 bindings,
18304 } => is_unit_values(variables, bindings),
18305 _ => false,
18306 }
18307}
18308
18309fn ground_expression_to_term(expression: &Expression) -> Option<GroundTerm> {
18310 match expression {
18311 Expression::NamedNode(node) => Some(GroundTerm::NamedNode(node.clone())),
18312 Expression::Literal(literal) => Some(GroundTerm::Literal(literal.clone())),
18313 _ => None,
18314 }
18315}
18316
18317fn push_values_into_union(pattern: GraphPattern) -> GraphPattern {
18319 match pattern {
18320 GraphPattern::Join { left, right } => {
18321 let left = push_values_into_union(*left);
18322 let right = push_values_into_union(*right);
18323 distribute_values_over_union(left, right)
18324 }
18325 GraphPattern::Union { left, right } => GraphPattern::Union {
18326 left: Box::new(push_values_into_union(*left)),
18327 right: Box::new(push_values_into_union(*right)),
18328 },
18329 GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
18330 expr,
18331 inner: Box::new(push_values_into_union(*inner)),
18332 },
18333 GraphPattern::LeftJoin {
18334 left,
18335 right,
18336 expression,
18337 } => GraphPattern::LeftJoin {
18338 left: Box::new(push_values_into_union(*left)),
18339 right: Box::new(push_values_into_union(*right)),
18340 expression,
18341 },
18342 GraphPattern::Extend {
18343 inner,
18344 variable,
18345 expression,
18346 } => {
18347 let inner = push_values_into_union(*inner);
18348 if is_join_identity_pattern(&inner)
18349 && let Some(ground) = ground_expression_to_term(&expression)
18350 {
18351 GraphPattern::Values {
18352 variables: vec![variable],
18353 bindings: vec![vec![Some(ground)]],
18354 }
18355 } else {
18356 GraphPattern::Extend {
18362 inner: Box::new(inner),
18363 variable,
18364 expression,
18365 }
18366 }
18367 }
18368 GraphPattern::Slice {
18369 inner,
18370 start,
18371 length,
18372 } => GraphPattern::Slice {
18373 inner: Box::new(push_values_into_union(*inner)),
18374 start,
18375 length,
18376 },
18377 GraphPattern::Group {
18378 inner,
18379 variables,
18380 aggregates,
18381 } => GraphPattern::Group {
18382 inner: Box::new(push_values_into_union(*inner)),
18383 variables,
18384 aggregates,
18385 },
18386 other => other,
18387 }
18388}
18389
18390fn distribute_values_over_union(left: GraphPattern, right: GraphPattern) -> GraphPattern {
18391 match (&left, &right) {
18397 (GraphPattern::Values { .. }, GraphPattern::Union { left: a, right: b }) => {
18398 let values = left;
18399 push_values_into_union(GraphPattern::Union {
18400 left: Box::new(GraphPattern::Join {
18401 left: Box::new(values.clone()),
18402 right: a.clone(),
18403 }),
18404 right: Box::new(GraphPattern::Join {
18405 left: Box::new(values),
18406 right: b.clone(),
18407 }),
18408 })
18409 }
18410 (GraphPattern::Union { left: a, right: b }, GraphPattern::Values { .. }) => {
18411 let values = right;
18412 push_values_into_union(GraphPattern::Union {
18413 left: Box::new(GraphPattern::Join {
18414 left: a.clone(),
18415 right: Box::new(values.clone()),
18416 }),
18417 right: Box::new(GraphPattern::Join {
18418 left: b.clone(),
18419 right: Box::new(values),
18420 }),
18421 })
18422 }
18423 _ => GraphPattern::Join {
18424 left: Box::new(left),
18425 right: Box::new(right),
18426 },
18427 }
18428}
18429
18430fn place_values_at_lca_with_live(pattern: GraphPattern, live_above: &[Variable]) -> GraphPattern {
18469 let mut mentions = Vec::new();
18476 collect_mentions(&pattern, &mut mentions);
18477 for variable in live_above {
18478 bump_mention(&mut mentions, variable);
18479 }
18480 place_values_with_mentions(pattern, &mentions)
18481}
18482
18483fn bump_mention(out: &mut Vec<(Variable, usize)>, variable: &Variable) {
18484 if let Some((_, count)) = out.iter_mut().find(|(name, _)| name == variable) {
18485 *count += 1;
18486 } else {
18487 out.push((variable.clone(), 1));
18488 }
18489}
18490
18491fn mention_count(out: &[(Variable, usize)], variable: &Variable) -> usize {
18492 out.iter()
18493 .find(|(name, _)| name == variable)
18494 .map_or(0, |(_, count)| *count)
18495}
18496
18497fn bump_term_pattern_mentions(out: &mut Vec<(Variable, usize)>, term: &TermPattern) {
18498 if let TermPattern::Variable(variable) = term {
18499 bump_mention(out, variable);
18500 }
18501}
18502
18503fn bump_named_node_pattern_mentions(out: &mut Vec<(Variable, usize)>, term: &NamedNodePattern) {
18504 if let NamedNodePattern::Variable(variable) = term {
18505 bump_mention(out, variable);
18506 }
18507}
18508
18509fn collect_expression_mentions(out: &mut Vec<(Variable, usize)>, expression: &Expression) {
18519 match expression {
18520 Expression::Variable(variable) | Expression::Bound(variable) => bump_mention(out, variable),
18521 Expression::NamedNode(_) | Expression::Literal(_) => {}
18522 Expression::Not(inner) | Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => {
18523 collect_expression_mentions(out, inner)
18524 }
18525 Expression::And(left, right)
18526 | Expression::Or(left, right)
18527 | Expression::SameTerm(left, right)
18528 | Expression::Equal(left, right)
18529 | Expression::Greater(left, right)
18530 | Expression::GreaterOrEqual(left, right)
18531 | Expression::Less(left, right)
18532 | Expression::LessOrEqual(left, right)
18533 | Expression::Add(left, right)
18534 | Expression::Subtract(left, right)
18535 | Expression::Multiply(left, right)
18536 | Expression::Divide(left, right) => {
18537 collect_expression_mentions(out, left);
18538 collect_expression_mentions(out, right);
18539 }
18540 Expression::FunctionCall(_, args) => {
18541 for arg in args {
18542 collect_expression_mentions(out, arg);
18543 }
18544 }
18545 Expression::If(cond, then_branch, else_branch) => {
18546 collect_expression_mentions(out, cond);
18547 collect_expression_mentions(out, then_branch);
18548 collect_expression_mentions(out, else_branch);
18549 }
18550 Expression::Coalesce(args) => {
18551 for arg in args {
18552 collect_expression_mentions(out, arg);
18553 }
18554 }
18555 Expression::In(inner, args) => {
18556 collect_expression_mentions(out, inner);
18557 for arg in args {
18558 collect_expression_mentions(out, arg);
18559 }
18560 }
18561 Expression::Exists(pattern) => collect_mentions(pattern, out),
18562 }
18563}
18564
18565fn collect_mentions(pattern: &GraphPattern, out: &mut Vec<(Variable, usize)>) {
18566 match pattern {
18567 GraphPattern::Bgp { patterns } => {
18568 for triple in patterns {
18569 bump_term_pattern_mentions(out, &triple.subject);
18570 bump_named_node_pattern_mentions(out, &triple.predicate);
18571 bump_term_pattern_mentions(out, &triple.object);
18572 }
18573 }
18574 GraphPattern::Path {
18575 subject, object, ..
18576 } => {
18577 bump_term_pattern_mentions(out, subject);
18578 bump_term_pattern_mentions(out, object);
18579 }
18580 GraphPattern::Values { variables, .. } => {
18581 for variable in variables {
18582 bump_mention(out, variable);
18583 }
18584 }
18585 GraphPattern::Extend {
18586 inner,
18587 variable,
18588 expression,
18589 } => {
18590 bump_mention(out, variable);
18591 collect_expression_mentions(out, expression);
18592 collect_mentions(inner, out);
18593 }
18594 GraphPattern::Filter { expr, inner } => {
18595 collect_expression_mentions(out, expr);
18596 collect_mentions(inner, out);
18597 }
18598 GraphPattern::Join { left, right }
18599 | GraphPattern::Union { left, right }
18600 | GraphPattern::Minus { left, right } => {
18601 collect_mentions(left, out);
18602 collect_mentions(right, out);
18603 }
18604 GraphPattern::LeftJoin {
18605 left,
18606 right,
18607 expression,
18608 } => {
18609 if let Some(expression) = expression {
18610 collect_expression_mentions(out, expression);
18611 }
18612 collect_mentions(left, out);
18613 collect_mentions(right, out);
18614 }
18615 GraphPattern::Group {
18616 inner,
18617 variables,
18618 aggregates,
18619 } => {
18620 for key in variables {
18621 bump_mention(out, key);
18622 }
18623 for (_, aggregate) in aggregates {
18624 match aggregate {
18625 AggregateExpression::FunctionCall { expr, .. } => {
18626 collect_expression_mentions(out, expr)
18627 }
18628 AggregateExpression::CountSolutions { .. } => {}
18629 }
18630 }
18631 collect_mentions(inner, out);
18632 }
18633 GraphPattern::Project { inner, variables } => {
18634 for variable in variables {
18635 bump_mention(out, variable);
18636 }
18637 collect_mentions(inner, out);
18638 }
18639 GraphPattern::OrderBy { inner, expression } => {
18640 for key in expression {
18641 let expr = match key {
18642 OrderExpression::Asc(expr) | OrderExpression::Desc(expr) => expr,
18643 };
18644 collect_expression_mentions(out, expr);
18645 }
18646 collect_mentions(inner, out);
18647 }
18648 GraphPattern::Distinct { inner }
18649 | GraphPattern::Reduced { inner }
18650 | GraphPattern::Slice { inner, .. } => collect_mentions(inner, out),
18651 GraphPattern::Graph { name, inner } => {
18652 bump_named_node_pattern_mentions(out, name);
18653 collect_mentions(inner, out);
18654 }
18655 GraphPattern::Service { name, inner, .. } => {
18656 bump_named_node_pattern_mentions(out, name);
18657 collect_mentions(inner, out);
18658 }
18659 }
18660}
18661
18662fn place_values_with_mentions(
18663 pattern: GraphPattern,
18664 mentions: &[(Variable, usize)],
18665) -> GraphPattern {
18666 let mut tables = Vec::new();
18667 let stripped = strip_top_level_values(pattern, &mut tables);
18668 let mut result = place_values_in_children(stripped, mentions);
18672 let mut placements: Vec<(Vec<usize>, GraphPattern)> = Vec::new();
18673 for (origin, variables, mut rows) in tables {
18674 if rows.len() == 1 {
18675 collect_one_row_placements(
18676 &result,
18677 &origin,
18678 variables,
18679 rows.pop().unwrap_or_default(),
18680 mentions,
18681 &mut placements,
18682 );
18683 } else {
18684 collect_multi_row_placement(
18685 &result,
18686 &origin,
18687 variables,
18688 rows,
18689 mentions,
18690 &mut placements,
18691 );
18692 }
18693 }
18694 placements.sort_by_key(|(target, _)| std::cmp::Reverse(target.len()));
18697 for (target, values) in placements {
18698 result = insert_binding_at(result, &target, values);
18699 }
18700 result
18701}
18702
18703fn place_values_in_children(pattern: GraphPattern, mentions: &[(Variable, usize)]) -> GraphPattern {
18704 let place = |child: GraphPattern| Box::new(place_values_with_mentions(child, mentions));
18705 match pattern {
18706 GraphPattern::Join { left, right } => GraphPattern::Join {
18707 left: place(*left),
18708 right: place(*right),
18709 },
18710 GraphPattern::Union { left, right } => GraphPattern::Union {
18711 left: place(*left),
18712 right: place(*right),
18713 },
18714 GraphPattern::Minus { left, right } => GraphPattern::Minus {
18715 left: place(*left),
18716 right: place(*right),
18717 },
18718 GraphPattern::LeftJoin {
18719 left,
18720 right,
18721 expression,
18722 } => GraphPattern::LeftJoin {
18723 left: place(*left),
18724 right: place(*right),
18725 expression,
18726 },
18727 GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
18728 expr,
18729 inner: place(*inner),
18730 },
18731 GraphPattern::Extend {
18732 inner,
18733 variable,
18734 expression,
18735 } => GraphPattern::Extend {
18736 inner: place(*inner),
18737 variable,
18738 expression,
18739 },
18740 GraphPattern::Group {
18741 inner,
18742 variables,
18743 aggregates,
18744 } => GraphPattern::Group {
18745 inner: place(*inner),
18746 variables,
18747 aggregates,
18748 },
18749 GraphPattern::Project { inner, variables } => GraphPattern::Project {
18750 inner: place(*inner),
18751 variables,
18752 },
18753 GraphPattern::OrderBy { inner, expression } => GraphPattern::OrderBy {
18754 inner: place(*inner),
18755 expression,
18756 },
18757 GraphPattern::Distinct { inner } => GraphPattern::Distinct {
18758 inner: place(*inner),
18759 },
18760 GraphPattern::Reduced { inner } => GraphPattern::Reduced {
18761 inner: place(*inner),
18762 },
18763 GraphPattern::Slice {
18764 inner,
18765 start,
18766 length,
18767 } => GraphPattern::Slice {
18768 inner: place(*inner),
18769 start,
18770 length,
18771 },
18772 GraphPattern::Graph { name, inner } => GraphPattern::Graph {
18773 name,
18774 inner: place(*inner),
18775 },
18776 GraphPattern::Service {
18777 name,
18778 inner,
18779 silent,
18780 } => GraphPattern::Service {
18781 name,
18782 inner: place(*inner),
18783 silent,
18784 },
18785 GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Values { .. } => {
18786 pattern
18787 }
18788 }
18789}
18790
18791type StrippedTable = (Vec<usize>, Vec<Variable>, Vec<Vec<Option<GroundTerm>>>);
18792
18793fn strip_top_level_values(pattern: GraphPattern, out: &mut Vec<StrippedTable>) -> GraphPattern {
18794 strip_top_level_values_at(pattern, &mut Vec::new(), out)
18795}
18796
18797fn strip_top_level_values_at(
18798 pattern: GraphPattern,
18799 path: &mut Vec<usize>,
18800 out: &mut Vec<StrippedTable>,
18801) -> GraphPattern {
18802 match pattern {
18803 GraphPattern::Values {
18804 variables,
18805 bindings,
18806 } if !bindings.is_empty() => {
18807 out.push((path.clone(), variables, bindings));
18808 empty_bgp()
18809 }
18810 GraphPattern::Join { left, right } => {
18811 path.push(0);
18812 let left = strip_top_level_values_at(*left, path, out);
18813 path.pop();
18814 path.push(1);
18815 let right = strip_top_level_values_at(*right, path, out);
18816 path.pop();
18817 GraphPattern::Join {
18818 left: Box::new(left),
18819 right: Box::new(right),
18820 }
18821 }
18822 GraphPattern::Union { left, right } => GraphPattern::Union { left, right },
18826 GraphPattern::Filter { .. } => pattern,
18832 GraphPattern::Extend { .. } => pattern,
18836 other => other,
18837 }
18838}
18839
18840fn empty_bgp() -> GraphPattern {
18841 GraphPattern::Bgp {
18842 patterns: Vec::new(),
18843 }
18844}
18845
18846fn collect_one_row_placements(
18847 pattern: &GraphPattern,
18848 origin: &[usize],
18849 variables: Vec<Variable>,
18850 row: Vec<Option<GroundTerm>>,
18851 mentions: &[(Variable, usize)],
18852 out: &mut Vec<(Vec<usize>, GraphPattern)>,
18853) {
18854 if variables.len() != row.len() {
18855 return;
18856 }
18857 let mut groups: std::collections::BTreeMap<Vec<usize>, Vec<(Variable, Option<GroundTerm>)>> =
18858 std::collections::BTreeMap::new();
18859 for (variable, cell) in variables.into_iter().zip(row) {
18860 let mut sites = Vec::new();
18861 collect_binding_sites(
18862 pattern,
18863 std::slice::from_ref(&variable),
18864 &mut Vec::new(),
18865 &mut sites,
18866 );
18867 let target = if sites.is_empty() {
18868 if mention_count(mentions, &variable) <= 1 {
18869 continue;
18872 }
18873 origin.to_vec()
18877 } else {
18878 let target = common_path_prefix(&sites).unwrap_or_default();
18879 safe_join_target(pattern, &target)
18880 };
18881 groups.entry(target).or_default().push((variable, cell));
18882 }
18883 for (target, columns) in groups {
18884 let values = GraphPattern::Values {
18885 variables: columns
18886 .iter()
18887 .map(|(variable, _)| variable.clone())
18888 .collect(),
18889 bindings: vec![columns.iter().map(|(_, term)| term.clone()).collect()],
18890 };
18891 out.push((target, values));
18892 }
18893}
18894
18895fn collect_multi_row_placement(
18896 pattern: &GraphPattern,
18897 origin: &[usize],
18898 variables: Vec<Variable>,
18899 rows: Vec<Vec<Option<GroundTerm>>>,
18900 mentions: &[(Variable, usize)],
18901 out: &mut Vec<(Vec<usize>, GraphPattern)>,
18902) {
18903 let mut kept_variables = Vec::new();
18910 let mut kept_rows: Vec<Vec<Option<GroundTerm>>> = vec![Vec::new(); rows.len()];
18911 for (index, variable) in variables.iter().enumerate() {
18912 if mention_count(mentions, variable) <= 1 {
18913 continue;
18914 }
18915 kept_variables.push(variable.clone());
18916 for (row_index, row) in rows.iter().enumerate() {
18917 kept_rows[row_index].push(row.get(index).cloned().flatten());
18918 }
18919 }
18920 if kept_variables.is_empty() {
18921 out.push((
18924 origin.to_vec(),
18925 GraphPattern::Values {
18926 variables,
18927 bindings: rows,
18928 },
18929 ));
18930 return;
18931 }
18932 let mut sites = Vec::new();
18933 let mut needs_origin = false;
18934 for variable in &kept_variables {
18935 let before = sites.len();
18936 collect_binding_sites(
18937 pattern,
18938 std::slice::from_ref(variable),
18939 &mut Vec::new(),
18940 &mut sites,
18941 );
18942 if sites.len() == before && mention_count(mentions, variable) > 1 {
18943 needs_origin = true;
18947 }
18948 }
18949 let target = if sites.is_empty() || needs_origin {
18950 origin.to_vec()
18951 } else {
18952 let target = common_path_prefix(&sites).unwrap_or_default();
18953 safe_join_target(pattern, &target)
18954 };
18955 out.push((
18956 target,
18957 GraphPattern::Values {
18958 variables: kept_variables,
18959 bindings: kept_rows,
18960 },
18961 ));
18962}
18963
18964fn insert_binding_at(
18965 pattern: GraphPattern,
18966 target: &[usize],
18967 binding: GraphPattern,
18968) -> GraphPattern {
18969 let Some((&index, rest)) = target.split_first() else {
18970 return GraphPattern::Join {
18971 left: Box::new(binding),
18972 right: Box::new(pattern),
18973 };
18974 };
18975 replace_algebra_child(pattern, index, &mut |child| {
18976 insert_binding_at(child, rest, binding.clone())
18977 })
18978}
18979
18980pub(crate) fn algebra_in_scope_vars(pattern: &GraphPattern, out: &mut Vec<Variable>) {
18985 let push_term = |out: &mut Vec<Variable>, term: &TermPattern| {
18986 if let TermPattern::Variable(v) = term
18987 && !out.contains(v)
18988 {
18989 out.push(v.clone());
18990 }
18991 };
18992 match pattern {
18993 GraphPattern::Bgp { patterns } => {
18994 for triple in patterns {
18995 push_term(out, &triple.subject);
18996 if let NamedNodePattern::Variable(v) = &triple.predicate
18997 && !out.contains(v)
18998 {
18999 out.push(v.clone());
19000 }
19001 push_term(out, &triple.object);
19002 }
19003 }
19004 GraphPattern::Path {
19005 subject, object, ..
19006 } => {
19007 push_term(out, subject);
19008 push_term(out, object);
19009 }
19010 GraphPattern::Join { left, right }
19011 | GraphPattern::Union { left, right }
19012 | GraphPattern::Minus { left, right }
19013 | GraphPattern::LeftJoin { left, right, .. } => {
19014 algebra_in_scope_vars(left, out);
19015 algebra_in_scope_vars(right, out);
19016 }
19017 GraphPattern::Filter { inner, .. } => algebra_in_scope_vars(inner, out),
19018 GraphPattern::Graph { name, inner } => {
19019 if let NamedNodePattern::Variable(v) = name
19020 && !out.contains(v)
19021 {
19022 out.push(v.clone());
19023 }
19024 algebra_in_scope_vars(inner, out);
19025 }
19026 GraphPattern::Extend {
19027 inner, variable, ..
19028 } => {
19029 algebra_in_scope_vars(inner, out);
19030 if !out.contains(variable) {
19031 out.push(variable.clone());
19032 }
19033 }
19034 GraphPattern::Values { variables, .. } => {
19035 for v in variables {
19036 if !out.contains(v) {
19037 out.push(v.clone());
19038 }
19039 }
19040 }
19041 GraphPattern::OrderBy { inner, .. }
19042 | GraphPattern::Slice { inner, .. }
19043 | GraphPattern::Distinct { inner }
19044 | GraphPattern::Reduced { inner }
19045 | GraphPattern::Service { inner, .. } => algebra_in_scope_vars(inner, out),
19046 GraphPattern::Group {
19047 inner,
19048 variables,
19049 aggregates,
19050 } => {
19051 algebra_in_scope_vars(inner, out);
19052 for v in variables {
19053 if !out.contains(v) {
19054 out.push(v.clone());
19055 }
19056 }
19057 for (result, _) in aggregates {
19058 if !out.contains(result) {
19059 out.push(result.clone());
19060 }
19061 }
19062 }
19063 GraphPattern::Project { variables, .. } => {
19065 for v in variables {
19066 if !out.contains(v) {
19067 out.push(v.clone());
19068 }
19069 }
19070 }
19071 }
19072}
19073
19074fn push_groundings_into_subselects(pattern: GraphPattern) -> GraphPattern {
19097 match pattern {
19098 GraphPattern::Join { left, right } => {
19099 let mut nodes = Vec::new();
19105 flatten_join_tree(*left, &mut nodes);
19106 flatten_join_tree(*right, &mut nodes);
19107 let mut values = Vec::new();
19108 let mut rest = Vec::new();
19109 for node in nodes {
19110 if matches!(node, GraphPattern::Values { .. }) {
19111 values.push(node);
19112 } else {
19113 rest.push(node);
19114 }
19115 }
19116 let mut rest_out = Vec::with_capacity(rest.len());
19117 for node in rest {
19118 rest_out.push(rewrite_subselect_join_context(node));
19119 }
19120 let mut rest = rest_out;
19121 let mut virtual_values: Vec<(GraphPattern, Vec<Variable>)> = Vec::new();
19125 for node in &rest {
19126 if let GraphPattern::Extend {
19127 inner,
19128 variable,
19129 expression,
19130 } = node
19131 && let Some(ground) = ground_expression_to_term(expression)
19132 {
19133 let mut scope = Vec::new();
19134 algebra_in_scope_vars(inner, &mut scope);
19135 if !scope.contains(variable) {
19136 virtual_values.push((
19137 GraphPattern::Values {
19138 variables: vec![variable.clone()],
19139 bindings: vec![vec![Some(ground)]],
19140 },
19141 vec![variable.clone()],
19142 ));
19143 }
19144 }
19145 }
19146 for subquery in &mut rest {
19147 for table in &values {
19148 let GraphPattern::Values { variables, .. } = table else {
19149 unreachable!("only Values collected");
19150 };
19151 try_push_values_into_subselect(subquery, table, variables);
19152 }
19153 for (table, variables) in &virtual_values {
19154 try_push_values_into_subselect(subquery, table, variables);
19155 }
19156 }
19157 let mut out = Vec::with_capacity(rest.len() + values.len());
19159 out.extend(values);
19160 out.extend(rest);
19161 rebuild_join_tree(out)
19162 }
19163 GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
19164 expr,
19165 inner: Box::new(push_groundings_into_subselects(*inner)),
19166 },
19167 GraphPattern::Union { left, right } => GraphPattern::Union {
19168 left: Box::new(push_groundings_into_subselects(*left)),
19169 right: Box::new(push_groundings_into_subselects(*right)),
19170 },
19171 GraphPattern::LeftJoin {
19177 left,
19178 right,
19179 expression,
19180 } => GraphPattern::LeftJoin {
19181 left: Box::new(push_groundings_into_subselects(*left)),
19182 right: Box::new(push_groundings_into_subselects(*right)),
19183 expression,
19184 },
19185 GraphPattern::Extend {
19186 inner,
19187 variable,
19188 expression,
19189 } => GraphPattern::Extend {
19190 inner: Box::new(push_groundings_into_subselects(*inner)),
19191 variable,
19192 expression,
19193 },
19194 GraphPattern::Graph { name, inner } => GraphPattern::Graph {
19195 name,
19196 inner: Box::new(push_groundings_into_subselects(*inner)),
19197 },
19198 GraphPattern::Project { inner, variables } => GraphPattern::Project {
19201 inner: Box::new(push_groundings_into_subselects(*inner)),
19202 variables,
19203 },
19204 GraphPattern::Slice {
19205 inner,
19206 start,
19207 length,
19208 } => GraphPattern::Slice {
19209 inner: Box::new(push_groundings_into_subselects(*inner)),
19210 start,
19211 length,
19212 },
19213 GraphPattern::Distinct { inner } => GraphPattern::Distinct {
19214 inner: Box::new(push_groundings_into_subselects(*inner)),
19215 },
19216 GraphPattern::Reduced { inner } => GraphPattern::Reduced {
19217 inner: Box::new(push_groundings_into_subselects(*inner)),
19218 },
19219 GraphPattern::Group {
19220 inner,
19221 variables,
19222 aggregates,
19223 } => GraphPattern::Group {
19224 inner: Box::new(push_groundings_into_subselects(*inner)),
19225 variables,
19226 aggregates,
19227 },
19228 other => other,
19229 }
19230}
19231
19232fn flatten_join_tree(pattern: GraphPattern, out: &mut Vec<GraphPattern>) {
19234 match pattern {
19235 GraphPattern::Join { left, right } => {
19236 flatten_join_tree(*left, out);
19237 flatten_join_tree(*right, out);
19238 }
19239 other => out.push(other),
19240 }
19241}
19242
19243fn rewrite_subselect_join_context(node: GraphPattern) -> GraphPattern {
19248 match node {
19249 GraphPattern::Project { inner, variables } => GraphPattern::Project {
19250 inner: Box::new(push_groundings_into_subselects(*inner)),
19251 variables,
19252 },
19253 GraphPattern::Union { left, right } => GraphPattern::Union {
19254 left: Box::new(push_groundings_into_subselects(*left)),
19255 right: Box::new(push_groundings_into_subselects(*right)),
19256 },
19257 GraphPattern::LeftJoin {
19261 left,
19262 right,
19263 expression,
19264 } => GraphPattern::LeftJoin {
19265 left: Box::new(push_groundings_into_subselects(*left)),
19266 right: Box::new(push_groundings_into_subselects(*right)),
19267 expression,
19268 },
19269 GraphPattern::Extend {
19270 inner,
19271 variable,
19272 expression,
19273 } => GraphPattern::Extend {
19274 inner: Box::new(push_groundings_into_subselects(*inner)),
19275 variable,
19276 expression,
19277 },
19278 GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
19279 expr,
19280 inner: Box::new(push_groundings_into_subselects(*inner)),
19281 },
19282 GraphPattern::Graph { name, inner } => GraphPattern::Graph {
19283 name,
19284 inner: Box::new(push_groundings_into_subselects(*inner)),
19285 },
19286 GraphPattern::Slice {
19287 inner,
19288 start,
19289 length,
19290 } => GraphPattern::Slice {
19291 inner: Box::new(push_groundings_into_subselects(*inner)),
19292 start,
19293 length,
19294 },
19295 GraphPattern::Distinct { inner } => GraphPattern::Distinct {
19296 inner: Box::new(push_groundings_into_subselects(*inner)),
19297 },
19298 GraphPattern::Reduced { inner } => GraphPattern::Reduced {
19299 inner: Box::new(push_groundings_into_subselects(*inner)),
19300 },
19301 GraphPattern::Group {
19302 inner,
19303 variables,
19304 aggregates,
19305 } => GraphPattern::Group {
19306 inner: Box::new(push_groundings_into_subselects(*inner)),
19307 variables,
19308 aggregates,
19309 },
19310 other => other,
19311 }
19312}
19313
19314fn rebuild_join_tree(nodes: Vec<GraphPattern>) -> GraphPattern {
19315 let mut nodes = nodes.into_iter();
19316 let Some(first) = nodes.next() else {
19317 return GraphPattern::Bgp {
19319 patterns: Vec::new(),
19320 };
19321 };
19322 nodes.fold(first, |left, right| GraphPattern::Join {
19323 left: Box::new(left),
19324 right: Box::new(right),
19325 })
19326}
19327
19328fn try_push_values_into_subselect(
19331 pattern: &mut GraphPattern,
19332 values: &GraphPattern,
19333 variables: &[Variable],
19334) -> bool {
19335 match pattern {
19336 GraphPattern::Slice { inner, .. } => {
19337 try_push_values_into_subselect(inner, values, variables)
19338 }
19339 GraphPattern::Project {
19340 inner,
19341 variables: projection,
19342 } => {
19343 if !variables.iter().all(|v| projection.contains(v)) {
19344 return false;
19345 }
19346 let clone = values.clone();
19347 let body = std::mem::replace(
19348 inner.as_mut(),
19349 GraphPattern::Bgp {
19350 patterns: Vec::new(),
19351 },
19352 );
19353 **inner = GraphPattern::Join {
19354 left: Box::new(clone),
19355 right: Box::new(body),
19356 };
19357 true
19358 }
19359 _ => false,
19361 }
19362}
19363
19364fn term_slot(
19365 pattern: &TermPattern,
19366) -> Result<(Option<EncodedTerm>, Option<Variable>), ComputeError> {
19367 Ok(match pattern {
19368 TermPattern::NamedNode(node) => (Some(EncodedTerm::from(node)), None),
19369 TermPattern::Literal(literal) => (Some(crate::plugin::encode_user_literal(literal)), None),
19370 TermPattern::Variable(variable) => (None, Some(variable.clone())),
19371 TermPattern::BlankNode(node) => {
19375 return Err(ComputeError::UnsupportedSparql(format!(
19376 "blank node {node} in a query pattern is not supported"
19377 )));
19378 }
19379 })
19380}
19381
19382fn named_node_slot(pattern: &NamedNodePattern) -> (Option<EncodedTerm>, Option<Variable>) {
19383 match pattern {
19384 NamedNodePattern::NamedNode(node) => (Some(EncodedTerm::from(node)), None),
19385 NamedNodePattern::Variable(variable) => (None, Some(variable.clone())),
19386 }
19387}
19388
19389#[cfg(test)]
19400pub(crate) mod count_split_probe {
19401 use spargebra::algebra::{AggregateExpression, AggregateFunction, Expression};
19402 use waratah_storage::{EncodedTerm, EncodedTriplePattern, NamedNode, Variable};
19403
19404 use super::{DomainScanKind, PlanNode, join_nodes};
19405 use crate::query::fixtures::count_split_scan;
19406
19407 fn var(name: &str) -> Variable {
19408 Variable::new(name).unwrap()
19409 }
19410
19411 fn term(iri: &str) -> EncodedTerm {
19412 EncodedTerm::from(&NamedNode::new(iri).unwrap())
19413 }
19414
19415 const P_IBRA: &str = "http://ex/ibraRegion";
19416 const P_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
19417 const C_SITE: &str = "https://w3id.org/tern/Site";
19418 const P_WITHIN: &str = "http://ex/withinIBRA";
19419
19420 pub(crate) fn root() -> PlanNode {
19421 let type_scan = PlanNode::Scan(count_split_scan(
19426 EncodedTriplePattern {
19427 subject: None,
19428 predicate: Some(term(P_TYPE)),
19429 object: Some(term(C_SITE)),
19430 graph_name: None,
19431 },
19432 Some(var("site")),
19433 None,
19434 6,
19435 ));
19436 let within_scan = PlanNode::Scan(count_split_scan(
19437 EncodedTriplePattern {
19438 subject: None,
19439 predicate: Some(term(P_WITHIN)),
19440 object: None,
19441 graph_name: None,
19442 },
19443 Some(var("site")),
19444 Some(var("r")),
19445 7,
19446 ));
19447 let site_counts = PlanNode::Group {
19448 inner: Box::new(join_nodes(type_scan, within_scan, None)),
19449 variables: vec![var("r")],
19450 aggregates: vec![(
19451 var("cs_nsite"),
19452 AggregateExpression::CountSolutions { distinct: false },
19453 )],
19454 const_strings: Vec::new(),
19455 const_blobs: Vec::new(),
19456 };
19457
19458 let domain_counts = PlanNode::DomainCounts {
19463 kind: DomainScanKind::PredicateDomain,
19464 constraints: vec![term(P_IBRA)],
19465 constraint_multiplicity: vec![1],
19466 constraint_var: None,
19467 head: var("r"),
19468 count: var("cs_nocc"),
19469 dead: Some(var("occ")),
19470 count_star: true,
19471 count_distinct: false,
19472 graph_name: None,
19473 graph_filter: None,
19474 merge_default_graph: false,
19475 iri_only: false,
19476 produced_row_count_estimate: 4,
19477 };
19478
19479 let count_join = join_nodes(domain_counts, site_counts, None);
19485 let product = PlanNode::Extend {
19486 inner: Box::new(count_join),
19487 variable: var("cs_prod"),
19488 expression: Expression::Multiply(
19489 Box::new(Expression::Variable(var("cs_nocc"))),
19490 Box::new(Expression::Variable(var("cs_nsite"))),
19491 ),
19492 const_strings: Vec::new(),
19493 const_blobs: Vec::new(),
19494 };
19495 let sum = PlanNode::Group {
19496 inner: Box::new(product),
19497 variables: Vec::new(),
19498 aggregates: vec![(
19499 var("cs_sum"),
19500 AggregateExpression::FunctionCall {
19501 name: AggregateFunction::Sum,
19502 expr: Expression::Variable(var("cs_prod")),
19503 distinct: false,
19504 },
19505 )],
19506 const_strings: Vec::new(),
19507 const_blobs: Vec::new(),
19508 };
19509 PlanNode::Extend {
19510 inner: Box::new(sum),
19511 variable: var("n"),
19512 expression: Expression::Variable(var("cs_sum")),
19513 const_strings: Vec::new(),
19514 const_blobs: Vec::new(),
19515 }
19516 }
19517}
19518
19519#[cfg(test)]
19520mod tests {
19521 use super::*;
19522 use crate::explain::ExplainFormat;
19523 use pretty_assertions::assert_eq;
19524 use spargebra::SparqlParser;
19525 use waratah_stats::{LiveQuadsProfile, StatsProfile, observe_quad};
19526 use waratah_storage::{CompareOp, Literal, NamedNode, PartitionAxis, StorageOp, encode_quad};
19527
19528 const DEMO: &str = r#"
19529 SELECT ?person ?weather WHERE {
19530 ?person <http://ex/livesIn> ?city .
19531 ?city <http://ex/hasWeather> ?weather .
19532 }
19533 "#;
19534
19535 fn var(name: &str) -> Variable {
19536 Variable::new(name).unwrap()
19537 }
19538
19539 #[derive(Debug)]
19542 struct CostTestPayload;
19543 impl crate::plugin::PluginPayload for CostTestPayload {
19544 fn plugin_id(&self) -> &'static str {
19545 "cost-test"
19546 }
19547 fn dyn_eq(&self, other: &dyn crate::plugin::PluginPayload) -> bool {
19551 other.as_any().downcast_ref::<CostTestPayload>().is_some()
19552 }
19553 }
19554
19555 fn cost_test_op(rows: u64, cost: Option<CustomOpCost>) -> CustomOp {
19556 CustomOp {
19557 plugin_id: "cost-test",
19558 op_id: "op",
19559 payload: crate::plugin::PluginPayloadBox::new(CostTestPayload),
19560 children: Vec::new(),
19561 variables: vec![var("g")],
19562 produced_row_count_estimate: rows,
19563 cost,
19564 pinned: Vec::new(),
19565 }
19566 }
19567
19568 fn probe_cost(memo_rows: u64) -> CustomOpCost {
19569 CustomOpCost {
19570 drain_rows: 2_000_000,
19571 per_key_unit: 1,
19572 inline_point_unit: 1,
19573 direct_probe: false,
19574 probe_keyed_columns: 0,
19575 probe_filter_unit: 1,
19576 probe_memo_entry_rows: memo_rows,
19577 }
19578 }
19579
19580 #[test]
19581 fn a_scan_filter_probe_examines_the_whole_output() {
19582 let op = cost_test_op(2_000_000, Some(probe_cost(262_144)));
19585 assert_eq!(op.probe_page_cost(500, Some(0)), Some((2_000_000, true)));
19586 assert_eq!(op.probe_page_cost(500, None), Some((2_000_000, true)));
19587 let direct = CustomOpCost {
19589 direct_probe: true,
19590 probe_keyed_columns: 0b1,
19591 probe_filter_unit: 1,
19592 ..probe_cost(262_144)
19593 };
19594 let op = cost_test_op(2_000_000, Some(direct));
19595 assert_eq!(op.probe_page_cost(500, Some(0)), Some((500, false)));
19596 }
19597
19598 #[test]
19602 fn a_keyed_column_prices_per_key_while_an_unkeyed_one_scans() {
19603 let cost = CustomOpCost {
19604 direct_probe: false,
19605 probe_keyed_columns: 0b1,
19606 probe_filter_unit: 1,
19607 ..probe_cost(16_777_216)
19608 };
19609 let mut op = cost_test_op(2_000_000, Some(cost));
19610 op.variables = vec![var("s"), var("g")];
19611 assert_eq!(op.probe_page_cost(1_000, Some(0)), Some((1_000, true)));
19613 assert_eq!(op.keyed_cost(1_000, Some(0)), Some(2_000_000 + 1_000));
19614 assert_eq!(op.probe_page_cost(1_000, Some(1)), Some((2_000_000, true)));
19616 assert_eq!(op.probe_page_cost(1_000, Some(9)), Some((2_000_000, true)));
19619 assert_eq!(op.probe_page_cost(1_000, None), Some((2_000_000, true)));
19620 }
19621
19622 #[test]
19623 fn the_drain_is_amortized_only_when_the_window_fits_the_memo() {
19624 let op = cost_test_op(2_000_000, Some(probe_cost(262_144)));
19626 assert!(!op.probe_drain_amortized());
19627 let op = cost_test_op(200_000, Some(probe_cost(262_144)));
19629 assert!(op.probe_drain_amortized());
19630 let op = cost_test_op(200_000, Some(probe_cost(0)));
19632 assert!(!op.probe_drain_amortized());
19633 }
19634
19635 #[test]
19636 fn the_custom_probe_seat_charges_once_or_per_page_by_memo_fit() {
19637 let seat = |produced: u64| {
19641 let probe = PlanNode::CustomNode(cost_test_op(produced, Some(probe_cost(262_144))));
19642 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/p", Some("o"), 500_000));
19645 seat_cost_total(None, &driver, &probe, &[var("g")], None, None)
19646 };
19647 let per_page = seat(2_000_000);
19648 let once = seat(200_000);
19649 assert!(
19650 per_page.rows > once.rows,
19651 "an over-budget window must price higher: per-page {} vs once {}",
19652 per_page.rows,
19653 once.rows
19654 );
19655 }
19656
19657 #[test]
19658 fn opaque_op_prices_at_none() {
19659 let op = cost_test_op(1000, None);
19662 assert_eq!(op.sweep_cost(), None);
19663 assert_eq!(op.keyed_cost(10, None), None);
19664 }
19665
19666 #[test]
19672 fn containing_push_bound_reproduces_sydney() {
19673 let driver = PlanNode::CustomNode(cost_test_op(8_000_000, None));
19674 let bound = containing_push_driver_bound(None, &driver, &var("g"), 24_576);
19675 assert_eq!(bound, Some(24_576), "1 row per key × 24,576 page keys");
19676 }
19677
19678 #[test]
19685 fn containing_push_bound_prices_the_dense_keyed_return() {
19686 let mut profile = StatsProfile::default();
19687 let mut subjects = waratah_stats::HyperLogLog::default_params();
19688 for i in 0..98_000u128 {
19689 subjects.add(i);
19690 }
19691 profile
19692 .subjects_per_predicate
19693 .insert(waratah_storage::StrHash::new("http://ex/dense"), subjects);
19694 profile
19695 .predicate_counts
19696 .insert(waratah_storage::StrHash::new("http://ex/dense"), 8_000_000);
19697 let driver = PlanNode::Scan(var_scan(
19698 Some("feature"),
19699 "http://ex/dense",
19700 Some("v"),
19701 8_000_000,
19702 ));
19703 let bound = containing_push_driver_bound(Some(&profile), &driver, &var("feature"), 24_576);
19704 let b = bound.expect("the subject HLL gives the domain");
19705 assert!(
19706 (1_500_000..3_000_000).contains(&b),
19707 "the keyed return is ~2M per page, not the subtree output's ~24K (got {b})"
19708 );
19709 }
19710
19711 #[test]
19728 fn containing_push_bound_on_a_join_driver_keeps_the_unpushed_page_count() {
19729 let mut profile = StatsProfile::default();
19730 for (pred, rows, subjects) in [
19731 ("http://ex/keyed", 244_793_u64, 241_786_u128),
19732 ("http://ex/other", 400_000, 400_000),
19733 ] {
19734 profile.predicate_counts.insert(StrHash::new(pred), rows);
19735 profile
19736 .subjects_per_predicate
19737 .insert(StrHash::new(pred), hll_with_n(subjects));
19738 }
19739 let keyed = PlanNode::Scan(var_scan(Some("r"), "http://ex/keyed", Some("v"), 244_793));
19740 let scan_bound = containing_push_driver_bound(Some(&profile), &keyed, &var("r"), 24_576)
19744 .expect("the subject HLL gives the domain");
19745 assert!(
19746 (24_500..=25_200).contains(&scan_bound),
19747 "a scan driver returns ~pushed × rows/domain (got {scan_bound})"
19748 );
19749
19750 let joined = PlanNode::Join {
19755 left: Box::new(keyed),
19756 right: Box::new(PlanNode::Scan(var_scan(
19757 Some("z"),
19758 "http://ex/other",
19759 Some("q"),
19760 400_000,
19761 ))),
19762 hash_keys: Vec::new(),
19763 probe_key_domains: Vec::new(),
19764 probe_key_overlap_milli: Vec::new(),
19765 rhs_hostable_keys: Vec::new().into(),
19766 meta: JoinMeta {
19767 semi_gate: None,
19768 star_arms: None,
19769 strategy: JoinStrategy::Broadcast,
19770 produced_row_count_estimate: 244_793,
19771 own_push_removed_row_count_estimate: 244_793,
19772 },
19773 };
19774 let join_bound = containing_push_driver_bound(Some(&profile), &joined, &var("r"), 24_576)
19775 .expect("the key domain is still known through the join");
19776 assert!(
19777 join_bound > 1_000_000_000,
19778 "the composed-read product dwarfs the output (got {join_bound})"
19779 );
19780 assert!(
19781 join_bound > scan_bound,
19782 "the join bound is a no-op above its output, not a narrowing"
19783 );
19784 }
19785
19786 #[test]
19791 fn containing_push_bound_unknown_domain_stands_down() {
19792 let driver = PlanNode::Scan(var_scan(
19793 Some("feature"),
19794 "http://ex/other",
19795 Some("x"),
19796 8_000_000,
19797 ));
19798 assert_eq!(
19799 containing_push_driver_bound(None, &driver, &var("geom"), 24_576),
19800 None,
19801 "no domain, no bound — standalone pricing"
19802 );
19803 }
19804
19805 #[test]
19818 fn containing_push_basis_is_unclamped_under_foreign_claim() {
19819 let mut profile = StatsProfile::default();
19820 profile
19821 .predicate_counts
19822 .insert(StrHash::new("http://ex/asWKT"), 817_201);
19823 profile
19824 .subjects_per_predicate
19825 .insert(StrHash::new("http://ex/asWKT"), hll_with_n(817_201));
19826 let mut claimed = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 514));
19829 let slots = match &claimed {
19830 PlanNode::Scan(scan) => scan.slot_of(&var("g")),
19831 _ => unreachable!("driver is a scan"),
19832 };
19833 assert_eq!(slots.len(), 1, "the subject slot hosts ?g");
19834 if let PlanNode::Scan(scan) = &mut claimed {
19835 scan.broadcasted = Some((var("g"), slots[0]));
19836 }
19837 let keys = [var("wkt")];
19838 assert_eq!(
19841 driver_whole_read_rows(&claimed, &keys, Some(&profile)),
19842 514,
19843 "the cost model's row basis stays the foreign-claim cell"
19844 );
19845 assert_eq!(
19848 pushed_return_bound_core(500, 514, Some(817_201)),
19849 Some(1),
19850 "the double-discounted cell basis is the 9-row walk's source"
19851 );
19852 let bound = containing_push_driver_bound(Some(&profile), &claimed, &var("g"), 500);
19855 let b = bound.expect("the ?g domain is sketched");
19856 assert!(
19857 (480..=520).contains(&b),
19858 "500 keys × ~1 row/key ≈ 500, not the claimed cell's 1 (got {b})"
19859 );
19860 let pristine = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 817_201));
19863 assert_eq!(
19864 containing_push_driver_bound(Some(&profile), &pristine, &var("g"), 500),
19865 Some(b),
19866 "same facts, same bound — the claim does not move it"
19867 );
19868 }
19869
19870 #[test]
19879 fn containing_push_basis_holds_through_containers() {
19880 let mut profile = StatsProfile::default();
19881 for (pred, rows, subjects, objects) in [
19882 ("http://ex/asWKT", 817_201_u64, 817_201_u128, 795_534_u128),
19883 ("http://ex/other", 400_000, 400_000, 400_000),
19884 ] {
19885 profile.predicate_counts.insert(StrHash::new(pred), rows);
19886 profile
19887 .subjects_per_predicate
19888 .insert(StrHash::new(pred), hll_with_n(subjects));
19889 profile
19890 .objects_per_predicate
19891 .insert(StrHash::new(pred), hll_with_n(objects));
19892 }
19893 let mut claimed = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 514));
19896 let slots = match &claimed {
19897 PlanNode::Scan(scan) => scan.slot_of(&var("g")),
19898 _ => unreachable!("claimed is a scan"),
19899 };
19900 if let PlanNode::Scan(scan) = &mut claimed {
19901 scan.broadcasted = Some((var("g"), slots[0]));
19902 }
19903 let expect_honest_bound = |label: &str, driver: &PlanNode| {
19904 let bound = containing_push_driver_bound(Some(&profile), driver, &var("g"), 500);
19905 let b = bound.unwrap_or_else(|| panic!("{label}: the ?g domain is known"));
19906 assert!(
19907 (480..=520).contains(&b),
19908 "{label}: ~1 row per key over the ~817K domain, not the claimed cell's 1 (got {b})"
19909 );
19910 };
19911 let filtered = PlanNode::Filter {
19915 inner: Box::new(claimed.clone()),
19916 early: None,
19917 residual: None,
19918 exists: Vec::new(),
19919 one_to_one: false,
19920 };
19921 expect_honest_bound("filter-wrapped", &filtered);
19922 let joined = PlanNode::Join {
19932 left: Box::new(claimed.clone()),
19933 right: Box::new(PlanNode::Scan(var_scan(
19934 Some("z"),
19935 "http://ex/other",
19936 Some("q"),
19937 400_000,
19938 ))),
19939 hash_keys: Vec::new(),
19940 probe_key_domains: Vec::new(),
19941 probe_key_overlap_milli: Vec::new(),
19942 rhs_hostable_keys: Vec::new().into(),
19943 meta: JoinMeta {
19944 semi_gate: None,
19945 star_arms: None,
19946 strategy: JoinStrategy::Broadcast,
19947 produced_row_count_estimate: 514,
19948 own_push_removed_row_count_estimate: 514,
19949 },
19950 };
19951 let join_bound = containing_push_driver_bound(Some(&profile), &joined, &var("g"), 500)
19952 .expect("the ?g domain is known");
19953 assert!(
19954 join_bound >= 514,
19955 "the join-driver bound no longer collapses below the honest composed cell (got {join_bound})"
19956 );
19957 let union = PlanNode::Union {
19968 left: Box::new(claimed),
19969 right: Box::new(PlanNode::Scan(var_scan(
19970 Some("g"),
19971 "http://ex/other",
19972 Some("q"),
19973 400_000,
19974 ))),
19975 };
19976 let union_bound = containing_push_driver_bound(Some(&profile), &union, &var("g"), 500)
19977 .expect("the ?g domain is known");
19978 assert!(
19987 (700..=800).contains(&union_bound),
19988 "the union-driver bound is the summed reads over the merged domain (got {union_bound})"
19989 );
19990 }
19991
19992 #[test]
20004 fn probe_side_mirror_keys_the_receiving_scan() {
20005 let mut profile = StatsProfile::default();
20006 for (pred, rows, subjects, objects) in [
20007 ("http://ex/wktDriver", 36_862_u64, 795_534_u128, 36_862_u128),
20008 ("http://ex/asWKT", 817_201, 817_201, 795_534),
20009 ] {
20010 profile.predicate_counts.insert(StrHash::new(pred), rows);
20011 profile
20012 .subjects_per_predicate
20013 .insert(StrHash::new(pred), hll_with_n(subjects));
20014 profile
20015 .objects_per_predicate
20016 .insert(StrHash::new(pred), hll_with_n(objects));
20017 }
20018 let driver = PlanNode::Scan(var_scan(
20019 Some("wkt"),
20020 "http://ex/wktDriver",
20021 Some("x"),
20022 36_862,
20023 ));
20024 let probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 817_201));
20025 let keys = [var("wkt")];
20026 let standalone = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
20027 assert!(
20032 standalone.rows > 80_000,
20033 "the interior-keyed road prices the phantom's probe half (got {})",
20034 standalone.rows
20035 );
20036 let push = ContainingPush {
20040 key: var("g"),
20041 pushed_val_count: 514,
20042 };
20043 let mirrored = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, Some(&push));
20044 let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
20045 let pages = 36_862u64.div_ceil(page);
20046 assert!(
20047 mirrored.rows > 36_862 + pages * 495 && mirrored.rows < 36_862 + pages * 540,
20048 "the probe work is the ~514-row pushed road per page (got {})",
20049 mirrored.rows
20050 );
20051 assert!(
20052 mirrored.seeks > pages * 495 && mirrored.seeks < pages * 540,
20053 "the pushed road seeks once per pushed term per page (got {})",
20054 mirrored.seeks
20055 );
20056 assert!(
20057 mirrored.rows < standalone.rows,
20058 "the mirror only ever lowers the cost estimate"
20059 );
20060 let foreign = ContainingPush {
20063 key: var("zz"),
20064 pushed_val_count: 514,
20065 };
20066 let stands_down =
20067 seat_cost_total(Some(&profile), &driver, &probe, &keys, None, Some(&foreign));
20068 assert_eq!(
20069 (stands_down.rows, stands_down.seeks),
20070 (standalone.rows, standalone.seeks),
20071 "a foreign key establishes no receiving-scan bound"
20072 );
20073 }
20074
20075 #[test]
20090 fn fetch_once_stamp_matches_the_mirrored_seat() {
20091 let _fc = crate::context::FetchConcurrencyPin::set(crate::context::QUERY_FETCH_CONCURRENCY);
20096 let mut profile = StatsProfile::default();
20097 for (pred, rows, subjects, objects) in [
20098 (
20099 "http://ex/wktDriver",
20100 2_000_000_u64,
20101 100_000_u128,
20102 2_000_000_u128,
20103 ),
20104 ("http://ex/asWKT", 20_000, 20_000, 5_000),
20105 ] {
20106 profile.predicate_counts.insert(StrHash::new(pred), rows);
20107 profile
20108 .subjects_per_predicate
20109 .insert(StrHash::new(pred), hll_with_n(subjects));
20110 profile
20111 .objects_per_predicate
20112 .insert(StrHash::new(pred), hll_with_n(objects));
20113 }
20114 let driver = PlanNode::Scan(var_scan(
20115 Some("wkt"),
20116 "http://ex/wktDriver",
20117 Some("x"),
20118 2_000_000,
20119 ));
20120 let probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 20_000));
20121 let keys = [var("wkt")];
20122 let push = ContainingPush {
20126 key: var("g"),
20127 pushed_val_count: 10,
20128 };
20129 let mirrored_seat =
20130 seat_cost_total(Some(&profile), &driver, &probe, &keys, None, Some(&push));
20131 assert!(
20132 mirrored_seat.rows > 2_000_000 && mirrored_seat.rows < 2_020_000,
20133 "the cost model prices the mirrored ~10-row road per page, under one whole read (got {})",
20134 mirrored_seat.rows
20135 );
20136 let mut mirrored_tree = PlanNode::Join {
20138 left: Box::new(driver.clone()),
20139 right: Box::new(probe.clone()),
20140 hash_keys: keys.to_vec(),
20141 probe_key_domains: Vec::new(),
20142 probe_key_overlap_milli: Vec::new(),
20143 rhs_hostable_keys: Vec::new().into(),
20144 meta: JoinMeta {
20145 semi_gate: None,
20146 star_arms: None,
20147 strategy: JoinStrategy::Broadcast,
20148 produced_row_count_estimate: 20_000,
20149 own_push_removed_row_count_estimate: 20_000,
20150 },
20151 };
20152 stamp_fetch_once(
20153 &mut mirrored_tree,
20154 Some(&profile),
20155 None,
20156 Some(&push),
20157 None,
20158 false,
20159 );
20160 let mirrored_stamp = match &mirrored_tree {
20161 PlanNode::Join { right, .. } => right.as_scan().and_then(|s| s.fetch_once),
20162 _ => unreachable!("tree is a join"),
20163 };
20164 assert_eq!(
20165 mirrored_stamp, None,
20166 "the stamp refuses Build on the mirrored road, exactly as the cost model's price does"
20167 );
20168 let mut plain_tree = PlanNode::Join {
20173 left: Box::new(driver),
20174 right: Box::new(probe),
20175 hash_keys: keys.to_vec(),
20176 probe_key_domains: Vec::new(),
20177 probe_key_overlap_milli: Vec::new(),
20178 rhs_hostable_keys: Vec::new().into(),
20179 meta: JoinMeta {
20180 semi_gate: None,
20181 star_arms: None,
20182 strategy: JoinStrategy::Broadcast,
20183 produced_row_count_estimate: 20_000,
20184 own_push_removed_row_count_estimate: 20_000,
20185 },
20186 };
20187 stamp_fetch_once(&mut plain_tree, Some(&profile), None, None, None, false);
20188 let plain_stamp = match &plain_tree {
20189 PlanNode::Join { right, .. } => right.as_scan().and_then(|s| s.fetch_once),
20190 _ => unreachable!("tree is a join"),
20191 };
20192 assert_eq!(
20193 plain_stamp,
20194 Some(20_000),
20195 "without the push the interior road Builds and the stamp writes it"
20196 );
20197 }
20198
20199 #[test]
20212 fn coverage_road_yields_to_the_ancestor_push() {
20213 let mut profile = StatsProfile::default();
20214 for (pred, rows, subjects, objects) in [
20221 ("http://ex/wktDriver", 20_000_u64, 5_000_u128, 20_000_u128),
20222 ("http://ex/asWKT", 20_000, 20_000, 5_000),
20223 ] {
20224 profile.predicate_counts.insert(StrHash::new(pred), rows);
20225 profile
20226 .subjects_per_predicate
20227 .insert(StrHash::new(pred), hll_with_n(subjects));
20228 profile
20229 .objects_per_predicate
20230 .insert(StrHash::new(pred), hll_with_n(objects));
20231 }
20232 let driver = PlanNode::Scan(var_scan(
20233 Some("wkt"),
20234 "http://ex/wktDriver",
20235 Some("x"),
20236 20_000,
20237 ));
20238 let probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 20_000));
20239 let keys = [var("wkt")];
20240 let standalone = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
20244 assert_eq!(
20245 (standalone.rows, standalone.seeks),
20246 (60_000, 0),
20247 "the once-read prices driver + whole read + memo extra, seeks-free"
20248 );
20249 let push = ContainingPush {
20255 key: var("g"),
20256 pushed_val_count: 10,
20257 };
20258 let yielded = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, Some(&push));
20259 assert!(
20260 yielded.rows > 20_000 + 2 && yielded.rows < 20_000 + 60,
20261 "the pushed road replaces the once-read: a small matched price (got {})",
20262 yielded.rows
20263 );
20264 assert!(
20265 yielded.seeks > 5 && yielded.seeks < 15,
20266 "one seek per pushed term per page (got {})",
20267 yielded.seeks
20268 );
20269 assert!(
20270 yielded.rows < standalone.rows,
20271 "the strongly selective ancestor list beats the once-read here — and the road switched"
20272 );
20273 }
20274
20275 #[test]
20284 fn disjoint_vocabularies_never_take_the_coverage_road() {
20285 let mut profile = StatsProfile::default();
20286 for (pred, rows, subjects, objects) in [
20287 ("http://ex/fromTown", 300_u64, 300_u128, 300_u128),
20289 ("http://ex/hasSpacePort", 3, 3, 3),
20295 ] {
20296 profile.predicate_counts.insert(StrHash::new(pred), rows);
20297 profile
20298 .subjects_per_predicate
20299 .insert(StrHash::new(pred), hll_with_n(subjects));
20300 profile
20301 .objects_per_predicate
20302 .insert(StrHash::new(pred), hll_with_n(objects));
20303 }
20304 let mut ports = waratah_stats::HyperLogLog::default_params();
20307 for i in 0..3u128 {
20308 ports.add(1_000_000 + i);
20309 }
20310 profile
20311 .objects_per_predicate
20312 .insert(StrHash::new("http://ex/hasSpacePort"), ports);
20313 let driver = PlanNode::Scan(var_scan(
20314 Some("me"),
20315 "http://ex/fromTown",
20316 Some("town"),
20317 300,
20318 ));
20319 let probe = PlanNode::Scan(var_scan(
20320 Some("sp"),
20321 "http://ex/hasSpacePort",
20322 Some("town"),
20323 30_000,
20324 ));
20325 let keys = [var("town")];
20326 let overlap = resolve_key_overlap_milli(Some(&profile), &driver, &probe, &keys[0]);
20328 assert!(overlap <= 30, "disjoint vocabularies, got {overlap} milli");
20329 let seat = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
20334 assert!(
20335 seat.rows < 30_000 + 300 + 10,
20336 "the disjoint push prunes the 30k arm to ~nothing (got {})",
20337 seat.rows
20338 );
20339 }
20340
20341 #[test]
20349 fn refinalize_restamps_leftjoin_overlap_stamps() {
20350 let mut profile = StatsProfile::default();
20351 for (pred, rows, subjects, objects) in [
20352 ("http://ex/required", 300_u64, 300_u128, 300_u128),
20353 ("http://ex/optional", 30_000, 3_u128, 3_u128),
20354 ] {
20355 profile.predicate_counts.insert(StrHash::new(pred), rows);
20359 profile
20360 .subjects_per_predicate
20361 .insert(StrHash::new(pred), hll_with_n(subjects));
20362 profile
20363 .objects_per_predicate
20364 .insert(StrHash::new(pred), hll_with_n(objects));
20365 }
20366 let left = PlanNode::Scan(var_scan(Some("a"), "http://ex/required", Some("k"), 300));
20367 let right = PlanNode::Scan(var_scan(Some("b"), "http://ex/optional", Some("k"), 30_000));
20368 let keys = vec![var("k")];
20369 let mut node = PlanNode::LeftJoin {
20371 left: Box::new(left),
20372 right: Box::new(right.clone()),
20373 hash_keys: keys.clone(),
20374 early_filter: None,
20375 residual_filter: None,
20376 probe_key_domains: Vec::new(),
20377 probe_key_overlap_milli: Vec::new(),
20378 meta: LeftJoinMeta {
20379 produced_row_count_estimate: 1,
20380 own_push_removed_row_count_estimate: 1,
20381 },
20382 };
20383 refinalize_joins(&mut node, Some(&profile), None);
20384 let PlanNode::LeftJoin {
20385 hash_keys,
20386 probe_key_domains,
20387 probe_key_overlap_milli,
20388 ..
20389 } = &node
20390 else {
20391 panic!("expected LeftJoin, got {node:?}")
20392 };
20393 assert_eq!(
20394 probe_key_overlap_milli.len(),
20395 hash_keys.len(),
20396 "one overlap stamp per hash key"
20397 );
20398 let expected = resolve_key_overlap_milli(
20402 Some(&profile),
20403 &PlanNode::Scan(var_scan(Some("a"), "http://ex/required", Some("k"), 300)),
20404 &PlanNode::Scan(var_scan(Some("b"), "http://ex/optional", Some("k"), 30_000)),
20405 &keys[0],
20406 );
20407 assert_eq!(
20408 probe_key_overlap_milli[0], expected,
20409 "runtime stamp and seat resolver must agree"
20410 );
20411 assert!(
20412 expected < VOCABULARY_OVERLAP_FULL_MILLI,
20413 "disjoint vocabularies: the stamp engaged, got {expected} milli"
20414 );
20415 assert_eq!(probe_key_domains.len(), hash_keys.len());
20418 }
20419
20420 #[test]
20432 fn unshippable_keys_never_price_the_build_road() {
20433 let mut profile = StatsProfile::default();
20434 for (pred, rows, subjects, objects) in [
20435 (
20436 "http://ex/wktDriver",
20437 2_000_000_u64,
20438 500_u128,
20439 2_000_000_u128,
20440 ),
20441 ("http://ex/asWKT", 20_000, 20_000, 5_000),
20442 ] {
20443 profile.predicate_counts.insert(StrHash::new(pred), rows);
20444 profile
20445 .subjects_per_predicate
20446 .insert(StrHash::new(pred), hll_with_n(subjects));
20447 profile
20448 .objects_per_predicate
20449 .insert(StrHash::new(pred), hll_with_n(objects));
20450 }
20451 let mut driver = PlanNode::Scan(var_scan(
20452 Some("wkt"),
20453 "http://ex/wktDriver",
20454 Some("x"),
20455 2_000_000,
20456 ));
20457 let mut probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 20_000));
20458 if let PlanNode::Scan(scan) = &mut driver {
20462 scan.graph = Some(var("graph_name"));
20463 }
20464 if let PlanNode::Scan(scan) = &mut probe {
20465 scan.graph = Some(var("graph_name"));
20466 }
20467 let keys = [var("graph_name")];
20468 let push = ContainingPush {
20471 key: var("g"),
20472 pushed_val_count: 10,
20473 };
20474 let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
20475 let pages = 2_000_000u64.div_ceil(page);
20476 let seat = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, Some(&push));
20477 assert!(
20478 seat.rows > 2_000_000 + pages * 8 && seat.rows < 2_000_000 + pages * 15,
20479 "the per-page pushed road is priced, not the once-build (got {})",
20480 seat.rows
20481 );
20482 assert!(
20483 seat.seeks > pages * 8 && seat.seeks < pages * 15,
20484 "one seek per pushed term per page (got {})",
20485 seat.seeks
20486 );
20487 let mut tree = PlanNode::Join {
20490 left: Box::new(driver),
20491 right: Box::new(probe),
20492 hash_keys: keys.to_vec(),
20493 probe_key_domains: Vec::new(),
20494 probe_key_overlap_milli: Vec::new(),
20495 rhs_hostable_keys: Vec::new().into(),
20496 meta: JoinMeta {
20497 semi_gate: None,
20498 star_arms: None,
20499 strategy: JoinStrategy::Broadcast,
20500 produced_row_count_estimate: 20_000,
20501 own_push_removed_row_count_estimate: 20_000,
20502 },
20503 };
20504 stamp_fetch_once(&mut tree, Some(&profile), None, Some(&push), None, false);
20505 let stamp = match &tree {
20506 PlanNode::Join { right, .. } => right.as_scan().and_then(|s| s.fetch_once),
20507 _ => unreachable!("tree is a join"),
20508 };
20509 assert_eq!(
20510 stamp, None,
20511 "an unshippable key writes no stamp — the executor refetches per page"
20512 );
20513 }
20514
20515 #[test]
20531 fn all_covered_walk_splits_on_the_push_combine_outcome() {
20532 let mut profile = StatsProfile::default();
20533 for (pred, rows, subjects, objects) in [
20534 ("http://ex/p1", 100_000_u64, 5_000_u128, 80_000_u128),
20537 ("http://ex/p2", 2_000, 1_000, 2_000),
20541 ("http://ex/p3", 1_000, 2_000, 5_000),
20542 ] {
20543 profile.predicate_counts.insert(StrHash::new(pred), rows);
20544 profile
20545 .subjects_per_predicate
20546 .insert(StrHash::new(pred), hll_with_n(subjects));
20547 profile
20548 .objects_per_predicate
20549 .insert(StrHash::new(pred), hll_with_n(objects));
20550 }
20551 let driver = PlanNode::Scan(var_scan(Some("wkt"), "http://ex/p1", Some("y"), 100_000));
20552 let inner = PlanNode::Join {
20553 left: Box::new(PlanNode::Scan(var_scan(
20554 Some("wkt"),
20555 "http://ex/p2",
20556 Some("m"),
20557 2_000,
20558 ))),
20559 right: Box::new(PlanNode::Scan(var_scan(
20560 Some("m"),
20561 "http://ex/p3",
20562 Some("y"),
20563 1_000,
20564 ))),
20565 hash_keys: vec![var("m")],
20566 probe_key_domains: Vec::new(),
20567 probe_key_overlap_milli: Vec::new(),
20568 rhs_hostable_keys: Vec::new().into(),
20569 meta: JoinMeta {
20570 semi_gate: None,
20571 star_arms: None,
20572 strategy: JoinStrategy::Broadcast,
20573 produced_row_count_estimate: 1_500,
20574 own_push_removed_row_count_estimate: 1_500,
20575 },
20576 };
20577 let push = ContainingPush {
20584 key: var("wkt"),
20585 pushed_val_count: 5_000,
20586 };
20587 let page_rows = seat_page_rows(&driver, &inner, None);
20589 let walk = {
20590 let mut budget = SUBTREE_WALK_NODE_BUDGET;
20591 subtree_page_cost(Some(&profile), &inner, &push, None, &mut budget)
20592 };
20593 let keys = [var("wkt")];
20601 let driver_rows = seat_driver_work_rows(&driver, &keys, Some(&profile)).min(
20602 containing_push_driver_bound(Some(&profile), &driver, &push.key, push.pushed_val_count)
20603 .unwrap_or(u64::MAX),
20604 );
20605 let pages = driver_rows.div_ceil(page_rows);
20606 assert!(pages > 1, "the fixture needs a multi-page driver");
20607 let combined = seat_cost_total(Some(&profile), &driver, &inner, &keys, None, Some(&push));
20608 assert_eq!(
20609 combined,
20610 SeatCost {
20611 rows: driver_rows + pages * walk.rows,
20612 seeks: pages * walk.seeks,
20613 },
20614 "Combined: the subtree re-executes per driver page"
20615 );
20616 assert_ne!(
20619 combined.rows,
20620 driver_rows + inner.produced_row_count_estimate(),
20621 "the all-covered road must not stay the unpushed once-read"
20622 );
20623 let keys = [var("y")];
20626 let driver_rows = seat_driver_work_rows(&driver, &keys, Some(&profile)).min(
20627 containing_push_driver_bound(Some(&profile), &driver, &push.key, push.pushed_val_count)
20628 .unwrap_or(u64::MAX),
20629 );
20630 let ancestor = seat_cost_total(Some(&profile), &driver, &inner, &keys, None, Some(&push));
20631 assert_eq!(
20632 ancestor,
20633 SeatCost {
20634 rows: driver_rows + walk.rows,
20635 seeks: walk.seeks,
20636 },
20637 "Ancestor: one conditioned execution serves every page"
20638 );
20639 }
20640
20641 #[test]
20648 fn join_driver_once_cost_prices_one_unpushed_seat() {
20649 let mut profile = StatsProfile::default();
20650 for (pred, rows, subjects, objects) in [
20651 ("http://ex/type", 500_u64, 500_u128, 500_u128),
20652 ("http://ex/hasGeom", 817_201, 793_204, 817_201),
20653 ] {
20654 profile.predicate_counts.insert(StrHash::new(pred), rows);
20655 profile
20656 .subjects_per_predicate
20657 .insert(StrHash::new(pred), hll_with_n(subjects));
20658 profile
20659 .objects_per_predicate
20660 .insert(StrHash::new(pred), hll_with_n(objects));
20661 }
20662 let type_scan = PlanNode::Scan(var_scan(Some("tr"), "http://ex/type", None, 500));
20663 let geom_scan = PlanNode::Scan(var_scan(
20664 Some("tr"),
20665 "http://ex/hasGeom",
20666 Some("g"),
20667 817_201,
20668 ));
20669 let inner = PlanNode::Join {
20670 left: Box::new(type_scan.clone()),
20671 right: Box::new(geom_scan.clone()),
20672 hash_keys: vec![var("tr")],
20673 probe_key_domains: Vec::new(),
20674 probe_key_overlap_milli: Vec::new(),
20675 rhs_hostable_keys: Vec::new().into(),
20676 meta: JoinMeta {
20677 semi_gate: None,
20678 star_arms: None,
20679 strategy: JoinStrategy::Broadcast,
20680 produced_row_count_estimate: 515,
20681 own_push_removed_row_count_estimate: 515,
20682 },
20683 };
20684 let once = driver_once_cost(Some(&profile), &inner, None);
20686 let seat = seat_cost_total(
20687 Some(&profile),
20688 &type_scan,
20689 &geom_scan,
20690 &[var("tr")],
20691 None,
20692 None,
20693 );
20694 assert_eq!(
20695 once, seat,
20696 "the once-cost delegates to ONE unpushed seat of the join"
20697 );
20698 assert!(
20702 once.rows < 500 + 817_201,
20703 "the once-cost must not bill the inner probe's whole read (got {})",
20704 once.rows
20705 );
20706 assert!(
20708 once.seeks > 0,
20709 "the inner seating's probe seeks must ride home"
20710 );
20711 }
20712
20713 #[test]
20728 fn hosting_custom_driver_prices_the_keyed_regime() {
20729 let mut profile = StatsProfile::default();
20730 for (pred, rows, subjects, objects) in [
20731 ("http://ex/geoCand", 36_862_u64, 36_862_u128, 36_862_u128),
20732 ("http://ex/asWKT", 817_201, 817_201, 795_534),
20733 ] {
20734 profile.predicate_counts.insert(StrHash::new(pred), rows);
20735 profile
20736 .subjects_per_predicate
20737 .insert(StrHash::new(pred), hll_with_n(subjects));
20738 profile
20739 .objects_per_predicate
20740 .insert(StrHash::new(pred), hll_with_n(objects));
20741 }
20742 let op_cost = CustomOpCost {
20745 drain_rows: 36_862,
20746 per_key_unit: 8,
20747 inline_point_unit: 1,
20748 direct_probe: true,
20749 probe_keyed_columns: 0b1,
20750 probe_filter_unit: 8,
20751 probe_memo_entry_rows: 0,
20752 };
20753 let inner_op = CustomOp {
20754 plugin_id: "cost-test",
20755 op_id: "op",
20756 payload: crate::plugin::PluginPayloadBox::new(CostTestPayload),
20757 children: Vec::new(),
20758 variables: vec![var("g"), var("wkt")],
20759 produced_row_count_estimate: 36_862,
20760 cost: Some(op_cost),
20761 pinned: Vec::new(),
20762 };
20763 let push = ContainingPush {
20766 key: var("g"),
20767 pushed_val_count: 500,
20768 };
20769 let keyed = inner_op.keyed_cost(push.pushed_val_count, Some(0)).unwrap();
20770 let geo_op = PlanNode::CustomNode(inner_op);
20771 let geom_scan =
20772 PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 817_201));
20773 let keys = [var("wkt")];
20774 let seat = seat_cost_total(
20775 Some(&profile),
20776 &geo_op,
20777 &geom_scan,
20778 &keys,
20779 None,
20780 Some(&push),
20781 );
20782 let domain = join_key_domain_for_node(Some(&profile), &geom_scan, &push.key).unwrap();
20787 let (probe_seeks, probe_matched) = probe_broadcast_price(
20788 817_201,
20789 &[(false, push.pushed_val_count, domain, 1_000)],
20790 false,
20791 );
20792 assert_eq!(
20793 seat,
20794 SeatCost {
20795 rows: keyed + probe_matched,
20796 seeks: probe_seeks,
20797 },
20798 "the conditioned custom driver prices keyed_cost, not the list length"
20799 );
20800 assert!(
20803 seat.rows > push.pushed_val_count + probe_matched,
20804 "the keyed driver term must exceed the bare list length (got {})",
20805 seat.rows
20806 );
20807 let unhosted = ContainingPush {
20810 key: var("zz"),
20811 pushed_val_count: 500,
20812 };
20813 let seat_unhosted = seat_cost_total(
20814 Some(&profile),
20815 &geo_op,
20816 &geom_scan,
20817 &keys,
20818 None,
20819 Some(&unhosted),
20820 );
20821 assert!(
20822 seat_unhosted.rows > 331_758,
20823 "an unhosted custom driver keeps the sweep (got {})",
20824 seat_unhosted.rows
20825 );
20826 }
20827
20828 #[test]
20847 fn same_slot_walks_hash_keys_in_order() {
20848 let mut profile = StatsProfile::default();
20849 for (pred, rows, subjects, objects) in [
20850 ("http://ex/asWKT", 20_000_u64, 1_000_u128, 1_000_u128),
20851 ("http://ex/wktDriver", 100_000, 500, 30_000),
20852 ("http://ex/gDriver", 100_000, 5_000, 100_000),
20853 ] {
20854 profile.predicate_counts.insert(StrHash::new(pred), rows);
20855 profile
20856 .subjects_per_predicate
20857 .insert(StrHash::new(pred), hll_with_n(subjects));
20858 profile
20859 .objects_per_predicate
20860 .insert(StrHash::new(pred), hll_with_n(objects));
20861 }
20862 let probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 20_000));
20863 let wide_push = ContainingPush {
20866 key: var("g"),
20867 pushed_val_count: 24_576,
20868 };
20869 let shape_keys_a = [(false, 148, 1_011, 1_000), (true, 8_890, 1_011, 1_000)];
20877 let road_a = probe_side_mirror_road(
20878 Some(&profile),
20879 &probe,
20880 &[var("wkt"), var("g")],
20881 &shape_keys_a,
20882 true,
20883 Some(&wide_push),
20884 );
20885 assert_eq!(
20886 road_a,
20887 Some(SeatCost {
20888 rows: 20_000,
20889 seeks: 24_576,
20890 }),
20891 "the surviving interior key sits on another slot: the wide ancestor road, priced"
20892 );
20893 let shape_keys_b = [(true, 1_229, 1_011, 1_000)];
20899 let road_b = probe_side_mirror_road(
20900 Some(&profile),
20901 &probe,
20902 &[var("g")],
20903 &shape_keys_b,
20904 true,
20905 Some(&wide_push),
20906 );
20907 assert_eq!(
20908 road_b,
20909 Some(SeatCost {
20910 rows: 20_000,
20911 seeks: 24_576,
20912 }),
20913 "a covered same-slot key still leaves the ancestor road"
20914 );
20915 let shape_keys_c = [(false, 122, 1_011, 1_000)];
20920 let road_c = probe_side_mirror_road(
20921 Some(&profile),
20922 &probe,
20923 &[var("g")],
20924 &shape_keys_c,
20925 true,
20926 Some(&wide_push),
20927 );
20928 assert_eq!(
20929 road_c, None,
20930 "the cheaper interior road bounds the intersected lists — keep it"
20931 );
20932 }
20933
20934 #[test]
20946 fn probe_side_mirror_prefers_the_ancestor_road_across_slots() {
20947 let mut profile = StatsProfile::default();
20948 for (pred, rows, subjects, objects) in [
20949 ("http://ex/wktDriver", 500_u64, 500_u128, 500_u128),
20950 ("http://ex/gDriver", 500, 500, 500),
20951 ("http://ex/asWKT", 817_201, 817_201, 795_534),
20952 ] {
20953 profile.predicate_counts.insert(StrHash::new(pred), rows);
20954 profile
20955 .subjects_per_predicate
20956 .insert(StrHash::new(pred), hll_with_n(subjects));
20957 profile
20958 .objects_per_predicate
20959 .insert(StrHash::new(pred), hll_with_n(objects));
20960 }
20961 let probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 817_201));
20962 let wide_push = ContainingPush {
20964 key: var("g"),
20965 pushed_val_count: 24_576,
20966 };
20967 let driver_wkt =
20973 PlanNode::Scan(var_scan(Some("wkt"), "http://ex/wktDriver", Some("x"), 500));
20974 let keys_wkt = [var("wkt")];
20975 let across = seat_cost_total(
20976 Some(&profile),
20977 &driver_wkt,
20978 &probe,
20979 &keys_wkt,
20980 None,
20981 Some(&wide_push),
20982 );
20983 assert!(
20984 across.rows > 500 + 24_000 && across.rows < 500 + 25_200,
20985 "the ancestor road is priced across slots: ~24,576 matched per page (got {})",
20986 across.rows
20987 );
20988 assert!(
20989 across.seeks > 24_000 && across.seeks < 25_200,
20990 "one seek per ancestor term per page (got {})",
20991 across.seeks
20992 );
20993 let standalone =
20994 seat_cost_total(Some(&profile), &driver_wkt, &probe, &keys_wkt, None, None);
20995 assert!(
20996 across.rows > standalone.rows,
20997 "the executor-faithful price is the WIDER road here — the interior road never runs"
20998 );
20999 let driver_g = PlanNode::Scan(var_scan(Some("g"), "http://ex/gDriver", Some("y"), 500));
21005 let keys_g = [var("g")];
21006 let same = seat_cost_total(
21007 Some(&profile),
21008 &driver_g,
21009 &probe,
21010 &keys_g,
21011 None,
21012 Some(&wide_push),
21013 );
21014 assert!(
21015 same.rows > 500 + 400 && same.rows < 500 + 600,
21016 "same slot intersects: the interior road (~500 matched) bounds the fetch (got {})",
21017 same.rows
21018 );
21019 assert!(
21020 same.seeks > 400 && same.seeks < 600,
21021 "the intersection fetches on the interior list, not the ancestor's (got {})",
21022 same.seeks
21023 );
21024 }
21025
21026 #[test]
21027 fn sweep_cost_is_drain_plus_every_candidate() {
21028 let op = cost_test_op(
21029 1000,
21030 Some(CustomOpCost {
21031 drain_rows: 90,
21032 per_key_unit: 8,
21033 inline_point_unit: 1,
21034 direct_probe: true,
21035 probe_keyed_columns: 0b1,
21036 probe_filter_unit: 8,
21037 probe_memo_entry_rows: 0,
21038 }),
21039 );
21040 assert_eq!(op.sweep_cost(), Some(90 + 1000 * 8));
21041 }
21042
21043 #[test]
21044 fn keyed_cost_picks_direct_until_the_drain_pays_off() {
21045 let op = cost_test_op(
21046 1000,
21047 Some(CustomOpCost {
21048 drain_rows: 900,
21049 per_key_unit: 8,
21050 inline_point_unit: 1,
21051 direct_probe: true,
21052 probe_keyed_columns: 0b1,
21053 probe_filter_unit: 8,
21054 probe_memo_entry_rows: 0,
21055 }),
21056 );
21057 assert_eq!(op.keyed_cost(10, Some(0)), Some(80));
21060 assert_eq!(op.keyed_cost(200, Some(0)), Some(1600));
21061 assert_eq!(op.keyed_cost(2000, Some(0)), Some(8900));
21065 }
21066
21067 #[test]
21068 fn keyed_cost_zero_keys_is_free_and_arithmetic_saturates() {
21069 let op = cost_test_op(
21070 u64::MAX,
21071 Some(CustomOpCost {
21072 drain_rows: u64::MAX,
21073 per_key_unit: 8,
21074 inline_point_unit: 1,
21075 direct_probe: true,
21076 probe_keyed_columns: 0b1,
21077 probe_filter_unit: 8,
21078 probe_memo_entry_rows: 0,
21079 }),
21080 );
21081 assert_eq!(op.keyed_cost(0, Some(0)), Some(0));
21082 assert_eq!(op.sweep_cost(), Some(u64::MAX));
21084 }
21085
21086 fn location_scan(estimate: u64) -> PlanNode {
21089 fn first_scan(node: &PlanNode) -> Option<PlanNode> {
21090 match node {
21091 PlanNode::Scan(_) => Some(node.clone()),
21092 PlanNode::Join { left, right, .. }
21093 | PlanNode::Union { left, right }
21094 | PlanNode::LeftJoin { left, right, .. } => {
21095 first_scan(left).or_else(|| first_scan(right))
21096 }
21097 PlanNode::Filter { inner, .. }
21098 | PlanNode::Extend { inner, .. }
21099 | PlanNode::Slice { inner, .. }
21100 | PlanNode::Distinct { inner, .. }
21101 | PlanNode::Sort { inner, .. }
21102 | PlanNode::Group { inner, .. }
21103 | PlanNode::JoinGraphVar { inner, .. } => first_scan(inner),
21104 PlanNode::CustomNode(op) => op.children.first().and_then(first_scan),
21105 _ => None,
21106 }
21107 }
21108 let plan = LogicalPlan::parse("SELECT ?g WHERE { ?s <http://ex/hasLocation> ?g }").unwrap();
21109 let mut scan = first_scan(&plan.root).expect("single-pattern plan has a scan");
21110 if let PlanNode::Scan(scan_op) = &mut scan {
21111 scan_op.produced_row_count_estimate = estimate;
21112 } else {
21113 panic!("expected a scan");
21114 }
21115 scan
21116 }
21117
21118 fn custom_op_node(estimate: u64) -> PlanNode {
21119 PlanNode::CustomNode(cost_test_op(estimate, None))
21120 }
21121
21122 fn op_left_join(op_est: u64, inner_est: u64) -> PlanNode {
21126 PlanNode::Join {
21127 left: Box::new(custom_op_node(op_est)),
21128 right: Box::new(location_scan(inner_est)),
21129 hash_keys: vec![var("g")],
21130 probe_key_domains: Vec::new(),
21131 probe_key_overlap_milli: Vec::new(),
21132 rhs_hostable_keys: Vec::new().into(),
21133 meta: JoinMeta {
21134 semi_gate: None,
21135 star_arms: None,
21136 strategy: JoinStrategy::Broadcast,
21137 produced_row_count_estimate: op_est,
21138 own_push_removed_row_count_estimate: op_est,
21139 },
21140 }
21141 }
21142
21143 #[test]
21144 fn ancestor_push_return_bound_flips_the_comparator_itself() {
21145 let mut join = op_left_join(5350, 7_827_555);
21154 let PlanNode::Join { right, .. } = &mut join else {
21155 panic!("still a join");
21156 };
21157 let PlanNode::Scan(scan) = &mut **right else {
21158 panic!("right arm is the scan");
21159 };
21160 scan.broadcasted = Some((var("tr"), PatternSlot::Subject));
21161 scan.ancestor_push_return_bound = Some(1525);
21162 refinalize_joins_without_ctx(&mut join, None);
21163 let PlanNode::Join { left, right, .. } = &join else {
21164 panic!("still a join");
21165 };
21166 assert!(
21167 matches!(&**left, PlanNode::Scan(_)),
21168 "inner drives: {left:?}"
21169 );
21170 assert!(matches!(&**right, PlanNode::CustomNode(_)), "op probes");
21171 }
21172
21173 #[test]
21174 fn comparator_keeps_a_pinned_op_on_the_probe_side() {
21175 let mut op = cost_test_op(1, None);
21186 op.pinned
21187 .push((var("g"), EncodedTerm::from(&Literal::from(1))));
21188 let mut join = PlanNode::Join {
21189 left: Box::new(location_scan(1)),
21190 right: Box::new(PlanNode::CustomNode(op)),
21191 hash_keys: vec![var("g")],
21192 probe_key_domains: Vec::new(),
21193 probe_key_overlap_milli: Vec::new(),
21194 rhs_hostable_keys: Vec::new().into(),
21195 meta: JoinMeta {
21196 semi_gate: None,
21197 star_arms: None,
21198 strategy: JoinStrategy::Broadcast,
21199 produced_row_count_estimate: 1,
21200 own_push_removed_row_count_estimate: 1,
21201 },
21202 };
21203 refinalize_joins_without_ctx(&mut join, None);
21204 let PlanNode::Join { left, right, .. } = &join else {
21205 panic!("still a join")
21206 };
21207 assert!(
21208 matches!(&**left, PlanNode::Scan(_)),
21209 "the point-read driver stays: {left:?}"
21210 );
21211 let PlanNode::CustomNode(op) = &**right else {
21212 panic!("the pinned op stays on the probe side")
21213 };
21214 assert_eq!(op.pinned.len(), 1, "the pin itself survives");
21215 }
21216
21217 #[test]
21218 fn recost_without_a_bound_keeps_today_reset_semantics() {
21219 let mut join = op_left_join(5350, 7_827_555);
21224 refinalize_joins_without_ctx(&mut join, None);
21225 let PlanNode::Join { left, right, .. } = &join else {
21226 panic!("still a join");
21227 };
21228 assert!(
21230 matches!(&**left, PlanNode::CustomNode(_)),
21231 "op still drives"
21232 );
21233 let PlanNode::Scan(scan) = &**right else {
21234 panic!("right arm is the scan");
21235 };
21236 assert_eq!(scan.produced_row_count_estimate, 7_827_555);
21237 assert!(scan.ancestor_push_return_bound.is_none());
21238 }
21239
21240 #[test]
21241 fn clear_broadcast_marks_removes_the_bound_with_the_claim() {
21242 let mut node = location_scan(1000);
21246 let PlanNode::Scan(scan) = &mut node else {
21247 panic!("location_scan builds a scan");
21248 };
21249 scan.broadcasted = Some((var("tr"), PatternSlot::Subject));
21250 scan.ancestor_push_return_bound = Some(100);
21251 clear_broadcast_marks(&mut node);
21252 let PlanNode::Scan(scan) = &node else {
21253 panic!("still a scan");
21254 };
21255 assert!(scan.broadcasted.is_none());
21256 assert!(scan.ancestor_push_return_bound.is_none());
21257 }
21258
21259 fn explain_est(sparql: &str, profile: Option<&StatsProfile>) -> String {
21260 LogicalPlan::explain(sparql, ExplainFormat::Estimate, false, profile).unwrap()
21261 }
21262
21263 fn explain_sse(sparql: &str, pretty: bool) -> String {
21264 LogicalPlan::explain(sparql, ExplainFormat::Sse, pretty, None).unwrap()
21265 }
21266
21267 fn explain_optimised(sparql: &str) -> String {
21268 LogicalPlan::explain(sparql, ExplainFormat::Optimised, false, None).unwrap()
21269 }
21270
21271 fn explain_optimised_sparql(sparql: &str) -> String {
21272 LogicalPlan::explain(sparql, ExplainFormat::OptimisedSparql, false, None).unwrap()
21273 }
21274
21275 fn domain_on_line(text: &str, line_contains: &str, variable: &str) -> Option<u64> {
21276 let start_at = text.find(line_contains)?;
21277 let slice = &text[start_at..];
21278 let needle = format!("(domain {variable} ");
21279 let start = slice.find(&needle)? + needle.len();
21280 let rest = &slice[start..];
21281 if rest.starts_with('?') {
21282 return None;
21283 }
21284 let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
21285 digits.parse().ok()
21286 }
21287
21288 fn rows_on_line(text: &str, line_contains: &str) -> u64 {
21290 let start_at = text
21291 .find(line_contains)
21292 .unwrap_or_else(|| panic!("no line containing {line_contains:?}: {text}"));
21293 let slice = &text[start_at..];
21294 let needle = "~";
21295 let start = slice.find(needle).expect("scan line prints ~N") + needle.len();
21296 let digits: String = slice[start..]
21297 .chars()
21298 .take_while(|c| c.is_ascii_digit())
21299 .collect();
21300 digits.parse().expect("numeric estimate")
21301 }
21302
21303 #[test]
21304 fn two_pattern_query_produces_two_scans_and_one_join() {
21305 let plan = LogicalPlan::parse(DEMO).unwrap();
21306 let scans = plan.scans().unwrap();
21307 assert_eq!(scans.len(), 2);
21308 let joins = plan.join_ops().unwrap();
21309 assert_eq!(joins.len(), 1);
21310 assert_eq!(joins[0].hash_keys, vec![var("city")]);
21311 assert_eq!(plan.projection, vec![var("person"), var("weather")]);
21312 }
21313
21314 #[test]
21315 fn selective_pattern_is_scanned_first() {
21316 let plan = LogicalPlan::parse(
21317 r#"
21318 SELECT ?person ?city WHERE {
21319 ?person <http://ex/livesIn> ?city .
21320 ?city <http://ex/hasWeather> "Sunny" .
21321 }
21322 "#,
21323 )
21324 .unwrap();
21325
21326 let scans = plan.scans().unwrap();
21327 assert_eq!(scans[0].bound_slots(), 3);
21328 assert_eq!(
21329 scans[0].pattern.object,
21330 Some(EncodedTerm::from(&Literal::from("Sunny")))
21331 );
21332 assert_eq!(
21333 waratah_router::select_axis(&scans[0].pattern).unwrap(),
21334 PartitionAxis::O
21335 );
21336 assert_eq!(scans[1].bound_slots(), 2);
21337 }
21338
21339 #[test]
21340 fn profile_reorders_selective_before_broad() {
21341 let mut live = LiveQuadsProfile::default();
21342 let person = NamedNode::new("http://ex/Person").unwrap();
21343 let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
21344 let hometown = NamedNode::new("http://ex/hasHometown").unwrap();
21345 let brisbane = NamedNode::new("http://ex/Brisbane").unwrap();
21346
21347 for i in 0..100 {
21348 let s = NamedNode::new(format!("http://ex/p{i}")).unwrap();
21349 observe_quad(
21350 &mut live,
21351 &encode_quad(&waratah_storage::Quad::new(
21352 s.clone(),
21353 type_pred.clone(),
21354 person.clone(),
21355 waratah_storage::GraphName::DefaultGraph,
21356 ))
21357 .unwrap(),
21358 StorageOp::Put,
21359 );
21360 if i < 5 {
21361 observe_quad(
21362 &mut live,
21363 &encode_quad(&waratah_storage::Quad::new(
21364 s,
21365 hometown.clone(),
21366 brisbane.clone(),
21367 waratah_storage::GraphName::DefaultGraph,
21368 ))
21369 .unwrap(),
21370 StorageOp::Put,
21371 );
21372 }
21373 }
21374 let profile = StatsProfile::from(live);
21375
21376 let plan = LogicalPlan::parse_with_profile(
21377 r#"
21378 SELECT ?person WHERE {
21379 ?person <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex/Person> .
21380 ?person <http://ex/hasHometown> <http://ex/Brisbane> .
21381 }
21382 "#,
21383 Some(&profile),
21384 )
21385 .unwrap();
21386
21387 let scans = plan.scans().unwrap();
21388 assert_eq!(scans[0].pattern.object, Some(EncodedTerm::from(&brisbane)));
21389 assert_eq!(scans[0].produced_row_count_estimate, 5);
21390 assert_eq!(
21391 scans[1].subject.as_ref().map(Variable::as_str),
21392 Some("person"),
21393 "type scan should stay the probe: {:?}",
21394 scans[1]
21395 );
21396 assert!(
21397 matches!(
21398 &scans[1].broadcasted,
21399 Some((v, PatternSlot::Subject)) if v.as_str() == "person"
21400 ),
21401 "Broadcast probe should annotate the type scan, got {:?}",
21402 scans[1].broadcasted
21403 );
21404 assert_eq!(
21405 plan.join_ops().unwrap()[0].meta.strategy,
21406 JoinStrategy::Broadcast,
21407 "small left side should hint broadcast"
21408 );
21409 }
21410
21411 #[test]
21412 fn hll_domain_selects_broadcast_despite_large_row_estimates() {
21413 let mut profile = StatsProfile::default();
21414 let pred_lives = waratah_storage::StrHash::new("http://ex/livesIn");
21415 let pred_weather = waratah_storage::StrHash::new("http://ex/hasWeather");
21416
21417 profile.total_puts = 200_000;
21418 profile.predicate_counts.insert(pred_lives, 100_000);
21419 profile.predicate_counts.insert(pred_weather, 50_000);
21420
21421 let mut cities = waratah_stats::HyperLogLog::default_params();
21422 for i in 0..40u128 {
21423 cities.add(i);
21424 }
21425 profile.objects_per_predicate.insert(pred_lives, cities);
21426 let mut weather_objs = waratah_stats::HyperLogLog::default_params();
21427 for i in 0..30u128 {
21428 weather_objs.add(i + 1_000);
21429 }
21430 profile
21431 .objects_per_predicate
21432 .insert(pred_weather, weather_objs);
21433 let mut weather_subjects = waratah_stats::HyperLogLog::default_params();
21434 for i in 0..40u128 {
21435 weather_subjects.add(i);
21436 }
21437 profile
21438 .subjects_per_predicate
21439 .insert(pred_weather, weather_subjects);
21440
21441 let sunny = EncodedTerm::from(&Literal::from("Sunny"));
21442 profile.object_cms.add(waratah_stats::term_key(&sunny), 80);
21443
21444 let plan = LogicalPlan::parse_with_profile(
21445 r#"
21446 SELECT ?person ?city WHERE {
21447 ?person <http://ex/livesIn> ?city .
21448 ?city <http://ex/hasWeather> "Sunny" .
21449 }
21450 "#,
21451 Some(&profile),
21452 )
21453 .unwrap();
21454
21455 let scans = plan.scans().unwrap();
21456 assert_eq!(
21457 scans[0].pattern.object,
21458 Some(EncodedTerm::from(&Literal::from("Sunny"))),
21459 "Sunny pattern should lead, got {:?}",
21460 scans[0]
21461 );
21462 assert!(
21463 matches!(
21464 &scans[1].broadcasted,
21465 Some((v, PatternSlot::Object)) if v.as_str() == "city"
21466 ),
21467 "Broadcast probe should annotate livesIn on ?city, got {:?}",
21468 scans[1].broadcasted
21469 );
21470 assert_eq!(
21471 plan.join_ops().unwrap()[0].meta.strategy,
21472 JoinStrategy::Broadcast,
21473 "small HLL join-key domain should hint broadcast; got {:?}",
21474 plan.join_ops().unwrap()[0].meta.strategy
21475 );
21476 }
21477
21478 #[test]
21479 fn hll_domain_selects_shuffle_when_both_sides_large() {
21480 let mut profile = StatsProfile::default();
21481 let pred_a = waratah_storage::StrHash::new("http://ex/a");
21482 let pred_b = waratah_storage::StrHash::new("http://ex/b");
21483 profile.total_puts = 500_000;
21484 profile.predicate_counts.insert(pred_a, 200_000);
21485 profile.predicate_counts.insert(pred_b, 200_000);
21486
21487 let mut big = waratah_stats::HyperLogLog::default_params();
21488 for i in 0..50_000u128 {
21489 big.add(i);
21490 }
21491 profile.objects_per_predicate.insert(pred_a, big.clone());
21492 profile.subjects_per_predicate.insert(pred_b, big);
21493
21494 let plan = LogicalPlan::parse_with_profile(
21495 r#"
21496 SELECT ?s ?o WHERE {
21497 ?s <http://ex/a> ?x .
21498 ?x <http://ex/b> ?o .
21499 }
21500 "#,
21501 Some(&profile),
21502 )
21503 .unwrap();
21504
21505 assert_eq!(
21506 plan.join_ops().unwrap()[0].meta.strategy,
21507 JoinStrategy::Shuffle,
21508 "large HLL domains on both sides should hint shuffle"
21509 );
21510 let mut annotated = false;
21511 for_each_scan(&plan.root, &mut |scan| {
21512 if scan.broadcasted.is_some() {
21513 annotated = true;
21514 }
21515 });
21516 assert!(
21517 !annotated,
21518 "Shuffle must not annotate probe scans: {:?}",
21519 plan.root
21520 );
21521 }
21522
21523 #[test]
21524 fn join_intersection_domain_selects_broadcast_not_first_child() {
21525 let mut profile = StatsProfile::default();
21530 let pred_p = StrHash::new("http://ex/p");
21531 let pred_q = StrHash::new("http://ex/q");
21532 let pred_r = StrHash::new("http://ex/r");
21533 profile.total_puts = 400_000;
21534 profile.predicate_counts.insert(pred_p, 50_000);
21535 profile.predicate_counts.insert(pred_q, 100_000);
21536 profile.predicate_counts.insert(pred_r, 200_000);
21537 profile
21538 .subjects_per_predicate
21539 .insert(pred_p, hll_with_n(50_000));
21540 profile
21541 .objects_per_predicate
21542 .insert(pred_p, hll_with_n(50_000));
21543 profile
21544 .subjects_per_predicate
21545 .insert(pred_q, hll_with_n(10));
21546 profile
21547 .objects_per_predicate
21548 .insert(pred_q, hll_with_n(100_000));
21549 profile
21550 .subjects_per_predicate
21551 .insert(pred_r, hll_with_n(80_000));
21552 profile
21553 .objects_per_predicate
21554 .insert(pred_r, hll_with_n(80_000));
21555
21556 let sparql = r#"
21557 SELECT ?x WHERE {
21558 ?x <http://ex/p> ?a .
21559 ?x <http://ex/q> ?b .
21560 ?x <http://ex/r> ?c .
21561 }
21562 "#;
21563 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
21564 let joins = plan.join_ops().unwrap();
21565 assert_eq!(joins.len(), 2, "left-deep three-scan join, got {joins:?}");
21566 assert_eq!(
21567 joins[1].meta.strategy,
21568 JoinStrategy::Broadcast,
21569 "inner join's ?x domain should be min(50k, 10), so the join into :r broadcasts; got {:?}",
21570 joins[1].meta.strategy
21571 );
21572
21573 let text = explain_est(sparql, Some(&profile));
21574 let outer = domain_on_line(&text, "(broadcast ?x)", "?x");
21575 assert!(
21576 outer.is_some_and(|n| n > 1 && n < 5_000),
21577 "Join should print the intersection ?x domain, not :p's 50k, got {outer:?}: {text}"
21578 );
21579 }
21580
21581 #[test]
21582 fn allow_list_domain_prefers_smallest_under_threshold_key_not_first() {
21583 let mut profile = StatsProfile::default();
21586 let pred_p = StrHash::new("http://ex/p");
21587 let pred_q = StrHash::new("http://ex/q");
21588 profile.total_puts = 200_000;
21589 profile.predicate_counts.insert(pred_p, 90_000);
21590 profile.predicate_counts.insert(pred_q, 100_000);
21591 profile
21592 .subjects_per_predicate
21593 .insert(pred_p, hll_with_n(50_000));
21594 profile.objects_per_predicate.insert(pred_p, hll_with_n(10));
21595 profile
21596 .subjects_per_predicate
21597 .insert(pred_q, hll_with_n(10));
21598 profile
21599 .objects_per_predicate
21600 .insert(pred_q, hll_with_n(50_000));
21601
21602 let plan = LogicalPlan::parse_with_profile(
21603 r#"
21604 SELECT ?k ?x WHERE {
21605 ?k <http://ex/p> ?x .
21606 ?x <http://ex/q> ?k .
21607 }
21608 "#,
21609 Some(&profile),
21610 )
21611 .unwrap();
21612
21613 let PlanNode::Join {
21614 left,
21615 hash_keys,
21616 meta,
21617 ..
21618 } = &plan.root
21619 else {
21620 panic!("expected Join, got {:?}", plan.root);
21621 };
21622 assert!(
21623 hash_keys.len() >= 2,
21624 "expected two join keys, got {hash_keys:?}"
21625 );
21626 assert_eq!(hash_keys[0].as_str(), "k", "left S-P-O puts ?k first");
21627 assert!(
21628 left.as_scan().is_some(),
21629 "p-scan should stay left (source order, equal rows): {left:?}"
21630 );
21631 assert_eq!(
21632 meta.strategy,
21633 JoinStrategy::Broadcast,
21634 "small ?x domain should hint broadcast, not first-key ?k shuffle; got {:?}",
21635 meta.strategy
21636 );
21637 }
21638
21639 const RDF_TYPE_IRI: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
21642
21643 fn join_of_grounded_scan<'a>(node: &'a PlanNode, term: &EncodedTerm) -> Option<&'a PlanNode> {
21646 fn grounds_cls(scan: &ScanOp, term: &EncodedTerm) -> bool {
21647 scan.object.as_ref().map(|v| v.as_str()) == Some("cls")
21648 && scan.pattern.object.as_ref() == Some(term)
21649 }
21650 match node {
21651 PlanNode::Join { left, right, .. } => {
21652 if left.as_scan().is_some_and(|scan| grounds_cls(scan, term))
21653 || right.as_scan().is_some_and(|scan| grounds_cls(scan, term))
21654 {
21655 return Some(node);
21656 }
21657 join_of_grounded_scan(left, term).or_else(|| join_of_grounded_scan(right, term))
21658 }
21659 PlanNode::LeftJoin { left, right, .. } | PlanNode::Union { left, right } => {
21660 join_of_grounded_scan(left, term).or_else(|| join_of_grounded_scan(right, term))
21661 }
21662 PlanNode::Filter { inner, .. }
21663 | PlanNode::Extend { inner, .. }
21664 | PlanNode::Distinct { inner, .. }
21665 | PlanNode::Sort { inner, .. }
21666 | PlanNode::Group { inner, .. }
21667 | PlanNode::JoinGraphVar { inner, .. } => join_of_grounded_scan(inner, term),
21668 PlanNode::CustomNode(op) => op
21669 .children
21670 .iter()
21671 .find_map(|child| join_of_grounded_scan(child, term)),
21672 PlanNode::SubSelect(sub) => join_of_grounded_scan(&sub.inner, term),
21673 _ => None,
21674 }
21675 }
21676
21677 fn grounded_class_scan(class: &EncodedTerm, rows: u64) -> PlanNode {
21680 PlanNode::Scan(ScanOp {
21681 ancestor_push_return_bound: None,
21682 fetch_once: None,
21683 pattern: EncodedTriplePattern {
21684 subject: None,
21685 predicate: Some(EncodedTerm::from(&NamedNode::new(RDF_TYPE_IRI).unwrap())),
21686 object: Some(class.clone()),
21687 graph_name: None,
21688 },
21689 subject: Some(var("feature")),
21690 predicate: None,
21691 object: Some(var("cls")),
21692 graph: None,
21693 produced_row_count_estimate: rows,
21694 broadcasted: None,
21695 graph_filter: None,
21696 grounded: vec![(var("cls"), PatternSlot::Object)],
21697 merge_default_graph: false,
21698 marks: Vec::new(),
21699 domain_scan: None,
21700 head_scan: None,
21701 head_scan_counts: None,
21702 domain_counts: None,
21703 iri_only: Vec::new(),
21704 eager: Vec::new(),
21705 join_domains: crate::plan::JoinDomainStamps::default(),
21706 })
21707 }
21708
21709 fn class_values_cartesian(term: &EncodedTerm) -> PlanNode {
21712 let values = PlanNode::Values(ValuesOp {
21713 variables: vec![var("cls")],
21714 rows: vec![vec![Some(term.clone())]],
21715 strings: Vec::new(),
21716 blobs: Vec::new(),
21717 });
21718 let feature_scan = PlanNode::Scan(ScanOp {
21719 ancestor_push_return_bound: None,
21720 fetch_once: None,
21721 pattern: EncodedTriplePattern {
21722 subject: None,
21723 predicate: Some(EncodedTerm::from(&NamedNode::new(RDF_TYPE_IRI).unwrap())),
21724 object: Some(EncodedTerm::from(
21725 &NamedNode::new("http://ex/Feature").unwrap(),
21726 )),
21727 graph_name: None,
21728 },
21729 subject: Some(var("feature")),
21730 predicate: None,
21731 object: None,
21732 graph: None,
21733 produced_row_count_estimate: 9_000,
21734 broadcasted: None,
21735 graph_filter: None,
21736 grounded: Vec::new(),
21737 merge_default_graph: false,
21738 marks: Vec::new(),
21739 domain_scan: None,
21740 head_scan: None,
21741 head_scan_counts: None,
21742 domain_counts: None,
21743 iri_only: Vec::new(),
21744 eager: Vec::new(),
21745 join_domains: crate::plan::JoinDomainStamps::default(),
21746 });
21747 PlanNode::Join {
21748 left: Box::new(values),
21749 right: Box::new(feature_scan),
21750 hash_keys: Vec::new(),
21751 probe_key_domains: Vec::new(),
21752 probe_key_overlap_milli: Vec::new(),
21753 rhs_hostable_keys: Vec::new().into(),
21754 meta: JoinMeta {
21755 semi_gate: None,
21756 star_arms: None,
21757 strategy: JoinStrategy::Hash,
21758 produced_row_count_estimate: 9_000,
21759 own_push_removed_row_count_estimate: 9_000,
21760 },
21761 }
21762 }
21763
21764 fn type_domain_profile() -> StatsProfile {
21765 let mut profile = StatsProfile {
21766 total_puts: 200_000,
21767 ..Default::default()
21768 };
21769 profile
21770 .predicate_counts
21771 .insert(StrHash::new(RDF_TYPE_IRI), 190_000);
21772 profile
21773 .subjects_per_predicate
21774 .insert(StrHash::new(RDF_TYPE_IRI), hll_with_n(100_000));
21775 profile
21776 .class_counts
21777 .insert(StrHash::new("http://ex/Feature"), 9_000);
21778 profile
21779 .class_counts
21780 .insert(StrHash::new("http://ex/FerryRoute"), 938);
21781 profile
21782 }
21783
21784 #[test]
21785 fn constant_class_key_lets_the_smaller_type_scan_drive_the_join() {
21786 let profile = type_domain_profile();
21794 let ferry = EncodedTerm::from(&NamedNode::new("http://ex/FerryRoute").unwrap());
21795 let sparql = r#"
21796 SELECT ?feature WHERE {
21797 VALUES ?cls { <http://ex/FerryRoute> }
21798 ?feature a <http://ex/Feature> .
21799 ?feature a ?cls .
21800 }
21801 "#;
21802 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
21803 let join = join_of_grounded_scan(&plan.root, &ferry)
21804 .expect("join over the grounded FerryRoute scan in plan");
21805 let PlanNode::Join {
21806 left, right, meta, ..
21807 } = join
21808 else {
21809 panic!("expected a Join, got {join:?}");
21810 };
21811 let ferry_scan = match (left.as_ref(), right.as_ref()) {
21817 (_, PlanNode::Scan(scan)) if scan.pattern.object.as_ref() == Some(&ferry) => scan,
21818 _ => panic!(
21819 "expected the grounded FerryRoute scan as the VALUES join's probe, got {join:?}"
21820 ),
21821 };
21822 assert_eq!(ferry_scan.produced_row_count_estimate, 938);
21823 assert_eq!(ferry_scan.pattern.object.as_ref(), Some(&ferry));
21824 assert_eq!(
21829 ferry_scan.join_domains.get(JoinKeySlot::Subject),
21830 JoinDomainStamp::Known(938),
21831 "broadcast grounding must promote the rdf:type subject stamp"
21832 );
21833 assert_eq!(
21834 meta.produced_row_count_estimate, 938,
21835 "join estimate must follow the driving scan, not the 9,000-row arm"
21836 );
21837 assert_eq!(
21838 meta.own_push_removed_row_count_estimate, 938,
21839 "the recorded pre-push stamp agrees here: the near-key ?feature \
21840 factor (9,000 distinct subjects among 9,000 rows) already models \
21841 the multiplicity the push conditions"
21842 );
21843 assert_eq!(meta.strategy, JoinStrategy::Broadcast);
21844 }
21845
21846 #[test]
21854 fn pinning_a_key_does_not_make_a_multi_column_custom_op_a_point() {
21855 let graph = EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap());
21856 let driver = PlanNode::Values(ValuesOp {
21857 variables: vec![var("g")],
21858 rows: vec![vec![Some(graph.clone())]],
21859 strings: Vec::new(),
21860 blobs: Vec::new(),
21861 });
21862
21863 let mut two_column = cost_test_op(1_000, None);
21864 two_column.variables = vec![var("s"), var("g")];
21865 let mut right = PlanNode::CustomNode(two_column);
21866 ground_and_recost_broadcasted_arm(&driver, &mut right, &[var("g")], None);
21867 let PlanNode::CustomNode(op) = &right else {
21868 panic!("expected the CustomNode");
21869 };
21870 assert_eq!(
21871 op.pinned,
21872 vec![(var("g"), graph)],
21873 "the grounded key still pins"
21874 );
21875 assert_eq!(
21876 op.produced_row_count_estimate, 1_000,
21877 "the free subject column keeps the window's cardinality"
21878 );
21879
21880 let mut one_column = cost_test_op(1_000, None);
21882 one_column.variables = vec![var("g")];
21883 let mut right = PlanNode::CustomNode(one_column);
21884 ground_and_recost_broadcasted_arm(&driver, &mut right, &[var("g")], None);
21885 let PlanNode::CustomNode(op) = &right else {
21886 panic!("expected the CustomNode");
21887 };
21888 assert_eq!(op.produced_row_count_estimate, 1);
21889 }
21890
21891 #[test]
21892 fn constant_key_excluded_from_allow_list_domain_aggregation() {
21893 let profile = type_domain_profile();
21898 let ferry = EncodedTerm::from(&NamedNode::new("http://ex/FerryRoute").unwrap());
21899 let cartesian = class_values_cartesian(&ferry);
21900 let ferry_scan = grounded_class_scan(&ferry, 938);
21901 let keys = [var("cls"), var("feature")];
21902 let producer_domain = join_key_domain_for_allow_list(
21903 Some(&profile),
21904 &cartesian,
21905 &ferry_scan,
21906 &keys,
21907 cartesian.produced_row_count_estimate(),
21908 );
21909 assert_eq!(
21910 producer_domain,
21911 Some(9_000),
21912 "?cls is a no-op filter and must not drag the minimum to 1"
21913 );
21914 let probe_domain = join_key_domain_for_allow_list(
21915 Some(&profile),
21916 &ferry_scan,
21917 &cartesian,
21918 &keys,
21919 ferry_scan.produced_row_count_estimate(),
21920 );
21921 assert_eq!(probe_domain, Some(938));
21922 }
21923
21924 #[test]
21925 fn conflicting_ground_join_keys_substitute_a_zero_row_node() {
21926 let ferry = EncodedTerm::from(&NamedNode::new("http://ex/FerryRoute").unwrap());
21930 let bus = EncodedTerm::from(&NamedNode::new("http://ex/BusRoute").unwrap());
21931 let cartesian = class_values_cartesian(&ferry);
21932
21933 let built = join_nodes(cartesian.clone(), grounded_class_scan(&bus, 938), None);
21935 let PlanNode::Values(values) = &built else {
21936 panic!("expected the zero-row substitution, got {built:?}");
21937 };
21938 assert!(values.rows.is_empty());
21943 assert_eq!(
21944 values
21945 .variables
21946 .iter()
21947 .map(Variable::as_str)
21948 .collect::<Vec<_>>(),
21949 vec!["cls", "feature"],
21950 "the union of both arms' output variables"
21951 );
21952 assert_eq!(built.produced_row_count_estimate(), 0);
21953
21954 let mut node = PlanNode::Join {
21958 left: Box::new(cartesian),
21959 right: Box::new(grounded_class_scan(&bus, 938)),
21960 hash_keys: vec![var("cls"), var("feature")],
21961 probe_key_domains: Vec::new(),
21962 probe_key_overlap_milli: Vec::new(),
21963 rhs_hostable_keys: Vec::new().into(),
21964 meta: JoinMeta {
21965 semi_gate: None,
21966 star_arms: None,
21967 strategy: JoinStrategy::Broadcast,
21968 produced_row_count_estimate: 9_000,
21969 own_push_removed_row_count_estimate: 9_000,
21970 },
21971 };
21972 refinalize_joins_without_ctx(&mut node, None);
21973 assert!(
21974 matches!(node, PlanNode::Values(ref values) if values.rows.is_empty()),
21975 "expected the zero-row substitution after refinalize, got {node:?}"
21976 );
21977 assert_eq!(node.produced_row_count_estimate(), 0);
21978 }
21979
21980 #[test]
21991 fn emptied_union_arm_keeps_hash_join_above() {
21992 let plan = LogicalPlan::parse(
21993 r#"SELECT ?s ?y WHERE {
21994 {
21995 VALUES ?b { <http://ex/crow> }
21996 VALUES ?b { <http://ex/other> }
21997 ?s <http://ex/p> ?y .
21998 }
21999 UNION
22000 {
22001 VALUES ?b { <http://ex/crow> }
22002 ?s <http://ex/q> ?y .
22003 }
22004 ?y <http://ex/rel> ?b .
22005 }"#,
22006 )
22007 .unwrap();
22008 let PlanNode::Join {
22009 hash_keys,
22010 left: root_left,
22011 right: root_right,
22012 ..
22013 } = &plan.root
22014 else {
22015 panic!("expected the root join over the union, got {:?}", plan.root)
22016 };
22017 let union = match (root_left.as_ref(), root_right.as_ref()) {
22019 (PlanNode::Union { .. }, _) => root_left,
22020 (_, PlanNode::Union { .. }) => root_right,
22021 _ => panic!(
22022 "expected the union under the root join, got {:?}",
22023 plan.root
22024 ),
22025 };
22026 let key_names: Vec<&str> = hash_keys.iter().map(Variable::as_str).collect();
22031 assert!(
22032 key_names.contains(&"b"),
22033 "?b stays always-bound above the union, so the join above is a \
22034 hash join on ?b, got keys {hash_keys:?}"
22035 );
22036 let PlanNode::Union { left, right, .. } = union.as_ref() else {
22037 panic!("expected the union on the left, got {union:?}")
22038 };
22039 let empty = [&**left, &**right].into_iter().find_map(|arm| {
22040 let mut node = arm;
22041 while let PlanNode::Filter { inner, .. } = node {
22042 node = inner;
22043 }
22044 match node {
22045 PlanNode::Values(values) if values.rows.is_empty() => Some(values),
22046 _ => None,
22047 }
22048 });
22049 let empty =
22050 empty.unwrap_or_else(|| panic!("expected one collapsed zero-row arm, got {union:?}"));
22051 assert!(
22052 empty.variables.iter().any(|v| v.as_str() == "b"),
22053 "the zero-row arm declares ?b, got {:?}",
22054 empty.variables
22055 );
22056 assert_eq!(
22057 empty.produced_row_count_estimate(),
22058 0,
22059 "the arm is still empty: zero rows execute"
22060 );
22061 }
22062
22063 #[test]
22071 fn path_probe_joined_on_its_end_prices_broadcast_keys() {
22072 let values = PlanNode::Values(ValuesOp {
22075 variables: vec![var("f")],
22076 rows: vec![vec![Some(EncodedTerm::from(
22077 &NamedNode::new("http://ex/FerryRoute").unwrap(),
22078 ))]],
22079 strings: Vec::new(),
22080 blobs: Vec::new(),
22081 });
22082 let branch = || {
22083 PropertyPath::Predicate(EncodedTerm::from(
22084 &NamedNode::new("http://ex/edge").unwrap(),
22085 ))
22086 };
22087 let path = PlanNode::Path(PathOp {
22088 subject_term: None,
22089 subject: Some(var("f")),
22090 path: PropertyPath::Alternative(Box::new(branch()), Box::new(branch())),
22091 object_term: None,
22092 object: Some(var("g")),
22093 produced_row_count_estimate: 2_000_000,
22094 strings: Vec::new(),
22095 graph: None,
22096 graph_name: None,
22097 graph_filter: None,
22098 merge_default_graph: false,
22099 });
22100 let keys = [var("f")];
22101 let (strategy, produced, own_push_removed) =
22102 finalize_inner_join_meta(&values, &path, &keys, None);
22103 assert_eq!(
22104 produced, 1,
22105 "the path is probed with the driver's 1 distinct key: the \
22106 values-broadcast bound, not the 2M unbound leaf price"
22107 );
22108 assert_eq!(
22109 own_push_removed, 2_000_000,
22110 "the own-push-removed record keeps the bare pattern price — the \
22111 (price ~N) EXPLAIN shows"
22112 );
22113 assert_eq!(strategy, JoinStrategy::Broadcast);
22114 let (_, estimate, own_push_removed) = finalize_inner_join_meta(&values, &path, &[], None);
22118 assert_eq!(estimate, 2_000_000);
22119 assert_eq!(own_push_removed, 2_000_000);
22120 assert_eq!(strategy, JoinStrategy::Broadcast);
22122 }
22123
22124 #[test]
22134 fn path_probe_bound_and_clamp_agree_on_both_ends_keyed_paths() {
22135 let geoms = PlanNode::Values(ValuesOp {
22138 variables: vec![var("geom")],
22139 rows: (0..375)
22140 .map(|i| {
22141 vec![Some(EncodedTerm::from(
22142 &NamedNode::new(format!("http://ex/g{i}")).unwrap(),
22143 ))]
22144 })
22145 .collect(),
22146 strings: Vec::new(),
22147 blobs: Vec::new(),
22148 });
22149 let features = PlanNode::Values(ValuesOp {
22150 variables: vec![var("feature")],
22151 rows: (0..10_000)
22152 .map(|i| {
22153 vec![Some(EncodedTerm::from(
22154 &NamedNode::new(format!("http://ex/f{i}")).unwrap(),
22155 ))]
22156 })
22157 .collect(),
22158 strings: Vec::new(),
22159 blobs: Vec::new(),
22160 });
22161 let driver = join_nodes(geoms, features, None);
22162 let branch = || {
22163 PropertyPath::Predicate(EncodedTerm::from(
22164 &NamedNode::new("http://ex/edge").unwrap(),
22165 ))
22166 };
22167 let path = PathOp {
22168 subject_term: None,
22169 subject: Some(var("feature")),
22170 path: PropertyPath::Alternative(Box::new(branch()), Box::new(branch())),
22171 object_term: None,
22172 object: Some(var("geom")),
22173 produced_row_count_estimate: 2_000_000,
22174 strings: Vec::new(),
22175 graph: None,
22176 graph_name: None,
22177 graph_filter: None,
22178 merge_default_graph: false,
22179 };
22180 let keys = [var("feature"), var("geom")];
22182 let bounded = path_probe_row_bound(
22183 &PlanNode::Path(path.clone()),
22184 &driver,
22185 &keys,
22186 2_000_000,
22187 None,
22188 );
22189 assert_eq!(
22190 bounded, 375,
22191 "the min over binding keys: the 375-element ?geom push is the \
22192 binding constraint, not the 10,000-element ?feature push that \
22193 sorts first"
22194 );
22195 let mut path_node = PlanNode::Path(path.clone());
22198 clamp_broadcast_probe_estimates(&driver, &mut path_node, &keys, None);
22199 let PlanNode::Path(clamped) = &path_node else {
22200 unreachable!("clamped a path");
22201 };
22202 assert_eq!(
22203 clamped.produced_row_count_estimate, 375,
22204 "the node clamp uses the same min-over-binding-keys rule the \
22205 swap's bound used"
22206 );
22207 }
22208
22209 #[test]
22217 fn optional_path_right_arm_prices_broadcast_keys() {
22218 let left = PlanNode::Values(ValuesOp {
22219 variables: vec![var("f")],
22220 rows: (0..5)
22221 .map(|i| {
22222 vec![Some(EncodedTerm::from(
22223 &NamedNode::new(format!("http://ex/f{i}")).unwrap(),
22224 ))]
22225 })
22226 .collect(),
22227 strings: Vec::new(),
22228 blobs: Vec::new(),
22229 });
22230 let branch = || {
22231 PropertyPath::Predicate(EncodedTerm::from(
22232 &NamedNode::new("http://ex/edge").unwrap(),
22233 ))
22234 };
22235 let path = PlanNode::Path(PathOp {
22236 subject_term: None,
22237 subject: Some(var("f")),
22238 path: PropertyPath::Alternative(Box::new(branch()), Box::new(branch())),
22239 object_term: None,
22240 object: Some(var("g")),
22241 produced_row_count_estimate: 2_000_000,
22242 strings: Vec::new(),
22243 graph: None,
22244 graph_name: None,
22245 graph_filter: None,
22246 merge_default_graph: false,
22247 });
22248 let keys = [var("f")];
22249 let estimate = estimate_left_join_rows(5, &left, &path, &keys, None);
22253 assert_eq!(
22254 estimate, 10,
22255 "5 pass-through rows + 5 values-broadcast matched rows, not the \
22256 2M unbound leaf price"
22257 );
22258 let meta = stamp_left_join_meta(5, &left, &path, &keys, None);
22264 assert_eq!(
22265 meta.produced_row_count_estimate, 10,
22266 "produced: the stage model (values-broadcast bound)"
22267 );
22268 assert_eq!(
22269 meta.own_push_removed_row_count_estimate, 2_000_005,
22270 "own-push-removed: the bare leaf price"
22271 );
22272 }
22273
22274 #[test]
22275 fn all_keys_constant_falls_back_to_todays_join() {
22276 let a = EncodedTerm::from(&NamedNode::new("http://ex/A").unwrap());
22281 let b = EncodedTerm::from(&NamedNode::new("http://ex/B").unwrap());
22282 let values = PlanNode::Values(ValuesOp {
22283 variables: vec![var("cls"), var("k")],
22284 rows: vec![vec![Some(a.clone()), Some(b.clone())]],
22285 strings: Vec::new(),
22286 blobs: Vec::new(),
22287 });
22288 let scan = PlanNode::Scan(ScanOp {
22289 ancestor_push_return_bound: None,
22290 fetch_once: None,
22291 pattern: EncodedTriplePattern {
22292 subject: Some(b),
22293 predicate: Some(EncodedTerm::from(
22294 &NamedNode::new("http://ex/pred").unwrap(),
22295 )),
22296 object: Some(a.clone()),
22297 graph_name: None,
22298 },
22299 subject: Some(var("k")),
22300 predicate: None,
22301 object: Some(var("cls")),
22302 graph: None,
22303 produced_row_count_estimate: 5,
22304 broadcasted: None,
22305 graph_filter: None,
22306 grounded: Vec::new(),
22307 merge_default_graph: false,
22308 marks: Vec::new(),
22309 domain_scan: None,
22310 head_scan: None,
22311 head_scan_counts: None,
22312 domain_counts: None,
22313 iri_only: Vec::new(),
22314 eager: Vec::new(),
22315 join_domains: crate::plan::JoinDomainStamps::default(),
22316 });
22317 let keys = [var("cls"), var("k")];
22318 assert_eq!(
22321 join_key_domain_for_allow_list(
22322 None,
22323 &values,
22324 &scan,
22325 &keys,
22326 values.produced_row_count_estimate()
22327 ),
22328 Some(1)
22329 );
22330 let built = join_nodes(values, scan, None);
22331 let PlanNode::Join { left, meta, .. } = &built else {
22332 panic!("the constant join must stay intact, got {built:?}");
22333 };
22334 assert!(
22335 matches!(left.as_ref(), PlanNode::Values(_)),
22336 "the 1-row VALUES arm drives, got {:?}",
22337 left
22338 );
22339 assert_eq!(
22346 meta.produced_row_count_estimate, 1,
22347 "the join meta follows the grounded point-lookup probe, not the \
22348 stale pre-ground price"
22349 );
22350 }
22351
22352 const TENANT_UNION: &str = r#"
22353 SELECT ?tenant ?x WHERE {
22354 ?tenant a <http://ex/Tenant> .
22355 {
22356 ?x <http://ex/hasTenant> ?tenant .
22357 ?x a <http://ex/Server> .
22358 } UNION {
22359 ?x <http://ex/hasTenant> ?tenant .
22360 ?x a <http://ex/VM> .
22361 }
22362 }
22363 "#;
22364
22365 fn hll_with_n(n: u128) -> waratah_stats::HyperLogLog {
22366 let mut hll = waratah_stats::HyperLogLog::default_params();
22367 for i in 0..n {
22368 hll.add(i);
22369 }
22370 hll
22371 }
22372
22373 #[test]
22374 fn term_dict_reserve_amount_guard_rails() {
22375 use super::{TERM_DICT_RESERVE_FLOOR, TERM_DICT_RESERVE_MAX, term_dict_reserve_amount};
22376 assert_eq!(term_dict_reserve_amount(0), None);
22379 assert_eq!(term_dict_reserve_amount(10), None);
22380 assert_eq!(term_dict_reserve_amount(TERM_DICT_RESERVE_FLOOR - 1), None);
22381 assert_eq!(
22383 term_dict_reserve_amount(TERM_DICT_RESERVE_FLOOR),
22384 Some(TERM_DICT_RESERVE_FLOOR)
22385 );
22386 assert_eq!(term_dict_reserve_amount(758_327), Some(758_327));
22387 assert_eq!(
22390 term_dict_reserve_amount(2_000_000),
22391 Some(TERM_DICT_RESERVE_MAX)
22392 );
22393 assert_eq!(
22394 term_dict_reserve_amount(u64::MAX),
22395 Some(TERM_DICT_RESERVE_MAX)
22396 );
22397 }
22398
22399 #[test]
22400 fn path_triple_estimates_track_sparopt_calibration() {
22401 assert_eq!(estimate_path_triple(true, true, true), 1);
22407 assert_eq!(estimate_path_triple(false, true, true), 1_000);
22408 assert_eq!(estimate_path_triple(false, false, true), 10_000);
22409 assert_eq!(estimate_path_triple(true, true, false), 10);
22410 assert_eq!(estimate_path_triple(false, false, false), 1_000_000_000);
22411 }
22412
22413 #[test]
22414 fn rdf_type_path_estimate_gets_the_plus_one() {
22415 let type_pred = EncodedTerm::from(&NamedNode::new(RDF_TYPE_IRI).unwrap());
22416 let other_pred = EncodedTerm::from(&NamedNode::new("http://ex/knows").unwrap());
22417 let base = estimate_path_triple(false, true, true);
22418 assert_eq!(
22419 estimate_path_size(false, &PropertyPath::Predicate(type_pred), true),
22420 base + 1,
22421 "an `rdf:type` predicate adds one to the base estimate"
22422 );
22423 assert_eq!(
22424 estimate_path_size(false, &PropertyPath::Predicate(other_pred), true),
22425 base,
22426 "any other predicate keeps the plain estimate"
22427 );
22428 }
22429
22430 #[test]
22431 fn estimated_distinct_terms_takes_per_variable_maxima() {
22432 use super::estimated_distinct_terms;
22433 let mut profile = StatsProfile::default();
22437 profile
22438 .subjects_per_predicate
22439 .insert(StrHash::new("http://ex/pA"), hll_with_n(100));
22440 profile
22441 .subjects_per_predicate
22442 .insert(StrHash::new("http://ex/pB"), hll_with_n(700));
22443 profile.total_puts = 800;
22444 let root = PlanNode::Union {
22445 left: Box::new(PlanNode::Scan(var_scan(
22446 Some("samp"),
22447 "http://ex/pA",
22448 Some("occ"),
22449 100_000,
22450 ))),
22451 right: Box::new(PlanNode::Scan(var_scan(
22452 Some("samp"),
22453 "http://ex/pB",
22454 Some("proc"),
22455 700_000,
22456 ))),
22457 };
22458 let mut maxima = Vec::new();
22459 estimated_distinct_terms(&root, &profile, &mut maxima);
22460 let estimate: u64 = maxima.iter().map(|(_, domain)| domain).sum();
22461 let expected = profile
22466 .subjects_per_predicate
22467 .get(&StrHash::new("http://ex/pB"))
22468 .expect("pB subjects HLL")
22469 .cardinality();
22470 assert_eq!(estimate, expected, "maxima were {maxima:?}");
22471 assert_eq!(
22472 maxima.len(),
22473 1,
22474 "no object-side domains in the profile: only ?samp contributes"
22475 );
22476 }
22477
22478 fn tenant_union_small_has_tenant_domain() -> StatsProfile {
22481 let mut profile = StatsProfile::default();
22482 let rdf_type = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
22483 let has_tenant = StrHash::new("http://ex/hasTenant");
22484 profile.total_puts = 300_000;
22485 profile
22486 .class_counts
22487 .insert(StrHash::new("http://ex/Tenant"), 50_000);
22488 profile
22489 .class_counts
22490 .insert(StrHash::new("http://ex/Server"), 100_000);
22491 profile
22492 .class_counts
22493 .insert(StrHash::new("http://ex/VM"), 100_000);
22494 profile.predicate_counts.insert(rdf_type, 250_000);
22495 profile.predicate_counts.insert(has_tenant, 100_000);
22496 profile
22497 .subjects_per_predicate
22498 .insert(rdf_type, hll_with_n(50_000));
22499 profile
22500 .objects_per_predicate
22501 .insert(rdf_type, hll_with_n(3));
22502 profile
22503 .subjects_per_predicate
22504 .insert(has_tenant, hll_with_n(80_000));
22505 profile
22506 .objects_per_predicate
22507 .insert(has_tenant, hll_with_n(40));
22508 profile
22509 }
22510
22511 fn tenant_union_small_type_scan_domain() -> StatsProfile {
22513 let mut profile = StatsProfile::default();
22514 let rdf_type = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
22515 let has_tenant = StrHash::new("http://ex/hasTenant");
22516 profile.total_puts = 300_000;
22517 profile
22518 .class_counts
22519 .insert(StrHash::new("http://ex/Tenant"), 20);
22520 profile
22521 .class_counts
22522 .insert(StrHash::new("http://ex/Server"), 100_000);
22523 profile
22524 .class_counts
22525 .insert(StrHash::new("http://ex/VM"), 100_000);
22526 profile.predicate_counts.insert(rdf_type, 200_020);
22527 profile.predicate_counts.insert(has_tenant, 100_000);
22528 profile
22529 .subjects_per_predicate
22530 .insert(rdf_type, hll_with_n(20));
22531 profile
22532 .objects_per_predicate
22533 .insert(rdf_type, hll_with_n(3));
22534 profile
22535 .subjects_per_predicate
22536 .insert(has_tenant, hll_with_n(80_000));
22537 profile
22538 .objects_per_predicate
22539 .insert(has_tenant, hll_with_n(50_000));
22540 profile
22541 }
22542
22543 fn assert_join_scan_union(root: &PlanNode, union_on_left: bool) {
22544 let PlanNode::Join {
22545 left,
22546 right,
22547 hash_keys,
22548 probe_key_domains: _,
22549 probe_key_overlap_milli: _,
22550 rhs_hostable_keys: _,
22551 meta,
22552 } = root
22553 else {
22554 panic!("expected Join at root, got {root:?}");
22555 };
22556 assert_eq!(
22557 hash_keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
22558 ["tenant"]
22559 );
22560 if union_on_left {
22561 assert!(
22562 left.as_union().is_some(),
22563 "expected Union on the left, got {left:?}"
22564 );
22565 assert!(
22566 right.as_broadcast_scan().is_some(),
22567 "expected Scan on the right, got {right:?}"
22568 );
22569 assert_eq!(meta.strategy, JoinStrategy::Broadcast);
22570 } else {
22571 assert!(
22572 left.as_broadcast_scan().is_some(),
22573 "expected Scan on the left, got {left:?}"
22574 );
22575 assert!(
22576 right.as_union().is_some(),
22577 "expected Union on the right, got {right:?}"
22578 );
22579 }
22580 }
22581
22582 #[test]
22583 fn join_scan_union_swaps_when_union_join_key_domain_is_smaller() {
22584 let plan = LogicalPlan::parse_with_profile(
22585 TENANT_UNION,
22586 Some(&tenant_union_small_has_tenant_domain()),
22587 )
22588 .unwrap();
22589 assert_join_scan_union(&plan.root, true);
22590 }
22591
22592 #[test]
22593 fn join_scan_union_keeps_scan_left_when_type_domain_is_smaller() {
22594 let plan = LogicalPlan::parse_with_profile(
22595 TENANT_UNION,
22596 Some(&tenant_union_small_type_scan_domain()),
22597 )
22598 .unwrap();
22599 assert_join_scan_union(&plan.root, false);
22600 }
22601
22602 #[test]
22603 fn join_scan_union_broadcast_annotates_has_tenant_scans() {
22604 let profile = tenant_union_small_type_scan_domain();
22605 let plan = LogicalPlan::parse_with_profile(TENANT_UNION, Some(&profile)).unwrap();
22606 assert_join_scan_union(&plan.root, false);
22607 let PlanNode::Join { right, meta, .. } = &plan.root else {
22608 panic!("expected Join at root, got {:?}", plan.root);
22609 };
22610 assert_eq!(meta.strategy, JoinStrategy::Broadcast);
22611 let mut has_tenant = Vec::new();
22612 for_each_scan(right, &mut |scan| {
22613 if scan.object.as_ref().is_some_and(|v| v.as_str() == "tenant") {
22614 has_tenant.push(scan);
22615 }
22616 });
22617 assert_eq!(
22618 has_tenant.len(),
22619 2,
22620 "two :hasTenant scans in UNION arms: {right:?}"
22621 );
22622 for scan in &has_tenant {
22623 assert!(
22624 matches!(
22625 scan.broadcasted,
22626 Some((ref v, PatternSlot::Object)) if v.as_str() == "tenant"
22627 ),
22628 "expected object broadcast on ?tenant, got {:?}",
22629 scan.broadcasted
22630 );
22631 assert!(
22632 scan.produced_row_count_estimate < 1_000,
22633 "allow-listed :hasTenant scan must not use catalog rows: {}",
22634 scan.produced_row_count_estimate
22635 );
22636 }
22637 let mut arm_type_broadcasts = 0;
22648 for_each_scan(right, &mut |scan| {
22649 if scan.subject.as_ref().is_some_and(|v| v.as_str() == "x")
22650 && scan.object.is_none()
22651 && scan.broadcasted.is_some()
22652 {
22653 assert!(
22654 matches!(
22655 scan.broadcasted,
22656 Some((ref v, PatternSlot::Subject)) if v.as_str() == "x"
22657 ),
22658 "arm type probe carries its arm join's ?x claim, got {:?}",
22659 scan.broadcasted
22660 );
22661 assert!(
22662 scan.produced_row_count_estimate < 1_000,
22663 "claimed arm type probe must not read catalog rows: {}",
22664 scan.produced_row_count_estimate
22665 );
22666 arm_type_broadcasts += 1;
22667 }
22668 });
22669 assert_eq!(
22670 arm_type_broadcasts, 2,
22671 "both Server/VM type scans are arm-join probes now: {right:?}"
22672 );
22673 let text = explain_est(TENANT_UNION, Some(&profile));
22674 assert!(
22675 text.matches("(broadcast ?tenant object)").count() >= 2,
22676 "EXPLAIN should annotate both :hasTenant scans: {text}"
22677 );
22678 }
22679
22680 #[test]
22681 fn join_scan_union_broadcast_annotates_type_scan() {
22682 let profile = tenant_union_small_has_tenant_domain();
22683 let plan = LogicalPlan::parse_with_profile(TENANT_UNION, Some(&profile)).unwrap();
22684 assert_join_scan_union(&plan.root, true);
22685 let PlanNode::Join { right, .. } = &plan.root else {
22686 panic!("expected Join at root, got {:?}", plan.root);
22687 };
22688 let scan = right
22689 .as_broadcast_scan()
22690 .expect("type scan should be the probe");
22691 assert!(
22692 matches!(
22693 scan.broadcasted,
22694 Some((ref v, PatternSlot::Subject)) if v.as_str() == "tenant"
22695 ),
22696 "expected subject broadcast on ?tenant, got {:?}",
22697 scan.broadcasted
22698 );
22699 assert!(
22700 scan.produced_row_count_estimate < 1_000,
22701 "allow-listed type scan must not use catalog rows: {}",
22702 scan.produced_row_count_estimate
22703 );
22704 let text = explain_est(TENANT_UNION, Some(&profile));
22705 assert!(
22706 text.contains("(broadcast ?tenant subject)"),
22707 "EXPLAIN should annotate the type scan: {text}"
22708 );
22709 }
22710
22711 fn collapse_recost_profile() -> StatsProfile {
22718 let mut profile = StatsProfile::default();
22719 let rdf_type = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
22720 let label = StrHash::new("http://ex/label");
22721 profile.total_puts = 300_000;
22722 profile
22724 .class_counts
22725 .insert(StrHash::new("http://ex/Big"), 10_000);
22726 profile
22727 .class_counts
22728 .insert(StrHash::new("http://ex/Sub"), 843);
22729 for i in 0..998u32 {
22736 profile
22737 .class_counts
22738 .insert(StrHash::new(&format!("http://ex/Filler{i}")), 1);
22739 }
22740 profile.predicate_counts.insert(rdf_type, 250_000);
22741 profile.predicate_counts.insert(label, 200_000);
22742 profile
22744 .subjects_per_predicate
22745 .insert(rdf_type, hll_with_n(74_083_307));
22746 profile
22747 .objects_per_predicate
22748 .insert(rdf_type, hll_with_n(1_000));
22749 profile
22750 .subjects_per_predicate
22751 .insert(label, hll_with_n(10_000));
22752 profile
22760 .objects_per_predicate
22761 .insert(label, hll_with_n(190_000));
22762 profile
22763 }
22764
22765 #[test]
22766 fn distinct_ground_object_scan_keeps_class_map_rows() {
22767 let profile = collapse_recost_profile();
22768 let text = explain_est(
22769 "SELECT DISTINCT ?x WHERE { ?x a <http://ex/Sub> }",
22770 Some(&profile),
22771 );
22772 assert_eq!(
22773 rows_on_line(&text, "(scan "),
22774 843,
22775 "ground object + single collapse key must use the exact class map, not the global HLL: {text}"
22776 );
22777 }
22778
22779 #[test]
22780 fn distinct_dead_subject_scan_uses_object_domain_rows() {
22781 let profile = collapse_recost_profile();
22782 let text = explain_est("SELECT DISTINCT ?o WHERE { ?s a ?o }", Some(&profile));
22788 assert!(
22789 text.contains("(head_scan classes@tsg)"),
22790 "dead S + insensitive O on rdf:type must rewrite to the TSG head scan: {text}"
22791 );
22792 let rows = rows_on_line(&text, "(scan ");
22793 assert_eq!(
22794 rows,
22795 profile.class_counts.len() as u64,
22796 "domain_scan rows come from the exact class count: {text}"
22797 );
22798 assert!(
22799 rows < 2_000,
22800 "distinct classes (~1k) must beat the 250k triple count: {text}"
22801 );
22802 }
22803
22804 fn predicate_domain_scan() -> ScanOp {
22808 let p1 = EncodedTerm::from(&NamedNode::new("http://ex/p1").unwrap());
22809 ScanOp {
22810 ancestor_push_return_bound: None,
22811 fetch_once: None,
22812 pattern: EncodedTriplePattern {
22813 subject: None,
22814 predicate: Some(p1.clone()),
22815 object: None,
22816 graph_name: None,
22817 },
22818 subject: None,
22819 predicate: None,
22820 object: None,
22821 graph: None,
22822 produced_row_count_estimate: 1,
22823 broadcasted: None,
22824 graph_filter: None,
22825 grounded: Vec::new(),
22826 merge_default_graph: false,
22827 marks: Vec::new(),
22828 domain_scan: Some(DomainScanKind::PredicateDomain),
22829 head_scan: None,
22830 head_scan_counts: None,
22831 domain_counts: None,
22832 iri_only: Vec::new(),
22833 eager: Vec::new(),
22834 join_domains: crate::plan::JoinDomainStamps::default(),
22835 }
22836 }
22837
22838 fn stamped_head_scan_profile() -> StatsProfile {
22839 let mut profile = StatsProfile::default();
22840 let p1 = StrHash::new("http://ex/p1");
22841 profile.predicate_counts.insert(p1, 9);
22842 profile.objects_per_predicate.insert(p1, hll_with_n(500));
22843 profile
22844 }
22845
22846 #[test]
22847 fn join_domain_stamp_is_known_for_bound_predicate_slots() {
22848 let mut profile = StatsProfile::default();
22849 let p = StrHash::new("http://ex/p");
22850 profile.predicate_counts.insert(p, 100);
22851 profile.subjects_per_predicate.insert(p, hll_with_n(500));
22852 profile.objects_per_predicate.insert(p, hll_with_n(50));
22853
22854 let scan = var_scan(Some("s"), "http://ex/p", Some("o"), 1);
22855 let stamps = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
22856 assert_eq!(
22859 stamps.get(JoinKeySlot::Subject),
22860 JoinDomainStamp::Known(profile.subject_domain(&p).unwrap())
22861 );
22862 assert_eq!(
22863 stamps.get(JoinKeySlot::Object),
22864 JoinDomainStamp::Known(profile.object_domain(&p).unwrap())
22865 );
22866 }
22867
22868 #[test]
22869 fn known_stamp_is_returned_without_a_live_lookup() {
22870 let mut scan = var_scan(Some("s"), "http://ex/p", Some("o"), 1);
22871 scan.join_domains = JoinDomainStamps {
22872 subject: JoinDomainStamp::Known(7),
22873 object: JoinDomainStamp::Known(9),
22874 };
22875 let mut profile = StatsProfile::default();
22878 let p = StrHash::new("http://ex/p");
22879 profile.predicate_counts.insert(p, 1);
22880 profile.subjects_per_predicate.insert(p, hll_with_n(500));
22881 assert_eq!(
22882 join_key_domain_for(Some(&profile), &scan, &[var("s")]),
22883 Some(7)
22884 );
22885 assert_eq!(
22886 join_key_domain_for(Some(&profile), &scan, &[var("o")]),
22887 Some(9)
22888 );
22889 }
22890
22891 #[test]
22892 fn with_pattern_drops_join_domain_stamps() {
22893 let mut profile = StatsProfile::default();
22894 let p = StrHash::new("http://ex/p");
22895 profile.predicate_counts.insert(p, 1);
22896 profile.objects_per_predicate.insert(p, hll_with_n(50));
22897
22898 let mut scan = var_scan(Some("s"), "http://ex/p", Some("o"), 1);
22899 scan.join_domains = JoinDomainStamps {
22900 subject: JoinDomainStamp::Known(7),
22901 object: JoinDomainStamp::Known(9),
22902 };
22903 let mut pattern = scan.pattern.clone();
22904 pattern.subject = Some(EncodedTerm::from(
22905 &NamedNode::new("http://ex/grounded-s").unwrap(),
22906 ));
22907 let grounded = scan.with_pattern(pattern);
22908 assert_eq!(
22909 grounded.join_domains,
22910 JoinDomainStamps::default(),
22911 "a rewritten pattern must not keep the old stamp"
22912 );
22913 assert_eq!(
22916 join_key_domain_for(Some(&profile), &grounded, &[var("o")]),
22917 Some(profile.object_domain(&p).unwrap())
22918 );
22919 assert_ne!(
22920 join_key_domain_for(Some(&profile), &grounded, &[var("o")]),
22921 Some(9)
22922 );
22923 }
22924
22925 #[test]
22926 fn grounded_slot_still_wins_over_a_known_stamp() {
22927 let mut scan = var_scan(Some("s"), "http://ex/p", Some("o"), 1);
22930 scan.pattern.subject = Some(EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()));
22931 scan.join_domains = JoinDomainStamps {
22932 subject: JoinDomainStamp::Known(999),
22933 object: JoinDomainStamp::Known(9),
22934 };
22935 assert_eq!(join_key_domain_for(None, &scan, &[var("s")]), Some(1));
22936 }
22937
22938 #[test]
22939 fn grounding_rdf_type_object_promotes_deferred_subject_stamp() {
22940 let mut profile = StatsProfile::default();
22941 let class = EncodedTerm::from(&NamedNode::new("http://ex/Student").unwrap());
22942 let class_hash = named_node_hash(&class).unwrap();
22943 profile.class_counts.insert(class_hash, 42);
22944
22945 let mut scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
22946 scan.join_domains = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
22947 assert_eq!(
22948 scan.join_domains.get(JoinKeySlot::Subject),
22949 JoinDomainStamp::Deferred,
22950 "a free rdf:type object can change the subject answer"
22951 );
22952
22953 scan.pattern.object = Some(class);
22955 scan.record_grounded(&var("c"), PatternSlot::Object, Some(&profile));
22956 assert_eq!(
22957 scan.join_domains.get(JoinKeySlot::Subject),
22958 JoinDomainStamp::Known(42)
22959 );
22960 assert_eq!(
22961 join_key_domain_for(Some(&profile), &scan, &[var("s")]),
22962 Some(42)
22963 );
22964 }
22965
22966 #[test]
22967 fn bind_scan_equality_promotes_rdf_type_subject_stamp() {
22968 let mut profile = StatsProfile::default();
22969 let class = EncodedTerm::from(&NamedNode::new("http://ex/Student").unwrap());
22970 let class_hash = named_node_hash(&class).unwrap();
22971 profile.class_counts.insert(class_hash, 42);
22972
22973 let mut scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
22974 scan.join_domains = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
22975 assert_eq!(
22976 scan.join_domains.get(JoinKeySlot::Subject),
22977 JoinDomainStamp::Deferred,
22978 "a free rdf:type object can change the subject answer"
22979 );
22980
22981 assert!(
22982 bind_scan_equality(&mut scan, &var("c"), &class, Some(&profile)),
22983 "identity grounding must bind the free rdf:type object"
22984 );
22985 assert_eq!(
22986 scan.join_domains.get(JoinKeySlot::Subject),
22987 JoinDomainStamp::Known(42),
22988 "bind_scan_equality must refresh the stamps after rebuilding the pattern"
22989 );
22990
22991 let mut prebound = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
22995 prebound.join_domains = JoinDomainStamps::classify(Some(&profile), &prebound.pattern);
22996 prebound.pattern.object = Some(class.clone());
22997 assert!(
22998 bind_scan_equality(&mut prebound, &var("c"), &class, Some(&profile)),
22999 "an already-pinned rdf:type object must still count as grounded"
23000 );
23001 assert_eq!(
23002 prebound.join_domains.get(JoinKeySlot::Subject),
23003 JoinDomainStamp::Known(42),
23004 "the existing-term branch must refresh the stamps too"
23005 );
23006 }
23007
23008 #[test]
23009 fn rdf_type_subject_stays_deferred_while_object_free() {
23010 let mut profile = StatsProfile::default();
23011 profile
23012 .class_counts
23013 .insert(StrHash::new("http://ex/Student"), 42);
23014 let mut scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
23015 scan.join_domains = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
23016 assert_eq!(
23017 scan.join_domains.get(JoinKeySlot::Subject),
23018 JoinDomainStamp::Deferred,
23019 "with class_counts present, a free rdf:type object can change the subject answer"
23020 );
23021 scan.refresh_join_domains(Some(&profile));
23024 assert_eq!(
23025 scan.join_domains.get(JoinKeySlot::Subject),
23026 JoinDomainStamp::Deferred
23027 );
23028 }
23029
23030 #[test]
23031 fn deferred_rdf_type_subject_prices_as_live_subject_hll() {
23032 let pred = StrHash::new(RDF_TYPE_IRI);
23033 let mut profile = StatsProfile::default();
23034 profile
23035 .class_counts
23036 .insert(StrHash::new("http://ex/Student"), 42);
23037 profile.subjects_per_predicate.insert(pred, hll_with_n(123));
23038 let mut scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
23039 scan.join_domains = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
23040 assert_eq!(
23041 scan.join_domains.get(JoinKeySlot::Subject),
23042 JoinDomainStamp::Deferred,
23043 "with class_counts present, a free rdf:type object can change the subject answer"
23044 );
23045 let live_subject = profile.subject_domain(&pred).unwrap();
23049 assert_eq!(
23050 join_key_domain_for(Some(&profile), &scan, &[var("s")]),
23051 Some(live_subject)
23052 );
23053 assert_ne!(
23054 join_key_domain_for(Some(&profile), &scan, &[var("s")]),
23055 Some(42)
23056 );
23057 }
23058
23059 #[test]
23060 fn rdf_type_object_stamp_uses_exact_classes_then_object_hll() {
23061 let scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
23062
23063 let mut exact = StatsProfile::default();
23067 exact.class_counts.insert(StrHash::new("http://ex/A"), 10);
23068 exact.class_counts.insert(StrHash::new("http://ex/B"), 20);
23069 let stamps = JoinDomainStamps::classify(Some(&exact), &scan.pattern);
23070 assert_eq!(
23071 stamps.get(JoinKeySlot::Object),
23072 JoinDomainStamp::Known(exact.class_counts.len() as u64)
23073 );
23074 assert_eq!(stamps.get(JoinKeySlot::Subject), JoinDomainStamp::Deferred);
23075
23076 let pred = StrHash::new(RDF_TYPE_IRI);
23080 let mut fallback = StatsProfile::default();
23081 fallback.predicate_counts.insert(pred, 100);
23082 fallback.objects_per_predicate.insert(pred, hll_with_n(77));
23083 let stamps = JoinDomainStamps::classify(Some(&fallback), &scan.pattern);
23084 assert_eq!(
23085 stamps.get(JoinKeySlot::Object),
23086 JoinDomainStamp::Known(fallback.object_domain(&pred).unwrap())
23087 );
23088 assert_eq!(
23089 stamps.get(JoinKeySlot::Subject),
23090 JoinDomainStamp::Unavailable,
23091 "no class_counts means object grounding cannot promote the subject stamp"
23092 );
23093 }
23094
23095 #[test]
23096 fn rdf_type_subject_without_class_counts_uses_subject_hll() {
23097 let pred = StrHash::new(RDF_TYPE_IRI);
23098 let mut profile = StatsProfile::default();
23099 profile.predicate_counts.insert(pred, 100);
23100 profile.subjects_per_predicate.insert(pred, hll_with_n(123));
23101 let scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
23102 let stamps = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
23103 assert_eq!(
23104 stamps.get(JoinKeySlot::Subject),
23105 JoinDomainStamp::Known(profile.subject_domain(&pred).unwrap()),
23106 "without class_counts the subject answer cannot change on object grounding"
23107 );
23108 assert_eq!(
23109 stamps.get(JoinKeySlot::Object),
23110 JoinDomainStamp::Unavailable,
23111 "no rdf:type object HLL to cache"
23112 );
23113 }
23114
23115 #[test]
23116 fn grounding_predicate_promotes_unknown_predicate_stamp() {
23117 let mut profile = StatsProfile::default();
23118 let p = StrHash::new("http://ex/p");
23119 profile.predicate_counts.insert(p, 10);
23120 profile.subjects_per_predicate.insert(p, hll_with_n(77));
23121 profile.objects_per_predicate.insert(p, hll_with_n(33));
23122
23123 let mut scan = var_scan(Some("s"), "http://ex/unused", Some("o"), 1);
23124 scan.pattern.predicate = None;
23125 scan.predicate = Some(var("p"));
23126 scan.join_domains = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
23127 assert_eq!(
23128 scan.join_domains.get(JoinKeySlot::Subject),
23129 JoinDomainStamp::UnknownPredicate
23130 );
23131 assert_eq!(
23132 scan.join_domains.get(JoinKeySlot::Object),
23133 JoinDomainStamp::UnknownPredicate
23134 );
23135
23136 scan.pattern.predicate = Some(EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()));
23137 scan.predicate = None;
23138 scan.record_grounded(&var("p"), PatternSlot::Predicate, Some(&profile));
23139 assert_eq!(
23140 scan.join_domains.get(JoinKeySlot::Subject),
23141 JoinDomainStamp::Known(profile.subject_domain(&p).unwrap())
23142 );
23143 assert_eq!(
23144 scan.join_domains.get(JoinKeySlot::Object),
23145 JoinDomainStamp::Known(profile.object_domain(&p).unwrap())
23146 );
23147 }
23148
23149 #[test]
23150 fn missing_profile_or_sketch_falls_back_live() {
23151 let scan = var_scan(Some("s"), "http://ex/p", Some("o"), 1);
23152 assert_eq!(
23153 JoinDomainStamps::classify(None, &scan.pattern).get(JoinKeySlot::Subject),
23154 JoinDomainStamp::NoProfile
23155 );
23156 let empty = StatsProfile::default();
23157 assert_eq!(
23158 JoinDomainStamps::classify(Some(&empty), &scan.pattern).get(JoinKeySlot::Subject),
23159 JoinDomainStamp::NoProfile
23160 );
23161 assert_eq!(join_key_domain_for(None, &scan, &[var("s")]), None);
23162 assert_eq!(join_key_domain_for(Some(&empty), &scan, &[var("s")]), None);
23163
23164 let mut other = StatsProfile::default();
23166 other
23167 .predicate_counts
23168 .insert(StrHash::new("http://ex/other"), 1);
23169 let stamps = JoinDomainStamps::classify(Some(&other), &scan.pattern);
23170 assert_eq!(
23171 stamps.get(JoinKeySlot::Subject),
23172 JoinDomainStamp::Unavailable
23173 );
23174 assert_eq!(
23175 stamps.get(JoinKeySlot::Object),
23176 JoinDomainStamp::Unavailable
23177 );
23178 assert_eq!(join_key_domain_for(Some(&other), &scan, &[var("s")]), None);
23179 }
23180
23181 #[test]
23182 fn predicate_head_domain_estimate_is_the_predicate_map_size() {
23183 let profile = stamped_head_scan_profile();
23184 let mut scan = predicate_domain_scan();
23185 scan.domain_scan = Some(DomainScanKind::SubjectPreds);
23186 assert_eq!(
23187 head_domain_estimate(&profile, &scan, PatternSlot::Predicate),
23188 Some(1),
23189 "the exact predicate map size bounds the distinct predicate heads"
23190 );
23191 assert_eq!(
23193 head_domain_estimate(&StatsProfile::default(), &scan, PatternSlot::Predicate),
23194 None
23195 );
23196 }
23197
23198 #[test]
23199 fn distinct_two_key_collapse_keeps_pattern_rows() {
23200 let profile = collapse_recost_profile();
23201 let text = explain_est(
23206 "SELECT DISTINCT ?s ?label WHERE { ?s <http://ex/label> ?label }",
23207 Some(&profile),
23208 );
23209 assert_eq!(
23210 rows_on_line(&text, "(scan "),
23211 200_000,
23212 "multi-key collapse must keep the pre-collapse row count: {text}"
23213 );
23214 }
23215
23216 #[test]
23217 fn distinct_single_key_collapse_takes_the_min_of_rows_and_domain() {
23218 let profile = collapse_recost_profile();
23219 let text = explain_est(
23222 "SELECT DISTINCT ?s WHERE { ?s <http://ex/label> ?o }",
23223 Some(&profile),
23224 );
23225 let expected = collapse_recost_profile()
23226 .subjects_per_predicate
23227 .get(&StrHash::new("http://ex/label"))
23228 .map(|hll| hll.cardinality())
23229 .expect("label subject HLL");
23230 assert_eq!(
23231 rows_on_line(&text, "(scan "),
23232 expected,
23233 "single-key collapse output is bounded by the key domain: {text}"
23234 );
23235 assert!(
23236 rows_on_line(&text, "(scan ") < 200_000,
23237 "min(rows, domain) must beat the pattern count here: {text}"
23238 );
23239 }
23240
23241 #[test]
23242 fn left_join_scan_union_does_not_swap() {
23243 let sparql = r#"
23244 SELECT ?tenant ?x WHERE {
23245 ?tenant a <http://ex/Tenant> .
23246 OPTIONAL {
23247 { ?x <http://ex/hasTenant> ?tenant . ?x a <http://ex/Server> }
23248 UNION
23249 { ?x <http://ex/hasTenant> ?tenant . ?x a <http://ex/VM> }
23250 }
23251 }
23252 "#;
23253 let plan =
23254 LogicalPlan::parse_with_profile(sparql, Some(&tenant_union_small_has_tenant_domain()))
23255 .unwrap();
23256 let PlanNode::LeftJoin { left, right, .. } = &plan.root else {
23257 panic!("expected LeftJoin at root, got {:?}", plan.root);
23258 };
23259 assert!(
23260 left.as_broadcast_scan().is_some(),
23261 "OPTIONAL must keep the required scan on the left, got {left:?}"
23262 );
23263 assert!(
23264 right.as_union().is_some(),
23265 "OPTIONAL Union must stay on the right, got {right:?}"
23266 );
23267 }
23268
23269 #[test]
23270 fn explain_estimates_prints_join_key_domains_with_profile() {
23271 let profile = tenant_union_small_has_tenant_domain();
23272 let text = explain_est(TENANT_UNION, Some(&profile));
23273 assert!(text.contains("(join "), "{text}");
23274 assert!(text.contains("(union "), "{text}");
23275 let union_tenant = domain_on_line(&text, "(union ", "?tenant");
23276 assert!(
23277 union_tenant.is_some_and(|n| n > 1 && n < 5_000),
23278 "Union should print a small numeric ?tenant domain, got {union_tenant:?}: {text}"
23279 );
23280 let join_tenant = domain_on_line(&text, "(join ", "?tenant");
23281 assert!(
23282 join_tenant.is_some_and(|n| n > 1),
23283 "Join should print a numeric ?tenant domain, got {join_tenant:?}: {text}"
23284 );
23285 let type_scan = text
23286 .lines()
23287 .find(|line| line.contains("(scan ") && line.contains("?tenant a"))
23288 .expect("type scan line");
23289 assert!(
23290 type_scan.contains("(domain ?tenant ") && !type_scan.contains("(domain ?tenant ?)"),
23291 "type scan should print an rdf:type subject domain: {text}"
23292 );
23293 }
23294
23295 #[test]
23296 fn explain_estimates_prints_unknown_domains_without_profile() {
23297 let text = explain_est(r#"SELECT ?s ?o WHERE { ?s <http://ex/p>* ?o }"#, None);
23298 assert!(text.contains("(path "), "{text}");
23299 assert!(
23300 text.contains("(domain ?s ?)") && text.contains("(domain ?o ?)"),
23301 "Path ends have no HLL: {text}"
23302 );
23303 let join_text = explain_est(
23304 r#"SELECT ?s WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?x }"#,
23305 None,
23306 );
23307 assert!(
23308 join_text.contains("(domain ?s ?)"),
23309 "missing profile should print ?v=?: {join_text}"
23310 );
23311 }
23312
23313 #[test]
23314 fn explain_estimates_omits_domain_on_grounded_path() {
23315 let text = explain_est(
23316 r#"ASK WHERE { <http://ex/a> <http://ex/p>* <http://ex/b> }"#,
23317 None,
23318 );
23319 let path_line = text
23320 .lines()
23321 .find(|line| line.contains("(path "))
23322 .unwrap_or(text.as_str());
23323 assert!(
23324 !path_line.contains("(domain"),
23325 "grounded path has no variable domain to print: {text}"
23326 );
23327 }
23328
23329 #[test]
23330 fn constants_are_encoded_and_variables_are_named() {
23331 let plan =
23332 LogicalPlan::parse("SELECT ?city WHERE { ?city <http://ex/hasWeather> \"Sunny\" }")
23333 .unwrap();
23334 let scan = plan.scans().unwrap()[0];
23335 assert_eq!(scan.subject, Some(var("city")));
23336 assert_eq!(scan.predicate, None);
23337 assert_eq!(
23338 scan.pattern.predicate,
23339 Some(EncodedTerm::from(
23340 &NamedNode::new("http://ex/hasWeather").unwrap()
23341 ))
23342 );
23343 assert_eq!(scan.pattern.graph_name, Some(EncodedTerm::DefaultGraph));
23344 assert_eq!(scan.variables(), vec![var("city")]);
23345 }
23346
23347 #[test]
23348 fn select_star_projects_every_pattern_variable() {
23349 let plan = LogicalPlan::parse("SELECT * WHERE { ?s <http://ex/livesIn> ?o }").unwrap();
23350 let mut projected: Vec<_> = plan.projection.iter().map(Variable::as_str).collect();
23351 projected.sort_unstable();
23352 assert_eq!(projected, ["o", "s"]);
23353 }
23354
23355 #[test]
23356 fn filter_and_optional_are_planned() {
23357 let filter_plan = LogicalPlan::parse(
23360 r#"SELECT ?s WHERE { ?s <http://ex/p> ?o FILTER(CONTAINS(STR(?o), "x")) }"#,
23361 )
23362 .unwrap();
23363 assert!(
23364 matches!(filter_plan.root, PlanNode::Filter { .. }),
23365 "got {:?}",
23366 filter_plan.root
23367 );
23368
23369 let opt_plan = LogicalPlan::parse(
23370 r#"SELECT ?s ?r WHERE { ?s <http://ex/p> ?o OPTIONAL { ?s <http://ex/q> ?r } }"#,
23371 )
23372 .unwrap();
23373 assert!(matches!(opt_plan.root, PlanNode::LeftJoin { .. }));
23374
23375 let union_plan = LogicalPlan::parse(
23376 r#"SELECT ?s WHERE { { ?s <http://ex/p> ?o } UNION { ?s <http://ex/q> ?o } }"#,
23377 )
23378 .unwrap();
23379 assert!(
23380 matches!(union_plan.root, PlanNode::Union { .. }),
23381 "got {:?}",
23382 union_plan.root
23383 );
23384 }
23385
23386 #[test]
23387 fn exact_comparison_keeps_the_compared_slot_materialized() {
23388 let plan =
23391 LogicalPlan::parse(r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y >= 1967) }"#)
23392 .unwrap();
23393 let PlanNode::Scan(scan) = &plan.root else {
23394 panic!("expected the scan root, got {:?}", plan.root);
23395 };
23396 assert!(
23397 scan.materialized_variables().contains(&var("y")),
23398 "compared slot must stay materialized: {:?}",
23399 scan.materialized_variables()
23400 );
23401 assert!(!plan.projection.contains(&var("y")));
23402 }
23403
23404 #[test]
23405 fn filter_comparisons_are_attached_to_the_scan() {
23406 let plan = LogicalPlan::parse(
23407 r#"SELECT ?r WHERE {
23408 ?r <http://ex/year> ?y
23409 FILTER(?y >= 1967 && ?y <= 1971)
23410 }"#,
23411 )
23412 .unwrap();
23413 let PlanNode::Scan(scan) = &plan.root else {
23416 panic!(
23417 "expected the exact filter to move into the scan, got {:?}",
23418 plan.root
23419 );
23420 };
23421 assert_eq!(scan.eager.len(), 2, "{:?}", scan.eager);
23422 assert!(scan.eager.contains(&SlotComparison {
23425 slot: QuadSlot::Object,
23426 op: CompareOp::Ge,
23427 term: EncodedTerm::from(&Literal::from(1967i64)),
23428 }));
23429 assert!(scan.eager.contains(&SlotComparison {
23430 slot: QuadSlot::Object,
23431 op: CompareOp::Le,
23432 term: EncodedTerm::from(&Literal::from(1971i64)),
23433 }));
23434 }
23435
23436 #[test]
23437 fn values_parameterised_filter_reaches_the_year_scan() {
23438 let plan = LogicalPlan::parse(
23443 r#"
23444 PREFIX sdo: <https://schema.org/>
23445 PREFIX scr: <https://koenigsnet/scraper-vocab/>
23446 PREFIX kn: <https://koenigsnet/ont/>
23447
23448 SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
23449 VALUES (?yearFrom ?yearTo) { (1967 1971) }
23450 ?r scr:datasetKind <https://koenigsnet/scraper-vocab/concept/dataset-kind/record> .
23451 ?r kn:year ?_y .
23452 FILTER(?_y >= ?yearFrom && ?_y <= ?yearTo)
23453 { ?r sdo:isPartOf ?v . ?v a sdo:DataCatalog . BIND(kn:catalog AS ?dim) }
23454 UNION
23455 { ?r scr:documentType ?v . BIND(scr:documentType AS ?dim) }
23456 UNION
23457 { ?r scr:subject ?v . BIND(scr:subject AS ?dim) }
23458 }
23459 GROUP BY ?dim ?v
23460 "#,
23461 )
23462 .unwrap();
23463 let year = EncodedTerm::from(&NamedNode::new("https://koenigsnet/ont/year").unwrap());
23464 let scan = find_scan(&plan.root, &year).expect("the year scan is in the plan");
23465 assert_eq!(scan.eager.len(), 2, "{:?}", scan.eager);
23466 assert!(scan.eager.contains(&SlotComparison {
23467 slot: QuadSlot::Object,
23468 op: CompareOp::Ge,
23469 term: EncodedTerm::from(&Literal::from(1967i64)),
23470 }));
23471 assert!(scan.eager.contains(&SlotComparison {
23472 slot: QuadSlot::Object,
23473 op: CompareOp::Le,
23474 term: EncodedTerm::from(&Literal::from(1971i64)),
23475 }));
23476 }
23477
23478 fn find_scan<'a>(node: &'a PlanNode, predicate: &EncodedTerm) -> Option<&'a ScanOp> {
23479 if let PlanNode::Scan(scan) = node {
23480 return (scan.pattern.predicate.as_ref() == Some(predicate)).then_some(scan);
23481 }
23482 let mut children: Vec<&PlanNode> = Vec::new();
23483 match node {
23484 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
23485 children.push(left);
23486 children.push(right);
23487 }
23488 PlanNode::LeftJoin { left, right, .. } => {
23489 children.push(left);
23490 children.push(right);
23491 }
23492 PlanNode::Filter { inner, .. }
23493 | PlanNode::Slice { inner, .. }
23494 | PlanNode::Distinct { inner, .. }
23495 | PlanNode::Sort { inner, .. }
23496 | PlanNode::Group { inner, .. }
23497 | PlanNode::Extend { inner, .. }
23498 | PlanNode::JoinGraphVar { inner, .. } => children.push(inner),
23499 PlanNode::SubSelect(sub) => children.push(&sub.inner),
23500 PlanNode::CustomNode(op) => children.extend(op.children.iter()),
23501 _ => {}
23502 }
23503 children
23504 .into_iter()
23505 .find_map(|child| find_scan(child, predicate))
23506 }
23507
23508 #[test]
23509 fn exists_and_not_exists_peel_and_classify() {
23510 let and_plan = LogicalPlan::parse(
23511 r#"SELECT ?s ?p ?o WHERE {
23512 ?s ?p ?o
23513 FILTER(EXISTS { ?s ?p <http://ex/brisbane> } && ?o != <http://ex/skip>)
23514 }"#,
23515 )
23516 .unwrap();
23517 let PlanNode::Filter { exists, early, .. } = &and_plan.root else {
23518 panic!("expected Filter, got {:?}", and_plan.root);
23519 };
23520 assert_eq!(exists.len(), 1);
23521 assert!(!exists[0].negated);
23522 assert_eq!(exists[0].kind, ExistsKind::SemiJoin);
23523 assert!(early.is_some(), "ordinary conjunct stays in early");
23524
23525 let ground = LogicalPlan::parse(
23526 r#"SELECT ?s WHERE {
23527 ?s <http://ex/livesIn> ?city
23528 FILTER EXISTS { <http://ex/alice> <http://ex/livesIn> <http://ex/brisbane> }
23529 }"#,
23530 )
23531 .unwrap();
23532 let PlanNode::Filter { exists, .. } = &ground.root else {
23533 panic!("expected Filter, got {:?}", ground.root);
23534 };
23535 assert_eq!(exists[0].kind, ExistsKind::Uncorrelated);
23536 assert!(exists[0].correlation.is_empty());
23537
23538 let nested = LogicalPlan::parse(
23539 r#"SELECT ?s WHERE {
23540 ?s <http://ex/p> <http://ex/o>
23541 FILTER EXISTS { ?s <http://ex/p> <http://ex/o1>
23542 FILTER EXISTS { ?s <http://ex/p> <http://ex/o2> } }
23543 }"#,
23544 )
23545 .unwrap();
23546 let PlanNode::Filter { exists, .. } = &nested.root else {
23547 panic!("expected Filter, got {:?}", nested.root);
23548 };
23549 assert_eq!(exists[0].kind, ExistsKind::NestedProbe);
23550 assert!(
23551 !exists[0].body.as_ref().inner_variables().is_empty()
23552 || matches!(exists[0].body.as_ref(), PlanNode::Filter { .. }),
23553 "nested EXISTS stays inside the body: {:?}",
23554 exists[0].body
23555 );
23556
23557 let not_plan = LogicalPlan::parse(
23558 r#"SELECT ?s WHERE {
23559 ?s <http://ex/livesIn> ?city
23560 FILTER NOT EXISTS { ?city <http://ex/hasWeather> "Sunny" }
23561 }"#,
23562 )
23563 .unwrap();
23564 let PlanNode::Filter { exists, .. } = ¬_plan.root else {
23565 panic!("expected Filter, got {:?}", not_plan.root);
23566 };
23567 assert!(exists[0].negated);
23568 assert_eq!(exists[0].kind, ExistsKind::SemiJoin);
23569 }
23570
23571 #[test]
23572 fn exists_in_bind_having_or_stays_unsupported() {
23573 let bind = LogicalPlan::parse(
23574 r#"SELECT ?s ?e WHERE {
23575 ?s <http://ex/p> ?o
23576 BIND(EXISTS { ?s <http://ex/q> ?x } AS ?e)
23577 }"#,
23578 );
23579 assert!(
23580 matches!(bind, Err(ComputeError::UnsupportedSparql(_))),
23581 "{bind:?}"
23582 );
23583 let having = LogicalPlan::parse(
23584 r#"SELECT ?p (COUNT(*) AS ?c) WHERE { ?s ?p ?o } GROUP BY ?p
23585 HAVING EXISTS { ?s <http://ex/q> ?o }"#,
23586 );
23587 assert!(
23588 matches!(having, Err(ComputeError::UnsupportedSparql(_))),
23589 "{having:?}"
23590 );
23591 let or_exists = LogicalPlan::parse(
23592 r#"SELECT ?s WHERE {
23593 ?s <http://ex/p> ?o
23594 FILTER(EXISTS { ?s <http://ex/q> ?x } || ?o = <http://ex/y>)
23595 }"#,
23596 );
23597 assert!(
23598 matches!(or_exists, Err(ComputeError::UnsupportedSparql(_))),
23599 "{or_exists:?}"
23600 );
23601 }
23602
23603 #[test]
23604 fn exists_expr_only_outer_var_is_nested_probe() {
23605 let plan = LogicalPlan::parse(
23606 r#"SELECT ?person ?tag WHERE {
23607 ?person <http://ex/tag> ?tag .
23608 FILTER EXISTS { ?person <http://ex/livesIn> ?city .
23609 ?city <http://ex/hasWeather> ?w .
23610 FILTER(?w = ?tag) }
23611 }"#,
23612 )
23613 .unwrap();
23614 let PlanNode::Filter { exists, .. } = &plan.root else {
23615 panic!("expected Filter, got {:?}", plan.root);
23616 };
23617 assert_eq!(exists[0].kind, ExistsKind::NestedProbe);
23618 let names: Vec<_> = exists[0].correlation.iter().map(Variable::as_str).collect();
23619 assert!(names.contains(&"person"), "{names:?}");
23620 assert!(names.contains(&"tag"), "{names:?}");
23621 }
23622
23623 #[test]
23624 fn exists_grounded_scans_with_outer_filter_var_is_nested_probe() {
23625 let plan = LogicalPlan::parse(
23626 r#"SELECT ?person WHERE {
23627 ?person <http://ex/livesIn> ?city .
23628 FILTER EXISTS { <http://ex/brisbane> <http://ex/hasWeather> "Sunny" .
23629 FILTER(?city = <http://ex/brisbane>) }
23630 }"#,
23631 )
23632 .unwrap();
23633 let PlanNode::Filter { exists, .. } = &plan.root else {
23634 panic!("expected Filter, got {:?}", plan.root);
23635 };
23636 assert_eq!(exists[0].kind, ExistsKind::NestedProbe);
23637 assert_eq!(
23638 exists[0]
23639 .correlation
23640 .iter()
23641 .map(Variable::as_str)
23642 .collect::<Vec<_>>(),
23643 ["city"]
23644 );
23645 }
23646
23647 #[test]
23648 fn exists_filter_on_body_column_stays_semijoin() {
23649 let plan = LogicalPlan::parse(
23650 r#"SELECT ?person WHERE {
23651 ?person <http://ex/livesIn> ?city .
23652 FILTER EXISTS { ?person <http://ex/livesIn> ?c
23653 FILTER(?person != <http://ex/carol>) }
23654 }"#,
23655 )
23656 .unwrap();
23657 let PlanNode::Filter { exists, .. } = &plan.root else {
23658 panic!("expected Filter, got {:?}", plan.root);
23659 };
23660 assert_eq!(exists[0].kind, ExistsKind::SemiJoin);
23661 assert_eq!(
23662 exists[0]
23663 .correlation
23664 .iter()
23665 .map(Variable::as_str)
23666 .collect::<Vec<_>>(),
23667 ["person"]
23668 );
23669 }
23670
23671 #[test]
23672 fn exists_correlated_subselect_is_unsupported() {
23673 let err = LogicalPlan::parse(
23674 r#"SELECT ?person WHERE {
23675 ?person <http://ex/livesIn> ?city .
23676 FILTER EXISTS { { SELECT ?x WHERE { ?person <http://ex/tag> ?x } } }
23677 }"#,
23678 );
23679 assert!(
23680 matches!(err, Err(ComputeError::UnsupportedSparql(ref msg)) if msg.contains("sub-SELECT")),
23681 "{err:?}"
23682 );
23683 }
23684
23685 #[test]
23686 fn exists_uncorrelated_subselect_plans() {
23687 let plan = LogicalPlan::parse(
23688 r#"SELECT ?s WHERE {
23689 ?s <http://ex/p> ?o
23690 FILTER EXISTS { { SELECT ?x WHERE { <http://ex/a> <http://ex/p> ?x } } }
23691 }"#,
23692 )
23693 .unwrap();
23694 let PlanNode::Filter { exists, .. } = &plan.root else {
23695 panic!("expected Filter, got {:?}", plan.root);
23696 };
23697 assert!(exists[0].correlation.is_empty());
23698 assert_eq!(exists[0].kind, ExistsKind::Uncorrelated);
23699 }
23700
23701 #[test]
23702 fn exists_explain_prints_kind() {
23703 let text = LogicalPlan::explain(
23704 r#"SELECT ?s WHERE {
23705 ?s <http://ex/livesIn> ?city
23706 FILTER EXISTS { ?city <http://ex/hasWeather> "Sunny" }
23707 }"#,
23708 crate::explain::ExplainFormat::Planned,
23709 false,
23710 None,
23711 )
23712 .unwrap();
23713 assert!(
23714 text.contains("(exists") && text.contains("semijoin"),
23715 "EXPLAIN should name EXISTS mode: {text}"
23716 );
23717 }
23718
23719 #[test]
23720 fn union_output_vars_intersect_always_bound() {
23721 let plan = LogicalPlan::parse(
23722 r#"SELECT ?s ?x ?r WHERE {
23723 { ?s <http://ex/p> ?x } UNION { ?s <http://ex/q> ?r }
23724 }"#,
23725 )
23726 .unwrap();
23727 let out = plan.root.output_vars();
23728 assert_eq!(
23729 out.always_bound
23730 .iter()
23731 .map(Variable::as_str)
23732 .collect::<Vec<_>>(),
23733 ["s"]
23734 );
23735 let maybe: Vec<_> = out.maybe_unbound.iter().map(Variable::as_str).collect();
23736 assert!(maybe.contains(&"x"), "{maybe:?}");
23737 assert!(maybe.contains(&"r"), "{maybe:?}");
23738 }
23739
23740 #[test]
23741 fn union_schema_is_left_to_right_without_duplicates() {
23742 let plan = LogicalPlan::parse(
23743 r#"SELECT ?s ?x ?r WHERE {
23744 { ?s <http://ex/p> ?x }
23745 UNION { ?s <http://ex/q> ?r }
23746 UNION { ?x <http://ex/r> ?r }
23747 }"#,
23748 )
23749 .unwrap();
23750 let arms = union_arms(&plan.root);
23751 assert_eq!(arms.len(), 3, "left-deep spine flattens to three arms");
23752 assert_eq!(
23753 union_schema(&arms)
23754 .iter()
23755 .map(Variable::as_str)
23756 .collect::<Vec<_>>(),
23757 ["s", "x", "r"],
23758 "arm order fixed, repeated names kept once"
23759 );
23760 }
23761
23762 #[test]
23763 fn join_after_union_hashes_only_shared_always_bound() {
23764 let plan = LogicalPlan::parse(
23765 r#"SELECT ?s ?o ?x ?r WHERE {
23766 ?s <http://ex/p> ?o .
23767 { ?s <http://ex/q> ?x } UNION { ?s <http://ex/r> ?r }
23768 }"#,
23769 )
23770 .unwrap();
23771 let PlanNode::Join {
23772 left,
23773 right,
23774 hash_keys,
23775 ..
23776 } = &plan.root
23777 else {
23778 panic!("expected Join at root, got {:?}", plan.root);
23779 };
23780 assert!(
23781 matches!(left.as_ref(), PlanNode::Union { .. })
23782 || matches!(right.as_ref(), PlanNode::Union { .. }),
23783 "expected a Union child, got left={left:?} right={right:?}"
23784 );
23785 assert_eq!(
23786 hash_keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
23787 ["s"],
23788 "only always-bound ?s should be a hash key: {hash_keys:?}"
23789 );
23790 assert!(!hash_keys.iter().any(|v| v.as_str() == "x"));
23791 assert!(!hash_keys.iter().any(|v| v.as_str() == "r"));
23792 }
23793
23794 #[test]
23795 fn optional_then_join_on_optional_var_excludes_it_from_hash_keys() {
23796 let plan = LogicalPlan::parse(
23797 r#"SELECT ?s ?x ?y WHERE {
23798 ?s <http://ex/p> ?o .
23799 OPTIONAL { ?s <http://ex/q> ?x }
23800 ?x <http://ex/r> ?y .
23801 }"#,
23802 )
23803 .unwrap();
23804
23805 let PlanNode::Join { hash_keys, .. } = &plan.root else {
23806 panic!("expected Join at root, got {:?}", plan.root);
23807 };
23808 assert!(
23809 !hash_keys.iter().any(|v| v.as_str() == "x"),
23810 "maybe-unbound ?x must not be a hard hash key: {hash_keys:?}"
23811 );
23812
23813 let outer = outermost_left_join(&plan.root);
23817 let PlanNode::LeftJoin { .. } = outer else {
23818 panic!("expected the OPTIONAL's LeftJoin, got {:#?}", plan.root);
23819 };
23820 let lj_out = outer.output_vars();
23821 assert!(
23822 lj_out.maybe_unbound.iter().any(|v| v.as_str() == "x"),
23823 "LeftJoin must expose ?x as maybe-unbound: {lj_out:?}"
23824 );
23825
23826 let out = plan.root.output_vars();
23827 assert!(out.always_bound.iter().any(|v| v.as_str() == "s"));
23828 assert!(
23831 out.always_bound.iter().any(|v| v.as_str() == "x"),
23832 "Join with an always-bound ?x arm should promote: {out:?}"
23833 );
23834 assert!(!out.maybe_unbound.iter().any(|v| v.as_str() == "x"));
23835 }
23836
23837 fn walk_plan<'a>(node: &'a PlanNode, visit: &mut impl FnMut(&'a PlanNode)) {
23838 visit(node);
23839 match node {
23840 PlanNode::Join { left, right, .. }
23841 | PlanNode::LeftJoin { left, right, .. }
23842 | PlanNode::Union { left, right } => {
23843 walk_plan(left, visit);
23844 walk_plan(right, visit);
23845 }
23846 PlanNode::Filter { inner, exists, .. } => {
23847 walk_plan(inner, visit);
23848 for clause in exists {
23849 walk_plan(&clause.body, visit);
23850 }
23851 }
23852 PlanNode::Extend { inner, .. }
23853 | PlanNode::Slice { inner, .. }
23854 | PlanNode::Distinct { inner, .. }
23855 | PlanNode::Sort { inner, .. }
23856 | PlanNode::Group { inner, .. }
23857 | PlanNode::JoinGraphVar { inner, .. } => walk_plan(inner, visit),
23858 PlanNode::SubSelect(sub) => walk_plan(&sub.inner, visit),
23859 PlanNode::CustomNode(custom) => {
23860 for child in &custom.children {
23861 walk_plan(child, visit);
23862 }
23863 }
23864 PlanNode::Scan(_)
23865 | PlanNode::Path(_)
23866 | PlanNode::Values(_)
23867 | PlanNode::NamedGraphs { .. }
23868 | PlanNode::NamedGraphExists { .. }
23869 | PlanNode::DomainCounts { .. }
23870 | PlanNode::HeadCounts { .. }
23871 | PlanNode::PatternCount { .. }
23872 | PlanNode::Unit => {}
23873 }
23874 }
23875
23876 fn values_in_plan(node: &PlanNode) -> Vec<&crate::plan::ValuesOp> {
23880 let mut out = Vec::new();
23881 walk_plan(node, &mut |current| {
23882 if let PlanNode::Values(values) = current {
23883 out.push(values);
23884 }
23885 });
23886 out
23887 }
23888
23889 fn has_left_join(node: &PlanNode) -> bool {
23890 let mut found = false;
23891 walk_plan(node, &mut |current| {
23892 if matches!(current, PlanNode::LeftJoin { .. }) {
23893 found = true;
23894 }
23895 });
23896 found
23897 }
23898
23899 fn first_residual(node: &PlanNode) -> Option<&Expression> {
23901 match node {
23902 PlanNode::Filter { residual, .. } => residual.as_ref(),
23903 PlanNode::Join { left, right, .. }
23904 | PlanNode::LeftJoin { left, right, .. }
23905 | PlanNode::Union { left, right } => {
23906 first_residual(left).or_else(|| first_residual(right))
23907 }
23908 PlanNode::CustomNode(custom) => custom.children.iter().find_map(first_residual),
23909 PlanNode::Extend { inner, .. }
23910 | PlanNode::Slice { inner, .. }
23911 | PlanNode::Distinct { inner, .. }
23912 | PlanNode::Sort { inner, .. }
23913 | PlanNode::Group { inner, .. }
23914 | PlanNode::JoinGraphVar { inner, .. } => first_residual(inner),
23915 PlanNode::SubSelect(sub) => first_residual(&sub.inner),
23916 PlanNode::Scan(_)
23917 | PlanNode::Path(_)
23918 | PlanNode::Values(_)
23919 | PlanNode::Unit
23920 | PlanNode::NamedGraphs { .. }
23921 | PlanNode::NamedGraphExists { .. }
23922 | PlanNode::DomainCounts { .. }
23923 | PlanNode::HeadCounts { .. }
23924 | PlanNode::PatternCount { .. } => None,
23925 }
23926 }
23927
23928 #[test]
23929 fn single_value_values_grounds_early_conjuncts() {
23930 let plan = LogicalPlan::parse(
23934 r#"SELECT ?b WHERE {
23935 VALUES ?a { 5 }
23936 ?s <http://ex/count> ?b .
23937 FILTER(?a < ?b)
23938 }"#,
23939 )
23940 .unwrap();
23941 assert!(
23944 !contains_filter(&plan.root),
23945 "the substituted integer comparison should move into the scan: {:?}",
23946 plan.root
23947 );
23948 let mut scans = Vec::new();
23949 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
23950 assert_eq!(scans.len(), 1);
23951 assert!(
23952 scans[0].eager.contains(&SlotComparison {
23953 slot: QuadSlot::Object,
23954 op: CompareOp::Gt,
23955 term: EncodedTerm::from(&Literal::from(5i64)),
23956 }),
23957 "the VALUES constant must reach the eager comparison: {:?}",
23958 scans[0].eager
23959 );
23960 assert!(
23961 scans[0].pattern.object.is_none(),
23962 "VALUES grounds the comparison, not the pattern: {:?}",
23963 scans[0]
23964 );
23965 }
23966
23967 #[test]
23968 fn single_value_values_grounds_residual_conjuncts() {
23969 let plan = LogicalPlan::parse(
23974 r#"SELECT ?s WHERE {
23975 VALUES ?needle { "Brisbane" }
23976 ?s <http://ex/name> ?n .
23977 FILTER(contains(?needle, "isbane"))
23978 }"#,
23979 )
23980 .unwrap();
23981 let residual = format!(
23982 "{:?}",
23983 first_residual(&plan.root).expect("plan carries a residual filter")
23984 );
23985 assert!(
23986 residual.contains("Brisbane"),
23987 "grounded residual: {residual}"
23988 );
23989 assert!(
23990 !residual.contains("needle"),
23991 "grounded residual: {residual}"
23992 );
23993 }
23994
23995 #[test]
23996 fn multi_row_values_does_not_ground_residual_conjuncts() {
23997 let plan = LogicalPlan::parse(
24000 r#"SELECT ?s WHERE {
24001 VALUES ?needle { "Brisbane" "Ipswich" }
24002 ?s <http://ex/name> ?n .
24003 FILTER(contains(?needle, "isbane"))
24004 }"#,
24005 )
24006 .unwrap();
24007 let residual = format!(
24008 "{:?}",
24009 first_residual(&plan.root).expect("plan carries a residual filter")
24010 );
24011 assert!(
24012 residual.contains("needle"),
24013 "ungrounded residual: {residual}"
24014 );
24015 }
24016
24017 fn has_hash_key(node: &PlanNode, name: &str) -> bool {
24018 let mut found = false;
24019 walk_plan(node, &mut |current| {
24020 if let PlanNode::Join { hash_keys, .. } = current
24021 && hash_keys.iter().any(|key| key.as_str() == name)
24022 {
24023 found = true;
24024 }
24025 });
24026 found
24027 }
24028
24029 #[test]
24030 fn strstarts_on_optional_var_becomes_inner_join() {
24031 let plan = LogicalPlan::parse(
24032 r#"SELECT ?inst ?search1 WHERE {
24033 OPTIONAL { ?inst <http://ex/label> ?search1 }
24034 FILTER(strstarts(str(?search1), "Brisbane"))
24035 { ?inst a <http://ex/City> }
24036 }"#,
24037 )
24038 .unwrap();
24039 assert!(
24040 !has_left_join(&plan.root),
24041 "OPTIONAL should be an inner join, got {:?}",
24042 plan.root
24043 );
24044 assert!(
24045 has_hash_key(&plan.root, "inst"),
24046 "city and label should join on ?inst, got {:?}",
24047 plan.root
24048 );
24049 }
24050
24051 #[test]
24052 fn nested_select_strstarts_optional_becomes_inner_join() {
24053 let plan = LogicalPlan::parse(
24054 r#"SELECT ?inst WHERE {
24055 {
24056 SELECT DISTINCT ?inst ?search1 WHERE {
24057 OPTIONAL { ?inst <http://ex/label> ?search1 }
24058 FILTER(strstarts(str(?search1), "Brisbane"))
24059 { ?inst a <http://ex/City> }
24060 } LIMIT 100
24061 }
24062 }"#,
24063 )
24064 .unwrap();
24065 let PlanNode::SubSelect(sub) = &plan.root else {
24066 panic!("expected subselect, got {:?}", plan.root);
24067 };
24068 assert!(
24069 !has_left_join(&sub.inner),
24070 "inner OPTIONAL should be an inner join, got {:?}",
24071 sub.inner
24072 );
24073 assert!(
24074 has_hash_key(&sub.inner, "inst"),
24075 "inner city and label should join on ?inst, got {:?}",
24076 sub.inner
24077 );
24078 }
24079
24080 #[test]
24081 fn filter_wrapped_only_around_optional_still_becomes_inner_join() {
24082 let plan = LogicalPlan::parse(
24083 r#"SELECT ?inst ?search1 WHERE {
24084 { ?inst a <http://ex/City> }
24085 {
24086 OPTIONAL { ?inst <http://ex/label> ?search1 }
24087 FILTER(strstarts(str(?search1), "Brisbane"))
24088 }
24089 }"#,
24090 )
24091 .unwrap();
24092 assert!(
24093 !has_left_join(&plan.root),
24094 "OPTIONAL under its own FILTER should still become an inner join, got {:?}",
24095 plan.root
24096 );
24097 assert!(has_hash_key(&plan.root, "inst"), "got {:?}", plan.root);
24098 }
24099
24100 #[test]
24101 fn optional_then_join_with_strstarts_keeps_left_join() {
24102 let plan = LogicalPlan::parse(
24105 r#"SELECT ?s ?x ?y WHERE {
24106 ?s <http://ex/p> ?o .
24107 OPTIONAL { ?s <http://ex/q> ?x }
24108 ?x <http://ex/r> ?y .
24109 FILTER(strstarts(str(?x), "a"))
24110 }"#,
24111 )
24112 .unwrap();
24113 assert!(
24114 has_left_join(&plan.root),
24115 "OPTIONAL must stay, got {:?}",
24116 plan.root
24117 );
24118 assert!(
24119 !has_hash_key(&plan.root, "x"),
24120 "?x is empty when the optional misses: {plan:?}"
24121 );
24122 }
24123
24124 #[test]
24125 fn optional_without_filter_stays_left_join() {
24126 let plan = LogicalPlan::parse(
24127 r#"SELECT ?inst ?search1 WHERE {
24128 OPTIONAL { ?inst <http://ex/label> ?search1 }
24129 { ?inst a <http://ex/City> }
24130 }"#,
24131 )
24132 .unwrap();
24133 assert!(has_left_join(&plan.root), "got {:?}", plan.root);
24134 }
24135
24136 #[test]
24137 fn or_with_isiri_keeps_left_join() {
24138 let plan = LogicalPlan::parse(
24139 r#"SELECT ?inst ?search1 WHERE {
24140 OPTIONAL { ?inst <http://ex/label> ?search1 }
24141 FILTER(strstarts(str(?search1), "Brisbane") || isIRI(?inst))
24142 { ?inst a <http://ex/City> }
24143 }"#,
24144 )
24145 .unwrap();
24146 assert!(has_left_join(&plan.root), "got {:?}", plan.root);
24147 }
24148
24149 #[test]
24150 fn coalesce_regex_keeps_left_join() {
24151 let plan = LogicalPlan::parse(
24152 r#"SELECT ?inst ?search1 WHERE {
24153 OPTIONAL { ?inst <http://ex/label> ?search1 }
24154 FILTER(regex(coalesce(str(?search1), str(?extractedLabel)), "Brisbane", "i"))
24155 { ?inst a <http://ex/City> }
24156 }"#,
24157 )
24158 .unwrap();
24159 assert!(has_left_join(&plan.root), "got {:?}", plan.root);
24160 }
24161
24162 #[test]
24163 fn later_pattern_that_binds_filtered_var_keeps_left_join() {
24164 let plan = LogicalPlan::parse(
24165 r#"SELECT ?inst ?search1 ?o WHERE {
24166 OPTIONAL { ?inst <http://ex/label> ?search1 }
24167 { ?inst a <http://ex/City> }
24168 { ?search1 <http://ex/p> ?o }
24169 FILTER(strstarts(str(?search1), "Brisbane"))
24170 }"#,
24171 )
24172 .unwrap();
24173 assert!(
24174 has_left_join(&plan.root),
24175 "the :p pattern can fill ?search1, got {:?}",
24176 plan.root
24177 );
24178 }
24179
24180 #[test]
24181 fn unsupported_syntax_returns_typed_errors() {
24182 for (query, expected) in [
24183 (
24184 "SELECT ?s WHERE { ?s <http://ex/p> ?o . MINUS { ?s <http://ex/q> ?o } }",
24185 "MINUS",
24186 ),
24187 (
24188 "ASK WHERE { ?s <http://ex/p> ?o }",
24189 "only SELECT queries are supported",
24190 ),
24191 ] {
24192 let error = LogicalPlan::parse(query).unwrap_err();
24193 let message = error.to_string();
24194 assert!(
24195 message.contains(expected),
24196 "{query}\n expected {expected:?} in {message:?}"
24197 );
24198 assert!(matches!(error, ComputeError::UnsupportedSparql(_)));
24199 }
24200 }
24201
24202 #[test]
24203 fn malformed_sparql_is_a_syntax_error() {
24204 let error = LogicalPlan::parse("SELECT ?s WHERE {").unwrap_err();
24205 assert!(matches!(error, ComputeError::Sparql(_)), "{error}");
24206 }
24207
24208 #[test]
24209 fn grouped_select_of_non_key_is_a_clear_syntax_error() {
24210 let error = LogicalPlan::parse(
24211 r#"SELECT ?b ?p (SAMPLE(?o) AS ?s) WHERE {
24212 BIND(<http://ex/s> AS ?b)
24213 ?b ?p ?o .
24214 }
24215 GROUP BY ?o"#,
24216 )
24217 .unwrap_err();
24218 let text = error.to_string();
24219 assert!(matches!(error, ComputeError::Sparql(_)), "{text}");
24220 assert!(
24221 text.contains("grouping keys and aggregate results"),
24222 "{text}"
24223 );
24224 assert!(!text.contains("expected one of"), "{text}");
24225 }
24226
24227 #[test]
24228 fn blank_node_in_bgp_becomes_an_unprojected_join_var() {
24229 let plan = LogicalPlan::parse("SELECT ?o WHERE { _:b <http://ex/p> ?o }").unwrap();
24230 assert_eq!(plan.projection, vec![var("o")]);
24231 let scans = plan.scans().unwrap();
24232 assert_eq!(scans.len(), 1);
24233 let scan = scans[0];
24234 assert_eq!(scan.object, Some(var("o")));
24235 let subject = scan
24236 .subject
24237 .as_ref()
24238 .expect("blank node becomes a variable");
24239 assert_ne!(subject, &var("o"));
24240 assert!(!plan.projection.contains(subject));
24241 }
24242
24243 #[test]
24244 fn blank_node_property_list_is_three_scans_joining_on_the_anon() {
24245 let plan = LogicalPlan::parse(
24246 r#"
24247 SELECT ?s ?c WHERE {
24248 ?s <http://ex/livesIn> [ <http://ex/hasWeather> "sunny"; <http://ex/hasName> ?c ]
24249 }
24250 "#,
24251 )
24252 .unwrap();
24253 assert_eq!(plan.projection, vec![var("s"), var("c")]);
24254 let scans = plan.scans().unwrap();
24255 assert_eq!(scans.len(), 3);
24256 assert_eq!(
24257 scans[0].pattern.object,
24258 Some(EncodedTerm::from(&Literal::from("sunny"))),
24259 "bound weather literal should lead the BGP"
24260 );
24261 let joins = plan.join_ops().unwrap();
24262 assert_eq!(joins.len(), 2);
24263 let anon = scans[0]
24264 .subject
24265 .as_ref()
24266 .expect("property list focus is a variable");
24267 assert!(!plan.projection.contains(anon));
24268 assert!(
24269 joins.iter().any(|edge| edge.hash_keys.contains(anon)),
24270 "anonymous node should be a join key: {joins:?}"
24271 );
24272 }
24273
24274 #[test]
24275 fn labeled_blank_node_coreference_shares_one_join_key() {
24276 let plan = LogicalPlan::parse(
24277 r#"
24278 SELECT ?o1 ?o2 WHERE {
24279 _:a <http://ex/p1> ?o1 .
24280 _:a <http://ex/p2> ?o2 .
24281 }
24282 "#,
24283 )
24284 .unwrap();
24285 assert_eq!(plan.projection, vec![var("o1"), var("o2")]);
24286 let scans = plan.scans().unwrap();
24287 assert_eq!(scans.len(), 2);
24288 let left = scans[0].subject.as_ref().expect("subject is a variable");
24289 let right = scans[1].subject.as_ref().expect("subject is a variable");
24290 assert_eq!(left, right, "same _:a label must be one variable");
24291 assert!(!plan.projection.contains(left));
24292 let joins = plan.join_ops().unwrap();
24293 assert_eq!(joins.len(), 1);
24294 assert_eq!(joins[0].hash_keys, vec![left.clone()]);
24295 }
24296
24297 #[test]
24298 fn select_star_does_not_project_blank_nodes() {
24299 let plan = LogicalPlan::parse("SELECT * WHERE { [] <http://ex/p> <http://ex/q> }").unwrap();
24300 assert!(
24301 plan.projection.is_empty(),
24302 "blank nodes are not in-scope for SELECT *: {:?}",
24303 plan.projection
24304 );
24305 let scans = plan.scans().unwrap();
24306 assert_eq!(scans.len(), 1);
24307 assert!(scans[0].subject.is_some());
24308 }
24309
24310 #[test]
24311 fn collection_lowers_to_rdf_first_rest_scans() {
24312 let plan =
24313 LogicalPlan::parse("SELECT ?x WHERE { ( ?x ) <http://ex/p> <http://ex/z> }").unwrap();
24314 assert_eq!(plan.projection, vec![var("x")]);
24315 let scans = plan.scans().unwrap();
24316 assert_eq!(scans.len(), 3, "rdf:first, rdf:rest rdf:nil, and :p :z");
24317 let first = EncodedTerm::from(
24318 &NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#first").unwrap(),
24319 );
24320 let rest = EncodedTerm::from(
24321 &NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest").unwrap(),
24322 );
24323 let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
24324 let predicates: Vec<_> = scans.iter().map(|s| s.pattern.predicate.clone()).collect();
24325 assert!(predicates.contains(&Some(first)), "{predicates:?}");
24326 assert!(predicates.contains(&Some(rest)), "{predicates:?}");
24327 assert!(predicates.contains(&Some(p)), "{predicates:?}");
24328 assert!(
24329 scans.iter().any(|s| s.object == Some(var("x"))),
24330 "rdf:first object should be ?x"
24331 );
24332 }
24333
24334 #[test]
24335 fn explain_sse_is_jena_s_expression() {
24336 let sse = explain_optimised(
24337 r#"
24338 SELECT ?person ?city WHERE {
24339 ?person <http://ex/livesIn> ?city .
24340 ?city <http://ex/hasWeather> "Sunny" .
24341 }
24342 "#,
24343 );
24344 assert!(sse.contains("(project"), "expected project wrapper: {sse}");
24346 assert!(sse.contains("(bgp"), "expected bgp: {sse}");
24347 assert!(
24348 sse.find("Sunny").unwrap() < sse.find("livesIn").unwrap(),
24349 "Sunny pattern should be ordered first: {sse}"
24350 );
24351 }
24352
24353 #[test]
24354 fn explain_sparql_uses_display_syntax() {
24355 let text =
24356 explain_optimised_sparql(r#"SELECT ?s WHERE { ?s <http://ex/p> ?o FILTER(?o = 1) }"#);
24357 assert!(text.contains("SELECT"), "{text}");
24358 assert!(text.contains("FILTER"), "{text}");
24359 assert!(!text.contains("(project"), "{text}");
24360 }
24361
24362 #[test]
24363 fn explain_ask_shows_existence_slice() {
24364 let sse = explain_sse(r#"ASK WHERE { ?s <http://ex/p> ?o }"#, false);
24365 assert!(sse.contains("(ask"), "expected ask wrapper: {sse}");
24366 assert!(
24367 !sse.contains("(slice"),
24368 "L0 ASK should not inject LIMIT 1: {sse}"
24369 );
24370 assert!(sse.contains("(bgp"), "expected bgp: {sse}");
24371
24372 let l1 = explain_optimised(r#"ASK WHERE { ?s <http://ex/p> ?o }"#);
24373 assert!(l1.contains("(slice"), "L1 ASK should show LIMIT 1: {l1}");
24374
24375 let text = explain_est(r#"ASK WHERE { ?s <http://ex/p> ?o }"#, None);
24376 assert!(text.contains("(slice ~"), "{text}");
24377 assert!(
24378 text.contains("(scan ") || text.contains("(triple"),
24379 "{text}"
24380 );
24381
24382 let sparql = explain_optimised_sparql(r#"ASK WHERE { ?s <http://ex/p> ?o }"#);
24383 assert!(sparql.contains("ASK"), "{sparql}");
24384 assert!(!sparql.contains("(ask"), "{sparql}");
24385 }
24386
24387 #[test]
24388 fn explain_construct_keeps_template_and_where_plan() {
24389 let sse = explain_sse(
24390 r#"CONSTRUCT { ?s <http://ex/p> ?o } WHERE { ?s <http://ex/p> ?o }"#,
24391 false,
24392 );
24393 assert!(
24394 sse.contains("(construct"),
24395 "expected construct wrapper: {sse}"
24396 );
24397 assert!(sse.contains("(bgp"), "expected WHERE bgp: {sse}");
24398
24399 let text = explain_est(
24400 r#"CONSTRUCT { ?s <http://ex/p> ?o } WHERE { ?s <http://ex/p> ?o }"#,
24401 None,
24402 );
24403 assert!(
24404 text.contains("(scan ") || text.contains("(triple"),
24405 "{text}"
24406 );
24407 assert!(text.starts_with("(construct"), "{text}");
24408
24409 let sparql = explain_optimised_sparql(
24410 r#"CONSTRUCT { ?s <http://ex/p> ?o } WHERE { ?s <http://ex/p> ?o }"#,
24411 );
24412 assert!(sparql.contains("CONSTRUCT"), "{sparql}");
24413 assert!(!sparql.contains("(construct"), "{sparql}");
24414 }
24415
24416 #[test]
24417 fn explain_estimates_annotates_plan_nodes() {
24418 let text = explain_est(
24419 r#"
24420 SELECT ?person ?city WHERE {
24421 ?person <http://ex/livesIn> ?city .
24422 ?city <http://ex/hasWeather> "Sunny" .
24423 }
24424 "#,
24425 None,
24426 );
24427 assert!(text.starts_with("(project ~"), "{text}");
24428 assert!(
24429 text.contains("(join ~") && text.contains("(shuffle ?city)"),
24430 "{text}"
24431 );
24432 assert!(text.contains("(domain ?city ?)"), "{text}");
24433 assert!(text.contains("\"Sunny\""), "{text}");
24434 let first_scan = text.find("(scan ").expect("first Scan");
24436 let second_scan = text[first_scan + 1..]
24437 .find("(scan ")
24438 .map(|i| i + first_scan + 1)
24439 .expect("second Scan");
24440 assert!(
24441 text[first_scan..second_scan].contains("\"Sunny\""),
24442 "Sunny scan should be first child: {text}"
24443 );
24444 assert!(
24445 text[second_scan..].contains("?person"),
24446 "livesIn scan should follow: {text}"
24447 );
24448 }
24449
24450 #[test]
24451 fn explain_estimates_renders_rdf_type_as_a() {
24452 let text = explain_est(
24453 r#"SELECT * WHERE { ?sub ?pred ?obj . OPTIONAL { ?sub a ?c } }"#,
24454 None,
24455 );
24456 assert!(
24457 text.contains("?sub a ?c") || text.contains("(triple ?sub a ?c)"),
24458 "rdf:type should render as SPARQL `a`: {text}"
24459 );
24460 assert!(
24461 !text.contains("?sub <#"),
24462 "optional type scan should not use a hash placeholder: {text}"
24463 );
24464 }
24465
24466 #[test]
24467 fn explain_estimates_optional_bind_broadcasts_without_copying_extend() {
24468 let sparql = r#"
24469 SELECT * WHERE {
24470 BIND(<http://ex/brisbane> AS ?b)
24471 ?b ?p ?o .
24472 OPTIONAL { ?s1 ?p2 ?b }
24473 }
24474 "#;
24475 let plan = LogicalPlan::parse(sparql).unwrap();
24476 let PlanNode::LeftJoin {
24477 right, hash_keys, ..
24478 } = &plan.root
24479 else {
24480 panic!("expected LeftJoin at root, got {:?}", plan.root);
24481 };
24482 assert!(
24483 hash_keys.iter().any(|v| v.as_str() == "b"),
24484 "optional join key should be ?b: {hash_keys:?}"
24485 );
24486 let PlanNode::Scan(scan) = right.as_ref() else {
24487 panic!("optional arm must stay a Scan, not Join(Extend, Scan): {right:?}");
24488 };
24489 assert!(
24490 scan.produced_row_count_estimate < 1_000_000,
24491 "bound optional scan must not use unbound ~3e6: {}",
24492 scan.produced_row_count_estimate
24493 );
24494 assert!(
24495 scan.pattern.object.is_some(),
24496 "single BIND IRI should ground the optional object slot"
24497 );
24498 assert_eq!(scan.object.as_ref().map(Variable::as_str), Some("b"));
24499 assert!(
24500 scan.broadcasted.is_none(),
24501 "unique BIND should not stamp broadcast, got {:?}",
24502 scan.broadcasted
24503 );
24504 assert_eq!(
24505 grounded_of(scan),
24506 vec![("b", PatternSlot::Object)],
24507 "expected grounded object on ?b, got {:?}",
24508 scan.grounded
24509 );
24510
24511 let text = explain_est(sparql, None);
24512 assert!(
24513 text.contains("(grounded ?b object)"),
24514 "EXPLAIN should annotate the optional scan: {text}"
24515 );
24516 }
24517
24518 #[test]
24519 fn ground_unit_bind_lowers_to_values() {
24520 let plan = LogicalPlan::parse(r#"SELECT ?c WHERE { BIND("hello" AS ?c) }"#).unwrap();
24521 match &plan.root {
24522 PlanNode::Values(values) => {
24523 assert_eq!(values.variables, vec![var("c")]);
24524 assert_eq!(values.rows.len(), 1);
24525 }
24526 other => panic!("expected Values from ground unit BIND, got {other:?}"),
24527 }
24528 assert_eq!(plan.projection, vec![var("c")]);
24529 }
24530
24531 #[test]
24532 fn bind_copy_after_scan_stays_extend() {
24533 let plan =
24534 LogicalPlan::parse(r#"SELECT ?c WHERE { ?s <http://ex/p> ?o . BIND(?s AS ?c) }"#)
24535 .unwrap();
24536 let mut found = false;
24537 fn walk(node: &PlanNode, found: &mut bool) {
24538 match node {
24539 PlanNode::Extend { .. } => *found = true,
24540 PlanNode::Join { left, right, .. }
24541 | PlanNode::Union { left, right }
24542 | PlanNode::LeftJoin { left, right, .. } => {
24543 walk(left, found);
24544 walk(right, found);
24545 }
24546 PlanNode::Filter { inner, .. }
24547 | PlanNode::Slice { inner, .. }
24548 | PlanNode::Distinct { inner, .. }
24549 | PlanNode::Sort { inner, .. }
24550 | PlanNode::Group { inner, .. } => {
24551 walk(inner, found);
24552 }
24553 _ => {}
24554 }
24555 }
24556 walk(&plan.root, &mut found);
24557 assert!(
24558 found,
24559 "BIND of a variable after a scan must stay Extend, got {:?}",
24560 plan.root
24561 );
24562 }
24563
24564 #[test]
24565 fn values_alone_is_a_values_node() {
24566 let plan =
24567 LogicalPlan::parse(r#"SELECT ?x WHERE { VALUES ?x { <http://ex/a> <http://ex/b> } }"#)
24568 .unwrap();
24569 let PlanNode::Values(values) = &plan.root else {
24570 panic!("expected Values, got {:?}", plan.root);
24571 };
24572 assert_eq!(values.variables, vec![var("x")]);
24573 assert_eq!(values.rows.len(), 2);
24574 assert_eq!(values.produced_row_count_estimate(), 2);
24575 }
24576
24577 #[test]
24578 fn values_undef_column_is_maybe_unbound() {
24579 let plan = LogicalPlan::parse(
24580 r#"SELECT ?x ?y WHERE { VALUES (?x ?y) { (<http://ex/a> UNDEF) } }"#,
24581 )
24582 .unwrap();
24583 let out = plan.root.output_vars();
24584 assert_eq!(
24585 out.always_bound
24586 .iter()
24587 .map(Variable::as_str)
24588 .collect::<Vec<_>>(),
24589 ["x"]
24590 );
24591 assert_eq!(
24592 out.maybe_unbound
24593 .iter()
24594 .map(Variable::as_str)
24595 .collect::<Vec<_>>(),
24596 ["y"]
24597 );
24598 }
24599
24600 #[test]
24601 fn small_values_sorts_left_of_a_scan_and_hints_broadcast() {
24602 let plan = LogicalPlan::parse(
24603 r#"
24604 SELECT ?person WHERE {
24605 ?person <http://ex/livesIn> ?city .
24606 VALUES ?city { <http://ex/brisbane> <http://ex/sydney> }
24607 }
24608 "#,
24609 )
24610 .unwrap();
24611 let PlanNode::Join {
24612 left,
24613 right,
24614 hash_keys,
24615 probe_key_domains: _,
24616 probe_key_overlap_milli: _,
24617 rhs_hostable_keys: _,
24618 meta,
24619 } = &plan.root
24620 else {
24621 panic!("expected Join, got {:?}", plan.root);
24622 };
24623 assert!(
24624 matches!(left.as_ref(), PlanNode::Values(_)),
24625 "small VALUES should be the left build side, got {left:?}"
24626 );
24627 assert!(matches!(right.as_ref(), PlanNode::Scan(_)));
24628 assert_eq!(hash_keys, &vec![var("city")]);
24629 assert_eq!(meta.strategy, JoinStrategy::Broadcast);
24630 let PlanNode::Scan(scan) = right.as_ref() else {
24631 unreachable!("asserted Scan");
24632 };
24633 assert!(
24634 scan.pattern.object.is_none(),
24635 "multi-row VALUES must not prefix the scan slot, got {scan:?}"
24636 );
24637 assert_eq!(
24638 scan.broadcasted
24639 .as_ref()
24640 .map(|(v, slot)| (v.as_str(), *slot)),
24641 Some(("city", PatternSlot::Object))
24642 );
24643 }
24644
24645 #[test]
24646 fn singleton_values_prefixes_broadcast_scan_object() {
24647 let brisbane = NamedNode::new("http://ex/brisbane").unwrap();
24648 let plan = LogicalPlan::parse(
24649 r#"
24650 SELECT ?person WHERE {
24651 ?person <http://ex/livesIn> ?city .
24652 VALUES ?city { <http://ex/brisbane> }
24653 }
24654 "#,
24655 )
24656 .unwrap();
24657 let PlanNode::Join {
24658 left,
24659 right,
24660 hash_keys,
24661 probe_key_domains: _,
24662 probe_key_overlap_milli: _,
24663 rhs_hostable_keys: _,
24664 meta,
24665 } = &plan.root
24666 else {
24667 panic!("expected Join, got {:?}", plan.root);
24668 };
24669 assert!(matches!(left.as_ref(), PlanNode::Values(_)));
24670 assert_eq!(hash_keys, &vec![var("city")]);
24671 assert_eq!(meta.strategy, JoinStrategy::Broadcast);
24672 let PlanNode::Scan(scan) = right.as_ref() else {
24673 panic!("expected Scan probe, got {right:?}");
24674 };
24675 assert_eq!(scan.object.as_ref().map(Variable::as_str), Some("city"));
24676 assert_eq!(scan.pattern.object, Some(EncodedTerm::from(&brisbane)));
24677 assert!(
24678 scan.broadcasted.is_none(),
24679 "unique VALUES should not stamp broadcast, got {:?}",
24680 scan.broadcasted
24681 );
24682 assert_eq!(
24683 grounded_of(scan),
24684 vec![("city", PatternSlot::Object)],
24685 "expected grounded object on ?city, got {:?}",
24686 scan.grounded
24687 );
24688 }
24689
24690 #[test]
24700 fn a_values_scan_pair_stays_together_through_reassociation() {
24701 fn values_joined_to(node: &PlanNode, predicate: &EncodedTerm) -> bool {
24702 match node {
24703 PlanNode::Join { left, right, .. } => {
24704 (matches!(**left, PlanNode::Values(_))
24705 && matches!(right.as_ref(), PlanNode::Scan(scan)
24706 if scan.pattern.predicate.as_ref() == Some(predicate)))
24707 || values_joined_to(left, predicate)
24708 || values_joined_to(right, predicate)
24709 }
24710 _ => false,
24711 }
24712 }
24713 let routes: Vec<String> = (0..100).map(|i| format!("http://ex/route{i}")).collect();
24714 let route_refs: Vec<&str> = routes.iter().map(String::as_str).collect();
24715 let values = values_node("cls", &route_refs);
24716 let ferry_predicate = EncodedTerm::from(&NamedNode::new("http://ex/type").unwrap());
24717 let ferry = PlanNode::Scan(var_scan(
24718 Some("feature"),
24719 "http://ex/type",
24720 Some("cls"),
24721 900,
24722 ));
24723 let cheaper = PlanNode::Scan(var_scan(Some("feature"), "http://ex/kind", Some("cls"), 50));
24726 let mut tree = test_join(test_join(values, ferry), cheaper);
24727 reassociate_inner_joins(&mut tree, None, None);
24728 assert!(
24729 values_joined_to(&tree, &ferry_predicate),
24730 "the table must stay directly above the placement-chosen scan: {}",
24731 crate::explain::plan_node_tag(&tree)
24732 );
24733 }
24734
24735 #[test]
24742 fn a_transparent_pairs_union_arm_is_reassociated() {
24743 fn directly_joins(node: &PlanNode, first: &EncodedTerm, second: &EncodedTerm) -> bool {
24744 let is = |candidate: &PlanNode, predicate: &EncodedTerm| {
24745 matches!(candidate, PlanNode::Scan(scan)
24746 if scan.pattern.predicate.as_ref() == Some(predicate))
24747 };
24748 match node {
24749 PlanNode::Join { left, right, .. } => {
24750 (is(left, first) && is(right, second))
24751 || (is(left, second) && is(right, first))
24752 || directly_joins(left, first, second)
24753 || directly_joins(right, first, second)
24754 }
24755 _ => false,
24756 }
24757 }
24758 let type_predicate = EncodedTerm::from(&NamedNode::new("http://ex/type").unwrap());
24759 let tag_predicate = EncodedTerm::from(&NamedNode::new("http://ex/tag").unwrap());
24760 let values = values_node("cls", &["http://ex/FerryRoute"]);
24761 let typed = PlanNode::Scan(var_scan(
24766 Some("feature"),
24767 "http://ex/type",
24768 Some("cls"),
24769 900,
24770 ));
24771 let tagged = PlanNode::Scan(var_scan(Some("ds"), "http://ex/tag", Some("dt"), 3));
24772 let named = PlanNode::Scan(var_scan(Some("feature"), "http://ex/name", Some("name"), 5));
24773 let arm = test_join(test_join(typed, tagged), named);
24774 let alias = PlanNode::Scan(var_scan(
24775 Some("feature"),
24776 "http://ex/alias",
24777 Some("cls"),
24778 100,
24779 ));
24780 let union = PlanNode::Union {
24781 left: Box::new(arm),
24782 right: Box::new(alias),
24783 };
24784 let mut tree = test_join(values, union);
24785 reassociate_inner_joins(&mut tree, None, None);
24786 let PlanNode::Join { left, right, .. } = &tree else {
24787 panic!("expected the transparent pair, got {tree:?}");
24788 };
24789 assert!(
24790 matches!(**left, PlanNode::Values(_)),
24791 "the table must stay the pair's left arm: {tree:?}"
24792 );
24793 let PlanNode::Union { left: arm, .. } = right.as_ref() else {
24794 panic!("expected the pair's UNION arm, got {right:?}");
24795 };
24796 assert!(
24797 !directly_joins(arm, &type_predicate, &tag_predicate),
24798 "the UNION arm must be reassociated out of its construction order: {}",
24799 crate::explain::plan_node_tag(arm)
24800 );
24801 }
24802
24803 #[test]
24807 fn only_a_keyed_values_scan_pair_is_transparent() {
24808 let values = values_node("cls", &["http://ex/FerryRoute"]);
24809 let keyed = PlanNode::Scan(var_scan(
24810 Some("feature"),
24811 "http://ex/type",
24812 Some("cls"),
24813 900,
24814 ));
24815 let cartesian = PlanNode::Scan(var_scan(Some("feature"), "http://ex/feature", None, 9_000));
24816 assert!(is_transparent_pair(&values, &keyed));
24817 assert!(!is_transparent_pair(&values, &cartesian));
24818 }
24819
24820 #[test]
24824 fn a_nested_values_pair_is_split() {
24825 let outer_values = values_node("other", &["http://ex/other"]);
24826 let inner_values = values_node("cls", &["http://ex/FerryRoute"]);
24827 let scan = PlanNode::Scan(var_scan(
24828 Some("feature"),
24829 "http://ex/type",
24830 Some("cls"),
24831 900,
24832 ));
24833 let inner = test_join(inner_values, scan);
24834 let outer = test_join(outer_values, inner);
24835 let mut operands = Vec::new();
24836 flatten_join_spine(outer, &mut operands);
24837 assert_eq!(
24838 operands.len(),
24839 2,
24840 "expected a bare table and the inner pair"
24841 );
24842 assert!(matches!(operands[0], JoinableSpineNode::Bare(_)));
24843 assert!(matches!(operands[1], JoinableSpineNode::TransparentJoin(_)));
24844 }
24845
24846 #[test]
24847 fn ground_bind_prefixes_broadcast_scan_object() {
24848 let brisbane = NamedNode::new("http://ex/brisbane").unwrap();
24849 let plan = LogicalPlan::parse(
24850 r#"
24851 SELECT ?person WHERE {
24852 BIND(<http://ex/brisbane> AS ?city)
24853 ?person <http://ex/livesIn> ?city .
24854 }
24855 "#,
24856 )
24857 .unwrap();
24858 let mut scans = Vec::new();
24859 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
24860 assert_eq!(scans.len(), 1);
24861 assert_eq!(scans[0].object.as_ref().map(Variable::as_str), Some("city"));
24862 assert_eq!(scans[0].pattern.object, Some(EncodedTerm::from(&brisbane)));
24863 }
24864
24865 #[test]
24866 fn singleton_values_prefixes_broadcast_path_end() {
24867 let brisbane = NamedNode::new("http://ex/brisbane").unwrap();
24868 let plan = LogicalPlan::parse(
24869 r#"
24870 SELECT ?person WHERE {
24871 VALUES ?city { <http://ex/brisbane> }
24872 ?person <http://ex/livesIn>* ?city .
24873 }
24874 "#,
24875 )
24876 .unwrap();
24877 let mut paths = Vec::new();
24878 for_each_path(&plan.root, &mut |path| paths.push(path));
24879 assert_eq!(paths.len(), 1, "expected a Path probe, got {:?}", plan.root);
24880 assert_eq!(paths[0].object.as_ref().map(Variable::as_str), Some("city"));
24881 assert_eq!(paths[0].object_term, Some(EncodedTerm::from(&brisbane)));
24882 }
24883
24884 #[test]
24885 fn bind_of_in_scope_variable_is_rejected() {
24886 let s = var("s");
24890 let o = var("o");
24891 let inner = GraphPattern::Bgp {
24892 patterns: vec![TriplePattern {
24893 subject: TermPattern::Variable(s.clone()),
24894 predicate: NamedNodePattern::NamedNode(NamedNode::new("http://ex/p").unwrap()),
24895 object: TermPattern::Variable(o),
24896 }],
24897 };
24898 let pattern = GraphPattern::Extend {
24899 inner: Box::new(inner),
24900 variable: s,
24901 expression: Expression::Literal(Literal::new_simple_literal("x")),
24902 };
24903 let error = lower_pattern(
24904 &pattern,
24905 None,
24906 &IncomingBound::default(),
24907 &QueryContext::from_snapshot(SnapshotId::latest()),
24908 &GraphScope::Default,
24909 )
24910 .unwrap_err();
24911 let message = error.to_string();
24912 assert!(message.contains("already in-scope"), "{message}");
24913 assert!(matches!(error, ComputeError::UnsupportedSparql(_)));
24914 }
24915
24916 #[test]
24917 fn select_expr_as_is_extend() {
24918 let plan =
24919 LogicalPlan::parse(r#"SELECT (?o AS ?c) WHERE { ?s <http://ex/livesIn> ?o }"#).unwrap();
24920 assert!(
24921 matches!(plan.root, PlanNode::Extend { .. }),
24922 "got {:?}",
24923 plan.root
24924 );
24925 assert_eq!(plan.projection, vec![var("c")]);
24926 }
24927
24928 #[test]
24929 fn projected_unbound_variable_is_allowed() {
24930 let plan = LogicalPlan::parse(r#"SELECT ?missing WHERE { ?s ?p ?o }"#).unwrap();
24931 assert_eq!(plan.projection, vec![var("missing")]);
24932 }
24933
24934 #[test]
24935 fn explain_sparql_keeps_values_in_a_join_tree() {
24936 let text = explain_optimised_sparql(
24937 r#"
24938 SELECT ?person WHERE {
24939 ?person <http://ex/livesIn> ?city .
24940 VALUES ?city { <http://ex/brisbane> }
24941 }
24942 "#,
24943 );
24944 assert!(
24945 text.contains("VALUES"),
24946 "VALUES must not be dropped: {text}"
24947 );
24948 assert!(text.contains("livesIn"), "{text}");
24949 }
24950
24951 #[test]
24952 fn values_is_copied_into_both_union_arms() {
24953 let text = explain_optimised_sparql(
24954 r#"
24955 SELECT ?s WHERE {
24956 VALUES ?city { <http://ex/brisbane> }
24957 { ?s <http://ex/livesIn> ?city }
24958 UNION
24959 { ?s <http://ex/hasWeather> ?city }
24960 }
24961 "#,
24962 );
24963 let count = text.matches("VALUES").count();
24964 assert!(
24965 count >= 2,
24966 "expected VALUES inside both UNION arms, got {count} in {text}"
24967 );
24968 let plan = LogicalPlan::parse(
24969 r#"
24970 SELECT ?s WHERE {
24971 VALUES ?city { <http://ex/brisbane> }
24972 { ?s <http://ex/livesIn> ?city }
24973 UNION
24974 { ?s <http://ex/hasWeather> ?city }
24975 }
24976 "#,
24977 )
24978 .unwrap();
24979 assert!(
24980 matches!(plan.root, PlanNode::Union { .. }),
24981 "root should be Union after VALUES push, got {:?}",
24982 plan.root
24983 );
24984 }
24985
24986 #[test]
24987 fn bind_is_copied_into_both_union_arms() {
24988 let sparql = r#"
24989 SELECT ?s WHERE {
24990 BIND(<http://ex/brisbane> AS ?b)
24991 { { ?s <http://ex/livesIn> ?b } UNION { ?b <http://ex/hasWeather> ?w } }
24992 }
24993 "#;
24994 let plan = LogicalPlan::parse(sparql).unwrap();
24995 assert!(
24996 matches!(plan.root, PlanNode::Union { .. }),
24997 "root should be Union after BIND→VALUES push, got {:?}",
24998 plan.root
24999 );
25000 assert_eq!(
25001 count_values_nodes(&plan.root),
25002 2,
25003 "expected VALUES in both UNION arms: {:?}",
25004 plan.root
25005 );
25006 let text = explain_optimised_sparql(sparql);
25007 assert!(
25008 text.matches("VALUES").count() >= 2,
25009 "EXPLAIN should show VALUES in both arms: {text}"
25010 );
25011 }
25012
25013 #[test]
25014 fn nested_union_three_arms_copies_values() {
25015 let plan = LogicalPlan::parse(
25016 r#"
25017 SELECT ?s WHERE {
25018 VALUES ?city { <http://ex/brisbane> }
25019 { ?s <http://ex/livesIn> ?city }
25020 UNION
25021 { ?s <http://ex/hasWeather> ?city }
25022 UNION
25023 { ?city <http://ex/hasWeather> ?s }
25024 }
25025 "#,
25026 )
25027 .unwrap();
25028 assert_eq!(
25029 count_values_nodes(&plan.root),
25030 3,
25031 "VALUES should reach all three UNION arms, got {:?}",
25032 plan.root
25033 );
25034 }
25035
25036 #[test]
25037 fn nested_union_three_arms_copies_bind() {
25038 let plan = LogicalPlan::parse(
25039 r#"
25040 SELECT ?s WHERE {
25041 BIND(<http://ex/brisbane> AS ?city)
25042 { ?s <http://ex/livesIn> ?city }
25043 UNION
25044 { ?s <http://ex/hasWeather> ?city }
25045 UNION
25046 { ?city <http://ex/hasWeather> ?s }
25047 }
25048 "#,
25049 )
25050 .unwrap();
25051 assert_eq!(
25052 count_values_nodes(&plan.root),
25053 3,
25054 "BIND→VALUES should reach all three UNION arms, got {:?}",
25055 plan.root
25056 );
25057 }
25058
25059 #[test]
25060 fn explain_optional_union_broadcasts_both_scans() {
25061 let sparql = r#"
25062 SELECT * WHERE {
25063 BIND(<http://ex/brisbane> AS ?b)
25064 OPTIONAL {
25065 { ?s <http://ex/livesIn> ?b }
25066 UNION
25067 { ?s <http://ex/hasWeather> ?b }
25068 }
25069 }
25070 "#;
25071 let plan = LogicalPlan::parse(sparql).unwrap();
25072 let PlanNode::LeftJoin { right, .. } = &plan.root else {
25073 panic!("expected LeftJoin at root, got {:?}", plan.root);
25074 };
25075 let mut grounded = Vec::new();
25076 for_each_scan(right, &mut |scan| {
25077 if !scan.grounded.is_empty() {
25078 grounded.push(scan);
25079 }
25080 });
25081 assert_eq!(
25082 grounded.len(),
25083 2,
25084 "both UNION optional scans should be grounded, got {right:?}"
25085 );
25086 for scan in &grounded {
25087 assert!(
25088 scan.broadcasted.is_none(),
25089 "unique BIND should not stamp broadcast, got {:?}",
25090 scan.broadcasted
25091 );
25092 assert_eq!(
25093 grounded_of(scan),
25094 vec![("b", PatternSlot::Object)],
25095 "expected grounded object on ?b, got {:?}",
25096 scan.grounded
25097 );
25098 assert!(
25099 scan.produced_row_count_estimate < 1_000_000,
25100 "bound optional scan must not use unbound ~3e6: {}",
25101 scan.produced_row_count_estimate
25102 );
25103 }
25104 let text = explain_est(sparql, None);
25105 assert!(
25106 text.matches("(grounded ?b object)").count() >= 2,
25107 "EXPLAIN should annotate both UNION scans: {text}"
25108 );
25109 }
25110
25111 #[test]
25112 fn explain_optional_join_broadcasts_the_key_scan() {
25113 let sparql = r#"
25114 SELECT * WHERE {
25115 BIND("Sunny" AS ?b)
25116 OPTIONAL {
25117 ?s1 <http://ex/livesIn> ?s2 .
25118 ?s2 <http://ex/hasWeather> ?b
25119 }
25120 }
25121 "#;
25122 let plan = LogicalPlan::parse(sparql).unwrap();
25123 let PlanNode::LeftJoin { right, .. } = &plan.root else {
25124 panic!("expected LeftJoin at root, got {:?}", plan.root);
25125 };
25126 let mut key_scans = Vec::new();
25127 for_each_scan(right, &mut |scan| {
25128 if scan.object.as_ref().is_some_and(|v| v.as_str() == "b") {
25129 key_scans.push(scan);
25130 }
25131 });
25132 assert_eq!(key_scans.len(), 1, "one scan should bind ?b: {right:?}");
25133 assert!(
25134 key_scans[0].broadcasted.is_none(),
25135 "unique BIND should not stamp broadcast, got {:?}",
25136 key_scans[0].broadcasted
25137 );
25138 assert_eq!(
25139 grounded_of(key_scans[0]),
25140 vec![("b", PatternSlot::Object)],
25141 "the ?b scan should be grounded, got {:?}",
25142 key_scans[0].grounded
25143 );
25144 }
25145
25146 #[test]
25147 fn explain_nested_optional_broadcasts_outer_key() {
25148 let sparql = r#"
25149 SELECT * WHERE {
25150 BIND(<http://ex/brisbane> AS ?b)
25151 OPTIONAL {
25152 ?s ?p ?b .
25153 OPTIONAL { ?s <http://ex/hasWeather> ?n }
25154 }
25155 }
25156 "#;
25157 let plan = LogicalPlan::parse(sparql).unwrap();
25158 let PlanNode::LeftJoin { right, .. } = &plan.root else {
25159 panic!("expected LeftJoin at root, got {:?}", plan.root);
25160 };
25161 let mut found = false;
25162 for_each_scan(right, &mut |scan| {
25163 if scan.object.as_ref().is_some_and(|v| v.as_str() == "b") {
25164 found = scan.broadcasted.is_none()
25165 && grounded_of(scan) == vec![("b", PatternSlot::Object)];
25166 }
25167 });
25168 assert!(
25169 found,
25170 "outer ?b should reach the nested required scan: {right:?}"
25171 );
25172 }
25173
25174 fn optional_right_join(node: &PlanNode) -> &PlanNode {
25175 let PlanNode::LeftJoin { right, .. } = node else {
25176 panic!("expected LeftJoin, got {node:?}");
25177 };
25178 right
25179 }
25180
25181 #[test]
25182 fn optional_fk_pattern_ordered_before_type_with_profile() {
25183 let mut live = LiveQuadsProfile::default();
25188 let rack_class = NamedNode::new("http://ex/Rack").unwrap();
25189 let server_class = NamedNode::new("http://ex/Server").unwrap();
25190 let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
25191 let located_in = NamedNode::new("http://ex/locatedIn").unwrap();
25192
25193 for i in 0..100 {
25194 let rack = NamedNode::new(format!("http://ex/rack{i}")).unwrap();
25195 observe_quad(
25196 &mut live,
25197 &encode_quad(&waratah_storage::Quad::new(
25198 rack,
25199 type_pred.clone(),
25200 rack_class.clone(),
25201 waratah_storage::GraphName::DefaultGraph,
25202 ))
25203 .unwrap(),
25204 StorageOp::Put,
25205 );
25206 }
25207 for i in 0..1000 {
25208 let server = NamedNode::new(format!("http://ex/server{i}")).unwrap();
25209 let rack = NamedNode::new(format!("http://ex/rack{}", i % 100)).unwrap();
25210 observe_quad(
25211 &mut live,
25212 &encode_quad(&waratah_storage::Quad::new(
25213 server.clone(),
25214 type_pred.clone(),
25215 server_class.clone(),
25216 waratah_storage::GraphName::DefaultGraph,
25217 ))
25218 .unwrap(),
25219 StorageOp::Put,
25220 );
25221 observe_quad(
25222 &mut live,
25223 &encode_quad(&waratah_storage::Quad::new(
25224 server,
25225 located_in.clone(),
25226 rack,
25227 waratah_storage::GraphName::DefaultGraph,
25228 ))
25229 .unwrap(),
25230 StorageOp::Put,
25231 );
25232 }
25233 let profile = StatsProfile::from(live);
25234
25235 let plan = LogicalPlan::parse_with_profile(
25236 r#"
25237 SELECT ?rack ?server WHERE {
25238 ?rack a <http://ex/Rack> .
25239 OPTIONAL {
25240 ?server a <http://ex/Server> .
25241 ?server <http://ex/locatedIn> ?rack .
25242 }
25243 }
25244 "#,
25245 Some(&profile),
25246 )
25247 .unwrap();
25248 let PlanNode::Join { left, right, .. } = optional_right_join(&plan.root) else {
25249 panic!(
25250 "expected Join on OPTIONAL right, got {:?}",
25251 optional_right_join(&plan.root)
25252 );
25253 };
25254 let driver = left.as_scan().expect("inner join left should be a scan");
25255 assert_eq!(
25256 driver.object.as_ref().map(Variable::as_str),
25257 Some("rack"),
25258 "FK :locatedIn ?rack should drive, got {left:?}"
25259 );
25260 let probe = right.as_scan().expect("inner join right should be a scan");
25261 assert!(
25262 probe.pattern.object.is_some() && probe.object.is_none(),
25263 "type scan should be the probe, got {right:?}"
25264 );
25265 }
25266
25267 #[test]
25268 fn optional_large_incoming_domain_lets_small_type_scan_drive() {
25269 let mut live = LiveQuadsProfile::default();
25272 let rack_class = NamedNode::new("http://ex/Rack").unwrap();
25273 let server_class = NamedNode::new("http://ex/Server").unwrap();
25274 let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
25275 let located_in = NamedNode::new("http://ex/locatedIn").unwrap();
25276
25277 for i in 0..2000 {
25278 let rack = NamedNode::new(format!("http://ex/rack{i}")).unwrap();
25279 observe_quad(
25280 &mut live,
25281 &encode_quad(&waratah_storage::Quad::new(
25282 rack.clone(),
25283 type_pred.clone(),
25284 rack_class.clone(),
25285 waratah_storage::GraphName::DefaultGraph,
25286 ))
25287 .unwrap(),
25288 StorageOp::Put,
25289 );
25290 let server = NamedNode::new(format!("http://ex/host{i}")).unwrap();
25291 observe_quad(
25292 &mut live,
25293 &encode_quad(&waratah_storage::Quad::new(
25294 server,
25295 located_in.clone(),
25296 rack,
25297 waratah_storage::GraphName::DefaultGraph,
25298 ))
25299 .unwrap(),
25300 StorageOp::Put,
25301 );
25302 }
25303 for i in 0..100 {
25304 let server = NamedNode::new(format!("http://ex/server{i}")).unwrap();
25305 observe_quad(
25306 &mut live,
25307 &encode_quad(&waratah_storage::Quad::new(
25308 server,
25309 type_pred.clone(),
25310 server_class.clone(),
25311 waratah_storage::GraphName::DefaultGraph,
25312 ))
25313 .unwrap(),
25314 StorageOp::Put,
25315 );
25316 }
25317 let profile = StatsProfile::from(live);
25318
25319 let plan = LogicalPlan::parse_with_profile(
25320 r#"
25321 SELECT ?rack ?server WHERE {
25322 ?rack a <http://ex/Rack> .
25323 OPTIONAL {
25324 ?server a <http://ex/Server> .
25325 ?server <http://ex/locatedIn> ?rack .
25326 }
25327 }
25328 "#,
25329 Some(&profile),
25330 )
25331 .unwrap();
25332 let PlanNode::Join { left, right, .. } = optional_right_join(&plan.root) else {
25333 panic!(
25334 "expected Join on OPTIONAL right, got {:?}",
25335 optional_right_join(&plan.root)
25336 );
25337 };
25338 let driver = left.as_scan().expect("inner join left should be a scan");
25339 assert!(
25340 driver.pattern.object.is_some() && driver.object.is_none(),
25341 "small :Server type scan should drive, got {left:?}"
25342 );
25343 let probe = right.as_scan().expect("inner join right should be a scan");
25344 assert_eq!(
25345 probe.object.as_ref().map(Variable::as_str),
25346 Some("rack"),
25347 "scaled :locatedIn should be the probe, got {right:?}"
25348 );
25349 }
25350
25351 #[test]
25352 fn incoming_domain_scales_scan_and_unbound_over_allow_list_cap() {
25353 let mut profile = StatsProfile::default();
25356 let located_in = NamedNode::new("http://ex/locatedIn").unwrap();
25357 let pred = waratah_storage::StrHash::new("http://ex/locatedIn");
25358 profile.total_puts = 2_000_000;
25359 profile.predicate_counts.insert(pred, 2_000_000);
25360 let mut objects = waratah_stats::HyperLogLog::default_params();
25361 for i in 0..20_000u128 {
25362 objects.add(i);
25363 }
25364 profile.objects_per_predicate.insert(pred, objects);
25365
25366 let pattern = TriplePattern {
25367 subject: TermPattern::Variable(var("server")),
25368 predicate: NamedNodePattern::NamedNode(located_in),
25369 object: TermPattern::Variable(var("rack")),
25370 };
25371
25372 let mut per_key_incoming = IncomingBound::default();
25373 per_key_incoming.insert(var("rack"), None);
25374 let per_key_scan = plan_scan_op(
25375 &pattern,
25376 Some(&profile),
25377 &per_key_incoming,
25378 &QueryContext::from_snapshot(SnapshotId::latest()),
25379 &GraphScope::Default,
25380 )
25381 .unwrap();
25382 assert_eq!(
25386 per_key_scan.join_domains.get(JoinKeySlot::Object),
25387 JoinDomainStamp::Known(profile.object_domain(&pred).unwrap()),
25388 "bound predicate + object HLL must stamp the object slot"
25389 );
25390 assert_eq!(
25391 per_key_scan.join_domains.get(JoinKeySlot::Subject),
25392 JoinDomainStamp::Unavailable,
25393 "no subject HLL for :locatedIn -> live fallback"
25394 );
25395 let per_key = per_key_scan.produced_row_count_estimate;
25396 assert!(
25397 (50..=200).contains(&per_key),
25398 "expected ~100 fan-out, got {per_key}"
25399 );
25400
25401 let mut at_cap = IncomingBound::default();
25402 at_cap.insert(var("rack"), Some(PUSHDOWN_TERMS_LIMIT));
25403 let at_cap_rows = plan_scan_op(
25404 &pattern,
25405 Some(&profile),
25406 &at_cap,
25407 &QueryContext::from_snapshot(SnapshotId::latest()),
25408 &GraphScope::Default,
25409 )
25410 .unwrap()
25411 .produced_row_count_estimate;
25412 let expected_scaled = 2_000_000.min(per_key.saturating_mul(PUSHDOWN_TERMS_LIMIT));
25413 assert_eq!(
25414 at_cap_rows, expected_scaled,
25415 "domain 20k should scale per-key, not leave {per_key}"
25416 );
25417 assert!(
25418 at_cap_rows > per_key,
25419 "scaled estimate must exceed per-key fan-out: {at_cap_rows} vs {per_key}"
25420 );
25421
25422 let mut over_cap = IncomingBound::default();
25423 over_cap.insert(var("rack"), Some(PUSHDOWN_TERMS_LIMIT + 1));
25424 let over_cap_rows = plan_scan_op(
25425 &pattern,
25426 Some(&profile),
25427 &over_cap,
25428 &QueryContext::from_snapshot(SnapshotId::latest()),
25429 &GraphScope::Default,
25430 )
25431 .unwrap()
25432 .produced_row_count_estimate;
25433 assert_eq!(
25434 over_cap_rows, 2_000_000,
25435 "domain 20_001 should cost unbound |P|, got {over_cap_rows}"
25436 );
25437 }
25438
25439 #[test]
25440 fn incoming_bound_predicate_uses_mean_count_and_scales_by_domain() {
25441 let mut profile = StatsProfile {
25444 total_puts: 100_000,
25445 ..StatsProfile::default()
25446 };
25447 for i in 0..10 {
25448 profile.predicate_counts.insert(
25449 waratah_storage::StrHash::new(&format!("http://ex/p{i}")),
25450 10_000,
25451 );
25452 }
25453
25454 let pattern = TriplePattern {
25455 subject: TermPattern::Variable(var("s")),
25456 predicate: NamedNodePattern::Variable(var("p")),
25457 object: TermPattern::Variable(var("o")),
25458 };
25459
25460 let mut per_key_incoming = IncomingBound::default();
25461 per_key_incoming.insert(var("p"), None);
25462 let per_key = plan_scan_op(
25463 &pattern,
25464 Some(&profile),
25465 &per_key_incoming,
25466 &QueryContext::from_snapshot(SnapshotId::latest()),
25467 &GraphScope::Default,
25468 )
25469 .unwrap()
25470 .produced_row_count_estimate;
25471 assert_eq!(per_key, 10_000, "unknown domain keeps mean |P|");
25472
25473 let mut scaled_incoming = IncomingBound::default();
25474 scaled_incoming.insert(var("p"), Some(3));
25475 let scaled = plan_scan_op(
25476 &pattern,
25477 Some(&profile),
25478 &scaled_incoming,
25479 &QueryContext::from_snapshot(SnapshotId::latest()),
25480 &GraphScope::Default,
25481 )
25482 .unwrap()
25483 .produced_row_count_estimate;
25484 assert_eq!(scaled, 30_000, "domain 3 should scale mean |P|");
25485
25486 let mut over_cap = IncomingBound::default();
25487 over_cap.insert(var("p"), Some(PUSHDOWN_TERMS_LIMIT + 1));
25488 let over_cap_rows = plan_scan_op(
25489 &pattern,
25490 Some(&profile),
25491 &over_cap,
25492 &QueryContext::from_snapshot(SnapshotId::latest()),
25493 &GraphScope::Default,
25494 )
25495 .unwrap()
25496 .produced_row_count_estimate;
25497 assert_eq!(
25498 over_cap_rows, 100_000,
25499 "over allow-list cap should cost unbound total_puts"
25500 );
25501 }
25502
25503 #[test]
25504 fn optional_fk_pattern_ordered_before_type_without_profile() {
25505 let plan = LogicalPlan::parse(
25508 r#"
25509 SELECT ?rack ?server WHERE {
25510 ?rack a <http://ex/Rack> .
25511 OPTIONAL {
25512 ?server a <http://ex/Server> .
25513 ?server <http://ex/locatedIn> ?rack .
25514 }
25515 }
25516 "#,
25517 )
25518 .unwrap();
25519 let PlanNode::Join { left, .. } = optional_right_join(&plan.root) else {
25520 panic!(
25521 "expected Join on OPTIONAL right, got {:?}",
25522 optional_right_join(&plan.root)
25523 );
25524 };
25525 let driver = left.as_scan().expect("inner join left should be a scan");
25526 assert_eq!(
25527 driver.object.as_ref().map(Variable::as_str),
25528 Some("rack"),
25529 "incoming-slot tie-break should put :locatedIn first, got {left:?}"
25530 );
25531 }
25532
25533 #[test]
25534 fn nested_optional_left_bgp_sees_outer_key() {
25535 let plan = LogicalPlan::parse(
25536 r#"
25537 SELECT * WHERE {
25538 ?x a <http://ex/X> .
25539 OPTIONAL {
25540 ?y a <http://ex/Y> .
25541 ?y <http://ex/locatedIn> ?x .
25542 OPTIONAL { ?z <http://ex/p> ?y }
25543 }
25544 }
25545 "#,
25546 )
25547 .unwrap();
25548 let nested = optional_right_join(&plan.root);
25549 let PlanNode::LeftJoin { left, .. } = nested else {
25550 panic!("expected nested LeftJoin, got {nested:?}");
25551 };
25552 let PlanNode::Join {
25553 left: driver_node, ..
25554 } = left.as_ref()
25555 else {
25556 panic!("expected Join on nested OPTIONAL left, got {left:?}");
25557 };
25558 let driver = driver_node
25559 .as_scan()
25560 .expect("nested left BGP driver should be a scan");
25561 assert_eq!(
25562 driver.object.as_ref().map(Variable::as_str),
25563 Some("x"),
25564 "outer ?x should order :locatedIn first on the nested left BGP, got {left:?}"
25565 );
25566 }
25567
25568 #[test]
25569 fn optional_maybe_unbound_does_not_leak_into_later_optional() {
25570 let plan = LogicalPlan::parse(
25573 r#"
25574 SELECT * WHERE {
25575 ?s <http://ex/p> ?x .
25576 OPTIONAL { ?x <http://ex/q> ?y }
25577 OPTIONAL { ?y <http://ex/r> ?z }
25578 }
25579 "#,
25580 )
25581 .unwrap();
25582 let scan = optional_right_join(&plan.root)
25583 .as_scan()
25584 .expect("second OPTIONAL right should be a scan");
25585 assert_eq!(
25586 scan.produced_row_count_estimate, 2_000_000,
25587 "P-only fallback; incoming ?y would drop this to 1e6: {scan:?}"
25588 );
25589 assert!(
25590 scan.broadcasted.is_none(),
25591 "no join key with the required side, got {:?}",
25592 scan.broadcasted
25593 );
25594 }
25595
25596 fn count_values_nodes(node: &PlanNode) -> usize {
25597 match node {
25598 PlanNode::Values(_) => 1,
25599 PlanNode::Join { left, right, .. }
25600 | PlanNode::Union { left, right }
25601 | PlanNode::LeftJoin { left, right, .. } => {
25602 count_values_nodes(left) + count_values_nodes(right)
25603 }
25604 PlanNode::Filter { inner, .. }
25605 | PlanNode::Extend { inner, .. }
25606 | PlanNode::Slice { inner, .. }
25607 | PlanNode::Distinct { inner, .. }
25608 | PlanNode::Sort { inner, .. }
25609 | PlanNode::Group { inner, .. } => count_values_nodes(inner),
25610 _ => 0,
25611 }
25612 }
25613
25614 fn for_each_scan<'a>(node: &'a PlanNode, f: &mut impl FnMut(&'a ScanOp)) {
25615 match node {
25616 PlanNode::Scan(scan) => f(scan),
25617 PlanNode::Join { left, right, .. }
25618 | PlanNode::Union { left, right }
25619 | PlanNode::LeftJoin { left, right, .. } => {
25620 for_each_scan(left, f);
25621 for_each_scan(right, f);
25622 }
25623 PlanNode::Filter { inner, .. }
25624 | PlanNode::Extend { inner, .. }
25625 | PlanNode::Slice { inner, .. }
25626 | PlanNode::Distinct { inner, .. }
25627 | PlanNode::Sort { inner, .. }
25628 | PlanNode::Group { inner, .. } => for_each_scan(inner, f),
25629 _ => {}
25630 }
25631 }
25632
25633 fn grounded_of(scan: &ScanOp) -> Vec<(&str, PatternSlot)> {
25634 scan.grounded
25635 .iter()
25636 .map(|(variable, slot)| (variable.as_str(), *slot))
25637 .collect()
25638 }
25639
25640 fn find_inner_join(node: &PlanNode) -> &PlanNode {
25641 match node {
25642 PlanNode::Join { .. } => node,
25643 PlanNode::Extend { inner, .. }
25644 | PlanNode::Filter { inner, .. }
25645 | PlanNode::Slice { inner, .. }
25646 | PlanNode::Distinct { inner, .. }
25647 | PlanNode::Sort { inner, .. }
25648 | PlanNode::Group { inner, .. } => find_inner_join(inner),
25649 PlanNode::LeftJoin { left, .. } => find_inner_join(left),
25650 other => panic!("expected Join under wrappers, got {other:?}"),
25651 }
25652 }
25653
25654 fn for_each_path<'a>(node: &'a PlanNode, f: &mut impl FnMut(&'a PathOp)) {
25655 match node {
25656 PlanNode::Path(path) => f(path),
25657 PlanNode::Join { left, right, .. }
25658 | PlanNode::Union { left, right }
25659 | PlanNode::LeftJoin { left, right, .. } => {
25660 for_each_path(left, f);
25661 for_each_path(right, f);
25662 }
25663 PlanNode::Filter { inner, .. }
25664 | PlanNode::Extend { inner, .. }
25665 | PlanNode::Slice { inner, .. }
25666 | PlanNode::Distinct { inner, .. }
25667 | PlanNode::Sort { inner, .. }
25668 | PlanNode::Group { inner, .. } => for_each_path(inner, f),
25669 _ => {}
25670 }
25671 }
25672
25673 #[test]
25674 fn empty_values_has_zero_rows() {
25675 let plan = LogicalPlan::parse(r#"SELECT ?x WHERE { VALUES ?x { } }"#).unwrap();
25676 let PlanNode::Values(values) = &plan.root else {
25677 panic!("expected Values, got {:?}", plan.root);
25678 };
25679 assert!(values.rows.is_empty());
25680 assert_eq!(values.produced_row_count_estimate(), 0);
25681 }
25682
25683 #[test]
25684 fn limit_and_offset_lower_to_slice() {
25685 let plan = LogicalPlan::parse("SELECT ?s WHERE { ?s <http://ex/p> ?o } LIMIT 10 OFFSET 3")
25686 .unwrap();
25687 match &plan.root {
25688 PlanNode::Slice {
25689 start,
25690 length,
25691 inner,
25692 } => {
25693 assert_eq!(*start, 3);
25694 assert_eq!(*length, Some(10));
25695 assert!(matches!(inner.as_ref(), PlanNode::Scan(_)));
25696 }
25697 other => panic!("expected Slice, got {other:?}"),
25698 }
25699 }
25700
25701 #[test]
25702 fn limit_zero_is_empty_slice() {
25703 let plan = LogicalPlan::parse("SELECT ?s WHERE { ?s <http://ex/p> ?o } LIMIT 0").unwrap();
25704 match &plan.root {
25705 PlanNode::Slice { start, length, .. } => {
25706 assert_eq!(*start, 0);
25707 assert_eq!(*length, Some(0));
25708 }
25709 other => panic!("expected Slice, got {other:?}"),
25710 }
25711 }
25712
25713 #[test]
25714 fn small_limit_rewrites_scan_join_to_broadcast() {
25715 let unlimited = LogicalPlan::parse(
25716 r#"SELECT ?s WHERE {
25717 ?s <http://ex/p> ?o .
25718 ?s <http://ex/q> ?x .
25719 }"#,
25720 )
25721 .unwrap();
25722 assert_ne!(
25723 unlimited.join_ops().unwrap()[0].meta.strategy,
25724 JoinStrategy::Broadcast,
25725 "unbounded join should not force Broadcast without stats"
25726 );
25727
25728 let limited = LogicalPlan::parse(
25729 r#"SELECT ?s WHERE {
25730 ?s <http://ex/p> ?o .
25731 ?s <http://ex/q> ?x .
25732 } LIMIT 1"#,
25733 )
25734 .unwrap();
25735 assert_eq!(
25736 limited.join_ops().unwrap()[0].meta.strategy,
25737 JoinStrategy::Broadcast
25738 );
25739 }
25740
25741 #[test]
25742 fn ask_join_rewrites_scan_join_to_broadcast() {
25743 let query = SparqlParser::new()
25744 .parse_query(
25745 r#"ASK {
25746 ?s <http://ex/p> ?o .
25747 ?s <http://ex/q> ?x .
25748 }"#,
25749 )
25750 .unwrap();
25751 let Query::Ask { pattern, .. } = query else {
25752 panic!("expected ASK");
25753 };
25754 let plan = LogicalPlan::from_ask_algebra(pattern, None).unwrap();
25755 match &plan.root {
25756 PlanNode::Slice { start, length, .. } => {
25757 assert_eq!(*start, 0);
25758 assert_eq!(*length, Some(1));
25759 }
25760 other => panic!("expected Slice, got {other:?}"),
25761 }
25762 assert_eq!(
25763 plan.join_ops().unwrap()[0].meta.strategy,
25764 JoinStrategy::Broadcast
25765 );
25766 }
25767
25768 #[test]
25769 fn order_by_lowers_between_project_and_slice() {
25770 let plan =
25771 LogicalPlan::parse("SELECT ?s WHERE { ?s <http://ex/p> ?o } ORDER BY ?s LIMIT 5")
25772 .expect("ORDER BY must plan");
25773 match &plan.root {
25774 PlanNode::Slice {
25775 start,
25776 length,
25777 inner,
25778 } => {
25779 assert_eq!(*start, 0);
25780 assert_eq!(*length, Some(5));
25781 match inner.as_ref() {
25782 PlanNode::Sort { keys, inner } => {
25783 assert_eq!(keys.len(), 1);
25784 assert!(!keys[0].descending);
25785 assert!(
25786 matches!(inner.as_ref(), PlanNode::Scan(_)),
25787 "expected Scan under Sort, got {inner:?}"
25788 );
25789 }
25790 other => panic!("expected Sort under Slice, got {other:?}"),
25791 }
25792 }
25793 other => panic!("expected Slice, got {other:?}"),
25794 }
25795 }
25796
25797 #[test]
25798 fn distinct_lowers_onto_the_select_projection() {
25799 let plan = LogicalPlan::parse("SELECT DISTINCT ?s WHERE { ?s <http://ex/p> ?o }").unwrap();
25800 match &plan.root {
25801 PlanNode::Distinct { columns, inner } => {
25802 assert_eq!(columns, &vec![var("s")]);
25803 assert!(
25804 matches!(inner.as_ref(), PlanNode::Scan(_)),
25805 "expected Scan under Distinct, got {inner:?}"
25806 );
25807 }
25808 other => panic!("expected Distinct, got {other:?}"),
25809 }
25810 assert_eq!(plan.projection, vec![var("s")]);
25811 }
25812
25813 #[test]
25814 fn distinct_then_limit_is_slice_over_distinct() {
25815 let plan =
25816 LogicalPlan::parse("SELECT DISTINCT ?s WHERE { ?s <http://ex/p> ?o } LIMIT 5").unwrap();
25817 match &plan.root {
25818 PlanNode::Slice {
25819 start,
25820 length,
25821 inner,
25822 } => {
25823 assert_eq!(*start, 0);
25824 assert_eq!(*length, Some(5));
25825 match inner.as_ref() {
25826 PlanNode::Distinct { columns, .. } => {
25827 assert_eq!(columns, &vec![var("s")]);
25828 }
25829 other => panic!("expected Distinct under Slice, got {other:?}"),
25830 }
25831 }
25832 other => panic!("expected Slice, got {other:?}"),
25833 }
25834 }
25835
25836 #[test]
25837 fn reduced_is_a_spec_legal_no_op() {
25838 let reduced = LogicalPlan::parse("SELECT REDUCED ?s WHERE { ?s <http://ex/p> ?o }")
25841 .expect("REDUCED must plan");
25842 let plain = LogicalPlan::parse("SELECT ?s WHERE { ?s <http://ex/p> ?o }")
25843 .expect("plain SELECT must plan");
25844 assert_eq!(reduced.projection, plain.projection);
25848 assert!(!plan_contains_distinct(&reduced.root));
25849 assert_eq!(format!("{:?}", reduced.root), format!("{:?}", plain.root));
25850 }
25851
25852 fn plan_contains_distinct(node: &PlanNode) -> bool {
25854 match node {
25855 PlanNode::Distinct { .. } => true,
25856 PlanNode::Scan(_)
25857 | PlanNode::Path(_)
25858 | PlanNode::Values(_)
25859 | PlanNode::Unit
25860 | PlanNode::NamedGraphs { .. }
25861 | PlanNode::NamedGraphExists { .. }
25862 | PlanNode::DomainCounts { .. }
25863 | PlanNode::HeadCounts { .. }
25864 | PlanNode::PatternCount { .. } => false,
25865 PlanNode::Join { left, right, .. }
25866 | PlanNode::LeftJoin { left, right, .. }
25867 | PlanNode::Union { left, right } => {
25868 plan_contains_distinct(left) || plan_contains_distinct(right)
25869 }
25870 PlanNode::Filter { inner, .. }
25871 | PlanNode::Extend { inner, .. }
25872 | PlanNode::Slice { inner, .. }
25873 | PlanNode::Sort { inner, .. }
25874 | PlanNode::Group { inner, .. }
25875 | PlanNode::JoinGraphVar { inner, .. } => plan_contains_distinct(inner),
25876 PlanNode::SubSelect(sub) => plan_contains_distinct(&sub.inner),
25877 PlanNode::CustomNode(custom) => custom.children.iter().any(plan_contains_distinct),
25878 }
25879 }
25880
25881 fn find_group(node: &PlanNode) -> &PlanNode {
25882 match node {
25883 PlanNode::Group { .. } => node,
25884 PlanNode::Extend { inner, .. }
25885 | PlanNode::Filter { inner, .. }
25886 | PlanNode::Slice { inner, .. }
25887 | PlanNode::Distinct { inner, .. }
25888 | PlanNode::Sort { inner, .. } => find_group(inner),
25889 other => panic!("expected Group under unary wrappers, got {other:?}"),
25890 }
25891 }
25892
25893 fn collect_scans<'a>(node: &'a PlanNode, out: &mut Vec<&'a ScanOp>) {
25896 match node {
25897 PlanNode::Scan(scan) => out.push(scan),
25898 PlanNode::Path(_)
25899 | PlanNode::Values(_)
25900 | PlanNode::NamedGraphs { .. }
25901 | PlanNode::NamedGraphExists { .. }
25902 | PlanNode::DomainCounts { .. }
25903 | PlanNode::HeadCounts { .. }
25904 | PlanNode::PatternCount { .. }
25905 | PlanNode::Unit => {}
25906 PlanNode::Join { left, right, .. }
25907 | PlanNode::LeftJoin { left, right, .. }
25908 | PlanNode::Union { left, right } => {
25909 collect_scans(left, out);
25910 collect_scans(right, out);
25911 }
25912 PlanNode::Filter { inner, .. }
25913 | PlanNode::Extend { inner, .. }
25914 | PlanNode::Slice { inner, .. }
25915 | PlanNode::Distinct { inner, .. }
25916 | PlanNode::Sort { inner, .. }
25917 | PlanNode::Group { inner, .. }
25918 | PlanNode::JoinGraphVar { inner, .. } => collect_scans(inner, out),
25919 PlanNode::SubSelect(sub) => collect_scans(&sub.inner, out),
25920 PlanNode::CustomNode(custom) => {
25921 for child in &custom.children {
25922 collect_scans(child, out);
25923 }
25924 }
25925 }
25926 }
25927
25928 #[test]
25929 fn count_distinct_star_keeps_all_inner_vars_uniformly_insensitive() {
25930 let plan = LogicalPlan::parse(
25931 "SELECT ?p (COUNT(DISTINCT *) AS ?c) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p",
25932 )
25933 .unwrap();
25934 let mut scans = Vec::new();
25935 collect_scans(&plan.root, &mut scans);
25936 assert!(!scans.is_empty());
25937 for scan in &scans {
25939 for variable in scan.slot_variables() {
25940 let mark = scan.bag_mark(&variable);
25941 assert!(mark.is_some(), "{variable} must be live, scan {scan:?}");
25942 assert_eq!(
25943 mark,
25944 Some(BagMark::Insensitive),
25945 "{variable} must be uniformly bag-insensitive (set-like), scan {scan:?}"
25946 );
25947 }
25948 }
25949 }
25950
25951 #[test]
25952 fn count_distinct_star_with_multiplicity_sibling_promotes_all_to_sensitive() {
25953 let plan = LogicalPlan::parse(
25954 "SELECT ?p (COUNT(DISTINCT *) AS ?c) (COUNT(?o) AS ?n) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p",
25955 )
25956 .unwrap();
25957 let mut scans = Vec::new();
25958 collect_scans(&plan.root, &mut scans);
25959 for scan in &scans {
25960 for variable in scan.slot_variables() {
25961 assert_eq!(
25962 scan.bag_mark(&variable),
25963 Some(BagMark::Sensitive),
25964 "{variable} must be uniformly bag-sensitive (multiplicity wins), scan {scan:?}"
25965 );
25966 }
25967 }
25968 }
25969
25970 #[test]
25971 fn count_distinct_star_disarms_scan_domain_counts() {
25972 let plan = LogicalPlan::parse(
25973 "SELECT ?p (COUNT(DISTINCT *) AS ?c) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p",
25974 )
25975 .unwrap();
25976 let mut scans = Vec::new();
25977 collect_scans(&plan.root, &mut scans);
25978 assert!(!scans.is_empty());
25979 for scan in &scans {
25980 assert!(
25981 scan.domain_counts.is_none(),
25982 "COUNT(DISTINCT *) inner vars are live, not counted — scan must stay plain or domain_scan, got {:?}",
25983 scan.domain_counts
25984 );
25985 }
25986 }
25987
25988 #[test]
25989 fn count_distinct_star_with_sample_sibling_gets_uniform_marks() {
25990 let plan = LogicalPlan::parse(
25998 "SELECT ?p (COUNT(DISTINCT *) AS ?c) (SAMPLE(?o) AS ?v) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p",
25999 )
26000 .unwrap();
26001 let mut scans = Vec::new();
26002 collect_scans(&plan.root, &mut scans);
26003 for scan in &scans {
26004 let marks: Vec<_> = scan
26005 .slot_variables()
26006 .into_iter()
26007 .map(|v| (v.clone(), scan.bag_mark(&v)))
26008 .collect();
26009 assert!(!marks.is_empty(), "all vars must be live: {marks:?}");
26010 assert!(
26011 marks.iter().all(|(_, m)| *m == marks[0].1),
26012 "marks must be uniform (never mixed): {marks:?}"
26013 );
26014 }
26015 }
26016
26017 #[test]
26018 fn having_optional_group_scan_schemas_align() {
26019 let plan = LogicalPlan::parse(
26020 r#"SELECT ?w (COUNT(*) AS ?c) WHERE {
26021 ?p <http://ex/livesIn> ?city .
26022 OPTIONAL { ?city <http://ex/hasWeather> ?w }
26023 } GROUP BY ?w HAVING (?w = "Sunny")"#,
26024 )
26025 .unwrap();
26026 let mut scans = Vec::new();
26027 collect_scans(&plan.root, &mut scans);
26028 for scan in &scans {
26029 let mat = scan.materialized_variables();
26030 assert_eq!(
26031 mat.iter().map(|v| v.as_str()).collect::<Vec<_>>(),
26032 scan.slot_variables()
26033 .iter()
26034 .filter(|v| scan.is_live(v) || scan.is_counted(v))
26035 .map(|v| v.as_str())
26036 .collect::<Vec<_>>(),
26037 "materialized_variables must match live+counted slots: {scan:?}"
26038 );
26039 }
26040 }
26041
26042 #[test]
26043 fn plain_count_star_still_prunes_dead_columns() {
26044 let plan = LogicalPlan::parse(
26048 "SELECT ?class (COUNT(*) AS ?n) WHERE { ?inst ?p ?class } GROUP BY ?class",
26049 )
26050 .unwrap();
26051 let group = find_group(&plan.root);
26052 let PlanNode::Group { inner, .. } = group else {
26053 panic!("expected Group, got {group:?}");
26054 };
26055 let PlanNode::Scan(scan) = inner.as_ref() else {
26056 panic!("expected Scan under Group");
26057 };
26058 assert_eq!(
26059 scan.bag_mark(scan.object.as_ref().unwrap()),
26060 Some(BagMark::Insensitive),
26061 "GROUP BY key stays bag-insensitive under COUNT(*)"
26062 );
26063 assert!(scan.is_live(scan.object.as_ref().unwrap()));
26064 assert!(scan.is_counted(scan.subject.as_ref().unwrap()));
26065 assert!(scan.is_counted(scan.predicate.as_ref().unwrap()));
26066 assert!(!scan.is_dropped(scan.subject.as_ref().unwrap()));
26067 assert!(!scan.is_dropped(scan.predicate.as_ref().unwrap()));
26068 }
26069
26070 #[test]
26071 fn plain_count_star_implicit_group_marks_non_keys_counted() {
26072 let plan = LogicalPlan::parse(
26073 "SELECT (COUNT(*) AS ?c) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p }",
26074 )
26075 .unwrap();
26076 let mut scans = Vec::new();
26077 collect_scans(&plan.root, &mut scans);
26078 for scan in &scans {
26079 assert!(
26080 !scan.marks.is_empty(),
26081 "liveness must annotate scans under COUNT(*): {scan:?}"
26082 );
26083 for variable in scan.slot_variables() {
26084 assert!(
26085 scan.is_counted(&variable)
26086 || scan.is_dropped(&variable)
26087 || scan.is_live(&variable),
26088 "implicit COUNT(*) marks slots counted, dropped, or live (join keys): {variable} {scan:?}"
26089 );
26090 }
26091 }
26092 }
26093
26094 #[test]
26095 fn count_without_group_by_lowers_to_pattern_count() {
26096 let plan =
26097 LogicalPlan::parse("SELECT (COUNT(*) AS ?c) WHERE { ?s <http://ex/p> ?o }").unwrap();
26098 assert_eq!(plan.projection, vec![var("c")]);
26099 let PlanNode::Extend {
26105 inner,
26106 variable,
26107 expression,
26108 ..
26109 } = &plan.root
26110 else {
26111 panic!("expected Extend over PatternCount, got {:?}", plan.root);
26112 };
26113 assert_eq!(variable, &var("c"));
26114 let PlanNode::PatternCount {
26115 count,
26116 count_star,
26117 counted,
26118 ..
26119 } = &**inner
26120 else {
26121 panic!("expected PatternCount under Extend, got {inner:?}");
26122 };
26123 assert!(count_star, "COUNT(*) has no counted variable");
26124 assert!(counted.is_none());
26125 assert_eq!(
26127 expression,
26128 &spargebra::algebra::Expression::Variable(count.clone())
26129 );
26130 let out = plan.root.output_vars();
26131 assert!(
26132 out.always_bound.iter().any(|v| v.as_str() == "c"),
26133 "{out:?}"
26134 );
26135 assert_eq!(plan.root.produced_row_count_estimate(), 1);
26136 }
26137
26138 #[test]
26139 fn group_by_variable_drops_non_key_inner_vars() {
26140 let plan = LogicalPlan::parse(
26141 "SELECT ?p (COUNT(?o) AS ?c) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p",
26142 )
26143 .unwrap();
26144 let group = find_group(&plan.root);
26145 let PlanNode::Group {
26146 variables,
26147 aggregates,
26148 ..
26149 } = group
26150 else {
26151 unreachable!();
26152 };
26153 assert_eq!(variables, &vec![var("p")]);
26154 assert!(matches!(
26155 aggregates[0].1,
26156 spargebra::algebra::AggregateExpression::FunctionCall {
26157 name: spargebra::algebra::AggregateFunction::Count,
26158 ..
26159 }
26160 ));
26161 let names: Vec<_> = group
26162 .output_vars()
26163 .all()
26164 .into_iter()
26165 .map(|v| v.as_str().to_owned())
26166 .collect();
26167 assert!(names.iter().any(|n| n == "p"), "{names:?}");
26168 assert!(
26169 !names.iter().any(|n| n == "s"),
26170 "non-key ?s must not be projected: {names:?}"
26171 );
26172 assert!(
26173 !names.iter().any(|n| n == "o"),
26174 "non-key ?o must not be projected: {names:?}"
26175 );
26176 let projected: Vec<_> = plan
26177 .root
26178 .output_vars()
26179 .all()
26180 .into_iter()
26181 .map(|v| v.as_str().to_owned())
26182 .collect();
26183 assert!(projected.iter().any(|n| n == "c"), "{projected:?}");
26184 }
26185
26186 #[test]
26187 fn having_is_filter_over_group() {
26188 let plan = LogicalPlan::parse(
26189 "SELECT ?p (COUNT(*) AS ?c) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p HAVING (COUNT(*) > 1)",
26190 )
26191 .unwrap();
26192 let mut node = &plan.root;
26193 while let PlanNode::Extend { inner, .. } = node {
26194 node = inner;
26195 }
26196 let PlanNode::Filter { inner, early, .. } = node else {
26197 panic!("expected Filter (HAVING) over Group, got {:?}", plan.root);
26198 };
26199 assert!(
26200 early.is_some(),
26201 "HAVING comparison should be an early filter"
26202 );
26203 assert!(
26204 matches!(inner.as_ref(), PlanNode::Group { .. }),
26205 "HAVING Filter inner should be Group, got {inner:?}"
26206 );
26207 }
26208
26209 #[test]
26210 fn subselect_lowers_to_opaque_boundary_and_renames_inner_vars() {
26211 let plan = LogicalPlan::parse(
26212 r#"SELECT ?city WHERE {
26213 { SELECT ?city WHERE { ?cat <http://ex/type> <http://ex/Cat> . ?cat <http://ex/livesIn> ?city } }
26214 ?city <http://ex/hasWeather> ?w .
26215 }"#,
26216 )
26217 .unwrap();
26218 let mut subs = Vec::new();
26219 find_subqueries(&plan.root, &mut subs);
26220 assert_eq!(subs.len(), 1, "one subselect boundary: {:?}", plan.root);
26221 assert_eq!(
26222 subs[0].variables,
26223 vec![var("city")],
26224 "boundary schema is the SELECT list"
26225 );
26226 let mut scans = Vec::new();
26229 collect_scans(&subs[0].inner, &mut scans);
26230 assert!(!scans.is_empty(), "subselect keeps its scans");
26231 let slot_names: Vec<String> = scans
26232 .iter()
26233 .flat_map(|scan| [&scan.subject, &scan.predicate, &scan.object])
26234 .flatten()
26235 .map(Variable::as_str)
26236 .map(str::to_owned)
26237 .collect();
26238 assert!(
26239 slot_names
26240 .iter()
26241 .any(|name| name.starts_with("sq_") && name.ends_with("_cat")),
26242 "non-projected ?cat should carry the random scope token: {slot_names:?}"
26243 );
26244 assert!(
26245 !slot_names.contains(&"cat".to_owned()),
26246 "non-projected ?cat must not keep its user-visible name: {slot_names:?}"
26247 );
26248 assert!(
26249 slot_names.contains(&"city".to_owned()),
26250 "projected ?city keeps its name: {slot_names:?}"
26251 );
26252 assert_eq!(plan.projection, vec![var("city")]);
26253 }
26254
26255 #[test]
26256 fn sibling_subqueries_get_distinct_random_scope_tokens() {
26257 let plan = LogicalPlan::parse(
26261 r#"SELECT ?a ?b WHERE {
26262 { SELECT ?a WHERE { ?s <http://ex/p> ?a } }
26263 { SELECT ?b WHERE { ?s <http://ex/p> ?b } }
26264 }"#,
26265 )
26266 .unwrap();
26267 let mut subs = Vec::new();
26268 find_subqueries(&plan.root, &mut subs);
26269 assert_eq!(subs.len(), 2, "{:?}", plan.root);
26270 let mut prefixes = Vec::new();
26271 for sub in &subs {
26272 let mut scans = Vec::new();
26273 collect_scans(&sub.inner, &mut scans);
26274 let renamed: Vec<&str> = scans
26275 .iter()
26276 .flat_map(|scan| [&scan.subject, &scan.object])
26277 .flatten()
26278 .map(Variable::as_str)
26279 .filter(|name| name.starts_with("sq_"))
26280 .collect();
26281 assert_eq!(
26282 renamed.len(),
26283 1,
26284 "the non-projected ?s is renamed exactly once per subquery: {renamed:?}"
26285 );
26286 let name = renamed[0];
26288 assert_eq!(name.len(), 3 + 16 + 1 + 1, "token is 16 chars: {name}");
26289 prefixes.push(name.trim_start_matches("sq_").split('_').next().unwrap());
26290 }
26291 assert_ne!(prefixes[0], prefixes[1], "tokens are per-subquery random");
26292 }
26293
26294 #[test]
26295 fn subselect_with_limit_keeps_boundary_schema() {
26296 let plan = LogicalPlan::parse(
26297 r#"SELECT ?x ?y WHERE {
26298 { SELECT ?x WHERE { ?s <http://ex/p> ?x } LIMIT 3 }
26299 ?x <http://ex/q> ?y .
26300 }"#,
26301 )
26302 .unwrap();
26303 let mut subs = Vec::new();
26304 find_subqueries(&plan.root, &mut subs);
26305 assert_eq!(subs.len(), 1, "{:?}", plan.root);
26306 assert_eq!(subs[0].variables, vec![var("x")]);
26307 assert!(
26310 matches!(
26311 subs[0].inner.as_ref(),
26312 PlanNode::Slice {
26313 length: Some(3),
26314 ..
26315 }
26316 ),
26317 "the boundary owns its LIMIT: {:?}",
26318 subs[0].inner
26319 );
26320 assert!(
26321 !matches!(plan.root, PlanNode::Slice { .. }),
26322 "no Slice may wrap the boundary from outside: {:?}",
26323 plan.root
26324 );
26325 }
26326
26327 #[test]
26328 fn subselect_modifier_spine_folds_inside_the_boundary() {
26329 let cases: &[(&str, bool, Option<u64>)] = &[
26335 ("SELECT ?x WHERE { ?s <http://ex/p> ?x }", false, None),
26336 (
26337 "SELECT DISTINCT ?x WHERE { ?s <http://ex/p> ?x }",
26338 true,
26339 None,
26340 ),
26341 (
26342 "SELECT ?x WHERE { ?s <http://ex/p> ?x } LIMIT 3",
26343 false,
26344 Some(3),
26345 ),
26346 (
26347 "SELECT DISTINCT ?x WHERE { ?s <http://ex/p> ?x } LIMIT 3",
26348 true,
26349 Some(3),
26350 ),
26351 ];
26352 for (select, distinct, limit) in cases {
26353 let query = format!("SELECT ?x WHERE {{ {{ {select} }} }}");
26354 let plan = LogicalPlan::parse(&query).unwrap();
26355 assert!(
26356 !matches!(
26357 plan.root,
26358 PlanNode::Slice { .. } | PlanNode::Distinct { .. }
26359 ),
26360 "{select}: no modifier may wrap the boundary: {:?}",
26361 plan.root
26362 );
26363 let mut subs = Vec::new();
26364 find_subqueries(&plan.root, &mut subs);
26365 assert_eq!(subs.len(), 1, "{select}: {:?}", plan.root);
26366 let sub = subs[0];
26367 assert_eq!(sub.variables, vec![var("x")], "{select}");
26368 let mut inner: &PlanNode = &sub.inner;
26371 match limit {
26372 Some(n) => {
26373 let PlanNode::Slice {
26374 inner: wrapped,
26375 length: Some(got),
26376 ..
26377 } = inner
26378 else {
26379 panic!("{select}: boundary must own its LIMIT: {:?}", sub.inner);
26380 };
26381 assert_eq!(*got, *n, "{select}");
26382 inner = wrapped;
26383 }
26384 None => assert!(
26385 !matches!(inner, PlanNode::Slice { .. }),
26386 "{select}: no LIMIT, no Slice: {:?}",
26387 sub.inner
26388 ),
26389 }
26390 if *distinct {
26391 let PlanNode::Distinct {
26392 inner: wrapped,
26393 columns,
26394 ..
26395 } = inner
26396 else {
26397 panic!("{select}: boundary must own its DISTINCT: {:?}", sub.inner);
26398 };
26399 assert_eq!(columns, &vec![var("x")], "{select}");
26400 inner = wrapped;
26401 } else {
26402 assert!(
26403 !matches!(inner, PlanNode::Distinct { .. }),
26404 "{select}: no DISTINCT, no Distinct: {:?}",
26405 sub.inner
26406 );
26407 }
26408 assert!(
26409 matches!(inner, PlanNode::Scan(_)),
26410 "{select}: body directly under the spine: {inner:?}"
26411 );
26412 }
26413 }
26414
26415 #[test]
26416 fn values_is_pushed_into_both_sibling_subqueries() {
26417 let plan = LogicalPlan::parse(
26418 r#"SELECT ?animal ?colour WHERE {
26419 VALUES ?city { <http://ex/brisbane> }
26420 {
26421 SELECT ?animal ?city WHERE {
26422 ?cat a <http://ex/Cat> .
26423 ?cat <http://ex/livesIn> ?city .
26424 BIND(?cat AS ?animal) .
26425 }
26426 }
26427 {
26428 SELECT ?animal ?city WHERE {
26429 ?dog a <http://ex/Dog> .
26430 ?dog <http://ex/livesIn> ?city .
26431 BIND(?dog AS ?animal) .
26432 }
26433 }
26434 ?animal <http://ex/hasColour> ?colour .
26435 }"#,
26436 )
26437 .unwrap();
26438 let brisbane = EncodedTerm::from(&NamedNode::new("http://ex/brisbane").unwrap());
26439 let mut subs = Vec::new();
26440 find_subqueries(&plan.root, &mut subs);
26441 assert_eq!(subs.len(), 2, "{:?}", plan.root);
26442 for sub in &subs {
26443 assert!(
26444 values_has_term(&sub.inner, &brisbane),
26445 "VALUES clone should join below the sub-SELECT boundary: {:?}",
26446 sub.inner
26447 );
26448 }
26449 assert!(
26451 values_has_term(&plan.root, &brisbane),
26452 "outer VALUES stays: {:?}",
26453 plan.root
26454 );
26455 }
26456
26457 #[test]
26458 fn ground_bind_pushes_into_subselect() {
26459 let plan = LogicalPlan::parse(
26464 r#"SELECT ?cat ?colour WHERE {
26465 BIND(<http://ex/brisbane> AS ?city)
26466 {
26467 SELECT ?cat ?city WHERE {
26468 ?cat a <http://ex/Cat> .
26469 ?cat <http://ex/livesIn> ?city .
26470 }
26471 }
26472 ?cat <http://ex/hasColour> ?colour .
26473 }"#,
26474 )
26475 .unwrap();
26476 let brisbane = EncodedTerm::from(&NamedNode::new("http://ex/brisbane").unwrap());
26477 let mut subs = Vec::new();
26478 find_subqueries(&plan.root, &mut subs);
26479 assert_eq!(subs.len(), 1, "{:?}", plan.root);
26480 assert!(
26481 values_has_term(&subs[0].inner, &brisbane),
26482 "ground BIND should ground the subquery: {:?}",
26483 subs[0].inner
26484 );
26485 }
26486
26487 #[test]
26488 fn outer_sameterm_grounds_subselect_scan_and_dead_projection_is_pruned() {
26489 let plan = LogicalPlan::parse(
26490 r#"SELECT ?cat ?colour WHERE {
26491 {
26492 SELECT ?cat ?city WHERE {
26493 ?cat a <http://ex/Cat> .
26494 ?cat <http://ex/livesIn> ?city .
26495 }
26496 }
26497 ?cat <http://ex/hasColour> ?colour .
26498 FILTER (sameTerm(?city, <http://ex/brisbane>))
26499 }"#,
26500 )
26501 .unwrap();
26502 let brisbane = EncodedTerm::from(&NamedNode::new("http://ex/brisbane").unwrap());
26503 let mut subs = Vec::new();
26504 find_subqueries(&plan.root, &mut subs);
26505 assert_eq!(subs.len(), 1, "{:?}", plan.root);
26506 let mut inner_scans = Vec::new();
26509 collect_scans(&subs[0].inner, &mut inner_scans);
26510 assert!(
26511 inner_scans
26512 .iter()
26513 .any(|scan| scan.pattern.object.as_ref() == Some(&brisbane)),
26514 "inner scan slot should be grounded: {:?}",
26515 subs[0].inner
26516 );
26517 assert_eq!(
26520 subs[0].variables,
26521 vec![var("cat")],
26522 "dead ?city projection should be pruned: {:?}",
26523 subs[0].inner
26524 );
26525 }
26526
26527 #[test]
26528 fn dead_projected_vars_are_pruned_from_the_boundary() {
26529 let plan = LogicalPlan::parse(
26530 r#"SELECT ?animal ?city ?colour WHERE {
26531 {
26532 SELECT ?animal ?city ?name1 WHERE {
26533 ?cat a <http://ex/Cat> .
26534 ?cat <http://ex/livesIn> ?city .
26535 ?cat <http://ex/hasName> ?name1 .
26536 BIND(?cat AS ?animal) .
26537 FILTER(strstarts(?name1, "A"))
26538 }
26539 }
26540 {
26541 SELECT ?animal ?city ?name2 WHERE {
26542 ?dog a <http://ex/Dog> .
26543 ?dog <http://ex/livesIn> ?city .
26544 ?dog <http://ex/hasName> ?name2 .
26545 BIND(?dog AS ?animal) .
26546 FILTER(strstarts(?name2, "A"))
26547 }
26548 }
26549 ?animal <http://ex/hasColour> ?colour .
26550 }"#,
26551 )
26552 .unwrap();
26553 let mut subs = Vec::new();
26554 find_subqueries(&plan.root, &mut subs);
26555 assert_eq!(subs.len(), 2, "{:?}", plan.root);
26556 for sub in &subs {
26557 assert_eq!(
26561 sub.variables,
26562 vec![var("animal"), var("city")],
26563 "dead projections should be pruned: {:?}",
26564 sub.inner
26565 );
26566 let mut inner_scans = Vec::new();
26567 collect_scans(&sub.inner, &mut inner_scans);
26568 assert!(
26569 inner_scans.iter().any(|scan| scan
26570 .object
26571 .as_ref()
26572 .is_some_and(|v| v.as_str().starts_with("name"))),
26573 "the name scan stays live for the inner FILTER: {:?}",
26574 sub.inner
26575 );
26576 }
26577 }
26578
26579 #[test]
26580 fn shared_projection_name_is_a_cross_boundary_join_key() {
26581 let plan = LogicalPlan::parse(
26582 r#"SELECT ?animal ?city ?colour WHERE {
26583 {
26584 SELECT ?animal ?city ?name WHERE {
26585 ?cat a <http://ex/Cat> .
26586 ?cat <http://ex/livesIn> ?city .
26587 ?cat <http://ex/hasName> ?name .
26588 BIND(?cat AS ?animal) .
26589 }
26590 }
26591 {
26592 SELECT ?animal ?city ?name WHERE {
26593 ?dog a <http://ex/Dog> .
26594 ?dog <http://ex/livesIn> ?city .
26595 ?dog <http://ex/hasName> ?name .
26596 BIND(?dog AS ?animal) .
26597 }
26598 }
26599 ?animal <http://ex/hasColour> ?colour .
26600 }"#,
26601 )
26602 .unwrap();
26603 let mut found = false;
26606 for_each_join(&plan.root, &mut |hash_keys| {
26607 if hash_keys.iter().any(|v| v.as_str() == "name") {
26608 found = true;
26609 }
26610 });
26611 assert!(found, "?name should be a join key: {:?}", plan.root);
26612 }
26613
26614 #[test]
26615 fn distinct_subselect_blocks_values_pushdown_but_stays_correct() {
26616 let plan = LogicalPlan::parse(
26617 r#"SELECT ?cat ?city WHERE {
26618 VALUES ?city { <http://ex/brisbane> }
26619 {
26620 SELECT DISTINCT ?cat ?city WHERE {
26621 ?cat a <http://ex/Cat> .
26622 ?cat <http://ex/livesIn> ?city .
26623 }
26624 }
26625 }"#,
26626 )
26627 .unwrap();
26628 let brisbane = EncodedTerm::from(&NamedNode::new("http://ex/brisbane").unwrap());
26629 let mut subs = Vec::new();
26630 find_subqueries(&plan.root, &mut subs);
26631 assert_eq!(subs.len(), 1, "{:?}", plan.root);
26632 assert!(
26633 !values_has_term(&subs[0].inner, &brisbane),
26634 "Distinct-spined subqueries are not pushed into in v1: {:?}",
26635 subs[0].inner
26636 );
26637 assert!(
26638 values_has_term(&plan.root, &brisbane),
26639 "outer VALUES still applies: {:?}",
26640 plan.root
26641 );
26642 }
26643
26644 #[test]
26645 fn order_by_in_subselect_lowers_inside_the_boundary() {
26646 let plan = LogicalPlan::parse(
26647 "SELECT ?x WHERE { { SELECT ?x WHERE { ?s <http://ex/p> ?x } ORDER BY ?x } }",
26648 )
26649 .expect("subselect ORDER BY must plan");
26650 let mut subs = Vec::new();
26651 find_subqueries(&plan.root, &mut subs);
26652 assert_eq!(subs.len(), 1, "{:?}", plan.root);
26653 assert!(
26654 matches!(subs[0].inner.as_ref(), PlanNode::Sort { .. }),
26655 "expected Sort inside SubSelect, got {:?}",
26656 subs[0].inner
26657 );
26658 }
26659
26660 #[test]
26661 fn exists_in_subselect_renames_inner_only_names() {
26662 let plan = LogicalPlan::parse(
26663 r#"SELECT ?x WHERE {
26664 { SELECT ?x WHERE { ?s <http://ex/p> ?x . FILTER(EXISTS { ?x <http://ex/q> ?z }) } }
26665 }"#,
26666 )
26667 .unwrap();
26668 let PlanNode::SubSelect(sub) = &plan.root else {
26669 panic!("expected SubSelect, got {:?}", plan.root);
26670 };
26671 let PlanNode::Filter { exists, .. } = sub.inner.as_ref() else {
26672 panic!("expected Filter inside subselect, got {:?}", sub.inner);
26673 };
26674 assert_eq!(exists.len(), 1);
26675 assert_eq!(exists[0].kind, ExistsKind::SemiJoin);
26676 assert_eq!(exists[0].correlation, vec![var("x")]);
26677 let PlanNode::Scan(scan) = exists[0].body.as_ref() else {
26678 panic!("expected Scan EXISTS body, got {:?}", exists[0].body);
26679 };
26680 assert_eq!(scan.subject, Some(var("x")));
26681 let object = scan.object.as_ref().expect("inner-only ?z");
26682 assert_ne!(object.as_str(), "z");
26683 assert!(
26684 object.as_str().starts_with("sq_"),
26685 "inner-only EXISTS var should be scope-renamed, got {object}"
26686 );
26687 }
26688
26689 #[test]
26690 fn nested_subselects_get_unique_scope_prefixes() {
26691 let plan = LogicalPlan::parse(
26692 r#"SELECT ?a WHERE {
26693 {
26694 SELECT ?a ?b WHERE {
26695 { SELECT ?b WHERE { ?s <http://ex/p> ?b } }
26696 ?a <http://ex/q> ?b .
26697 }
26698 }
26699 }"#,
26700 )
26701 .unwrap();
26702 let mut subs = Vec::new();
26703 find_subqueries(&plan.root, &mut subs);
26704 assert_eq!(subs.len(), 2, "{:?}", plan.root);
26705 let [inner, outer] = subs.as_slice() else {
26711 unreachable!("two sub-SELECT boundaries");
26712 };
26713 assert_eq!(outer.variables, vec![var("a")]);
26714 assert_eq!(inner.variables, vec![var("b")]);
26715 let mut inner_scans = Vec::new();
26716 collect_scans(&inner.inner, &mut inner_scans);
26717 let slot_names: Vec<String> = inner_scans
26718 .iter()
26719 .flat_map(|scan| [&scan.subject, &scan.object])
26720 .flatten()
26721 .map(Variable::as_str)
26722 .map(str::to_owned)
26723 .collect();
26724 assert!(
26725 slot_names
26726 .iter()
26727 .any(|name| name.starts_with("sq_") && name.ends_with("_s")),
26728 "the nested scope's own token renames ?s: {slot_names:?}"
26729 );
26730 assert!(
26731 slot_names.contains(&"b".to_owned()),
26732 "?b stays consistent through the middle scope: {slot_names:?}"
26733 );
26734 }
26735
26736 #[test]
26737 fn middle_layer_rename_extends_into_nested_boundary_subtree() {
26738 let plan = LogicalPlan::parse(
26743 r#"SELECT ?x WHERE {
26744 { SELECT ?x WHERE {
26745 { SELECT ?b WHERE { ?s <http://ex/p> ?b } }
26746 ?t <http://ex/q> ?b .
26747 BIND(?b AS ?x) .
26748 } }
26749 }"#,
26750 )
26751 .unwrap();
26752 let mut subs = Vec::new();
26753 find_subqueries(&plan.root, &mut subs);
26754 assert_eq!(subs.len(), 2, "{:?}", plan.root);
26755 let [inner, outer] = subs.as_slice() else {
26756 unreachable!("two sub-SELECT boundaries");
26757 };
26758 assert_eq!(
26759 outer.variables,
26760 vec![var("x")],
26761 "B1 schema: {:?}",
26762 plan.root
26763 );
26764 assert_eq!(inner.variables.len(), 1, "{:?}", inner.inner);
26767 let renamed = &inner.variables[0];
26768 assert_ne!(
26769 renamed.as_str(),
26770 "b",
26771 "B2's ?b is renamed in B1's scope: {renamed}"
26772 );
26773 let mut inner_scans = Vec::new();
26775 collect_scans(&inner.inner, &mut inner_scans);
26776 assert_eq!(inner_scans.len(), 1, "{:?}", inner.inner);
26777 assert_eq!(
26778 inner_scans[0].object.as_ref(),
26779 Some(renamed),
26780 "B2's subtree must bind the boundary's declared output name"
26781 );
26782 let mut outer_scans = Vec::new();
26785 collect_scans(&outer.inner, &mut outer_scans);
26786 assert!(
26787 outer_scans
26788 .iter()
26789 .any(|scan| scan.object.as_ref() == Some(renamed)),
26790 "B1's q-scan joins on the renamed name: {:?}",
26791 outer.inner
26792 );
26793 let mut inner_joins_named = false;
26794 for_each_join(&outer.inner, &mut |hash_keys| {
26795 if hash_keys.contains(renamed) {
26796 inner_joins_named = true;
26797 }
26798 });
26799 assert!(
26800 inner_joins_named,
26801 "the renamed name is a join key inside B1: {:?}",
26802 outer.inner
26803 );
26804 }
26805
26806 fn find_subqueries<'a>(node: &'a PlanNode, out: &mut Vec<&'a SubSelectOp>) {
26807 match node {
26808 PlanNode::SubSelect(sub) => {
26809 find_subqueries(&sub.inner, out);
26810 out.push(sub);
26811 }
26812 PlanNode::Join { left, right, .. }
26813 | PlanNode::LeftJoin { left, right, .. }
26814 | PlanNode::Union { left, right } => {
26815 find_subqueries(left, out);
26816 find_subqueries(right, out);
26817 }
26818 PlanNode::Filter { inner, .. }
26819 | PlanNode::Extend { inner, .. }
26820 | PlanNode::Slice { inner, .. }
26821 | PlanNode::Distinct { inner, .. }
26822 | PlanNode::Sort { inner, .. }
26823 | PlanNode::Group { inner, .. }
26824 | PlanNode::JoinGraphVar { inner, .. } => find_subqueries(inner, out),
26825 PlanNode::CustomNode(custom) => {
26826 for child in &custom.children {
26827 find_subqueries(child, out);
26828 }
26829 }
26830 PlanNode::Scan(_)
26831 | PlanNode::Path(_)
26832 | PlanNode::Values(_)
26833 | PlanNode::NamedGraphs { .. }
26834 | PlanNode::NamedGraphExists { .. }
26835 | PlanNode::DomainCounts { .. }
26836 | PlanNode::HeadCounts { .. }
26837 | PlanNode::PatternCount { .. }
26838 | PlanNode::Unit => {}
26839 }
26840 }
26841
26842 fn for_each_join(node: &PlanNode, f: &mut impl FnMut(&[Variable])) {
26843 match node {
26844 PlanNode::Join {
26845 hash_keys,
26846 left,
26847 right,
26848 ..
26849 } => {
26850 f(hash_keys);
26851 for_each_join(left, f);
26852 for_each_join(right, f);
26853 }
26854 PlanNode::Union { left, right } | PlanNode::LeftJoin { left, right, .. } => {
26855 for_each_join(left, f);
26856 for_each_join(right, f);
26857 }
26858 PlanNode::Filter { inner, .. }
26859 | PlanNode::Extend { inner, .. }
26860 | PlanNode::Slice { inner, .. }
26861 | PlanNode::Distinct { inner, .. }
26862 | PlanNode::Sort { inner, .. }
26863 | PlanNode::Group { inner, .. }
26864 | PlanNode::JoinGraphVar { inner, .. } => for_each_join(inner, f),
26865 PlanNode::SubSelect(sub) => for_each_join(&sub.inner, f),
26866 PlanNode::CustomNode(custom) => {
26867 for child in &custom.children {
26868 for_each_join(child, f);
26869 }
26870 }
26871 PlanNode::Scan(_)
26872 | PlanNode::Path(_)
26873 | PlanNode::Values(_)
26874 | PlanNode::NamedGraphs { .. }
26875 | PlanNode::NamedGraphExists { .. }
26876 | PlanNode::DomainCounts { .. }
26877 | PlanNode::HeadCounts { .. }
26878 | PlanNode::PatternCount { .. }
26879 | PlanNode::Unit => {}
26880 }
26881 }
26882
26883 #[test]
26884 fn ask_over_aggregate_subselect_is_slice_over_pattern_count() {
26885 let query = SparqlParser::new()
26886 .parse_query("ASK { SELECT (COUNT(*) AS ?c) WHERE { ?s <http://ex/p> ?o } }")
26887 .unwrap();
26888 let Query::Ask { pattern, .. } = query else {
26889 panic!("expected ASK");
26890 };
26891 let plan = LogicalPlan::from_ask_algebra(pattern, None).unwrap();
26892 match &plan.root {
26893 PlanNode::Slice {
26894 start,
26895 length,
26896 inner,
26897 } => {
26898 assert_eq!(*start, 0);
26899 assert_eq!(*length, Some(1));
26900 let count_node = match &**inner {
26904 PlanNode::Extend { inner, .. } => &**inner,
26905 other => other,
26906 };
26907 assert!(
26908 matches!(
26909 count_node,
26910 PlanNode::PatternCount {
26911 count_star: true,
26912 ..
26913 }
26914 ),
26915 "ASK SubSelect should lower to PatternCount: {inner:?}"
26916 );
26917 }
26918 other => panic!("expected Slice LIMIT 1 over PatternCount, got {other:?}"),
26919 }
26920 }
26921
26922 #[test]
26923 fn explain_sparql_keeps_limit() {
26924 let text =
26925 explain_optimised_sparql("SELECT ?s WHERE { ?s <http://ex/p> ?o } LIMIT 5 OFFSET 1");
26926 assert!(text.contains("LIMIT"), "{text}");
26927 assert!(text.contains("OFFSET"), "{text}");
26928 }
26929
26930 fn contains_filter(node: &PlanNode) -> bool {
26931 match node {
26932 PlanNode::Filter { .. } => true,
26933 PlanNode::Join { left, right, .. }
26934 | PlanNode::Union { left, right }
26935 | PlanNode::LeftJoin { left, right, .. } => {
26936 contains_filter(left) || contains_filter(right)
26937 }
26938 PlanNode::Extend { inner, .. }
26939 | PlanNode::Slice { inner, .. }
26940 | PlanNode::Distinct { inner, .. }
26941 | PlanNode::Sort { inner, .. }
26942 | PlanNode::Group { inner, .. } => contains_filter(inner),
26943 _ => false,
26944 }
26945 }
26946
26947 fn values_has_term(node: &PlanNode, term: &EncodedTerm) -> bool {
26948 match node {
26949 PlanNode::Values(values) => values
26950 .rows
26951 .iter()
26952 .any(|row| row.iter().any(|cell| cell.as_ref() == Some(term))),
26953 PlanNode::Join { left, right, .. }
26954 | PlanNode::Union { left, right }
26955 | PlanNode::LeftJoin { left, right, .. } => {
26956 values_has_term(left, term) || values_has_term(right, term)
26957 }
26958 PlanNode::Filter { inner, .. }
26959 | PlanNode::Extend { inner, .. }
26960 | PlanNode::Slice { inner, .. }
26961 | PlanNode::Distinct { inner, .. }
26962 | PlanNode::Sort { inner, .. }
26963 | PlanNode::Group { inner, .. } => values_has_term(inner, term),
26964 _ => false,
26965 }
26966 }
26967
26968 fn first_join_strategy(node: &PlanNode) -> Option<JoinStrategy> {
26969 match node {
26970 PlanNode::Join { meta, .. } => Some(meta.strategy),
26971 PlanNode::Slice { inner, .. }
26972 | PlanNode::Distinct { inner, .. }
26973 | PlanNode::Sort { inner, .. }
26974 | PlanNode::Filter { inner, .. }
26975 | PlanNode::Extend { inner, .. }
26976 | PlanNode::Group { inner, .. } => first_join_strategy(inner),
26977 PlanNode::LeftJoin { left, right, .. } | PlanNode::Union { left, right } => {
26978 first_join_strategy(left).or_else(|| first_join_strategy(right))
26979 }
26980 _ => None,
26981 }
26982 }
26983
26984 #[test]
26985 fn identity_equality_filter_grounds_scan_slot() {
26986 let sparql = r#"SELECT ?o WHERE { ?s <http://ex/hasWeather> ?o FILTER(?o = "Sunny") }"#;
26987 let plan = LogicalPlan::parse(sparql).unwrap();
26988 assert!(
26989 !contains_filter(&plan.root),
26990 "identity-safe = should fold into the scan, got {:?}",
26991 plan.root
26992 );
26993 let mut scans = Vec::new();
26994 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
26995 assert_eq!(scans.len(), 1);
26996 assert_eq!(scans[0].object.as_ref().map(Variable::as_str), Some("o"));
26997 assert_eq!(
26998 scans[0].pattern.object,
26999 Some(EncodedTerm::from(&Literal::from("Sunny")))
27000 );
27001 assert_eq!(plan.projection, vec![var("o")]);
27002
27003 let text = explain_est(sparql, None);
27004 assert!(
27005 text.contains("\"Sunny\""),
27006 "EXPLAIN should show the bound term: {text}"
27007 );
27008 assert!(
27009 !text.contains("(filter"),
27010 "folded equality should not leave a Filter node: {text}"
27011 );
27012 }
27013
27014 #[test]
27015 fn identity_equality_filter_grounds_iri_slot() {
27016 let plan = LogicalPlan::parse(
27017 r#"SELECT ?c WHERE { ?p <http://ex/livesIn> ?c FILTER(?c = <http://ex/Brisbane>) }"#,
27018 )
27019 .unwrap();
27020 assert!(
27021 !contains_filter(&plan.root),
27022 "IRI = should fold into the scan, got {:?}",
27023 plan.root
27024 );
27025 let mut scans = Vec::new();
27026 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
27027 assert_eq!(scans.len(), 1);
27028 assert_eq!(scans[0].object.as_ref().map(Variable::as_str), Some("c"));
27029 assert_eq!(
27030 scans[0].pattern.object,
27031 Some(EncodedTerm::from(
27032 &NamedNode::new("http://ex/Brisbane").unwrap()
27033 ))
27034 );
27035 }
27036
27037 #[test]
27038 fn identity_equality_and_grounds_both_scans() {
27039 let plan = LogicalPlan::parse(
27040 r#"SELECT ?s WHERE {
27041 ?s <http://ex/livesIn> ?c .
27042 ?c <http://ex/hasWeather> ?w
27043 FILTER(?c = <http://ex/Brisbane> && ?w = "Sunny")
27044 }"#,
27045 )
27046 .unwrap();
27047 assert!(
27048 !contains_filter(&plan.root),
27049 "&& of identity-safe equalities should fold, got {:?}",
27050 plan.root
27051 );
27052 let brisbane = EncodedTerm::from(&NamedNode::new("http://ex/Brisbane").unwrap());
27053 let sunny = EncodedTerm::from(&Literal::from("Sunny"));
27054 let mut saw_brisbane = false;
27055 let mut saw_sunny = false;
27056 for_each_scan(&plan.root, &mut |scan| {
27057 if scan.pattern.object.as_ref() == Some(&brisbane) {
27058 saw_brisbane = true;
27059 assert_eq!(scan.subject.as_ref().map(Variable::as_str), Some("s"));
27060 }
27061 if scan.pattern.object.as_ref() == Some(&sunny) {
27062 saw_sunny = true;
27063 assert_eq!(scan.object.as_ref().map(Variable::as_str), Some("w"));
27064 }
27065 });
27066 assert!(
27067 saw_brisbane && saw_sunny,
27068 "both slots should be ground, got {:?}",
27069 plan.root
27070 );
27071 }
27072
27073 #[test]
27074 fn numeric_equality_filter_is_not_folded() {
27075 let plan =
27076 LogicalPlan::parse(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v FILTER(?v = 1.0e0) }"#)
27077 .unwrap();
27078 assert!(
27079 !contains_filter(&plan.root),
27080 "the exact numeric = moves into the scan, got {:?}",
27081 plan.root
27082 );
27083 let PlanNode::Scan(scan) = &plan.root else {
27084 panic!("expected the scan root, got {:?}", plan.root);
27085 };
27086 assert!(
27087 scan.pattern.object.is_none(),
27088 "numeric = must not ground the scan: {scan:?}"
27089 );
27090 assert!(scan.eager.contains(&SlotComparison {
27091 slot: QuadSlot::Object,
27092 op: CompareOp::Eq,
27093 term: EncodedTerm::from(&Literal::from(1.0f64)),
27094 }));
27095 }
27096
27097 #[test]
27098 fn sameterm_filter_grounds_any_constant() {
27099 let plan = LogicalPlan::parse(
27100 r#"SELECT ?c WHERE { ?p <http://ex/livesIn> ?c FILTER(sameTerm(?c, <http://ex/Brisbane>)) }"#,
27101 )
27102 .unwrap();
27103 assert!(
27104 !contains_filter(&plan.root),
27105 "sameTerm should fold for any ground term, got {:?}",
27106 plan.root
27107 );
27108 let mut scans = Vec::new();
27109 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
27110 assert_eq!(
27111 scans[0].pattern.object,
27112 Some(EncodedTerm::from(
27113 &NamedNode::new("http://ex/Brisbane").unwrap()
27114 ))
27115 );
27116 }
27117
27118 #[test]
27119 fn bind_sameterm_grounds_scan_subject() {
27120 let iri = NamedNode::new("http://yago-knowledge.org/resource/Crow_Hill_Q20861371").unwrap();
27121 let plan = LogicalPlan::parse(
27122 r#"SELECT ?o ?b WHERE {
27123 ?b ?p ?o .
27124 BIND(<http://yago-knowledge.org/resource/Crow_Hill_Q20861371> AS ?c)
27125 FILTER(sameTerm(?b, ?c))
27126 }"#,
27127 )
27128 .unwrap();
27129 assert!(
27130 !contains_filter(&plan.root),
27131 "var-var sameTerm with grounded BIND should fold, got {:?}",
27132 plan.root
27133 );
27134 assert!(
27135 matches!(plan.root, PlanNode::Extend { .. }),
27136 "BIND column ?c should remain as Extend, got {:?}",
27137 plan.root
27138 );
27139 let mut scans = Vec::new();
27140 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
27141 assert_eq!(scans.len(), 1);
27142 assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("b"));
27143 assert_eq!(scans[0].pattern.subject, Some(EncodedTerm::from(&iri)));
27144 }
27145
27146 #[test]
27147 fn identity_filter_grounds_repeated_variable_slots() {
27148 let painting = NamedNode::new("http://schema.org/Painting").unwrap();
27149 let encoded = EncodedTerm::from(&painting);
27150 let sparql = r#"
27151 SELECT ?b WHERE {
27152 ?b a ?b .
27153 BIND(<http://schema.org/Painting> AS ?c)
27154 FILTER(sameTerm(?b, ?c))
27155 }
27156 "#;
27157 let plan = LogicalPlan::parse(sparql).unwrap();
27158 assert!(
27159 !contains_filter(&plan.root),
27160 "identity-safe sameTerm should fold, got {:?}",
27161 plan.root
27162 );
27163 let mut scans = Vec::new();
27164 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
27165 assert_eq!(scans.len(), 1);
27166 assert_eq!(scans[0].pattern.subject, Some(encoded.clone()));
27167 assert_eq!(scans[0].pattern.object, Some(encoded));
27168 assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("b"));
27169 assert_eq!(scans[0].object.as_ref().map(Variable::as_str), Some("b"));
27170 assert!(
27171 scans[0].broadcasted.is_none(),
27172 "identity fold should not stamp broadcast, got {:?}",
27173 scans[0].broadcasted
27174 );
27175 assert_eq!(
27176 grounded_of(scans[0]),
27177 vec![("b", PatternSlot::Subject), ("b", PatternSlot::Object)],
27178 "both repeated ?b slots should be grounded, got {:?}",
27179 scans[0].grounded
27180 );
27181 assert_eq!(
27182 scans[0].produced_row_count_estimate, 1,
27183 "fully bound triple is a point lookup"
27184 );
27185 let text = explain_est(sparql, None);
27186 assert!(
27187 text.contains("(grounded ?b subject, ?b object)"),
27188 "EXPLAIN should list both grounded slots: {text}"
27189 );
27190 }
27191
27192 fn painting_identity_fold_sparql() -> &'static str {
27193 r#"
27194 SELECT ?s ?b WHERE {
27195 ?s a ?b .
27196 ?b a ?b .
27197 BIND(<http://ex/Painting> AS ?c)
27198 FILTER(sameTerm(?b, ?c))
27199 }
27200 "#
27201 }
27202
27203 fn painting_class_profile() -> (NamedNode, StatsProfile) {
27204 let painting = NamedNode::new("http://ex/Painting").unwrap();
27205 let mut profile = StatsProfile::default();
27206 profile.predicate_counts.insert(
27207 waratah_storage::StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
27208 50_000_000,
27209 );
27210 profile
27211 .class_counts
27212 .insert(waratah_storage::StrHash::new("http://ex/Painting"), 910_224);
27213 profile.total_puts = 50_000_000;
27214 (painting, profile)
27215 }
27216
27217 #[test]
27218 fn refinalize_swaps_selective_scan_left() {
27219 let (painting, profile) = painting_class_profile();
27220 let painting_term = EncodedTerm::from(&painting);
27221 let plan = LogicalPlan::parse_with_profile(painting_identity_fold_sparql(), Some(&profile))
27222 .unwrap();
27223 let PlanNode::Join {
27224 left, right, meta, ..
27225 } = find_inner_join(&plan.root)
27226 else {
27227 panic!("expected Join, got {:?}", plan.root);
27228 };
27229 let PlanNode::Scan(left_scan) = left.as_ref() else {
27230 panic!("expected left Scan after swap, got {left:?}");
27231 };
27232 let PlanNode::Scan(right_scan) = right.as_ref() else {
27233 panic!("expected right Scan after swap, got {right:?}");
27234 };
27235 assert_eq!(
27236 bound_slots(&left_scan.pattern),
27237 4,
27238 "point lookup should drive: {left_scan:?}"
27239 );
27240 assert_eq!(left_scan.produced_row_count_estimate, 1);
27241 assert_eq!(right_scan.pattern.object.as_ref(), Some(&painting_term));
27242 assert_eq!(right_scan.produced_row_count_estimate, 910_224);
27246 assert_eq!(
27253 right_scan.join_domains.get(JoinKeySlot::Subject),
27254 JoinDomainStamp::Known(910_224),
27255 "identity-fold grounding must promote the rdf:type subject stamp"
27256 );
27257 assert!(
27258 right_scan.broadcasted.is_none(),
27259 "grounded key slot must not be claimed, got {:?}",
27260 right_scan.broadcasted
27261 );
27262 assert_eq!(meta.produced_row_count_estimate, 910_224);
27263 assert!(
27264 left_scan.broadcasted.is_none(),
27265 "driver must not keep probe broadcast, got {:?}",
27266 left_scan.broadcasted
27267 );
27268 }
27269
27270 #[test]
27271 fn refinalize_promotes_broadcast_after_swap() {
27272 let (_, profile) = painting_class_profile();
27273 let plan = LogicalPlan::parse_with_profile(painting_identity_fold_sparql(), Some(&profile))
27274 .unwrap();
27275 let PlanNode::Join { right, meta, .. } = find_inner_join(&plan.root) else {
27276 panic!("expected Join, got {:?}", plan.root);
27277 };
27278 assert_eq!(
27279 meta.strategy,
27280 JoinStrategy::Broadcast,
27281 "1-row driver after swap should Broadcast, got {:?}",
27282 meta.strategy
27283 );
27284 let PlanNode::Scan(right_scan) = right.as_ref() else {
27285 panic!("expected class scan on the right, got {right:?}");
27286 };
27287 assert_eq!(right_scan.produced_row_count_estimate, 910_224);
27290 assert!(
27291 right_scan.broadcasted.is_none(),
27292 "grounded key slot must not be claimed, got {:?}",
27293 right_scan.broadcasted
27294 );
27295 let text = explain_est(painting_identity_fold_sparql(), Some(&profile));
27296 assert!(
27297 text.contains("(domain ?b 1)"),
27298 "grounded join key domain is 1: {text}"
27299 );
27300 }
27301
27302 fn var_scan(subject: Option<&str>, predicate: &str, object: Option<&str>, rows: u64) -> ScanOp {
27306 ScanOp {
27307 ancestor_push_return_bound: None,
27308 fetch_once: None,
27309 pattern: EncodedTriplePattern {
27310 subject: None,
27311 predicate: Some(EncodedTerm::from(&NamedNode::new(predicate).unwrap())),
27312 object: None,
27313 graph_name: None,
27314 },
27315 subject: subject.map(|v| Variable::new(v).unwrap()),
27316 predicate: None,
27317 object: object.map(|v| Variable::new(v).unwrap()),
27318 graph: None,
27319 produced_row_count_estimate: rows,
27320 broadcasted: None,
27321 graph_filter: None,
27322 grounded: Vec::new(),
27323 merge_default_graph: false,
27324 marks: Vec::new(),
27325 domain_scan: None,
27326 head_scan: None,
27327 head_scan_counts: None,
27328 domain_counts: None,
27329 iri_only: Vec::new(),
27330 eager: Vec::new(),
27331 join_domains: crate::plan::JoinDomainStamps::default(),
27332 }
27333 }
27334
27335 fn values_node(var: &str, terms: &[&str]) -> PlanNode {
27336 PlanNode::Values(ValuesOp {
27337 variables: vec![Variable::new(var).unwrap()],
27338 rows: terms
27339 .iter()
27340 .map(|t| vec![Some(EncodedTerm::from(&NamedNode::new(*t).unwrap()))])
27341 .collect(),
27342 strings: Vec::new(),
27343 blobs: Vec::new(),
27344 })
27345 }
27346
27347 fn broadcast_join(left: PlanNode, right: PlanNode, keys: &[&str], rows: u64) -> PlanNode {
27348 PlanNode::Join {
27349 left: Box::new(left),
27350 right: Box::new(right),
27351 hash_keys: keys.iter().map(|k| Variable::new(*k).unwrap()).collect(),
27352 probe_key_domains: Vec::new(),
27353 probe_key_overlap_milli: Vec::new(),
27354 rhs_hostable_keys: Vec::new().into(),
27355 meta: JoinMeta {
27356 semi_gate: None,
27357 star_arms: None,
27358 strategy: JoinStrategy::Broadcast,
27359 produced_row_count_estimate: rows,
27360 own_push_removed_row_count_estimate: rows,
27361 },
27362 }
27363 }
27364
27365 fn left_join_node(left: PlanNode, right: PlanNode, keys: &[&str], rows: u64) -> PlanNode {
27366 PlanNode::LeftJoin {
27367 left: Box::new(left),
27368 right: Box::new(right),
27369 hash_keys: keys.iter().map(|k| Variable::new(*k).unwrap()).collect(),
27370 probe_key_domains: Vec::new(),
27371 probe_key_overlap_milli: Vec::new(),
27372 early_filter: None,
27373 residual_filter: None,
27374 meta: LeftJoinMeta {
27375 produced_row_count_estimate: rows,
27376 own_push_removed_row_count_estimate: rows,
27377 },
27378 }
27379 }
27380
27381 #[test]
27386 fn restamp_claims_outermost_join_first() {
27387 let inner_alone = broadcast_join(
27390 values_node("z", &["http://ex/z1", "http://ex/z2"]),
27391 PlanNode::Scan(var_scan(Some("y"), "http://ex/p", Some("z"), 1_000)),
27392 &["z"],
27393 100,
27394 );
27395 let mut control = inner_alone;
27396 restamp_broadcast_marks(&mut control, None);
27397 let PlanNode::Join { right, .. } = &control else {
27398 panic!("expected Join, got {control:?}")
27399 };
27400 let PlanNode::Scan(scan) = right.as_ref() else {
27401 panic!("expected Scan probe, got {right:?}")
27402 };
27403 assert_eq!(
27404 scan.broadcasted.as_ref().map(|(v, s)| (v.as_str(), *s)),
27405 Some(("z", PatternSlot::Object)),
27406 "inner join alone claims its own key: {:?}",
27407 scan.broadcasted
27408 );
27409
27410 let inner = broadcast_join(
27413 values_node("z", &["http://ex/z1", "http://ex/z2"]),
27414 PlanNode::Scan(var_scan(Some("y"), "http://ex/p", Some("z"), 1_000)),
27415 &["z"],
27416 100,
27417 );
27418 let mut nested = broadcast_join(
27419 values_node("y", &["http://ex/y1", "http://ex/y2"]),
27420 inner,
27421 &["y"],
27422 10,
27423 );
27424 restamp_broadcast_marks(&mut nested, None);
27425 let mut shared: Option<&ScanOp> = None;
27426 for_each_scan(&nested, &mut |scan| {
27427 if scan.broadcasted.is_some() {
27428 assert!(shared.is_none(), "exactly one claimed scan: {nested:?}");
27429 shared = Some(scan);
27430 }
27431 });
27432 let shared = shared.expect("the shared scan is claimed exactly once");
27433 assert_eq!(
27434 shared.broadcasted.as_ref().map(|(v, s)| (v.as_str(), *s)),
27435 Some(("y", PatternSlot::Subject)),
27436 "the OUTER join's key wins the claim: {:?}",
27437 shared.broadcasted
27438 );
27439 assert_eq!(
27440 shared.produced_row_count_estimate, 2,
27441 "claim-clamp prices the probe at the driver's key domain"
27442 );
27443 }
27444
27445 #[test]
27448 fn claim_clamp_is_monotone_min() {
27449 let mut big = broadcast_join(
27452 values_node("b", &["http://ex/k1", "http://ex/k2", "http://ex/k3"]),
27453 PlanNode::Scan(var_scan(Some("b"), "http://ex/p", Some("c"), 10)),
27454 &["b"],
27455 10,
27456 );
27457 restamp_broadcast_marks(&mut big, None);
27458 let PlanNode::Join { right, .. } = &big else {
27459 panic!("expected Join, got {big:?}")
27460 };
27461 let PlanNode::Scan(scan) = right.as_ref() else {
27462 panic!("expected Scan probe, got {right:?}")
27463 };
27464 assert_eq!(
27465 scan.produced_row_count_estimate, 3,
27466 "clamp lowers to the key domain"
27467 );
27468
27469 let mut small = broadcast_join(
27470 values_node("b", &["http://ex/k1", "http://ex/k2", "http://ex/k3"]),
27471 PlanNode::Scan(var_scan(Some("b"), "http://ex/p", Some("c"), 2)),
27472 &["b"],
27473 2,
27474 );
27475 restamp_broadcast_marks(&mut small, None);
27476 let PlanNode::Join { right, .. } = &small else {
27477 panic!("expected Join, got {small:?}")
27478 };
27479 let PlanNode::Scan(scan) = right.as_ref() else {
27480 panic!("expected Scan probe, got {right:?}")
27481 };
27482 assert_eq!(
27483 scan.produced_row_count_estimate, 2,
27484 "a clamp must never RAISE a cheaper exact estimate"
27485 );
27486 assert!(scan.broadcasted.is_some(), "still claimed");
27487 }
27488
27489 #[test]
27494 fn pushed_scan_return_bound_multiplies_fan_out() {
27495 let klass = EncodedTerm::from(&NamedNode::new("http://ex/Klass").unwrap());
27496 let klass_domain = |count: u64| {
27497 let mut profile = StatsProfile::default();
27498 profile
27499 .class_counts
27500 .insert(StrHash::new("http://ex/Klass"), count);
27501 profile
27502 };
27503 let class_type_scan = |price: u64| ScanOp {
27505 ancestor_push_return_bound: None,
27506 fetch_once: None,
27507 pattern: EncodedTriplePattern {
27508 subject: None,
27509 predicate: Some(RDF_TYPE.clone()),
27510 object: Some(klass.clone()),
27511 graph_name: None,
27512 },
27513 subject: Some(var("class")),
27514 predicate: None,
27515 object: None,
27516 graph: None,
27517 produced_row_count_estimate: price,
27518 broadcasted: None,
27519 graph_filter: None,
27520 grounded: Vec::new(),
27521 merge_default_graph: false,
27522 marks: vec![(var("class"), Liveness::Live, BagMark::Sensitive)],
27523 domain_scan: None,
27524 head_scan: None,
27525 head_scan_counts: None,
27526 domain_counts: None,
27527 iri_only: Vec::new(),
27528 eager: Vec::new(),
27529 join_domains: crate::plan::JoinDomainStamps::default(),
27530 };
27531 let key = var("class");
27532 assert_eq!(
27535 pushed_scan_return_bound(
27536 100,
27537 5_000,
27538 &class_type_scan(5_000),
27539 &key,
27540 Some(&klass_domain(1_000))
27541 ),
27542 500
27543 );
27544 assert_eq!(
27547 pushed_scan_return_bound(
27548 500,
27549 1_000,
27550 &class_type_scan(1_000),
27551 &key,
27552 Some(&klass_domain(2))
27553 ),
27554 1_000
27555 );
27556 assert_eq!(
27558 pushed_scan_return_bound(
27559 10_000,
27560 100,
27561 &class_type_scan(100),
27562 &key,
27563 Some(&klass_domain(1_000))
27564 ),
27565 100
27566 );
27567 let unprofiled = var_scan(Some("class"), "http://ex/other", None, 100);
27570 assert_eq!(
27571 pushed_scan_return_bound(10, 100, &unprofiled, &key, None),
27572 10,
27573 "no probe domain → fan-out 1 → min(price, pushed values)"
27574 );
27575 }
27576
27577 #[test]
27586 fn independent_optionals_rotate_small_fanout_first() {
27587 let mut profile = StatsProfile::default();
27588 profile
27589 .class_counts
27590 .insert(StrHash::new("http://ex/Klass"), 21_124);
27591 profile
27592 .predicate_counts
27593 .insert(StrHash::new("http://ex/label"), 376_482);
27594 profile
27595 .subjects_per_predicate
27596 .insert(StrHash::new("http://ex/label"), hll_with_n(11_025));
27597 profile
27598 .predicate_counts
27599 .insert(StrHash::new("http://ex/sub"), 13_968);
27600 profile
27601 .subjects_per_predicate
27602 .insert(StrHash::new("http://ex/sub"), hll_with_n(10_718));
27603 profile.total_puts = 500_000;
27604 let sparql = r#"
27605 SELECT ?class ?label ?parent WHERE {
27606 ?class a <http://ex/Klass> .
27607 OPTIONAL { ?class <http://ex/label> ?label }
27608 OPTIONAL { ?class <http://ex/sub> ?parent }
27609 }
27610 "#;
27611 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
27612 let outer = outermost_left_join(&plan.root);
27616 let PlanNode::LeftJoin {
27617 left: inner_join,
27618 right: outer_right,
27619 ..
27620 } = outer
27621 else {
27622 panic!("expected the outermost LeftJoin, got {:#?}", plan.root)
27623 };
27624 let outer_rows = outer_right.produced_row_count_estimate();
27628 assert!(
27629 outer_rows >= 300_000,
27630 "outer optional must be the label side (~376k), got {outer_rows}: {outer_right:#?}"
27631 );
27632 let PlanNode::LeftJoin {
27633 right: inner_right,
27634 meta: inner_meta,
27635 ..
27636 } = inner_join.as_ref()
27637 else {
27638 panic!("expected the rotated inner LeftJoin, got {inner_join:#?}")
27639 };
27640 let inner_rows = inner_right.produced_row_count_estimate();
27641 assert!(
27642 inner_rows <= 20_000,
27643 "inner optional must be the subClassOf side (~14k), got {inner_rows}"
27644 );
27645 let card_sub = profile
27648 .subjects_per_predicate
27649 .get(&StrHash::new("http://ex/sub"))
27650 .map(|hll| hll.cardinality())
27651 .unwrap_or(10_718);
27652 let expected_inner = (21_124u64).saturating_sub(card_sub) + 13_968;
27653 assert_eq!(
27654 inner_meta.produced_row_count_estimate, expected_inner,
27655 "rotated inner prices at unmatched + subClassOf rows"
27656 );
27657 }
27658
27659 #[test]
27664 fn independent_optional_delays_past_later_required_pattern() {
27665 let mut profile = StatsProfile::default();
27666 profile
27667 .class_counts
27668 .insert(StrHash::new("http://ex/Person"), 1_000);
27669 profile
27670 .predicate_counts
27671 .insert(StrHash::new("http://ex/email"), 3_000);
27672 profile
27673 .subjects_per_predicate
27674 .insert(StrHash::new("http://ex/email"), hll_with_n(1_000));
27675 profile
27676 .predicate_counts
27677 .insert(StrHash::new("http://ex/worksIn"), 1_000);
27678 profile
27679 .subjects_per_predicate
27680 .insert(StrHash::new("http://ex/worksIn"), hll_with_n(1_000));
27681 profile.total_puts = 10_000;
27682 let sparql = r#"
27683 SELECT ?p ?email ?dept WHERE {
27684 ?p a <http://ex/Person> .
27685 OPTIONAL { ?p <http://ex/email> ?email }
27686 ?p <http://ex/worksIn> ?dept .
27687 }
27688 "#;
27689 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
27690 fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
27691 match node {
27692 PlanNode::Scan(scan) => {
27693 scan.pattern.predicate.as_ref()
27694 == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
27695 }
27696 PlanNode::Join { left, right, .. }
27697 | PlanNode::Union { left, right }
27698 | PlanNode::LeftJoin { left, right, .. } => {
27699 scan_with_predicate(left, iri) || scan_with_predicate(right, iri)
27700 }
27701 PlanNode::Filter { inner, .. } => scan_with_predicate(inner, iri),
27702 _ => false,
27703 }
27704 }
27705 let outer = outermost_left_join(&plan.root);
27706 let PlanNode::LeftJoin { left, right, .. } = outer else {
27707 panic!("expected the delayed LeftJoin, got {:#?}", plan.root)
27708 };
27709 assert!(
27710 scan_with_predicate(right, "http://ex/email"),
27711 "the OPTIONAL arm stays the outer right: {right:#?}"
27712 );
27713 assert!(
27714 scan_with_predicate(left, "http://ex/worksIn"),
27715 "the later required pattern moved under the required side: {left:#?}"
27716 );
27717 assert!(
27718 !scan_with_predicate(left, "http://ex/email"),
27719 "no email scan below the delay: {left:#?}"
27720 );
27721 }
27722
27723 #[test]
27727 fn independent_optional_delays_and_keeps_the_boundary_schema() {
27728 let mut profile = StatsProfile::default();
27729 profile
27730 .predicate_counts
27731 .insert(StrHash::new("http://ex/kind"), 100);
27732 profile
27733 .predicate_counts
27734 .insert(StrHash::new("http://ex/email"), 300);
27735 profile
27736 .predicate_counts
27737 .insert(StrHash::new("http://ex/worksIn"), 100);
27738 profile
27739 .subjects_per_predicate
27740 .insert(StrHash::new("http://ex/kind"), hll_with_n(100));
27741 profile
27742 .subjects_per_predicate
27743 .insert(StrHash::new("http://ex/email"), hll_with_n(100));
27744 profile
27745 .subjects_per_predicate
27746 .insert(StrHash::new("http://ex/worksIn"), hll_with_n(100));
27747 profile.total_puts = 1_000;
27748 let mut node = PlanNode::Join {
27749 left: Box::new(left_join_node(
27750 PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
27751 PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 300)),
27752 &["p"],
27753 300,
27754 )),
27755 right: Box::new(PlanNode::Scan(var_scan(
27756 Some("p"),
27757 "http://ex/worksIn",
27758 Some("d"),
27759 100,
27760 ))),
27761 hash_keys: vec![var("p")],
27762 probe_key_domains: Vec::new(),
27763 probe_key_overlap_milli: Vec::new(),
27764 rhs_hostable_keys: Vec::new().into(),
27765 meta: JoinMeta {
27766 semi_gate: None,
27767 star_arms: None,
27768 strategy: JoinStrategy::Hash,
27769 produced_row_count_estimate: 300,
27770 own_push_removed_row_count_estimate: 300,
27771 },
27772 };
27773 refinalize_joins_without_ctx(&mut node, Some(&profile));
27774 let PlanNode::LeftJoin { left, right, .. } = &node else {
27775 panic!("expected the delayed LeftJoin, got {node:#?}")
27776 };
27777 assert!(
27778 matches!(right.as_ref(), PlanNode::Scan(scan) if scan.pattern.predicate.as_ref()
27779 == Some(&EncodedTerm::from(&NamedNode::new("http://ex/email").unwrap()))),
27780 "the OPTIONAL arm stays the outer right: {right:#?}"
27781 );
27782 assert!(
27783 matches!(left.as_ref(), PlanNode::Join { .. }),
27784 "the required side re-united as a Join: {left:#?}"
27785 );
27786 let after = node.output_vars();
27787 let mut always: Vec<&str> = after.always_bound.iter().map(Variable::as_str).collect();
27790 let mut maybe: Vec<&str> = after.maybe_unbound.iter().map(Variable::as_str).collect();
27791 always.sort_unstable();
27792 maybe.sort_unstable();
27793 assert_eq!(
27794 (always, maybe),
27795 (vec!["d", "k", "p"], vec!["e"]),
27796 "boundary schema unchanged by the delay"
27797 );
27798 }
27799
27800 #[test]
27804 fn optional_delay_blocked_when_required_mentions_optional_var() {
27805 let mut profile = StatsProfile::default();
27806 profile
27807 .class_counts
27808 .insert(StrHash::new("http://ex/Person"), 1_000);
27809 profile
27810 .predicate_counts
27811 .insert(StrHash::new("http://ex/email"), 3_000);
27812 profile
27813 .subjects_per_predicate
27814 .insert(StrHash::new("http://ex/email"), hll_with_n(1_000));
27815 profile
27816 .predicate_counts
27817 .insert(StrHash::new("http://ex/worksIn"), 1_000);
27818 profile
27819 .subjects_per_predicate
27820 .insert(StrHash::new("http://ex/worksIn"), hll_with_n(1_000));
27821 profile
27822 .predicate_counts
27823 .insert(StrHash::new("http://ex/x"), 500);
27824 profile.total_puts = 10_000;
27825 let sparql = r#"
27826 SELECT ?p ?email ?y WHERE {
27827 ?p a <http://ex/Person> .
27828 OPTIONAL { ?p <http://ex/email> ?email }
27829 ?p <http://ex/worksIn> ?dept .
27830 ?email <http://ex/x> ?y .
27831 }
27832 "#;
27833 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
27834 fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
27835 match node {
27836 PlanNode::Scan(scan) => {
27837 scan.pattern.predicate.as_ref()
27838 == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
27839 }
27840 PlanNode::Join { left, right, .. }
27841 | PlanNode::Union { left, right }
27842 | PlanNode::LeftJoin { left, right, .. } => {
27843 scan_with_predicate(left, iri) || scan_with_predicate(right, iri)
27844 }
27845 PlanNode::Filter { inner, .. } => scan_with_predicate(inner, iri),
27846 _ => false,
27847 }
27848 }
27849 let outer = outermost_left_join(&plan.root);
27850 let PlanNode::LeftJoin { left, .. } = outer else {
27851 panic!("expected the outermost LeftJoin, got {:#?}", plan.root)
27852 };
27853 assert!(
27854 !scan_with_predicate(left, "http://ex/worksIn"),
27855 "the required pattern reading ?email must stay ABOVE the optional: {left:#?}"
27856 );
27857 }
27858
27859 #[test]
27862 fn optional_delay_blocked_when_optional_key_not_bound_by_left() {
27863 let mut node = PlanNode::Join {
27864 left: Box::new(left_join_node(
27865 PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
27866 PlanNode::Scan(var_scan(Some("x"), "http://ex/email", Some("e"), 300)),
27867 &["x"],
27868 300,
27869 )),
27870 right: Box::new(PlanNode::Scan(var_scan(
27871 Some("p"),
27872 "http://ex/worksIn",
27873 Some("d"),
27874 100,
27875 ))),
27876 hash_keys: vec![var("p")],
27877 probe_key_domains: Vec::new(),
27878 probe_key_overlap_milli: Vec::new(),
27879 rhs_hostable_keys: Vec::new().into(),
27880 meta: JoinMeta {
27881 semi_gate: None,
27882 star_arms: None,
27883 strategy: JoinStrategy::Hash,
27884 produced_row_count_estimate: 300,
27885 own_push_removed_row_count_estimate: 300,
27886 },
27887 };
27888 assert!(
27889 !delay_optional_through_join(&mut node, None),
27890 "?x is not bound by the required side"
27891 );
27892 assert!(matches!(node, PlanNode::Join { .. }), "shape unchanged");
27893 }
27894
27895 #[test]
27898 fn optional_delay_blocked_within_margin() {
27899 let mut profile = StatsProfile::default();
27900 profile
27901 .predicate_counts
27902 .insert(StrHash::new("http://ex/kind"), 100);
27903 profile
27904 .predicate_counts
27905 .insert(StrHash::new("http://ex/email"), 100);
27906 profile
27907 .predicate_counts
27908 .insert(StrHash::new("http://ex/worksIn"), 100);
27909 profile
27910 .subjects_per_predicate
27911 .insert(StrHash::new("http://ex/kind"), hll_with_n(100));
27912 profile
27913 .subjects_per_predicate
27914 .insert(StrHash::new("http://ex/email"), hll_with_n(100));
27915 profile
27916 .subjects_per_predicate
27917 .insert(StrHash::new("http://ex/worksIn"), hll_with_n(100));
27918 profile.total_puts = 1_000;
27919 let mut node = PlanNode::Join {
27920 left: Box::new(left_join_node(
27921 PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
27922 PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 100)),
27923 &["p"],
27924 100,
27925 )),
27926 right: Box::new(PlanNode::Scan(var_scan(
27927 Some("p"),
27928 "http://ex/worksIn",
27929 Some("d"),
27930 100,
27931 ))),
27932 hash_keys: vec![var("p")],
27933 probe_key_domains: Vec::new(),
27934 probe_key_overlap_milli: Vec::new(),
27935 rhs_hostable_keys: Vec::new().into(),
27936 meta: JoinMeta {
27937 semi_gate: None,
27938 star_arms: None,
27939 strategy: JoinStrategy::Hash,
27940 produced_row_count_estimate: 100,
27941 own_push_removed_row_count_estimate: 100,
27942 },
27943 };
27944 refinalize_joins_without_ctx(&mut node, Some(&profile));
27945 assert!(
27946 matches!(node, PlanNode::Join { .. }),
27947 "equal stage sums: the margin must decline, got {node:#?}"
27948 );
27949 }
27950
27951 #[test]
27956 fn optional_delay_blocked_when_required_shares_nothing() {
27957 let mut node = PlanNode::Join {
27958 left: Box::new(left_join_node(
27959 PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
27960 PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 300)),
27961 &["p"],
27962 300,
27963 )),
27964 right: Box::new(PlanNode::Scan(var_scan(
27965 Some("z"),
27966 "http://ex/q",
27967 Some("w"),
27968 50,
27969 ))),
27970 hash_keys: Vec::new(),
27971 probe_key_domains: Vec::new(),
27972 probe_key_overlap_milli: Vec::new(),
27973 rhs_hostable_keys: Vec::new().into(),
27974 meta: JoinMeta {
27975 semi_gate: None,
27976 star_arms: None,
27977 strategy: JoinStrategy::Hash,
27978 produced_row_count_estimate: 15_000,
27979 own_push_removed_row_count_estimate: 15_000,
27980 },
27981 };
27982 let _ = &mut node;
27983 assert!(
27984 !delay_optional_through_join(&mut node, None),
27985 "a cartesian R must not move under the OPTIONAL"
27986 );
27987 assert!(matches!(node, PlanNode::Join { .. }), "shape unchanged");
27988 }
27989
27990 #[test]
27996 fn optional_delay_blocked_when_filter_reads_required_side_var() {
27997 let mut profile = StatsProfile::default();
27998 profile
27999 .class_counts
28000 .insert(StrHash::new("http://ex/Person"), 1_000);
28001 profile
28002 .predicate_counts
28003 .insert(StrHash::new("http://ex/email"), 3_000);
28004 profile
28005 .subjects_per_predicate
28006 .insert(StrHash::new("http://ex/email"), hll_with_n(1_000));
28007 profile
28008 .predicate_counts
28009 .insert(StrHash::new("http://ex/worksIn"), 1_000);
28010 profile
28011 .subjects_per_predicate
28012 .insert(StrHash::new("http://ex/worksIn"), hll_with_n(1_000));
28013 profile.total_puts = 10_000;
28014 let sparql = r#"
28015 SELECT ?p ?email ?dept WHERE {
28016 ?p a <http://ex/Person> .
28017 OPTIONAL { ?p <http://ex/email> ?email . FILTER(?email = ?dept) }
28018 ?p <http://ex/worksIn> ?dept .
28019 }
28020 "#;
28021 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28022 fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
28023 match node {
28024 PlanNode::Scan(scan) => {
28025 scan.pattern.predicate.as_ref()
28026 == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
28027 }
28028 PlanNode::Join { left, right, .. }
28029 | PlanNode::Union { left, right }
28030 | PlanNode::LeftJoin { left, right, .. } => {
28031 scan_with_predicate(left, iri) || scan_with_predicate(right, iri)
28032 }
28033 PlanNode::Filter { inner, .. } => scan_with_predicate(inner, iri),
28034 _ => false,
28035 }
28036 }
28037 let outer = outermost_left_join(&plan.root);
28038 let PlanNode::LeftJoin { left, .. } = outer else {
28039 panic!("expected the outermost LeftJoin, got {:#?}", plan.root)
28040 };
28041 assert!(
28042 !scan_with_predicate(left, "http://ex/worksIn"),
28043 "a filter reading ?dept pins the OPTIONAL in place: {left:#?}"
28044 );
28045 }
28046
28047 #[test]
28051 fn optional_delay_blocked_when_union_arm_mentions_optional_var() {
28052 let mut node = PlanNode::Join {
28053 left: Box::new(left_join_node(
28054 PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
28055 PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 300)),
28056 &["p"],
28057 300,
28058 )),
28059 right: Box::new(PlanNode::Union {
28060 left: Box::new(PlanNode::Scan(var_scan(
28061 Some("p"),
28062 "http://ex/worksIn",
28063 Some("d"),
28064 100,
28065 ))),
28066 right: Box::new(PlanNode::Scan(var_scan(
28067 Some("e"),
28068 "http://ex/x",
28069 Some("y"),
28070 500,
28071 ))),
28072 }),
28073 hash_keys: vec![var("p")],
28074 probe_key_domains: Vec::new(),
28075 probe_key_overlap_milli: Vec::new(),
28076 rhs_hostable_keys: Vec::new().into(),
28077 meta: JoinMeta {
28078 semi_gate: None,
28079 star_arms: None,
28080 strategy: JoinStrategy::Hash,
28081 produced_row_count_estimate: 300,
28082 own_push_removed_row_count_estimate: 300,
28083 },
28084 };
28085 assert!(
28086 !delay_optional_through_join(&mut node, None),
28087 "the Union arm reading ?email blocks the delay"
28088 );
28089 assert!(matches!(node, PlanNode::Join { .. }), "shape unchanged");
28090 }
28091
28092 #[test]
28096 fn optional_delay_bubbles_across_two_joins() {
28097 let mut profile = StatsProfile::default();
28098 profile
28099 .predicate_counts
28100 .insert(StrHash::new("http://ex/kind"), 100);
28101 profile
28102 .predicate_counts
28103 .insert(StrHash::new("http://ex/email"), 300);
28104 profile
28105 .predicate_counts
28106 .insert(StrHash::new("http://ex/worksIn"), 100);
28107 profile
28108 .predicate_counts
28109 .insert(StrHash::new("http://ex/office"), 100);
28110 for predicate in [
28111 "http://ex/kind",
28112 "http://ex/email",
28113 "http://ex/worksIn",
28114 "http://ex/office",
28115 ] {
28116 profile
28117 .subjects_per_predicate
28118 .insert(StrHash::new(predicate), hll_with_n(100));
28119 }
28120 profile.total_puts = 1_000;
28121 let mut node = PlanNode::Join {
28122 left: Box::new(PlanNode::Join {
28123 left: Box::new(left_join_node(
28124 PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
28125 PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 300)),
28126 &["p"],
28127 300,
28128 )),
28129 right: Box::new(PlanNode::Scan(var_scan(
28130 Some("p"),
28131 "http://ex/worksIn",
28132 Some("d"),
28133 100,
28134 ))),
28135 hash_keys: vec![var("p")],
28136 probe_key_domains: Vec::new(),
28137 probe_key_overlap_milli: Vec::new(),
28138 rhs_hostable_keys: Vec::new().into(),
28139 meta: JoinMeta {
28140 semi_gate: None,
28141 star_arms: None,
28142 strategy: JoinStrategy::Hash,
28143 produced_row_count_estimate: 300,
28144 own_push_removed_row_count_estimate: 300,
28145 },
28146 }),
28147 right: Box::new(PlanNode::Scan(var_scan(
28148 Some("p"),
28149 "http://ex/office",
28150 Some("off"),
28151 100,
28152 ))),
28153 hash_keys: vec![var("p")],
28154 probe_key_domains: Vec::new(),
28155 probe_key_overlap_milli: Vec::new(),
28156 rhs_hostable_keys: Vec::new().into(),
28157 meta: JoinMeta {
28158 semi_gate: None,
28159 star_arms: None,
28160 strategy: JoinStrategy::Hash,
28161 produced_row_count_estimate: 300,
28162 own_push_removed_row_count_estimate: 300,
28163 },
28164 };
28165 refinalize_joins_without_ctx(&mut node, Some(&profile));
28166 fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
28167 match node {
28168 PlanNode::Scan(scan) => {
28169 scan.pattern.predicate.as_ref()
28170 == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
28171 }
28172 PlanNode::Join { left, right, .. }
28173 | PlanNode::Union { left, right }
28174 | PlanNode::LeftJoin { left, right, .. } => {
28175 scan_with_predicate(left, iri) || scan_with_predicate(right, iri)
28176 }
28177 PlanNode::Filter { inner, .. } => scan_with_predicate(inner, iri),
28178 _ => false,
28179 }
28180 }
28181 let PlanNode::LeftJoin { left, right, .. } = &node else {
28182 panic!("expected the bubbled LeftJoin, got {node:#?}")
28183 };
28184 assert!(
28185 scan_with_predicate(right, "http://ex/email"),
28186 "the OPTIONAL stays the outer right: {right:#?}"
28187 );
28188 assert!(
28189 scan_with_predicate(left, "http://ex/worksIn")
28190 && scan_with_predicate(left, "http://ex/office"),
28191 "both later required patterns joined under the required side: {left:#?}"
28192 );
28193 }
28194
28195 #[test]
28207 fn delay_clears_the_dissolved_join_claims_on_the_required_side() {
28208 let mut profile = StatsProfile::default();
28209 profile
28210 .predicate_counts
28211 .insert(StrHash::new("http://ex/kind"), 100);
28212 profile
28213 .predicate_counts
28214 .insert(StrHash::new("http://ex/email"), 300);
28215 profile
28216 .predicate_counts
28217 .insert(StrHash::new("http://ex/worksIn"), 200);
28218 profile
28219 .subjects_per_predicate
28220 .insert(StrHash::new("http://ex/kind"), hll_with_n(100));
28221 profile
28222 .subjects_per_predicate
28223 .insert(StrHash::new("http://ex/email"), hll_with_n(100));
28224 profile
28225 .subjects_per_predicate
28226 .insert(StrHash::new("http://ex/worksIn"), hll_with_n(200));
28227 profile.total_puts = 1_000;
28228 let mut node = PlanNode::Join {
28229 left: Box::new(left_join_node(
28230 PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
28231 PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 300)),
28232 &["p"],
28233 300,
28234 )),
28235 right: Box::new(PlanNode::Scan(var_scan(
28236 Some("p"),
28237 "http://ex/worksIn",
28238 Some("d"),
28239 200,
28240 ))),
28241 hash_keys: vec![var("p")],
28242 probe_key_domains: Vec::new(),
28243 probe_key_overlap_milli: Vec::new(),
28244 rhs_hostable_keys: Vec::new().into(),
28245 meta: JoinMeta {
28246 semi_gate: None,
28247 star_arms: None,
28248 strategy: JoinStrategy::Hash,
28249 produced_row_count_estimate: 300,
28250 own_push_removed_row_count_estimate: 300,
28251 },
28252 };
28253 if let PlanNode::Join { left, .. } = &mut node
28256 && let PlanNode::LeftJoin { left, .. } = left.as_mut()
28257 && let PlanNode::Scan(scan) = left.as_mut()
28258 {
28259 scan.broadcasted = Some((var("p"), PatternSlot::Subject));
28260 }
28261 refinalize_joins_without_ctx(&mut node, Some(&profile));
28262 restamp_broadcast_marks(&mut node, Some(&profile));
28263 let PlanNode::LeftJoin { left: inner, .. } = &node else {
28264 panic!("expected the delayed LeftJoin, got {node:#?}")
28265 };
28266 fn find_scan<'a>(node: &'a PlanNode, predicate: &str) -> Option<&'a ScanOp> {
28267 match node {
28268 PlanNode::Scan(scan)
28269 if scan.pattern.predicate.as_ref()
28270 == Some(&EncodedTerm::from(&NamedNode::new(predicate).unwrap())) =>
28271 {
28272 Some(scan)
28273 }
28274 PlanNode::Join { left, right, .. }
28275 | PlanNode::Union { left, right }
28276 | PlanNode::LeftJoin { left, right, .. } => {
28277 find_scan(left, predicate).or_else(|| find_scan(right, predicate))
28278 }
28279 PlanNode::Filter { inner, .. } => find_scan(inner, predicate),
28280 _ => None,
28281 }
28282 }
28283 let kind = find_scan(inner, "http://ex/kind")
28284 .expect("the kind scan moved under the required side");
28285 assert!(
28286 kind.broadcasted.is_none(),
28287 "the dissolved join's claim must be retired, not preserved by \
28288 claim-skip: {:?}",
28289 kind.broadcasted
28290 );
28291 let works_in = find_scan(inner, "http://ex/worksIn")
28292 .expect("the worksIn scan joined under the required side");
28293 assert_eq!(
28294 works_in.broadcasted.as_ref().map(|(v, _)| v.as_str()),
28295 Some("p"),
28296 "sanity: the new inner join claims its own probe, so the \
28297 unmarked kind scan is not just a silent restamp"
28298 );
28299 }
28300
28301 #[test]
28307 fn suffix_greedy_orders_three_arms() {
28308 let mut profile = StatsProfile::default();
28309 profile
28310 .class_counts
28311 .insert(StrHash::new("http://ex/Klass"), 21_124);
28312 for (predicate, rows, subjects) in [
28313 ("http://ex/label", 376_482, 11_025),
28314 ("http://ex/sub", 13_968, 10_718),
28315 ("http://ex/note", 42_000, 21_000),
28316 ] {
28317 profile
28318 .predicate_counts
28319 .insert(StrHash::new(predicate), rows);
28320 profile
28321 .subjects_per_predicate
28322 .insert(StrHash::new(predicate), hll_with_n(subjects));
28323 }
28324 profile.total_puts = 500_000;
28325 let sparql = r#"
28326 SELECT ?class ?label ?parent ?note WHERE {
28327 ?class a <http://ex/Klass> .
28328 OPTIONAL { ?class <http://ex/label> ?label }
28329 OPTIONAL { ?class <http://ex/sub> ?parent }
28330 OPTIONAL { ?class <http://ex/note> ?note }
28331 }
28332 "#;
28333 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28334 let outer = outermost_left_join(&plan.root);
28335 let mut whole_read_rows = Vec::new();
28337 let mut cursor = outer;
28338 while let PlanNode::LeftJoin { left, right, .. } = cursor {
28339 whole_read_rows.push(right.produced_row_count_estimate());
28340 cursor = left;
28341 }
28342 assert_eq!(
28343 whole_read_rows.len(),
28344 3,
28345 "all three arms on one spine: {outer:#?}"
28346 );
28347 assert!(
28348 whole_read_rows[0] >= 300_000,
28349 "outermost is the big-fan-out label side (~376k), got {:?}",
28350 whole_read_rows
28351 );
28352 assert!(
28353 (30_000..=100_000).contains(&whole_read_rows[1]),
28354 "middle is the note side (~42-48k), got {:?}",
28355 whole_read_rows
28356 );
28357 assert!(
28358 whole_read_rows[2] <= 25_000,
28359 "innermost is the sub side (~14k), got {:?}",
28360 whole_read_rows
28361 );
28362 }
28363
28364 #[test]
28369 fn suffix_reorder_stops_at_dependent_arm() {
28370 let mut profile = StatsProfile::default();
28371 profile
28372 .class_counts
28373 .insert(StrHash::new("http://ex/Klass"), 21_124);
28374 for (predicate, rows, subjects) in [
28375 ("http://ex/label", 376_482, 11_025),
28376 ("http://ex/multi", 200_000, 10_000),
28377 ("http://ex/x", 200, 100),
28378 ] {
28379 profile
28380 .predicate_counts
28381 .insert(StrHash::new(predicate), rows);
28382 profile
28383 .subjects_per_predicate
28384 .insert(StrHash::new(predicate), hll_with_n(subjects));
28385 }
28386 profile.total_puts = 500_000;
28387 let sparql = r#"
28388 SELECT ?class ?label ?m ?y WHERE {
28389 ?class a <http://ex/Klass> .
28390 OPTIONAL { ?class <http://ex/label> ?label }
28391 OPTIONAL { ?class <http://ex/multi> ?m }
28392 OPTIONAL { ?class <http://ex/x> ?y . FILTER(?y = ?label) }
28393 }
28394 "#;
28395 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28396 let outer = outermost_left_join(&plan.root);
28397 fn arm_predicate(node: &PlanNode) -> Option<String> {
28399 let PlanNode::Scan(scan) = node else {
28400 return None;
28401 };
28402 let predicate = scan.pattern.predicate.as_ref()?;
28403 Some(format!("{:?}", predicate))
28404 }
28405 let mut spine_predicates = Vec::new();
28406 let mut cursor = outer;
28407 while let PlanNode::LeftJoin { left, right, .. } = cursor {
28408 spine_predicates.push(arm_predicate(right));
28409 cursor = left;
28410 }
28411 assert_eq!(spine_predicates.len(), 3, "{outer:#?}");
28414 assert!(
28415 spine_predicates[2].is_some(),
28416 "the depended-on label arm stays INNERMOST: {spine_predicates:?}"
28417 );
28418 assert!(
28419 spine_predicates[1].is_some() && spine_predicates[0].is_some(),
28420 "the run's two arms reordered above it: {spine_predicates:?}"
28421 );
28422 let mut whole_read_rows = Vec::new();
28425 let mut cursor = outer;
28426 while let PlanNode::LeftJoin { left, right, .. } = cursor {
28427 whole_read_rows.push(right.produced_row_count_estimate());
28428 cursor = left;
28429 }
28430 assert!(
28431 whole_read_rows[0] >= 150_000 && whole_read_rows[1] <= 1_000,
28432 "greedy run order is x-then-multi: {whole_read_rows:?}"
28433 );
28434 }
28435
28436 #[test]
28439 fn suffix_reorder_keeps_order_within_margin() {
28440 let mut profile = StatsProfile::default();
28441 profile
28442 .class_counts
28443 .insert(StrHash::new("http://ex/Klass"), 21_124);
28444 for (predicate, rows, subjects) in [
28445 ("http://ex/p1", 21_000, 21_000),
28446 ("http://ex/p2", 20_000, 20_000),
28447 ("http://ex/p3", 19_000, 19_000),
28448 ] {
28449 profile
28450 .predicate_counts
28451 .insert(StrHash::new(predicate), rows);
28452 profile
28453 .subjects_per_predicate
28454 .insert(StrHash::new(predicate), hll_with_n(subjects));
28455 }
28456 profile.total_puts = 100_000;
28457 let sparql = r#"
28458 SELECT ?class ?a ?b ?c WHERE {
28459 ?class a <http://ex/Klass> .
28460 OPTIONAL { ?class <http://ex/p1> ?a }
28461 OPTIONAL { ?class <http://ex/p2> ?b }
28462 OPTIONAL { ?class <http://ex/p3> ?c }
28463 }
28464 "#;
28465 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28466 let outer = outermost_left_join(&plan.root);
28467 let mut whole_read_rows = Vec::new();
28470 let mut cursor = outer;
28471 while let PlanNode::LeftJoin { left, right, .. } = cursor {
28472 whole_read_rows.push(right.produced_row_count_estimate());
28473 cursor = left;
28474 }
28475 assert_eq!(whole_read_rows.len(), 3, "{outer:#?}");
28476 assert!(
28477 whole_read_rows[0] <= whole_read_rows[2],
28478 "uniform fan-outs keep query order (p3 outermost, p1 \
28479 innermost): {whole_read_rows:?}"
28480 );
28481 }
28482
28483 #[test]
28491 fn maybe_bound_output_read_by_later_arm_blocks_reorder() {
28492 let mut profile = StatsProfile::default();
28493 profile
28494 .class_counts
28495 .insert(StrHash::new("http://ex/Klass"), 21_124);
28496 for (predicate, rows, subjects) in [
28497 ("http://ex/p", 200_000, 10_000),
28498 ("http://ex/q", 5_000, 5_000),
28499 ("http://ex/r", 200, 100),
28500 ] {
28501 profile
28502 .predicate_counts
28503 .insert(StrHash::new(predicate), rows);
28504 profile
28505 .subjects_per_predicate
28506 .insert(StrHash::new(predicate), hll_with_n(subjects));
28507 }
28508 profile.total_puts = 500_000;
28509 let sparql = r#"
28510 SELECT ?class ?x ?y ?z WHERE {
28511 ?class a <http://ex/Klass> .
28512 OPTIONAL { ?class <http://ex/p> ?x .
28513 OPTIONAL { ?class <http://ex/q> ?y } }
28514 OPTIONAL { ?class <http://ex/r> ?z . FILTER(?z = ?y) }
28515 }
28516 "#;
28517 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28518 fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
28519 match node {
28520 PlanNode::Scan(scan) => {
28521 scan.pattern.predicate.as_ref()
28522 == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
28523 }
28524 PlanNode::Join { left, right, .. }
28525 | PlanNode::Union { left, right }
28526 | PlanNode::LeftJoin { left, right, .. } => {
28527 scan_with_predicate(left, iri) || scan_with_predicate(right, iri)
28528 }
28529 PlanNode::Filter { inner, .. } => scan_with_predicate(inner, iri),
28530 _ => false,
28531 }
28532 }
28533 let outer = outermost_left_join(&plan.root);
28534 let mut arms = Vec::new();
28536 let mut cursor = outer;
28537 while let PlanNode::LeftJoin { left, right, .. } = cursor {
28538 arms.push(right.as_ref());
28539 cursor = left;
28540 }
28541 assert_eq!(arms.len(), 2, "{outer:#?}");
28542 assert!(
28547 scan_with_predicate(arms[0], "http://ex/r"),
28548 "outermost is the reading arm: {outer:#?}"
28549 );
28550 assert!(
28551 scan_with_predicate(arms[1], "http://ex/p")
28552 && scan_with_predicate(arms[1], "http://ex/q"),
28553 "innermost is the producing arm with its nested optional: {outer:#?}"
28554 );
28555 }
28556
28557 #[test]
28561 fn dependent_optional_key_blocks_rotation() {
28562 let mut profile = StatsProfile::default();
28563 profile
28564 .class_counts
28565 .insert(StrHash::new("http://ex/Klass"), 21_124);
28566 profile
28567 .predicate_counts
28568 .insert(StrHash::new("http://ex/label"), 376_482);
28569 profile
28570 .subjects_per_predicate
28571 .insert(StrHash::new("http://ex/label"), hll_with_n(11_025));
28572 profile
28573 .predicate_counts
28574 .insert(StrHash::new("http://ex/x"), 1_000);
28575 profile.total_puts = 500_000;
28576 let sparql = r#"
28577 SELECT ?class ?label ?y WHERE {
28578 ?class a <http://ex/Klass> .
28579 OPTIONAL { ?class <http://ex/label> ?label }
28580 OPTIONAL { ?label <http://ex/x> ?y }
28581 }
28582 "#;
28583 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28584 let outer = outermost_left_join(&plan.root);
28585 let PlanNode::LeftJoin {
28586 right: outer_right, ..
28587 } = outer
28588 else {
28589 panic!("expected the outermost LeftJoin, got {:#?}", plan.root)
28590 };
28591 assert!(
28594 outer_right.produced_row_count_estimate() <= 5_000,
28595 "dependent key (?label) must keep query order — outer stays the \
28596 small ?label-keyed arm, got {outer_right:#?}"
28597 );
28598 }
28599
28600 #[test]
28603 fn dependent_optional_filter_blocks_rotation() {
28604 let mut profile = StatsProfile::default();
28605 profile
28606 .class_counts
28607 .insert(StrHash::new("http://ex/Klass"), 21_124);
28608 profile
28609 .predicate_counts
28610 .insert(StrHash::new("http://ex/label"), 376_482);
28611 profile
28612 .subjects_per_predicate
28613 .insert(StrHash::new("http://ex/label"), hll_with_n(11_025));
28614 profile
28615 .predicate_counts
28616 .insert(StrHash::new("http://ex/sub"), 13_968);
28617 profile
28618 .subjects_per_predicate
28619 .insert(StrHash::new("http://ex/sub"), hll_with_n(10_718));
28620 profile.total_puts = 500_000;
28621 let sparql = r#"
28622 SELECT ?class ?label ?parent WHERE {
28623 ?class a <http://ex/Klass> .
28624 OPTIONAL { ?class <http://ex/label> ?label }
28625 OPTIONAL { ?class <http://ex/sub> ?parent . FILTER(?parent != ?label) }
28626 }
28627 "#;
28628 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28629 let outer = outermost_left_join(&plan.root);
28630 let PlanNode::LeftJoin {
28631 right: outer_right, ..
28632 } = outer
28633 else {
28634 panic!("expected the outermost LeftJoin, got {:#?}", plan.root)
28635 };
28636 assert!(
28640 outer_right.produced_row_count_estimate() <= 20_000,
28641 "FILTER referencing ?label makes the pair dependent — query order \
28642 keeps the subClassOf optional OUTER, got {outer_right:#?}"
28643 );
28644 }
28645
28646 #[test]
28647 fn high_fanout_probe_clamp_prices_rows_not_keys() {
28648 let mut profile = StatsProfile::default();
28649 profile
28650 .class_counts
28651 .insert(StrHash::new("http://ex/Klass"), 21_124);
28652 profile
28653 .predicate_counts
28654 .insert(StrHash::new("http://ex/label"), 376_482);
28655 profile
28656 .subjects_per_predicate
28657 .insert(StrHash::new("http://ex/label"), hll_with_n(11_025));
28658 profile.total_puts = 500_000;
28659 let sparql = r#"
28660 SELECT ?class ?label WHERE {
28661 ?class a <http://ex/Klass> .
28662 OPTIONAL { ?class <http://ex/label> ?label }
28663 }
28664 "#;
28665 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28666 let label = EncodedTerm::from(&NamedNode::new("http://ex/label").unwrap());
28667 let mut label_scan: Option<&ScanOp> = None;
28668 for_each_scan(&plan.root, &mut |scan| {
28669 if scan.pattern.predicate.as_ref() == Some(&label) {
28670 label_scan = Some(scan);
28671 }
28672 });
28673 let scan = label_scan.expect("label scan in plan");
28674 assert_eq!(
28675 scan.broadcasted.as_ref().map(|(v, s)| (v.as_str(), *s)),
28676 Some(("class", PatternSlot::Subject)),
28677 "the LeftJoin claims the label probe on ?class"
28678 );
28679 assert_eq!(
28680 scan.produced_row_count_estimate, 376_482,
28681 "fan-out-aware clamp: 21,124 pushed values × ~34 rows/key (≈722k) capped at \\
28682 the price — NOT the values-broadcast 21,124"
28683 );
28684 let card = profile
28690 .subjects_per_predicate
28691 .get(&StrHash::new("http://ex/label"))
28692 .map(|hll| hll.cardinality())
28693 .unwrap_or(11_025);
28694 let expected_leftjoin = (21_124u64).saturating_sub(card) + 376_482;
28695 let mut leftjoin_meta: Option<LeftJoinMeta> = None;
28696 walk_plan_node_meta(&plan.root, &mut leftjoin_meta);
28697 let meta = leftjoin_meta.expect("a LeftJoin in the plan");
28698 assert_eq!(
28699 meta.own_push_removed_row_count_estimate, expected_leftjoin,
28700 "own-push-removed: unmatched + |R| under containment"
28701 );
28702 assert_eq!(
28703 meta.produced_row_count_estimate, expected_leftjoin,
28704 "push-aware leaves it: probe settled count = price"
28705 );
28706 }
28707
28708 fn walk_plan_node_meta(node: &PlanNode, out: &mut Option<LeftJoinMeta>) {
28710 if out.is_none()
28711 && let PlanNode::LeftJoin { meta, .. } = node
28712 {
28713 *out = Some(*meta);
28714 }
28715 match node {
28716 PlanNode::LeftJoin { left, right, .. }
28717 | PlanNode::Join { left, right, .. }
28718 | PlanNode::Union { left, right } => {
28719 walk_plan_node_meta(left, out);
28720 walk_plan_node_meta(right, out);
28721 }
28722 PlanNode::Filter { inner, .. }
28723 | PlanNode::Extend { inner, .. }
28724 | PlanNode::Slice { inner, .. }
28725 | PlanNode::Distinct { inner, .. }
28726 | PlanNode::Sort { inner, .. }
28727 | PlanNode::Group { inner, .. } => walk_plan_node_meta(inner, out),
28728 PlanNode::SubSelect(sub) => walk_plan_node_meta(&sub.inner, out),
28729 _ => {}
28730 }
28731 }
28732
28733 fn outermost_left_join(node: &PlanNode) -> &PlanNode {
28736 match node {
28737 PlanNode::LeftJoin { .. } => node,
28738 PlanNode::Filter { inner, .. }
28739 | PlanNode::Extend { inner, .. }
28740 | PlanNode::Slice { inner, .. }
28741 | PlanNode::Distinct { inner, .. }
28742 | PlanNode::Sort { inner, .. }
28743 | PlanNode::Group { inner, .. }
28744 | PlanNode::JoinGraphVar { inner, .. } => outermost_left_join(inner),
28745 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
28746 let found = outermost_left_join(left);
28747 if matches!(found, PlanNode::LeftJoin { .. }) {
28748 found
28749 } else {
28750 outermost_left_join(right)
28751 }
28752 }
28753 other => other,
28754 }
28755 }
28756
28757 #[test]
28760 fn restamp_skips_grounded_and_point_lookup_probes() {
28761 let mut grounded = var_scan(Some("b"), "http://ex/p", Some("c"), 50);
28762 grounded
28763 .grounded
28764 .push((Variable::new("b").unwrap(), PatternSlot::Subject));
28765 let mut tree = broadcast_join(
28766 values_node("b", &["http://ex/k1"]),
28767 PlanNode::Scan(grounded),
28768 &["b"],
28769 1,
28770 );
28771 restamp_broadcast_marks(&mut tree, None);
28772 let PlanNode::Join { right, .. } = &tree else {
28773 panic!("expected Join, got {tree:?}")
28774 };
28775 let PlanNode::Scan(scan) = right.as_ref() else {
28776 panic!("expected Scan probe, got {right:?}")
28777 };
28778 assert!(
28779 scan.broadcasted.is_none(),
28780 "grounded key slot must not be claimed: {:?}",
28781 scan.broadcasted
28782 );
28783
28784 let mut point = var_scan(None, "http://ex/p", None, 1);
28785 point.pattern.subject = Some(EncodedTerm::from(&NamedNode::new("http://ex/s1").unwrap()));
28786 point.pattern.object = Some(EncodedTerm::from(&NamedNode::new("http://ex/o1").unwrap()));
28787 point.pattern.graph_name = Some(EncodedTerm::DefaultGraph);
28788 point.subject = None;
28789 point.object = None;
28790 let mut tree = broadcast_join(
28791 values_node("b", &["http://ex/k1"]),
28792 PlanNode::Scan(point),
28793 &["b"],
28794 1,
28795 );
28796 restamp_broadcast_marks(&mut tree, None);
28797 let PlanNode::Join { right, .. } = &tree else {
28798 panic!("expected Join, got {tree:?}")
28799 };
28800 let PlanNode::Scan(scan) = right.as_ref() else {
28801 panic!("expected Scan probe, got {right:?}")
28802 };
28803 assert!(
28804 scan.broadcasted.is_none(),
28805 "point lookups are exempt from claiming: {:?}",
28806 scan.broadcasted
28807 );
28808 }
28809
28810 #[test]
28814 fn swap_clears_old_probe_and_restamp_reclaims_new_one() {
28815 let mut small = var_scan(Some("b"), "http://ex/q", Some("d"), 5);
28818 small.broadcasted = Some((Variable::new("b").unwrap(), PatternSlot::Subject));
28819 let mut tree = PlanNode::Join {
28820 left: Box::new(PlanNode::Scan(var_scan(
28821 Some("b"),
28822 "http://ex/p",
28823 Some("c"),
28824 500,
28825 ))),
28826 right: Box::new(PlanNode::Scan(small)),
28827 hash_keys: vec![Variable::new("b").unwrap()],
28828 probe_key_domains: Vec::new(),
28829 probe_key_overlap_milli: Vec::new(),
28830 rhs_hostable_keys: Vec::new().into(),
28831 meta: JoinMeta {
28832 semi_gate: None,
28833 star_arms: None,
28834 strategy: JoinStrategy::Hash,
28835 produced_row_count_estimate: 500,
28836 own_push_removed_row_count_estimate: 500,
28837 },
28838 };
28839 refinalize_joins_without_ctx(&mut tree, None);
28842 let PlanNode::Join { left, meta, .. } = &tree else {
28843 panic!("expected Join, got {tree:?}")
28844 };
28845 assert_eq!(meta.strategy, JoinStrategy::Broadcast);
28846 let PlanNode::Scan(driver) = left.as_ref() else {
28847 panic!("expected the small scan to drive, got {left:?}")
28848 };
28849 assert!(
28850 driver.broadcasted.is_none(),
28851 "swap-time clear_broadcast_marks removed the old probe's stale mark"
28852 );
28853 restamp_broadcast_marks(&mut tree, None);
28854 let PlanNode::Join { right, .. } = &tree else {
28855 panic!("expected Join, got {tree:?}")
28856 };
28857 let PlanNode::Scan(probe) = right.as_ref() else {
28858 panic!("expected the big scan as probe, got {right:?}")
28859 };
28860 assert_eq!(
28861 probe.broadcasted.as_ref().map(|(v, s)| (v.as_str(), *s)),
28862 Some(("b", PatternSlot::Subject)),
28863 "the boundary restamp claims the swapped-in probe: {:?}",
28864 probe.broadcasted
28865 );
28866 assert_eq!(
28867 probe.produced_row_count_estimate, 5,
28868 "claim-clamp prices the probe at the driver's estimate (no HLL)"
28869 );
28870 }
28871
28872 #[test]
28882 fn original_query_shape_keeps_cartesian_driving_and_marks_the_ispartof_probe() {
28883 let mut profile = StatsProfile::default();
28884 profile
28885 .class_counts
28886 .insert(StrHash::new("http://schema.org/Dataset"), 5);
28887 profile
28888 .class_counts
28889 .insert(StrHash::new("http://example.org/ontology/Submission"), 100);
28890 profile.predicate_counts.insert(
28891 StrHash::new("http://example.org/ontology/isPartOf"),
28892 237_016,
28893 );
28894 profile.objects_per_predicate.insert(
28895 StrHash::new("http://example.org/ontology/isPartOf"),
28896 hll_with_n(121),
28897 );
28898 profile.subjects_per_predicate.insert(
28899 StrHash::new("http://example.org/ontology/isPartOf"),
28900 hll_with_n(114_739),
28901 );
28902 profile.subjects_per_predicate.insert(
28903 StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
28904 hll_with_n(125_483),
28905 );
28906 profile.total_puts = 300_000;
28907
28908 let sparql = r#"
28909 PREFIX schema: <http://schema.org/>
28910 PREFIX myOnt: <http://example.org/ontology/>
28911 SELECT * WHERE {
28912 ?ds a schema:Dataset .
28913 ?sub a myOnt:Submission .
28914 ?sub myOnt:isPartOf ?ds .
28915 }
28916 "#;
28917 let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28918 let mut outer: Option<&PlanNode> = None;
28920 fn find_two_key_join<'a>(node: &'a PlanNode, out: &mut Option<&'a PlanNode>) {
28921 match node {
28922 PlanNode::Join {
28923 left,
28924 right,
28925 hash_keys,
28926 ..
28927 } => {
28928 let names: Vec<&str> = hash_keys.iter().map(Variable::as_str).collect();
28929 if names.contains(&"ds") && names.contains(&"sub") && out.is_none() {
28930 *out = Some(node);
28931 }
28932 let _ = (left, right);
28933 find_two_key_join(left, out);
28934 find_two_key_join(right, out);
28935 }
28936 PlanNode::JoinGraphVar { inner, .. }
28937 | PlanNode::Extend { inner, .. }
28938 | PlanNode::Filter { inner, .. } => find_two_key_join(inner, out),
28939 _ => {}
28940 }
28941 }
28942 find_two_key_join(&plan.root, &mut outer);
28943 let Some(join) = outer else {
28944 panic!("expected the [?ds, ?sub] join, got {:?}", plan.root)
28945 };
28946 let PlanNode::Join {
28947 left,
28948 right,
28949 hash_keys,
28950 probe_key_domains: _,
28951 probe_key_overlap_milli: _,
28952 rhs_hostable_keys: _,
28953 meta,
28954 } = join
28955 else {
28956 unreachable!()
28957 };
28958 assert_eq!(
28959 meta.strategy,
28960 JoinStrategy::Broadcast,
28961 "the small cartesian driver keeps the join Broadcast"
28962 );
28963 assert!(
28964 matches!(left.as_ref(), PlanNode::Join { .. }),
28965 "the type-scan cartesian drives (no swap): {:?}",
28966 left
28967 );
28968 let key_order: Vec<&str> = hash_keys.iter().map(Variable::as_str).collect();
28969 assert_eq!(
28970 key_order,
28971 vec!["sub", "ds"],
28972 "keys ordered by expected probe return: ?sub (100 keys × ~2 rows) \\
28973 beats ?ds (5 keys × ~1,959 rows)"
28974 );
28975 let PlanNode::Scan(is_part_of) = right.as_ref() else {
28976 panic!("expected the isPartOf scan as probe, got {right:?}")
28977 };
28978 assert_eq!(
28979 is_part_of
28980 .broadcasted
28981 .as_ref()
28982 .map(|(v, s)| (v.as_str(), *s)),
28983 Some(("sub", PatternSlot::Subject)),
28984 "the claim names the cheapest key — the runtime broadcasts ~100 subject \\
28985 terms (~200 rows back), not 5 dataset terms (~113,688 rows back): {:?}",
28986 is_part_of.broadcasted
28987 );
28988 let expected_probe_rows = {
28997 let sub_domain = profile
28998 .subjects_per_predicate
28999 .get(&StrHash::new("http://example.org/ontology/isPartOf"))
29000 .map(|hll| hll.cardinality())
29001 .unwrap_or(114_739);
29002 pushed_return_bound_core(100, 237_016, Some(sub_domain)).unwrap_or(237_016)
29003 };
29004 assert_eq!(
29005 is_part_of.produced_row_count_estimate, expected_probe_rows,
29006 "claim-clamp prices the probe at pushed values × rows per key (~207)"
29007 );
29008 let mut claimed: Vec<(String, PatternSlot)> = Vec::new();
29012 for_each_scan(&plan.root, &mut |scan| {
29013 if let Some((v, s)) = &scan.broadcasted {
29014 claimed.push((v.as_str().to_string(), *s));
29015 }
29016 });
29017 assert_eq!(
29018 claimed,
29019 vec![("sub".to_string(), PatternSlot::Subject)],
29020 "one coherent mark: the isPartOf scan as the driven probe, on the \\
29021 cheapest key"
29022 );
29023 assert_eq!(
29031 meta.produced_row_count_estimate, 8,
29032 "push-aware product over [?sub, ?ds] with the fan-out-aware probe count"
29033 );
29034 assert_eq!(
29042 meta.own_push_removed_row_count_estimate, 8,
29043 "finalize's own-push-removed stamp survives the push-aware restamp"
29044 );
29045 }
29046
29047 #[test]
29054 fn greedy_assoc_defers_cartesian() {
29055 let mut profile = StatsProfile::default();
29056 profile
29057 .predicate_counts
29058 .insert(StrHash::new("http://ex/p1"), 10);
29059 profile
29060 .predicate_counts
29061 .insert(StrHash::new("http://ex/p3"), 1_000);
29062 profile
29063 .predicate_counts
29064 .insert(StrHash::new("http://ex/p2"), 100_000);
29065 profile.total_puts = 200_000;
29066 let plan = LogicalPlan::parse_with_profile(
29067 r#"SELECT * WHERE {
29068 ?a <http://ex/p1> ?x .
29069 ?c <http://ex/p3> ?z .
29070 ?a <http://ex/p2> ?y .
29071 }"#,
29072 Some(&profile),
29073 )
29074 .unwrap();
29075 fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
29076 matches!(
29077 node,
29078 PlanNode::Scan(scan)
29079 if scan.pattern.predicate.as_ref()
29080 == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
29081 )
29082 }
29083 let PlanNode::Join {
29084 left,
29085 right,
29086 hash_keys,
29087 ..
29088 } = &plan.root
29089 else {
29090 panic!("expected a join root, got {:?}", plan.root)
29091 };
29092 assert!(
29093 hash_keys.is_empty(),
29094 "the deferred cartesian is the root, got keys {hash_keys:?}"
29095 );
29096 assert!(
29097 scan_with_predicate(right, "http://ex/p3"),
29098 "the disconnected p3 scan folds last, got {right:?}"
29099 );
29100 let PlanNode::Join {
29101 left: inner_left,
29102 right: inner_right,
29103 hash_keys: inner_keys,
29104 ..
29105 } = left.as_ref()
29106 else {
29107 panic!("expected the connected pair inside, got {left:?}")
29108 };
29109 assert_eq!(
29110 inner_keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
29111 vec!["a"],
29112 "the connected pair joins on ?a"
29113 );
29114 assert!(scan_with_predicate(inner_left, "http://ex/p1"));
29115 assert!(scan_with_predicate(inner_right, "http://ex/p2"));
29116 }
29117
29118 #[test]
29123 fn greedy_assoc_picks_smallest_join_output_not_smallest_leaf() {
29124 let mut profile = StatsProfile::default();
29125 profile
29126 .predicate_counts
29127 .insert(StrHash::new("http://ex/p1"), 10);
29128 profile
29129 .predicate_counts
29130 .insert(StrHash::new("http://ex/p2"), 100_000);
29131 profile
29132 .predicate_counts
29133 .insert(StrHash::new("http://ex/p3"), 500_000);
29134 profile
29135 .subjects_per_predicate
29136 .insert(StrHash::new("http://ex/p1"), hll_with_n(10));
29137 profile
29138 .subjects_per_predicate
29139 .insert(StrHash::new("http://ex/p2"), hll_with_n(10));
29140 profile
29141 .subjects_per_predicate
29142 .insert(StrHash::new("http://ex/p3"), hll_with_n(1_000_000));
29143 profile.total_puts = 1_000_000;
29144 let plan = LogicalPlan::parse_with_profile(
29145 r#"SELECT * WHERE {
29146 ?a <http://ex/p1> ?x .
29147 ?a <http://ex/p2> ?y .
29148 ?a <http://ex/p3> ?z .
29149 }"#,
29150 Some(&profile),
29151 )
29152 .unwrap();
29153 fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
29154 matches!(
29155 node,
29156 PlanNode::Scan(scan)
29157 if scan.pattern.predicate.as_ref()
29158 == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
29159 )
29160 }
29161 let PlanNode::Join {
29164 left,
29165 right,
29166 hash_keys,
29167 ..
29168 } = &plan.root
29169 else {
29170 panic!("expected a join root, got {:?}", plan.root)
29171 };
29172 assert_eq!(
29173 hash_keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
29174 vec!["a"],
29175 "all three leaves share ?a"
29176 );
29177 assert!(
29178 scan_with_predicate(right, "http://ex/p2"),
29179 "the small-?a-domain p2 scan (big join output) folds last, got {right:?}"
29180 );
29181 let PlanNode::Join {
29182 right: inner_right, ..
29183 } = left.as_ref()
29184 else {
29185 panic!("expected the inner join, got {left:?}")
29186 };
29187 assert!(
29188 scan_with_predicate(inner_right, "http://ex/p3"),
29189 "the huge-?a-domain p3 scan (tiny join output) folds second, got {inner_right:?}"
29190 );
29191 }
29192
29193 #[test]
29198 fn no_statistic_assoc_ties_ignore_input_order() {
29199 let plan = |sparql: &str| LogicalPlan::parse(sparql).unwrap();
29200 let first = plan(
29201 r#"SELECT * WHERE {
29202 ?x <http://ex/p1> ?a .
29203 ?x <http://ex/p2> ?b .
29204 ?x <http://ex/p3> ?c .
29205 }"#,
29206 );
29207 let second = plan(
29208 r#"SELECT * WHERE {
29209 ?x <http://ex/p3> ?c .
29210 ?x <http://ex/p1> ?a .
29211 ?x <http://ex/p2> ?b .
29212 }"#,
29213 );
29214
29215 fn assert_all_estimates_equal(node: &PlanNode, expected: u64) {
29218 assert_eq!(
29219 node.produced_row_count_estimate(),
29220 expected,
29221 "no-statistics estimate must tie with the root, got {node:?}"
29222 );
29223 if let PlanNode::Join { left, right, .. } = node {
29224 assert_all_estimates_equal(left, expected);
29225 assert_all_estimates_equal(right, expected);
29226 }
29227 }
29228 let expected = first.root.produced_row_count_estimate();
29229 assert_all_estimates_equal(&first.root, expected);
29230 assert_all_estimates_equal(&second.root, expected);
29231
29232 assert_eq!(first.root, second.root);
29235 }
29236
29237 #[test]
29241 fn hash_key_reorder_without_profile_keeps_structural_order() {
29242 let mut keys: Vec<Variable> = ["b", "a"]
29243 .iter()
29244 .map(|k| Variable::new(*k).unwrap())
29245 .collect();
29246 let left = PlanNode::Unit;
29247 let right = PlanNode::Scan(var_scan(Some("b"), "http://ex/p", Some("a"), 10));
29248 reorder_hash_keys_by_probe_return(
29249 &mut keys,
29250 &mut Vec::new(),
29251 &mut Vec::new(),
29252 &left,
29253 &right,
29254 None,
29255 );
29256 assert_eq!(
29257 keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
29258 vec!["b", "a"],
29259 "no profile ⇒ no information ⇒ original order"
29260 );
29261 }
29262
29263 #[test]
29269 fn hash_key_reorder_sorts_unknown_cost_last() {
29270 let x = EncodedTerm::from(&NamedNode::new("http://ex/X").unwrap());
29271 let y = EncodedTerm::from(&NamedNode::new("http://ex/Y").unwrap());
29272 let driver = PlanNode::Values(ValuesOp {
29273 variables: vec![var("a"), var("b")],
29274 rows: vec![vec![Some(x), Some(y)]],
29275 strings: Vec::new(),
29276 blobs: Vec::new(),
29277 });
29278 let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/p", Some("b"), 10));
29279 let mut keys = vec![var("a"), var("b")];
29280 reorder_hash_keys_by_probe_return(
29281 &mut keys,
29282 &mut Vec::new(),
29283 &mut Vec::new(),
29284 &driver,
29285 &probe,
29286 None,
29287 );
29288 assert_eq!(
29289 keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
29290 vec!["b", "a"],
29291 "unknown-cost ?a must sort behind the hosted, shippable ?b"
29292 );
29293 }
29294
29295 #[test]
29302 fn grounding_uses_any_ground_unique_key_not_just_first() {
29303 let mut profile = StatsProfile::default();
29304 let p = StrHash::new("http://ex/p");
29305 let q = StrHash::new("http://ex/q");
29306 profile.predicate_counts.insert(p, 5_000);
29307 profile.predicate_counts.insert(q, 500_000);
29308 profile.subjects_per_predicate.insert(p, hll_with_n(100));
29309 profile
29310 .subjects_per_predicate
29311 .insert(q, hll_with_n(100_000));
29312 profile.objects_per_predicate.insert(p, hll_with_n(50));
29313 profile.objects_per_predicate.insert(q, hll_with_n(10));
29314 profile.total_puts = 600_000;
29315
29316 let x = EncodedTerm::from(&NamedNode::new("http://ex/X").unwrap());
29317 let driver = PlanNode::Join {
29320 left: Box::new(PlanNode::Values(ValuesOp {
29321 variables: vec![var("x")],
29322 rows: vec![vec![Some(x.clone())]],
29323 strings: Vec::new(),
29324 blobs: Vec::new(),
29325 })),
29326 right: Box::new(PlanNode::Scan(var_scan(
29327 Some("s"),
29328 "http://ex/p",
29329 Some("x"),
29330 5_000,
29331 ))),
29332 hash_keys: vec![var("x")],
29333 probe_key_domains: Vec::new(),
29334 probe_key_overlap_milli: Vec::new(),
29335 rhs_hostable_keys: Vec::new().into(),
29336 meta: JoinMeta {
29337 semi_gate: None,
29338 star_arms: None,
29339 strategy: JoinStrategy::Hash,
29340 produced_row_count_estimate: 100,
29341 own_push_removed_row_count_estimate: 100,
29342 },
29343 };
29344 let mut tree = PlanNode::Join {
29345 left: Box::new(driver),
29346 right: Box::new(PlanNode::Scan(var_scan(
29347 Some("s"),
29348 "http://ex/q",
29349 Some("x"),
29350 500_000,
29351 ))),
29352 hash_keys: vec![var("s"), var("x")],
29353 probe_key_domains: Vec::new(),
29354 probe_key_overlap_milli: Vec::new(),
29355 rhs_hostable_keys: Vec::new().into(),
29356 meta: JoinMeta {
29357 semi_gate: None,
29358 star_arms: None,
29359 strategy: JoinStrategy::Hash,
29360 produced_row_count_estimate: 1,
29361 own_push_removed_row_count_estimate: 1,
29362 },
29363 };
29364 refinalize_joins_without_ctx(&mut tree, Some(&profile));
29365 restamp_broadcast_marks(&mut tree, Some(&profile));
29366 let PlanNode::Join {
29367 left: _,
29368 right,
29369 hash_keys,
29370 probe_key_domains: _,
29371 probe_key_overlap_milli: _,
29372 rhs_hostable_keys: _,
29373 meta,
29374 } = &tree
29375 else {
29376 panic!("expected Join, got {tree:?}")
29377 };
29378 let key_order: Vec<&str> = hash_keys.iter().map(Variable::as_str).collect();
29379 assert_eq!(
29380 key_order,
29381 vec!["s", "x"],
29382 "?s's push is cheaper (?x's tiny object domain gives it a huge \\
29383 uniform fan-out): {key_order:?}"
29384 );
29385 let PlanNode::Scan(probe) = right.as_ref() else {
29386 panic!("expected the :q scan as probe, got {right:?}")
29387 };
29388 assert_eq!(meta.strategy, JoinStrategy::Broadcast);
29389 assert_eq!(
29390 probe
29391 .grounded
29392 .iter()
29393 .map(|(v, s)| (v.as_str(), *s))
29394 .collect::<Vec<_>>(),
29395 vec![("x", PatternSlot::Object)],
29396 "the SECOND key grounds — ground-uniqueness, not sort position, \\
29397 decides: {:?}",
29398 probe.grounded
29399 );
29400 assert_eq!(probe.pattern.object, Some(x));
29401 assert_eq!(
29402 probe.broadcasted.as_ref().map(|(v, s)| (v.as_str(), *s)),
29403 Some(("s", PatternSlot::Subject)),
29404 "the claim names the first key (delivery), grounding took ?x: {:?}",
29405 probe.broadcasted
29406 );
29407 assert!(
29408 probe.produced_row_count_estimate < 500_000,
29409 "grounded probe re-priced below its catalog estimate: {}",
29410 probe.produced_row_count_estimate
29411 );
29412 }
29413
29414 #[test]
29415 fn bind_iri_equality_grounds_scan_subject() {
29416 let iri = NamedNode::new("http://yago-knowledge.org/resource/Crow_Hill_Q20861371").unwrap();
29417 let plan = LogicalPlan::parse(
29418 r#"SELECT ?o ?b WHERE {
29419 ?b ?p ?o .
29420 BIND(<http://yago-knowledge.org/resource/Crow_Hill_Q20861371> AS ?c)
29421 FILTER(?b = ?c)
29422 }"#,
29423 )
29424 .unwrap();
29425 assert!(
29426 !contains_filter(&plan.root),
29427 "IRI = with grounded BIND should fold, got {:?}",
29428 plan.root
29429 );
29430 let mut scans = Vec::new();
29431 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29432 assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("b"));
29433 assert_eq!(scans[0].pattern.subject, Some(EncodedTerm::from(&iri)));
29434 }
29435
29436 #[test]
29437 fn values_singleton_sameterm_grounds_scan_subject() {
29438 let iri = NamedNode::new("http://ex/CrowHill").unwrap();
29439 let plan = LogicalPlan::parse(
29440 r#"SELECT ?o ?b WHERE {
29441 VALUES ?c { <http://ex/CrowHill> }
29442 ?b ?p ?o .
29443 FILTER(sameTerm(?b, ?c))
29444 }"#,
29445 )
29446 .unwrap();
29447 assert!(
29448 !contains_filter(&plan.root),
29449 "singleton VALUES sameTerm should fold, got {:?}",
29450 plan.root
29451 );
29452 let mut scans = Vec::new();
29453 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29454 assert_eq!(scans.len(), 1);
29455 assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("b"));
29456 assert_eq!(scans[0].pattern.subject, Some(EncodedTerm::from(&iri)));
29457 }
29458
29459 #[test]
29460 fn values_two_column_row_grounds_both_scan_slots() {
29461 let a = EncodedTerm::from(&NamedNode::new("http://ex/a").unwrap());
29462 let b = EncodedTerm::from(&NamedNode::new("http://ex/b").unwrap());
29463 let plan = LogicalPlan::parse(
29464 r#"SELECT ?s ?p ?o WHERE {
29465 VALUES (?a ?b) { (<http://ex/a> <http://ex/b>) }
29466 ?s ?p ?o .
29467 FILTER(sameTerm(?s, ?a) && sameTerm(?o, ?b))
29468 }"#,
29469 )
29470 .unwrap();
29471 assert!(
29472 !contains_filter(&plan.root),
29473 "one-row two-column VALUES should fold both conjuncts, got {:?}",
29474 plan.root
29475 );
29476 let mut scans = Vec::new();
29477 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29478 assert_eq!(scans.len(), 1);
29479 assert_eq!(scans[0].pattern.subject, Some(a));
29480 assert_eq!(scans[0].pattern.object, Some(b));
29481 assert!(
29482 scans[0].pattern.predicate.is_none(),
29483 "predicate should stay unbound, got {:?}",
29484 scans[0]
29485 );
29486 }
29487
29488 #[test]
29489 fn str_filter_grounds_object_and_drops_filter() {
29490 let green_str = EncodedTerm::from(&Literal::new_simple_literal(
29491 "https://example.org/colour/green",
29492 ));
29493 let plan = LogicalPlan::parse(
29494 r#"SELECT ?s WHERE {
29495 ?s <http://ex/p> ?colour .
29496 FILTER(?colour = STR(<https://example.org/colour/green>))
29497 }"#,
29498 )
29499 .unwrap();
29500 assert!(
29501 !contains_filter(&plan.root),
29502 "STR equality should fold like a plain string: {:?}",
29503 plan.root
29504 );
29505 let mut scans = Vec::new();
29506 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29507 assert_eq!(scans.len(), 1);
29508 assert_eq!(scans[0].pattern.object, Some(green_str));
29509 assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("s"));
29510 }
29511
29512 #[test]
29513 fn bind_str_sameterm_grounds_scan_subject() {
29514 let lexical = "http://ex/Resource";
29515 let ground_str = EncodedTerm::from(&Literal::new_simple_literal(lexical));
29516 let plan = LogicalPlan::parse(
29517 r#"SELECT ?o ?s WHERE {
29518 ?s ?p ?o .
29519 BIND(STR(<http://ex/Resource>) AS ?c)
29520 FILTER(sameTerm(?s, ?c))
29521 }"#,
29522 )
29523 .unwrap();
29524 assert!(
29525 !contains_filter(&plan.root),
29526 "BIND(STR(iri)) + sameTerm should ground ?s: {:?}",
29527 plan.root
29528 );
29529 let mut scans = Vec::new();
29530 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29531 assert_eq!(scans.len(), 1);
29532 assert_eq!(scans[0].pattern.subject, Some(ground_str));
29533 }
29534
29535 #[test]
29536 fn constant_arithmetic_equalities_drop_filter() {
29537 for sparql in [
29538 r#"SELECT ?s WHERE { ?s <http://ex/p> ?o . FILTER(4.1 - 3.2 = 0.9) }"#,
29539 r#"SELECT ?s WHERE { ?s <http://ex/p> ?o . FILTER(ABS(-1) = 1) }"#,
29540 ] {
29541 let plan = LogicalPlan::parse(sparql).unwrap();
29542 assert!(
29543 !contains_filter(&plan.root),
29544 "constant numeric equality should fold away: {:?}",
29545 plan.root
29546 );
29547 }
29548 }
29549
29550 #[test]
29551 fn variable_equals_folded_arithmetic_keeps_filter() {
29552 let plan = LogicalPlan::parse(
29553 r#"SELECT ?s ?n WHERE {
29554 ?s <http://ex/p> ?n .
29555 FILTER(?n = 4.1 - 3.2)
29556 }"#,
29557 )
29558 .unwrap();
29559 assert!(
29560 !contains_filter(&plan.root),
29561 "the exact folded comparison moves into the scan: {:?}",
29562 plan.root
29563 );
29564 let mut scans = Vec::new();
29565 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29566 assert!(
29567 scans[0].pattern.object.is_none(),
29568 "numeric literal must not identity-fold the object slot: {:?}",
29569 scans[0]
29570 );
29571 assert!(
29572 scans[0]
29573 .eager
29574 .iter()
29575 .any(|comparison| comparison.op == CompareOp::Eq
29576 && matches!(comparison.term, EncodedTerm::DecimalLiteral(_))),
29577 "the scan must carry the exact decimal equality: {:?}",
29578 scans[0].eager
29579 );
29580 }
29581
29582 #[test]
29583 fn sha1_on_boolean_is_not_constant_folded() {
29584 let plan =
29585 LogicalPlan::parse(r#"SELECT ?s WHERE { ?s <http://ex/p> ?o . FILTER(SHA1(true)) }"#)
29586 .unwrap();
29587 assert!(
29588 contains_filter(&plan.root),
29589 "SHA1 must stay a residual filter, not fold away: {:?}",
29590 plan.root
29591 );
29592 let PlanNode::Filter { residual, .. } = &plan.root else {
29593 panic!("expected Filter root");
29594 };
29595 assert!(
29596 matches!(
29597 residual.as_ref(),
29598 Some(Expression::FunctionCall(
29599 spargebra::algebra::Function::Sha1,
29600 _
29601 ))
29602 ),
29603 "expected SHA1 residual, got {residual:?}"
29604 );
29605 }
29606
29607 #[test]
29608 fn bind_numeric_equality_is_not_folded() {
29609 let plan = LogicalPlan::parse(
29610 r#"SELECT ?x WHERE {
29611 ?x <http://ex/p> ?v .
29612 BIND(1.0e0 AS ?c)
29613 FILTER(?v = ?c)
29614 }"#,
29615 )
29616 .unwrap();
29617 assert!(
29618 !contains_filter(&plan.root),
29619 "the exact numeric = moves into the scan, got {:?}",
29620 plan.root
29621 );
29622 let mut scans = Vec::new();
29623 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29624 assert_eq!(scans.len(), 1);
29625 assert!(
29626 scans[0].pattern.object.is_none(),
29627 "numeric = must not ground the scan: {:?}",
29628 scans[0]
29629 );
29630 assert!(
29631 scans[0].eager.contains(&SlotComparison {
29632 slot: QuadSlot::Object,
29633 op: CompareOp::Eq,
29634 term: EncodedTerm::from(&Literal::from(1.0f64)),
29635 }),
29636 "the scan must carry the eager numeric =: {:?}",
29637 scans[0].eager
29638 );
29639 }
29640
29641 #[test]
29642 fn values_multi_row_sameterm_is_not_folded() {
29643 let plan = LogicalPlan::parse(
29644 r#"SELECT ?o ?b WHERE {
29645 VALUES ?c { <http://ex/a> <http://ex/b> }
29646 ?b ?p ?o .
29647 FILTER(sameTerm(?b, ?c))
29648 }"#,
29649 )
29650 .unwrap();
29651 assert!(
29652 contains_filter(&plan.root),
29653 "multi-row VALUES sameTerm must stay a Filter, got {:?}",
29654 plan.root
29655 );
29656 let mut scans = Vec::new();
29657 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29658 assert_eq!(scans.len(), 1);
29659 assert!(
29660 scans[0].pattern.subject.is_none()
29661 && scans[0].pattern.predicate.is_none()
29662 && scans[0].pattern.object.is_none(),
29663 "multi-row VALUES must not ground the scan: {:?}",
29664 scans[0]
29665 );
29666 }
29667
29668 #[test]
29669 fn union_scan_and_conflicting_values_grounds_scan_but_keeps_filter() {
29670 let crow = EncodedTerm::from(&NamedNode::new("http://ex/crow").unwrap());
29671 let other = EncodedTerm::from(&NamedNode::new("http://ex/other").unwrap());
29672 let plan = LogicalPlan::parse(
29673 r#"SELECT ?b WHERE {
29674 { ?b ?p ?o } UNION { VALUES ?b { <http://ex/other> } }
29675 FILTER(sameTerm(?b, <http://ex/crow>))
29676 }"#,
29677 )
29678 .unwrap();
29679 assert!(
29680 contains_filter(&plan.root),
29681 "conflicting VALUES arm must keep FILTER so <other> cannot leak, got {:?}",
29682 plan.root
29683 );
29684 assert!(
29685 values_has_term(&plan.root, &other),
29686 "VALUES <other> must stay a producer, got {:?}",
29687 plan.root
29688 );
29689 let mut scans = Vec::new();
29690 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29691 assert_eq!(
29692 scans.len(),
29693 1,
29694 "expected the BGP arm's scan, got {:?}",
29695 plan.root
29696 );
29697 assert_eq!(
29698 scans[0].pattern.subject,
29699 Some(crow),
29700 "scan arm should still be prefixed, got {:?}",
29701 scans[0]
29702 );
29703 }
29704
29705 #[test]
29706 fn bind_around_union_grounds_scan_but_keeps_filter() {
29707 let crow = EncodedTerm::from(&NamedNode::new("http://ex/crow").unwrap());
29708 let other = EncodedTerm::from(&NamedNode::new("http://ex/other").unwrap());
29709 let plan = LogicalPlan::parse(
29710 r#"SELECT ?b ?c WHERE {
29711 { ?b ?p ?o } UNION { VALUES ?b { <http://ex/other> } }
29712 BIND(<http://ex/crow> AS ?c)
29713 FILTER(sameTerm(?b, ?c))
29714 }"#,
29715 )
29716 .unwrap();
29717 assert!(
29718 contains_filter(&plan.root),
29719 "BIND outside UNION must not drop FILTER when a VALUES arm disagrees, got {:?}",
29720 plan.root
29721 );
29722 assert!(
29723 values_has_term(&plan.root, &other),
29724 "VALUES <other> must stay, got {:?}",
29725 plan.root
29726 );
29727 let mut scans = Vec::new();
29728 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29729 assert_eq!(scans.len(), 1);
29730 assert_eq!(
29731 scans[0].pattern.subject,
29732 Some(crow),
29733 "scan arm should still be prefixed, got {:?}",
29734 scans[0]
29735 );
29736 }
29737
29738 #[test]
29739 fn union_join_arms_with_disagreeing_values_keep_filter() {
29740 let crow = EncodedTerm::from(&NamedNode::new("http://ex/crow").unwrap());
29741 let other = EncodedTerm::from(&NamedNode::new("http://ex/other").unwrap());
29742 let plan = LogicalPlan::parse(
29743 r#"SELECT ?s ?b WHERE {
29744 {
29745 VALUES ?b { <http://ex/crow> }
29746 ?s <http://ex/p> ?b
29747 } UNION {
29748 VALUES ?b { <http://ex/other> }
29749 ?s <http://ex/q> ?b
29750 }
29751 FILTER(sameTerm(?b, <http://ex/crow>))
29752 }"#,
29753 )
29754 .unwrap();
29755 assert!(
29756 contains_filter(&plan.root),
29757 "VALUES <other> inside a UNION join arm must keep FILTER, got {:?}",
29758 plan.root
29759 );
29760 assert!(
29761 values_has_term(&plan.root, &other),
29762 "disagreeing VALUES must not be rewritten away, got {:?}",
29763 plan.root
29764 );
29765 let mut scans = Vec::new();
29766 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29767 assert_eq!(
29768 scans.len(),
29769 2,
29770 "expected a scan per UNION arm, got {:?}",
29771 plan.root
29772 );
29773 assert!(
29774 scans
29775 .iter()
29776 .any(|scan| scan.pattern.object.as_ref() == Some(&crow))
29777 && scans
29778 .iter()
29779 .any(|scan| scan.pattern.object.as_ref() == Some(&other)),
29780 "each VALUES join prefixes its own scan; a later sameTerm does not overwrite the disagreeing arm, got {:?}",
29781 plan.root
29782 );
29783 }
29784
29785 #[test]
29786 fn union_both_arms_agreeing_values_drops_filter() {
29787 let crow = EncodedTerm::from(&NamedNode::new("http://ex/crow").unwrap());
29788 let plan = LogicalPlan::parse(
29789 r#"SELECT ?s ?b WHERE {
29790 {
29791 VALUES ?b { <http://ex/crow> }
29792 ?s <http://ex/p> ?b
29793 } UNION {
29794 VALUES ?b { <http://ex/crow> }
29795 ?s <http://ex/q> ?b
29796 }
29797 FILTER(sameTerm(?b, <http://ex/crow>))
29798 }"#,
29799 )
29800 .unwrap();
29801 assert!(
29802 !contains_filter(&plan.root),
29803 "agreeing VALUES in both UNION arms should drop FILTER, got {:?}",
29804 plan.root
29805 );
29806 let mut scans = Vec::new();
29807 for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29808 assert_eq!(scans.len(), 2);
29809 assert!(
29810 scans
29811 .iter()
29812 .all(|scan| scan.pattern.object.as_ref() == Some(&crow)),
29813 "both scans should be prefixed, got {:?}",
29814 plan.root
29815 );
29816 }
29817
29818 #[test]
29819 fn optional_union_conflicting_values_grounds_scan_but_keeps_filter() {
29820 let crow = EncodedTerm::from(&NamedNode::new("http://ex/crow").unwrap());
29821 let other = EncodedTerm::from(&NamedNode::new("http://ex/other").unwrap());
29822 let plan = LogicalPlan::parse(
29823 r#"SELECT * WHERE {
29824 ?person <http://ex/livesIn> ?city .
29825 OPTIONAL {
29826 { ?b ?p ?o } UNION { VALUES ?b { <http://ex/other> } }
29827 FILTER(sameTerm(?b, <http://ex/crow>))
29828 }
29829 }"#,
29830 )
29831 .unwrap();
29832 let PlanNode::LeftJoin {
29833 right,
29834 early_filter,
29835 ..
29836 } = &plan.root
29837 else {
29838 panic!("expected LeftJoin, got {:?}", plan.root);
29839 };
29840 assert!(
29841 early_filter.is_some() || contains_filter(right),
29842 "OPTIONAL early filter must stay when a VALUES arm disagrees, early={early_filter:?} right={right:?}"
29843 );
29844 assert!(
29845 values_has_term(right, &other),
29846 "VALUES <other> must stay on the optional side, got {right:?}"
29847 );
29848 let mut scans = Vec::new();
29849 for_each_scan(right, &mut |scan| scans.push(scan));
29850 assert_eq!(
29851 scans.len(),
29852 1,
29853 "expected the optional BGP scan, got {right:?}"
29854 );
29855 assert_eq!(
29856 scans[0].pattern.subject,
29857 Some(crow),
29858 "optional scan arm should still be prefixed, got {:?}",
29859 scans[0]
29860 );
29861 }
29862
29863 #[test]
29864 fn optional_inner_equality_filter_grounds_right_scan() {
29865 let plan = LogicalPlan::parse(
29866 r#"SELECT * WHERE {
29867 ?person <http://ex/livesIn> ?city .
29868 OPTIONAL { ?city <http://ex/hasWeather> ?w FILTER(?w = "Sunny") }
29869 }"#,
29870 )
29871 .unwrap();
29872 let PlanNode::LeftJoin {
29873 right,
29874 early_filter,
29875 ..
29876 } = &plan.root
29877 else {
29878 panic!("expected LeftJoin, got {:?}", plan.root);
29879 };
29880 assert!(
29881 early_filter.is_none(),
29882 "identity-safe OPTIONAL FILTER should fold, early={early_filter:?}"
29883 );
29884 assert!(
29885 !contains_filter(right),
29886 "folded OPTIONAL FILTER should not leave a Filter, got {right:?}"
29887 );
29888 let PlanNode::Scan(scan) = right.as_ref() else {
29889 panic!("expected Scan, got {right:?}");
29890 };
29891 assert_eq!(
29892 scan.pattern.object,
29893 Some(EncodedTerm::from(&Literal::from("Sunny")))
29894 );
29895 assert_eq!(scan.object.as_ref().map(Variable::as_str), Some("w"));
29896 }
29897
29898 #[test]
29899 fn optional_inner_bind_sameterm_grounds_right_scan() {
29900 let iri = NamedNode::new("http://ex/CrowHill").unwrap();
29901 let plan = LogicalPlan::parse(
29902 r#"SELECT * WHERE {
29903 ?person <http://ex/livesIn> ?city .
29904 OPTIONAL {
29905 ?b ?p ?o .
29906 BIND(<http://ex/CrowHill> AS ?c)
29907 FILTER(sameTerm(?b, ?c))
29908 }
29909 }"#,
29910 )
29911 .unwrap();
29912 let PlanNode::LeftJoin {
29913 right,
29914 early_filter,
29915 ..
29916 } = &plan.root
29917 else {
29918 panic!("expected LeftJoin, got {:?}", plan.root);
29919 };
29920 assert!(
29921 early_filter.is_none(),
29922 "OPTIONAL var-var sameTerm should fold, early={early_filter:?}"
29923 );
29924 assert!(
29925 !contains_filter(right),
29926 "folded OPTIONAL BIND sameTerm should not leave a Filter, got {right:?}"
29927 );
29928 let mut scans = Vec::new();
29929 for_each_scan(right, &mut |scan| scans.push(scan));
29930 assert_eq!(scans.len(), 1, "expected one optional scan, got {right:?}");
29931 assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("b"));
29932 assert_eq!(
29933 scans[0].pattern.subject,
29934 Some(EncodedTerm::from(&iri)),
29935 "optional scan subject should be grounded"
29936 );
29937 }
29938
29939 #[test]
29940 fn outer_filter_on_optional_var_grounds_but_keeps_filter() {
29941 let plan = LogicalPlan::parse(
29942 r#"SELECT * WHERE {
29943 ?person <http://ex/livesIn> ?city .
29944 OPTIONAL { ?city <http://ex/hasWeather> ?w }
29945 FILTER(?w = "Sunny")
29946 }"#,
29947 )
29948 .unwrap();
29949 let PlanNode::Filter { inner, early, .. } = &plan.root else {
29950 panic!(
29951 "outer FILTER on maybe-unbound ?w must stay Filter(LeftJoin), got {:?}",
29952 plan.root
29953 );
29954 };
29955 assert!(
29956 early.is_some(),
29957 "maybe-unbound identity FILTER must be kept, early={early:?}"
29958 );
29959 let PlanNode::LeftJoin { right, .. } = inner.as_ref() else {
29960 panic!("expected LeftJoin under Filter, got {inner:?}");
29961 };
29962 let PlanNode::Scan(scan) = right.as_ref() else {
29963 panic!("expected optional Scan, got {right:?}");
29964 };
29965 assert_eq!(
29966 scan.pattern.object,
29967 Some(EncodedTerm::from(&Literal::from("Sunny"))),
29968 "optional scan should still be grounded"
29969 );
29970 }
29971
29972 #[test]
29973 fn having_identity_on_optional_group_key_grounds_but_keeps_filter() {
29974 let plan = LogicalPlan::parse(
29975 r#"SELECT ?w (COUNT(*) AS ?c) WHERE {
29976 ?person <http://ex/livesIn> ?city .
29977 OPTIONAL { ?city <http://ex/hasWeather> ?w }
29978 } GROUP BY ?w HAVING (?w = "Sunny")"#,
29979 )
29980 .unwrap();
29981 let mut node = &plan.root;
29982 while let PlanNode::Extend { inner, .. } = node {
29983 node = inner;
29984 }
29985 let PlanNode::Filter { inner, early, .. } = node else {
29986 panic!(
29987 "HAVING on maybe-unbound group key must stay Filter(Group), got {:?}",
29988 plan.root
29989 );
29990 };
29991 assert!(
29992 early.is_some(),
29993 "maybe-unbound identity HAVING must be kept, early={early:?}"
29994 );
29995 assert!(
29996 matches!(inner.as_ref(), PlanNode::Group { .. }),
29997 "HAVING Filter inner should be Group, got {inner:?}"
29998 );
29999 let sunny = EncodedTerm::from(&Literal::from("Sunny"));
30000 let mut grounded = false;
30001 for_each_scan(inner, &mut |scan| {
30002 if scan.object.as_ref().map(Variable::as_str) == Some("w") {
30003 grounded = scan.pattern.object.as_ref() == Some(&sunny);
30004 }
30005 });
30006 assert!(
30007 grounded,
30008 "optional ?w scan should still be grounded, got {inner:?}"
30009 );
30010 }
30011
30012 #[test]
30013 fn ask_inequality_filter_moves_to_the_scan_and_broadcasts() {
30014 let query = SparqlParser::new()
30015 .parse_query(
30016 r#"ASK {
30017 ?p <http://ex/livesIn> ?c .
30018 ?c <http://ex/hasWeather> ?w FILTER(?w != "Sunny")
30019 }"#,
30020 )
30021 .unwrap();
30022 let Query::Ask { pattern, .. } = query else {
30023 panic!("expected ASK");
30024 };
30025 let plan = LogicalPlan::from_ask_algebra(pattern, None).unwrap();
30026 assert_eq!(
30027 first_join_strategy(&plan.root),
30028 Some(JoinStrategy::Broadcast)
30029 );
30030 assert!(
30034 !contains_filter(&plan.root),
30035 "the exact != must move into the scan: {:?}",
30036 plan.root
30037 );
30038 let mut moved = 0;
30039 let mut seen = Vec::new();
30040 for_each_scan(&plan.root, &mut |scan| {
30041 seen.extend(scan.eager.clone());
30042 if scan.eager.contains(&SlotComparison {
30043 slot: QuadSlot::Object,
30044 op: CompareOp::Ne,
30045 term: EncodedTerm::from(&Literal::from("Sunny")),
30046 }) {
30047 moved += 1;
30048 assert!(
30049 scan.pattern.object.is_none(),
30050 "!= must not identity-ground the object: {scan:?}"
30051 );
30052 }
30053 });
30054 assert_eq!(
30055 moved, 1,
30056 "one weather scan carries the eager !=; saw {seen:?}"
30057 );
30058 let text = explain_est(
30059 r#"ASK {
30060 ?p <http://ex/livesIn> ?c .
30061 ?c <http://ex/hasWeather> ?w FILTER(?w != "Sunny")
30062 }"#,
30063 None,
30064 );
30065 assert!(!text.contains("(filter"), "{text}");
30066 assert!(text.contains("broadcast"), "{text}");
30067 }
30068
30069 #[test]
30070 fn ask_equality_filter_folds_then_broadcasts_bare_scan() {
30071 let query = SparqlParser::new()
30072 .parse_query(
30073 r#"ASK {
30074 ?p <http://ex/livesIn> ?c .
30075 ?c <http://ex/hasWeather> ?w FILTER(?w = "Sunny")
30076 }"#,
30077 )
30078 .unwrap();
30079 let Query::Ask { pattern, .. } = query else {
30080 panic!("expected ASK");
30081 };
30082 let plan = LogicalPlan::from_ask_algebra(pattern, None).unwrap();
30083 assert_eq!(
30084 first_join_strategy(&plan.root),
30085 Some(JoinStrategy::Broadcast)
30086 );
30087 assert!(
30088 !contains_filter(&plan.root),
30089 "folded = should leave a bare Scan, got {:?}",
30090 plan.root
30091 );
30092 let sunny = EncodedTerm::from(&Literal::from("Sunny"));
30093 let mut saw_sunny = false;
30094 for_each_scan(&plan.root, &mut |scan| {
30095 if scan.pattern.object.as_ref() == Some(&sunny) {
30096 saw_sunny = true;
30097 assert_eq!(scan.object.as_ref().map(Variable::as_str), Some("w"));
30098 }
30099 });
30100 assert!(
30101 saw_sunny,
30102 "Sunny should be a bound scan slot: {:?}",
30103 plan.root
30104 );
30105 let text = explain_est(
30106 r#"ASK {
30107 ?p <http://ex/livesIn> ?c .
30108 ?c <http://ex/hasWeather> ?w FILTER(?w = "Sunny")
30109 }"#,
30110 None,
30111 );
30112 assert!(!text.contains("(filter"), "{text}");
30113 assert!(text.contains("\"Sunny\""), "{text}");
30114 assert!(text.contains("broadcast"), "{text}");
30115 }
30116
30117 #[test]
30118 fn sequence_path_stays_bgp_scans() {
30119 let plan =
30120 LogicalPlan::parse(r#"SELECT ?s ?o WHERE { ?s <http://ex/p>/<http://ex/q> ?o }"#)
30121 .unwrap();
30122 assert!(
30123 plan.root.as_path().is_none(),
30124 "simple / must not lower to Path: {:?}",
30125 plan.root
30126 );
30127 let scans = plan.scans().unwrap();
30128 assert_eq!(scans.len(), 2, "expected two BGP scans, got {scans:?}");
30129 assert_eq!(plan.join_ops().unwrap().len(), 1);
30130 }
30131
30132 #[test]
30133 fn inverse_path_stays_swapped_bgp() {
30134 let plan =
30135 LogicalPlan::parse(r#"SELECT ?s WHERE { ?s ^<http://ex/p> <http://ex/b> }"#).unwrap();
30136 assert!(plan.root.as_path().is_none(), "got {:?}", plan.root);
30137 let scans = plan.scans().unwrap();
30138 assert_eq!(scans.len(), 1);
30139 assert_eq!(
30140 scans[0].pattern.subject,
30141 Some(EncodedTerm::from(&NamedNode::new("http://ex/b").unwrap()))
30142 );
30143 assert_eq!(scans[0].object.as_ref().map(Variable::as_str), Some("s"));
30144 }
30145
30146 #[test]
30147 fn star_path_lowers_to_path_node() {
30148 let plan =
30149 LogicalPlan::parse(r#"SELECT ?o WHERE { <http://ex/a> <http://ex/p>* ?o }"#).unwrap();
30150 let path = plan.root.as_path().expect("expected Path");
30151 assert!(matches!(path.path, PropertyPath::ZeroOrMore(_)));
30152 assert!(path.subject_term.is_some());
30153 assert_eq!(path.object.as_ref().map(Variable::as_str), Some("o"));
30154 assert_eq!(plan.projection, vec![var("o")]);
30155 }
30156
30157 #[test]
30158 fn blank_node_path_start_is_unprojected_var() {
30159 let plan = LogicalPlan::parse(r#"SELECT ?o WHERE { _:s <http://ex/p>* ?o }"#).unwrap();
30160 assert_eq!(plan.projection, vec![var("o")]);
30161 let path = plan.root.as_path().expect("expected Path");
30162 let start = path
30163 .subject
30164 .as_ref()
30165 .expect("blank node becomes a variable");
30166 assert_ne!(start, &var("o"));
30167 assert!(!plan.projection.contains(start));
30168 assert!(path.subject_term.is_none());
30169 }
30170
30171 #[test]
30172 fn unbound_star_sorts_after_selective_scan() {
30173 let plan = LogicalPlan::parse(
30174 r#"SELECT ?s ?y WHERE {
30175 ?s <http://ex/p> ?x .
30176 ?x <http://ex/knows>* ?y .
30177 }"#,
30178 )
30179 .unwrap();
30180 let PlanNode::Join {
30181 left, right, meta, ..
30182 } = &plan.root
30183 else {
30184 panic!("expected Join, got {:?}", plan.root);
30185 };
30186 assert!(
30187 left.as_scan().is_some(),
30188 "selective scan should be left of unbound *: {left:?}"
30189 );
30190 let path = right.as_path().expect("Path on the right");
30191 assert!(matches!(path.path, PropertyPath::ZeroOrMore(_)));
30192 assert!(path.subject_term.is_none());
30193 assert_eq!(meta.strategy, JoinStrategy::Broadcast);
30194 }
30195
30196 #[test]
30197 fn open_star_and_plus_cost_as_all_pairs() {
30198 let open_star =
30199 LogicalPlan::parse(r#"SELECT ?s ?o WHERE { ?s <http://ex/p>* ?o }"#).unwrap();
30200 let open_plus =
30201 LogicalPlan::parse(r#"SELECT ?s ?o WHERE { ?s <http://ex/p>+ ?o }"#).unwrap();
30202 let bound =
30203 LogicalPlan::parse(r#"SELECT ?o WHERE { <http://ex/a> <http://ex/p>* ?o }"#).unwrap();
30204 let open_star_rows = open_star
30205 .root
30206 .as_path()
30207 .unwrap()
30208 .produced_row_count_estimate;
30209 let open_plus_rows = open_plus
30210 .root
30211 .as_path()
30212 .unwrap()
30213 .produced_row_count_estimate;
30214 let bound_rows = bound.root.as_path().unwrap().produced_row_count_estimate;
30215 assert_eq!(open_star_rows, u64::MAX / 4);
30216 assert_eq!(open_plus_rows, u64::MAX / 4);
30217 assert!(
30218 bound_rows < open_star_rows,
30219 "one-end * must cost below open *: {bound_rows} vs {open_star_rows}"
30220 );
30221 }
30222
30223 #[test]
30224 fn identity_filter_grounds_path_end() {
30225 let sparql = r#"SELECT ?s ?o WHERE { ?s <http://ex/p>* ?o FILTER(?o = <http://ex/t>) }"#;
30226 let plan = LogicalPlan::parse(sparql).unwrap();
30227 assert!(
30228 !contains_filter(&plan.root),
30229 "identity-safe = should fold into the Path, got {:?}",
30230 plan.root
30231 );
30232 let path = plan.root.as_path().expect("expected Path");
30233 assert_eq!(path.object.as_ref().map(Variable::as_str), Some("o"));
30234 assert_eq!(
30235 path.object_term,
30236 Some(EncodedTerm::from(&NamedNode::new("http://ex/t").unwrap()))
30237 );
30238 assert!(
30239 path.produced_row_count_estimate < 1_000_000_000,
30240 "bound end must recost below unbound *: {}",
30241 path.produced_row_count_estimate
30242 );
30243 let text = explain_est(sparql, None);
30244 assert!(!text.contains("(filter"), "{text}");
30245 }
30246
30247 #[test]
30248 fn sameterm_grounds_path_end() {
30249 let plan = LogicalPlan::parse(
30250 r#"SELECT ?s ?o WHERE { ?s <http://ex/p>* ?o FILTER(sameTerm(?o, <http://ex/t>)) }"#,
30251 )
30252 .unwrap();
30253 assert!(
30254 !contains_filter(&plan.root),
30255 "sameTerm should fold into the Path, got {:?}",
30256 plan.root
30257 );
30258 let mut paths = Vec::new();
30259 for_each_path(&plan.root, &mut |path| paths.push(path));
30260 assert_eq!(paths.len(), 1);
30261 assert_eq!(
30262 paths[0].object_term,
30263 Some(EncodedTerm::from(&NamedNode::new("http://ex/t").unwrap()))
30264 );
30265 }
30266
30267 #[test]
30268 fn bind_sameterm_grounds_path_end_and_strings() {
30269 let iri = NamedNode::new("http://yago-knowledge.org/resource/Crow_Hill_Q20861371").unwrap();
30270 let encoded = EncodedTerm::from(&iri);
30271 let expected_strings =
30272 waratah_storage::strings_entries_for_term(&Term::NamedNode(iri.clone()), &encoded);
30273 let plan = LogicalPlan::parse(
30274 r#"SELECT ?s ?o WHERE {
30275 ?s <http://ex/p>* ?o .
30276 BIND(<http://yago-knowledge.org/resource/Crow_Hill_Q20861371> AS ?c)
30277 FILTER(sameTerm(?o, ?c))
30278 }"#,
30279 )
30280 .unwrap();
30281 assert!(
30282 !contains_filter(&plan.root),
30283 "BIND sameTerm should fold into the Path, got {:?}",
30284 plan.root
30285 );
30286 let mut paths = Vec::new();
30287 for_each_path(&plan.root, &mut |path| paths.push(path));
30288 assert_eq!(paths.len(), 1);
30289 assert_eq!(paths[0].object.as_ref().map(Variable::as_str), Some("o"));
30290 assert_eq!(paths[0].object_term, Some(encoded));
30291 for (hash, raw) in &expected_strings {
30292 assert!(
30293 paths[0].strings.iter().any(|(h, s)| h == hash && s == raw),
30294 "path.strings should include {raw}, got {:?}",
30295 paths[0].strings
30296 );
30297 }
30298 }
30299
30300 #[test]
30301 fn numeric_equality_does_not_ground_path() {
30302 let plan =
30303 LogicalPlan::parse(r#"SELECT ?s ?o WHERE { ?s <http://ex/p>* ?o FILTER(?o = 1) }"#)
30304 .unwrap();
30305 assert!(
30306 contains_filter(&plan.root),
30307 "numeric = must stay a Filter, got {:?}",
30308 plan.root
30309 );
30310 let mut paths = Vec::new();
30311 for_each_path(&plan.root, &mut |path| paths.push(path));
30312 assert_eq!(paths.len(), 1);
30313 assert!(
30314 paths[0].object_term.is_none() && paths[0].subject_term.is_none(),
30315 "numeric = must not ground Path ends: {:?}",
30316 paths[0]
30317 );
30318 }
30319
30320 #[test]
30321 fn outer_filter_after_optional_path_keeps_filter() {
30322 let plan = LogicalPlan::parse(
30323 r#"SELECT * WHERE {
30324 ?s <http://ex/p> ?x
30325 OPTIONAL { ?x <http://ex/knows>* ?o }
30326 FILTER(?o = <http://ex/t>)
30327 }"#,
30328 )
30329 .unwrap();
30330 assert!(
30331 contains_filter(&plan.root),
30332 "outer FILTER on maybe-unbound Path var must stay, got {:?}",
30333 plan.root
30334 );
30335 let PlanNode::Filter { inner, early, .. } = &plan.root else {
30336 panic!("expected Filter(LeftJoin), got {:?}", plan.root);
30337 };
30338 assert!(
30339 early.is_some(),
30340 "maybe-unbound identity FILTER must be kept, early={early:?}"
30341 );
30342 let PlanNode::LeftJoin { right, .. } = inner.as_ref() else {
30343 panic!("expected LeftJoin under Filter, got {inner:?}");
30344 };
30345 let mut paths = Vec::new();
30346 for_each_path(right, &mut |path| paths.push(path));
30347 assert_eq!(paths.len(), 1);
30348 assert_eq!(
30349 paths[0].object_term,
30350 Some(EncodedTerm::from(&NamedNode::new("http://ex/t").unwrap())),
30351 "optional Path should still be grounded"
30352 );
30353 }
30354
30355 #[test]
30356 fn graph_var_is_supported_and_blocks_default() {
30357 let plan = LogicalPlan::parse(r#"SELECT ?s ?g WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#)
30358 .unwrap();
30359 let scans = plan.scans().unwrap();
30360 assert_eq!(scans.len(), 1);
30361 assert_eq!(scans[0].graph.as_ref().map(Variable::as_str), Some("g"));
30362 assert!(scans[0].pattern.graph_name.is_none());
30363 let filter = scans[0]
30364 .graph_filter
30365 .as_ref()
30366 .expect("unbound GRAPH ?g must send a block-list");
30367 assert!(filter.is_exclude());
30368 assert_eq!(filter.terms(), &[EncodedTerm::DefaultGraph]);
30369 let sse = explain_est(
30370 r#"SELECT ?s ?g WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#,
30371 None,
30372 );
30373 assert!(
30374 sse.contains("graph_filter block(1)"),
30375 "EXPLAIN should show the DefaultGraph block-list: {sse}"
30376 );
30377 }
30378
30379 #[test]
30380 fn graph_same_term_grounds_g() {
30381 let plan = LogicalPlan::parse(
30382 r#"SELECT ?s ?g WHERE {
30383 GRAPH ?g { ?s <http://ex/p> ?o }
30384 FILTER(sameTerm(?g, <http://ex/A>))
30385 }"#,
30386 )
30387 .unwrap();
30388 let scans = plan.scans().unwrap();
30389 assert_eq!(scans.len(), 1);
30390 assert_eq!(
30391 scans[0].pattern.graph_name,
30392 Some(EncodedTerm::from(&NamedNode::new("http://ex/A").unwrap()))
30393 );
30394 assert!(
30395 scans[0].graph_filter.is_none(),
30396 "grounded G must not keep a graph_filter: {:?}",
30397 scans[0].graph_filter
30398 );
30399 let sse = explain_est(
30400 r#"SELECT ?s ?g WHERE {
30401 GRAPH ?g { ?s <http://ex/p> ?o }
30402 FILTER(sameTerm(?g, <http://ex/A>))
30403 }"#,
30404 None,
30405 );
30406 assert!(
30407 !sse.contains("graph_filter"),
30408 "grounded G should not show graph_filter: {sse}"
30409 );
30410 }
30411
30412 #[test]
30413 fn graph_not_same_term_folds_into_block_list() {
30414 let plan = LogicalPlan::parse(
30415 r#"SELECT ?s ?g WHERE {
30416 GRAPH ?g { ?s <http://ex/p> ?o }
30417 FILTER(!sameTerm(?g, <http://ex/A>) && !sameTerm(?g, <http://ex/B>))
30418 }"#,
30419 )
30420 .unwrap();
30421 let scans = plan.scans().unwrap();
30422 assert_eq!(scans.len(), 1);
30423 let filter = scans[0]
30424 .graph_filter
30425 .as_ref()
30426 .expect("!sameTerm should fold into the GRAPH block-list");
30427 assert!(filter.is_exclude());
30428 let a = EncodedTerm::from(&NamedNode::new("http://ex/A").unwrap());
30429 let b = EncodedTerm::from(&NamedNode::new("http://ex/B").unwrap());
30430 assert!(filter.contains_member(&EncodedTerm::DefaultGraph));
30431 assert!(filter.contains_member(&a));
30432 assert!(filter.contains_member(&b));
30433 assert_eq!(filter.len(), 3);
30434 assert!(
30435 !contains_filter(&plan.root),
30436 "folded !sameTerm conjuncts should drop the Filter, got {:?}",
30437 plan.root
30438 );
30439 }
30440
30441 #[test]
30442 fn graph_not_same_term_on_optional_pushes_block_list_but_keeps_filter() {
30443 let plan = LogicalPlan::parse(
30444 r#"SELECT ?s ?g WHERE {
30445 ?s <http://ex/p> ?o
30446 OPTIONAL { GRAPH ?g { ?s <http://ex/q> ?x } }
30447 FILTER(!sameTerm(?g, <http://ex/g1>))
30448 }"#,
30449 )
30450 .unwrap();
30451 let PlanNode::Filter { inner, early, .. } = &plan.root else {
30452 panic!(
30453 "maybe-unbound !sameTerm(?g) must stay Filter, got {:?}",
30454 plan.root
30455 );
30456 };
30457 assert!(
30458 early.is_some(),
30459 "OPTIONAL-miss rows need the residual !sameTerm, early={early:?}"
30460 );
30461 let g1 = EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap());
30462 let mut graph_scan_blocked = false;
30463 for_each_scan(inner, &mut |scan| {
30464 if scan.graph.as_ref().map(Variable::as_str) == Some("g") {
30465 graph_scan_blocked = scan
30466 .graph_filter
30467 .as_ref()
30468 .is_some_and(|f| f.is_exclude() && f.contains_member(&g1));
30469 }
30470 });
30471 assert!(
30472 graph_scan_blocked,
30473 "GRAPH scan should still get the g1 block-list, got {inner:?}"
30474 );
30475 }
30476
30477 #[test]
30478 fn graph_not_same_term_on_union_keeps_filter() {
30479 let plan = LogicalPlan::parse(
30480 r#"SELECT ?s ?g WHERE {
30481 { ?s <http://ex/p> ?o }
30482 UNION
30483 { GRAPH ?g { ?s <http://ex/q> ?x } }
30484 FILTER(!sameTerm(?g, <http://ex/g1>))
30485 }"#,
30486 )
30487 .unwrap();
30488 let PlanNode::Filter { inner, early, .. } = &plan.root else {
30489 panic!(
30490 "UNION omit of ?g must keep !sameTerm Filter, got {:?}",
30491 plan.root
30492 );
30493 };
30494 assert!(
30495 early.is_some(),
30496 "UNION arm without ?g needs the residual !sameTerm, early={early:?}"
30497 );
30498 let g1 = EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap());
30499 let mut graph_scan_blocked = false;
30500 for_each_scan(inner, &mut |scan| {
30501 if scan.graph.as_ref().map(Variable::as_str) == Some("g") {
30502 graph_scan_blocked = scan
30503 .graph_filter
30504 .as_ref()
30505 .is_some_and(|f| f.is_exclude() && f.contains_member(&g1));
30506 }
30507 });
30508 assert!(
30509 graph_scan_blocked,
30510 "GRAPH UNION arm should still get the g1 block-list, got {inner:?}"
30511 );
30512 }
30513
30514 #[test]
30515 fn two_triple_graph_join_keys_include_g() {
30516 let plan = LogicalPlan::parse(
30517 r#"SELECT ?s ?x WHERE {
30518 GRAPH ?g { ?s <http://ex/p> ?o . ?o <http://ex/q> ?x }
30519 }"#,
30520 )
30521 .unwrap();
30522 let joins = plan.join_ops().unwrap();
30523 assert_eq!(joins.len(), 1);
30524 assert!(
30525 joins[0].hash_keys.iter().any(|v| v.as_str() == "g"),
30526 "same-graph BGP must join on ?g: {:?}",
30527 joins[0].hash_keys
30528 );
30529 assert!(
30530 joins[0].hash_keys.iter().any(|v| v.as_str() == "o"),
30531 "inner object join key should remain: {:?}",
30532 joins[0].hash_keys
30533 );
30534 }
30535
30536 #[test]
30537 fn from_named_without_from_empties_bare_bgp() {
30538 let plan = LogicalPlan::parse(
30539 r#"SELECT ?s FROM NAMED <http://ex/g> WHERE { ?s <http://ex/p> ?o }"#,
30540 )
30541 .unwrap();
30542 assert!(
30543 matches!(&plan.root, PlanNode::Values(v) if v.rows.is_empty()),
30544 "FROM NAMED without FROM must not scan the SPARQL default graph: {:?}",
30545 plan.root
30546 );
30547 }
30548
30549 #[test]
30550 fn from_named_without_from_empties_bare_path() {
30551 let plan = LogicalPlan::parse(
30552 r#"SELECT ?s FROM NAMED <http://ex/g> WHERE { ?s <http://ex/p>+ ?o }"#,
30553 )
30554 .unwrap();
30555 assert!(
30556 matches!(&plan.root, PlanNode::Values(v) if v.rows.is_empty()),
30557 "empty SPARQL default must empty a default-graph path: {:?}",
30558 plan.root
30559 );
30560 }
30561
30562 #[test]
30563 fn from_named_without_from_keeps_values() {
30564 let plan =
30565 LogicalPlan::parse(r#"SELECT ?x FROM NAMED <http://ex/g> WHERE { VALUES ?x { 1 } }"#)
30566 .unwrap();
30567 match &plan.root {
30568 PlanNode::Values(values) => {
30569 assert_eq!(values.variables, vec![var("x")]);
30570 assert_eq!(values.rows.len(), 1);
30571 }
30572 other => panic!("VALUES is not a default-graph scan: {other:?}"),
30573 }
30574 }
30575
30576 #[test]
30577 fn from_named_without_from_keeps_bind() {
30578 let plan =
30579 LogicalPlan::parse(r#"SELECT ?x FROM NAMED <http://ex/g> WHERE { BIND(1 AS ?x) }"#)
30580 .unwrap();
30581 match &plan.root {
30582 PlanNode::Values(values) => {
30583 assert_eq!(values.variables, vec![var("x")]);
30584 assert_eq!(values.rows.len(), 1);
30585 }
30586 PlanNode::Extend {
30587 inner, variable, ..
30588 } => {
30589 assert_eq!(variable.as_str(), "x");
30590 assert!(
30591 matches!(inner.as_ref(), PlanNode::Unit),
30592 "BIND over empty group must keep Unit, got {inner:?}"
30593 );
30594 }
30595 other => panic!("BIND is not a default-graph scan: {other:?}"),
30596 }
30597 }
30598
30599 #[test]
30600 fn from_named_without_from_empty_group_is_unit() {
30601 let plan = LogicalPlan::parse(r#"SELECT * FROM NAMED <http://ex/g> WHERE { }"#).unwrap();
30602 assert!(
30603 matches!(plan.root, PlanNode::Unit),
30604 "empty group is join identity, not 0-row VALUES: {:?}",
30605 plan.root
30606 );
30607 }
30608
30609 #[test]
30610 fn from_named_union_values_with_default_bgp_keeps_values_arm() {
30611 let plan = LogicalPlan::parse(
30612 r#"SELECT ?x FROM NAMED <http://ex/g> WHERE {
30613 { VALUES ?x { 1 } } UNION { ?s <http://ex/p> ?o }
30614 }"#,
30615 )
30616 .unwrap();
30617 fn values_rows(node: &PlanNode) -> Option<usize> {
30618 match node {
30619 PlanNode::Values(values) => Some(values.rows.len()),
30620 PlanNode::Union { left, right } => values_rows(left).or_else(|| values_rows(right)),
30621 PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
30622 values_rows(left).or_else(|| values_rows(right))
30623 }
30624 PlanNode::Filter { inner, .. }
30625 | PlanNode::Extend { inner, .. }
30626 | PlanNode::Slice { inner, .. }
30627 | PlanNode::Distinct { inner, .. }
30628 | PlanNode::Sort { inner, .. } => values_rows(inner),
30629 _ => None,
30630 }
30631 }
30632 assert!(
30633 values_rows(&plan.root).is_some_and(|n| n == 1),
30634 "UNION VALUES arm must survive empty SPARQL default: {:?}",
30635 plan.root
30636 );
30637 }
30638
30639 #[test]
30640 fn from_named_union_values_join_graph_keeps_tables() {
30641 let plan = LogicalPlan::parse(
30642 r#"SELECT ?s ?g FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2> WHERE {
30643 { VALUES ?g { <http://ex/g1> } } UNION { VALUES ?g { <http://ex/g2> } }
30644 GRAPH ?g { ?s <http://ex/p> ?o }
30645 }"#,
30646 )
30647 .unwrap();
30648 fn nonempty_values(node: &PlanNode) -> bool {
30649 match node {
30650 PlanNode::Values(values) => !values.rows.is_empty(),
30651 PlanNode::Union { left, right }
30652 | PlanNode::Join { left, right, .. }
30653 | PlanNode::LeftJoin { left, right, .. } => {
30654 nonempty_values(left) || nonempty_values(right)
30655 }
30656 PlanNode::Filter { inner, .. }
30657 | PlanNode::Extend { inner, .. }
30658 | PlanNode::Slice { inner, .. }
30659 | PlanNode::Distinct { inner, .. }
30660 | PlanNode::Sort { inner, .. } => nonempty_values(inner),
30661 _ => false,
30662 }
30663 }
30664 fn has_scan(node: &PlanNode) -> bool {
30665 match node {
30666 PlanNode::Scan(_) => true,
30667 PlanNode::Union { left, right }
30668 | PlanNode::Join { left, right, .. }
30669 | PlanNode::LeftJoin { left, right, .. } => has_scan(left) || has_scan(right),
30670 PlanNode::Filter { inner, .. }
30671 | PlanNode::Extend { inner, .. }
30672 | PlanNode::Slice { inner, .. }
30673 | PlanNode::Distinct { inner, .. }
30674 | PlanNode::Sort { inner, .. } => has_scan(inner),
30675 _ => false,
30676 }
30677 }
30678 assert!(
30679 nonempty_values(&plan.root),
30680 "UNION VALUES ⋈ GRAPH must not wipe VALUES: {:?}",
30681 plan.root
30682 );
30683 assert!(
30684 has_scan(&plan.root),
30685 "GRAPH scan must remain: {:?}",
30686 plan.root
30687 );
30688 }
30689
30690 #[test]
30691 fn from_without_from_named_empties_graph() {
30692 let plan = LogicalPlan::parse(
30693 r#"SELECT ?s ?g FROM <http://ex/g> WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#,
30694 )
30695 .unwrap();
30696 assert!(
30697 matches!(&plan.root, PlanNode::Values(v) if v.rows.is_empty()),
30698 "FROM without FROM NAMED must empty GRAPH: {:?}",
30699 plan.root
30700 );
30701 }
30702
30703 #[test]
30704 fn from_named_graph_var_uses_allow_list() {
30705 let plan = LogicalPlan::parse(
30706 r#"SELECT ?s ?g FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2>
30707 WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#,
30708 )
30709 .unwrap();
30710 let scans = plan.scans().unwrap();
30711 assert_eq!(scans.len(), 1);
30712 let filter = scans[0]
30713 .graph_filter
30714 .as_ref()
30715 .expect("enumerated FROM NAMED must be an allow-list");
30716 assert!(!filter.is_exclude());
30717 assert_eq!(filter.len(), 2);
30718 let sse = explain_est(
30719 r#"SELECT ?s ?g FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2>
30720 WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#,
30721 None,
30722 );
30723 assert!(
30724 sse.contains("graph_filter allow(2)"),
30725 "EXPLAIN should show the FROM NAMED allow-list: {sse}"
30726 );
30727 }
30728
30729 fn tree_has_named_graphs(node: &PlanNode) -> bool {
30730 match node {
30731 PlanNode::NamedGraphs { .. } => true,
30732 PlanNode::Join { left, right, .. }
30733 | PlanNode::Union { left, right }
30734 | PlanNode::LeftJoin { left, right, .. } => {
30735 tree_has_named_graphs(left) || tree_has_named_graphs(right)
30736 }
30737 PlanNode::Filter { inner, .. }
30738 | PlanNode::Extend { inner, .. }
30739 | PlanNode::Slice { inner, .. }
30740 | PlanNode::Distinct { inner, .. }
30741 | PlanNode::Sort { inner, .. }
30742 | PlanNode::Group { inner, .. }
30743 | PlanNode::JoinGraphVar { inner, .. } => tree_has_named_graphs(inner),
30744 _ => false,
30745 }
30746 }
30747
30748 fn tree_has_named_graph_exists(node: &PlanNode) -> bool {
30749 match node {
30750 PlanNode::NamedGraphExists { .. } => true,
30751 PlanNode::Join { left, right, .. }
30752 | PlanNode::Union { left, right }
30753 | PlanNode::LeftJoin { left, right, .. } => {
30754 tree_has_named_graph_exists(left) || tree_has_named_graph_exists(right)
30755 }
30756 PlanNode::Filter { inner, .. }
30757 | PlanNode::Extend { inner, .. }
30758 | PlanNode::Slice { inner, .. }
30759 | PlanNode::Distinct { inner, .. }
30760 | PlanNode::Sort { inner, .. }
30761 | PlanNode::Group { inner, .. }
30762 | PlanNode::JoinGraphVar { inner, .. } => tree_has_named_graph_exists(inner),
30763 _ => false,
30764 }
30765 }
30766
30767 fn tree_has_join_graph_var(node: &PlanNode) -> bool {
30768 match node {
30769 PlanNode::JoinGraphVar { .. } => true,
30770 PlanNode::Join { left, right, .. }
30771 | PlanNode::Union { left, right }
30772 | PlanNode::LeftJoin { left, right, .. } => {
30773 tree_has_join_graph_var(left) || tree_has_join_graph_var(right)
30774 }
30775 PlanNode::Filter { inner, .. }
30776 | PlanNode::Extend { inner, .. }
30777 | PlanNode::Slice { inner, .. }
30778 | PlanNode::Distinct { inner, .. }
30779 | PlanNode::Sort { inner, .. }
30780 | PlanNode::Group { inner, .. } => tree_has_join_graph_var(inner),
30781 _ => false,
30782 }
30783 }
30784
30785 #[test]
30786 fn from_named_scan_free_graph_joins_values_domain() {
30787 let plan = LogicalPlan::parse(
30788 r#"SELECT ?g ?x FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2>
30789 WHERE { GRAPH ?g { VALUES ?x { 1 } } }"#,
30790 )
30791 .unwrap();
30792 assert!(
30793 !tree_has_named_graphs(&plan.root),
30794 "FROM NAMED must not use the catalog leaf: {:?}",
30795 plan.root
30796 );
30797 let PlanNode::Join { hash_keys, .. } = &plan.root else {
30798 panic!(
30799 "expected cartesian Join(domain VALUES, inner VALUES), got {:?}",
30800 plan.root
30801 );
30802 };
30803 assert!(
30804 hash_keys.is_empty(),
30805 "scan-free GRAPH domain join is cartesian, got {hash_keys:?}"
30806 );
30807 let g1 = EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap());
30808 let g2 = EncodedTerm::from(&NamedNode::new("http://ex/g2").unwrap());
30809 assert!(
30810 values_has_term(&plan.root, &g1) && values_has_term(&plan.root, &g2),
30811 "domain VALUES must list FROM NAMED IRIs: {:?}",
30812 plan.root
30813 );
30814 }
30815
30816 #[test]
30817 fn engine_empty_graph_iri_is_named_graph_exists() {
30818 let plan = LogicalPlan::parse(r#"SELECT * WHERE { GRAPH <http://ex/g1> { } }"#).unwrap();
30819 match &plan.root {
30820 PlanNode::NamedGraphExists { graph } => {
30821 assert_eq!(
30822 graph,
30823 &EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap())
30824 );
30825 }
30826 other => panic!("engine GRAPH <iri> {{ }} must be NamedGraphExists, got {other:?}"),
30827 }
30828 }
30829
30830 #[test]
30831 fn from_named_empty_graph_iri_stays_unit() {
30832 let plan = LogicalPlan::parse(
30833 r#"SELECT * FROM NAMED <http://ex/g1> WHERE { GRAPH <http://ex/g1> { } }"#,
30834 )
30835 .unwrap();
30836 assert!(
30837 matches!(plan.root, PlanNode::Unit),
30838 "FROM NAMED GRAPH <g> {{ }} is dataset membership, not catalog: {:?}",
30839 plan.root
30840 );
30841 }
30842
30843 #[test]
30844 fn values_empty_graph_var_rewrites_named_graphs_to_exists() {
30845 let plan =
30846 LogicalPlan::parse(r#"SELECT ?g WHERE { VALUES ?g { <http://ex/g1> } GRAPH ?g { } }"#)
30847 .unwrap();
30848 assert!(
30849 !tree_has_named_graphs(&plan.root),
30850 "unique VALUES IRI must not list the catalog: {:?}",
30851 plan.root
30852 );
30853 assert!(
30854 tree_has_named_graph_exists(&plan.root),
30855 "expected NamedGraphExists, got {:?}",
30856 plan.root
30857 );
30858 }
30859
30860 #[test]
30861 fn graph_var_optional_uses_join_graph_var() {
30862 let plan = LogicalPlan::parse(
30863 r#"SELECT ?g ?s WHERE { GRAPH ?g { ?s ?p ?o OPTIONAL { ?s ?p ?g } } }"#,
30864 )
30865 .unwrap();
30866 let PlanNode::JoinGraphVar {
30867 inner,
30868 graph_var,
30869 active_var,
30870 } = &plan.root
30871 else {
30872 panic!("expected JoinGraphVar wrap, got {:?}", plan.root);
30873 };
30874 assert_eq!(graph_var.as_str(), "g");
30875 assert!(
30876 active_var.as_str().starts_with("gact_"),
30877 "active G slot must be minted, got {active_var}"
30878 );
30879 let PlanNode::LeftJoin { hash_keys, .. } = inner.as_ref() else {
30880 panic!("expected LeftJoin under JoinGraphVar, got {inner:?}");
30881 };
30882 assert!(
30883 !hash_keys.iter().any(|k| k.as_str() == "g"),
30884 "OPTIONAL must not join on SPARQL ?g: {hash_keys:?}"
30885 );
30886 assert!(
30887 hash_keys.iter().any(|k| k == active_var),
30888 "OPTIONAL should join on the active-graph var: {hash_keys:?}"
30889 );
30890 }
30891
30892 #[test]
30893 fn graph_var_bgp_without_inner_g_keeps_graph_slot() {
30894 let plan = LogicalPlan::parse(r#"SELECT ?s ?g WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#)
30895 .unwrap();
30896 let PlanNode::Scan(scan) = &plan.root else {
30897 panic!("expected Scan, got {:?}", plan.root);
30898 };
30899 assert_eq!(scan.graph.as_ref().map(Variable::as_str), Some("g"));
30900 assert!(
30901 !tree_has_join_graph_var(&plan.root),
30902 "P does not mention ?g, so no JoinGraphVar: {:?}",
30903 plan.root
30904 );
30905 }
30906
30907 #[test]
30908 fn engine_empty_graph_var_is_named_graphs_leaf() {
30909 let plan = LogicalPlan::parse(r#"SELECT ?g WHERE { GRAPH ?g { } }"#).unwrap();
30910 match &plan.root {
30911 PlanNode::NamedGraphs {
30912 variable,
30913 produced_row_count_estimate,
30914 } => {
30915 assert_eq!(variable.as_str(), "g");
30916 assert_eq!(*produced_row_count_estimate, NAMED_GRAPHS_ESTIMATED_ROWS);
30917 }
30918 other => panic!("engine GRAPH ?g {{ }} must be NamedGraphs, got {other:?}"),
30919 }
30920 }
30921
30922 #[test]
30923 fn named_graphs_leaf_uses_profile_count() {
30924 let profile = StatsProfile {
30925 named_graph_count: 7,
30926 total_puts: 1,
30927 ..StatsProfile::default()
30928 };
30929 let plan =
30930 LogicalPlan::parse_with_profile(r#"SELECT ?g WHERE { GRAPH ?g { } }"#, Some(&profile))
30931 .unwrap();
30932 assert_eq!(plan.root.produced_row_count_estimate(), 7);
30933 }
30934
30935 #[test]
30936 fn graph_bgp_does_not_cartesian_domain() {
30937 let plan = LogicalPlan::parse(r#"SELECT ?s ?g WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#)
30938 .unwrap();
30939 assert!(
30940 matches!(&plan.root, PlanNode::Scan(_)),
30941 "BGP that always binds ?g must stay a Scan, got {:?}",
30942 plan.root
30943 );
30944 }
30945
30946 #[test]
30947 fn nested_graph_var_joins_outer_from_named_domain() {
30948 let plan = LogicalPlan::parse(
30949 r#"SELECT ?g ?h ?s FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2>
30950 WHERE { GRAPH ?g { GRAPH ?h { ?s <http://ex/p> ?o } } }"#,
30951 )
30952 .unwrap();
30953 assert!(
30954 !tree_has_named_graphs(&plan.root),
30955 "FROM NAMED nested GRAPH must not call the catalog: {:?}",
30956 plan.root
30957 );
30958 let mut inner_graphs = Vec::new();
30959 for_each_scan(&plan.root, &mut |scan| {
30960 inner_graphs.push(scan.graph.as_ref().map(Variable::as_str).map(str::to_owned));
30961 });
30962 assert_eq!(
30963 inner_graphs,
30964 vec![Some("h".into())],
30965 "inner scan must stay scoped to ?h: {:?}",
30966 plan.root
30967 );
30968 let PlanNode::Join { hash_keys, .. } = &plan.root else {
30969 panic!(
30970 "expected Join(outer domain, inner GRAPH), got {:?}",
30971 plan.root
30972 );
30973 };
30974 assert!(
30975 hash_keys.is_empty(),
30976 "outer ?g is not on the inner scan, so the domain join is cartesian: {hash_keys:?}"
30977 );
30978 }
30979
30980 #[test]
30981 fn graph_optional_leftjoins_from_named_domain() {
30982 let plan = LogicalPlan::parse(
30983 r#"SELECT ?g ?o FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2>
30984 WHERE { GRAPH ?g { OPTIONAL { <http://ex/s> <http://ex/p> ?o } } }"#,
30985 )
30986 .unwrap();
30987 match &plan.root {
30988 PlanNode::LeftJoin {
30989 left, hash_keys, ..
30990 } => {
30991 assert_eq!(
30992 hash_keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
30993 ["g"]
30994 );
30995 assert!(
30996 matches!(left.as_ref(), PlanNode::Values(_)),
30997 "required side must be the FROM NAMED domain, got {left:?}"
30998 );
30999 }
31000 other => panic!("expected LeftJoin(domain, scan) on ?g, got {other:?}"),
31001 }
31002 }
31003
31004 #[test]
31005 fn graph_iri_grounds_inner_scan() {
31006 let plan = LogicalPlan::parse(
31007 r#"SELECT ?s WHERE { GRAPH <http://ex/g1> { ?s <http://ex/p> ?o } }"#,
31008 )
31009 .unwrap();
31010 let scans = plan.scans().unwrap();
31011 assert_eq!(scans.len(), 1);
31012 assert_eq!(
31013 scans[0].pattern.graph_name,
31014 Some(EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap()))
31015 );
31016 assert!(scans[0].graph.is_none());
31017 assert!(scans[0].graph_filter.is_none());
31018 }
31019
31020 #[test]
31021 fn from_named_plus_disjoint_values_is_empty_allow() {
31022 let plan = LogicalPlan::parse(
31023 r#"SELECT ?s FROM NAMED <http://ex/g1> WHERE {
31024 VALUES ?g { <http://ex/g2> }
31025 GRAPH ?g { ?s <http://ex/p> ?o }
31026 }"#,
31027 )
31028 .unwrap();
31029 let scans = plan.scans().unwrap();
31030 assert_eq!(scans.len(), 1);
31031 let filter = scans[0]
31032 .graph_filter
31033 .as_ref()
31034 .expect("disjoint G push must keep an empty allow-list, not clear the filter");
31035 assert!(
31036 filter.is_empty_allow(),
31037 "expected empty allow-list, got {filter:?}"
31038 );
31039 assert!(
31040 scans[0].pattern.graph_name.is_none(),
31041 "must not ground G to a graph outside FROM NAMED: {:?}",
31042 scans[0].pattern.graph_name
31043 );
31044 }
31045
31046 #[test]
31047 fn from_named_plus_legal_values_grounds_g() {
31048 let plan = LogicalPlan::parse(
31049 r#"SELECT ?s FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2> WHERE {
31050 VALUES ?g { <http://ex/g2> }
31051 GRAPH ?g { ?s <http://ex/p> ?o }
31052 }"#,
31053 )
31054 .unwrap();
31055 let scans = plan.scans().unwrap();
31056 assert_eq!(scans.len(), 1);
31057 assert_eq!(
31058 scans[0].pattern.graph_name,
31059 Some(EncodedTerm::from(&NamedNode::new("http://ex/g2").unwrap()))
31060 );
31061 assert!(
31062 scans[0].graph_filter.is_none(),
31063 "legal singleton may drop the residual: {:?}",
31064 scans[0].graph_filter
31065 );
31066 }
31067
31068 #[test]
31069 fn from_named_plus_disjoint_same_term_is_empty_allow() {
31070 let plan = LogicalPlan::parse(
31071 r#"SELECT ?s FROM NAMED <http://ex/g1> WHERE {
31072 GRAPH ?g { ?s <http://ex/p> ?o }
31073 FILTER(sameTerm(?g, <http://ex/g2>))
31074 }"#,
31075 )
31076 .unwrap();
31077 let scans = plan.scans().unwrap();
31078 assert_eq!(scans.len(), 1);
31079 let filter = scans[0]
31080 .graph_filter
31081 .as_ref()
31082 .expect("sameTerm outside FROM NAMED must not clear the filter");
31083 assert!(
31084 filter.is_empty_allow(),
31085 "expected empty allow-list, got {filter:?}"
31086 );
31087 assert!(scans[0].pattern.graph_name.is_none());
31088 }
31089
31090 fn domain_counts_root(plan: &LogicalPlan) -> Option<(&DomainScanKind, &Variable, &Variable)> {
31095 let PlanNode::Extend {
31096 inner,
31097 variable: alias,
31098 expression: Expression::Variable(copy),
31099 ..
31100 } = &plan.root
31101 else {
31102 return None;
31103 };
31104 let PlanNode::DomainCounts {
31105 kind, head, count, ..
31106 } = inner.as_ref()
31107 else {
31108 return None;
31109 };
31110 (copy == count).then_some((kind, head, alias))
31111 }
31112
31113 #[test]
31114 fn group_count_var_lowers_to_domain_counts() {
31115 let plan = LogicalPlan::parse(
31116 "SELECT ?o (COUNT(?s) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31117 )
31118 .unwrap();
31119 let Some((_, head, alias)) = domain_counts_root(&plan) else {
31120 panic!(
31121 "expected DomainCounts under the alias Extend, got {:?}",
31122 plan.root
31123 );
31124 };
31125 assert_eq!(head.as_str(), "o");
31126 assert_eq!(alias.as_str(), "n");
31127 let vars = plan.root.variables();
31130 assert!(vars.contains(&var("o")) && vars.contains(&var("n")));
31131 }
31132
31133 #[test]
31134 fn group_count_star_lowers_to_domain_counts() {
31135 let plan = LogicalPlan::parse(
31136 "SELECT ?o (COUNT(*) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31137 )
31138 .unwrap();
31139 assert!(domain_counts_root(&plan).is_some());
31140 }
31141
31142 #[test]
31143 fn group_count_on_object_head_lowers_to_domain_counts() {
31144 let plan = LogicalPlan::parse(
31147 "SELECT ?o (COUNT(?s) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31148 )
31149 .unwrap();
31150 assert!(domain_counts_root(&plan).is_some());
31151 }
31152
31153 #[test]
31154 fn group_count_on_predicate_head_lowers_to_domain_counts() {
31155 let plan = LogicalPlan::parse(
31158 "SELECT ?p (COUNT(?s) AS ?n) WHERE { ?s ?p <http://ex/o> } GROUP BY ?p",
31159 )
31160 .unwrap();
31161 assert!(
31162 domain_counts_root(&plan).is_some(),
31163 "root = {:?}",
31164 plan.root
31165 );
31166 }
31167
31168 #[test]
31169 fn domain_counts_explain_renders_kind_and_estimate() {
31170 let text = explain_est(
31171 "SELECT ?o (COUNT(?s) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31172 None,
31173 );
31174 assert!(
31175 text.contains("domain_counts") && text.contains("predicate_domain@posg"),
31176 "unexpected explain: {text}"
31177 );
31178 }
31179
31180 #[tokio::test]
31184 async fn count_split_empty_relation_join_yields_zero() {
31185 use crate::error::RetryPolicy;
31186 use crate::query::caches::QueryCaches;
31187 use crate::query::fixtures::{CountingStore, NullResolve, count_split_quads_disjoint};
31188 use oxsdatatypes::Integer;
31189 use waratah_router::ClusterConfig;
31190 use waratah_storage::SnapshotId;
31191
31192 let store = CountingStore::new(count_split_quads_disjoint());
31193 let engine = crate::query::QueryEngine::new(
31194 store,
31195 NullResolve,
31196 ClusterConfig::local_dev().router(16).unwrap(),
31197 RetryPolicy::none(),
31198 );
31199 let ctx = QueryContext::from_snapshot(SnapshotId::latest());
31200 let mut cache = QueryCaches::new();
31201 let solutions = engine
31202 .execute_node(&count_split_probe::root(), &ctx, &mut cache, None)
31203 .await
31204 .unwrap();
31205 assert_eq!(solutions.len(), 1, "the implicit group still has one row");
31206 let rows = solutions.optional_rows().unwrap();
31207 assert_eq!(
31208 rows[0][0],
31209 Some(EncodedTerm::IntegerLiteral(Integer::from(0)))
31210 );
31211 }
31212
31213 #[tokio::test]
31220 async fn count_split_emitted_shape_executes_and_sums_exactly() {
31221 use crate::error::RetryPolicy;
31222 use crate::query::caches::QueryCaches;
31223 use crate::query::fixtures::{CountingStore, NullResolve, count_split_quads};
31224 use oxsdatatypes::Integer;
31225 use waratah_router::ClusterConfig;
31226 use waratah_storage::SnapshotId;
31227
31228 let store = CountingStore::new(count_split_quads());
31229 let engine = crate::query::QueryEngine::new(
31230 store,
31231 NullResolve,
31232 ClusterConfig::local_dev().router(16).unwrap(),
31233 RetryPolicy::none(),
31234 );
31235 let ctx = QueryContext::from_snapshot(SnapshotId::latest());
31236 let mut cache = QueryCaches::new();
31237 let solutions = engine
31238 .execute_node(&count_split_probe::root(), &ctx, &mut cache, None)
31239 .await
31240 .unwrap();
31241 assert_eq!(solutions.len(), 1, "a bare count folds to exactly one row");
31242 let rows = solutions.optional_rows().unwrap();
31243 assert_eq!(
31244 rows[0][0],
31245 Some(EncodedTerm::IntegerLiteral(Integer::from(23))),
31246 "the sum-of-products combine must reproduce the join's count exactly"
31247 );
31248 }
31249
31250 fn count_split_arms(plan: &LogicalPlan) -> Option<(&PlanNode, &PlanNode)> {
31256 let PlanNode::Extend { inner, .. } = &plan.root else {
31257 return None;
31258 };
31259 let PlanNode::Group {
31260 inner,
31261 variables,
31262 aggregates,
31263 ..
31264 } = inner.as_ref()
31265 else {
31266 return None;
31267 };
31268 if !variables.is_empty()
31269 || !matches!(
31270 &aggregates[0].1,
31271 AggregateExpression::FunctionCall {
31272 name: AggregateFunction::Sum,
31273 ..
31274 }
31275 )
31276 {
31277 return None;
31278 }
31279 let PlanNode::Extend {
31280 inner,
31281 expression: Expression::Multiply(..),
31282 ..
31283 } = inner.as_ref()
31284 else {
31285 return None;
31286 };
31287 let PlanNode::Join { left, right, .. } = inner.as_ref() else {
31288 return None;
31289 };
31290 Some((left, right))
31291 }
31292
31293 fn count_split_profile(rows: u32, sites: u32, within: u32, regions: u32) -> StatsProfile {
31297 let mut live = LiveQuadsProfile::default();
31298 let ibra = NamedNode::new("http://ex/ibraRegion").unwrap();
31299 let ty = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
31300 let site_class = NamedNode::new("https://w3id.org/tern/Site").unwrap();
31301 let pwithin = NamedNode::new("http://ex/withinIBRA").unwrap();
31302 let mut observe = |s: NamedNode, p: &NamedNode, o: NamedNode| {
31303 let quad = waratah_storage::Quad::new(
31304 s,
31305 p.clone(),
31306 o,
31307 waratah_storage::GraphName::DefaultGraph,
31308 );
31309 observe_quad(&mut live, &encode_quad(&quad).unwrap(), StorageOp::Put);
31310 };
31311 for i in 0..rows {
31312 observe(
31313 NamedNode::new(format!("http://ex/occ{i}")).unwrap(),
31314 &ibra,
31315 NamedNode::new(format!("http://ex/r{}", i % regions)).unwrap(),
31316 );
31317 }
31318 for i in 0..sites {
31319 observe(
31320 NamedNode::new(format!("http://ex/site{i}")).unwrap(),
31321 &ty,
31322 site_class.clone(),
31323 );
31324 }
31325 for i in 0..within {
31326 observe(
31327 NamedNode::new(format!("http://ex/site{}", i % sites.max(1))).unwrap(),
31328 &pwithin,
31329 NamedNode::new(format!("http://ex/r{}", i % regions)).unwrap(),
31330 );
31331 }
31332 StatsProfile::from(live)
31333 }
31334
31335 const COVERAGE_SITES: &str = r#"
31336 SELECT (COUNT(*) AS ?n) WHERE {
31337 ?occ <http://ex/ibraRegion> ?r .
31338 ?site a <https://w3id.org/tern/Site> ;
31339 <http://ex/withinIBRA> ?r .
31340 }
31341 "#;
31342
31343 fn is_predicate_domain_relation(arm: &PlanNode, predicate: &str, key: &str) -> bool {
31344 let predicate = EncodedTerm::from(&NamedNode::new(predicate).unwrap());
31345 matches!(
31346 arm,
31347 PlanNode::DomainCounts {
31348 kind: DomainScanKind::PredicateDomain,
31349 constraints,
31350 head,
31351 ..
31352 } if head == &var(key) && constraints.as_slice() == [predicate]
31353 )
31354 }
31355
31356 fn is_key_count_collapse(arm: &PlanNode, key: &str) -> bool {
31357 let PlanNode::Group {
31358 variables,
31359 aggregates,
31360 ..
31361 } = arm
31362 else {
31363 return false;
31364 };
31365 variables.as_slice() == [var(key)]
31366 && matches!(
31367 &aggregates[0].1,
31368 AggregateExpression::CountSolutions { distinct: false }
31369 )
31370 }
31371
31372 #[test]
31373 fn count_split_fires_on_bare_join_count() {
31374 let profile = count_split_profile(40_000, 600, 700, 37);
31375 let plan = LogicalPlan::parse_with_profile(COVERAGE_SITES, Some(&profile)).unwrap();
31376 let Some((left, right)) = count_split_arms(&plan) else {
31377 panic!("expected a count-split plan, got {:?}", plan.root);
31378 };
31379 assert!(
31380 is_predicate_domain_relation(left, "http://ex/ibraRegion", "r")
31381 && is_key_count_collapse(right, "r")
31382 || is_predicate_domain_relation(right, "http://ex/ibraRegion", "r")
31383 && is_key_count_collapse(left, "r"),
31384 "expected the occurrence DomainCounts relation plus the site collapse, \
31385 got {left:?} and {right:?}"
31386 );
31387 }
31388
31389 #[test]
31390 fn count_split_binds_a_counted_variable_to_the_dead_slot() {
31391 let profile = count_split_profile(40_000, 600, 700, 37);
31392 let plan = LogicalPlan::parse_with_profile(
31393 r#"
31394 SELECT (COUNT(?occ) AS ?n) WHERE {
31395 ?occ <http://ex/ibraRegion> ?r .
31396 ?site a <https://w3id.org/tern/Site> ;
31397 <http://ex/withinIBRA> ?r .
31398 }
31399 "#,
31400 Some(&profile),
31401 )
31402 .unwrap();
31403 let Some((left, right)) = count_split_arms(&plan) else {
31404 panic!("expected a count-split plan, got {:?}", plan.root);
31405 };
31406 let relation = if is_predicate_domain_relation(left, "http://ex/ibraRegion", "r") {
31407 left
31408 } else {
31409 assert!(
31410 is_predicate_domain_relation(right, "http://ex/ibraRegion", "r"),
31411 "expected the occurrence DomainCounts relation, got {right:?}"
31412 );
31413 right
31414 };
31415 let PlanNode::DomainCounts {
31416 dead, count_star, ..
31417 } = relation
31418 else {
31419 unreachable!("relation matched as DomainCounts");
31420 };
31421 assert_eq!(dead.as_ref(), Some(&var("occ")));
31422 assert!(!count_star, "COUNT(?occ) keeps the counted spelling");
31423 }
31424
31425 #[test]
31426 fn count_split_serves_two_storage_arms() {
31427 let mut live = LiveQuadsProfile::default();
31428 let p1 = NamedNode::new("http://ex/p1").unwrap();
31429 let p2 = NamedNode::new("http://ex/p2").unwrap();
31430 for i in 0..2_000 {
31431 let key = NamedNode::new(format!("http://ex/k{}", i % 40)).unwrap();
31432 for predicate in [&p1, &p2] {
31433 let quad = waratah_storage::Quad::new(
31434 NamedNode::new(format!("http://ex/a{i}")).unwrap(),
31435 predicate.clone(),
31436 key.clone(),
31437 waratah_storage::GraphName::DefaultGraph,
31438 );
31439 observe_quad(&mut live, &encode_quad(&quad).unwrap(), StorageOp::Put);
31440 }
31441 }
31442 let profile = StatsProfile::from(live);
31443 let plan = LogicalPlan::parse_with_profile(
31444 r#"SELECT (COUNT(*) AS ?n) WHERE {
31445 ?a <http://ex/p1> ?k . ?b <http://ex/p2> ?k
31446 }"#,
31447 Some(&profile),
31448 )
31449 .unwrap();
31450 let Some((left, right)) = count_split_arms(&plan) else {
31451 panic!("expected a count-split plan, got {:?}", plan.root);
31452 };
31453 assert!(
31454 matches!(left, PlanNode::DomainCounts { .. })
31455 && matches!(right, PlanNode::DomainCounts { .. }),
31456 "both arms should be stored relations, got {left:?} and {right:?}"
31457 );
31458 }
31459
31460 #[test]
31461 fn count_split_refuses_distinct_count() {
31462 let profile = count_split_profile(40_000, 600, 700, 37);
31463 let plan = LogicalPlan::parse_with_profile(
31464 r#"
31465 SELECT (COUNT(DISTINCT ?occ) AS ?n) WHERE {
31466 ?occ <http://ex/ibraRegion> ?r .
31467 ?site a <https://w3id.org/tern/Site> ;
31468 <http://ex/withinIBRA> ?r .
31469 }
31470 "#,
31471 Some(&profile),
31472 )
31473 .unwrap();
31474 assert!(count_split_arms(&plan).is_none());
31475 }
31476
31477 #[test]
31478 fn count_split_refuses_group_by() {
31479 let profile = count_split_profile(40_000, 600, 700, 37);
31480 let plan = LogicalPlan::parse_with_profile(
31481 r#"
31482 SELECT ?r (COUNT(*) AS ?n) WHERE {
31483 ?occ <http://ex/ibraRegion> ?r .
31484 ?site a <https://w3id.org/tern/Site> ;
31485 <http://ex/withinIBRA> ?r .
31486 }
31487 GROUP BY ?r
31488 "#,
31489 Some(&profile),
31490 )
31491 .unwrap();
31492 assert!(count_split_arms(&plan).is_none());
31493 }
31494
31495 #[test]
31496 fn count_split_refuses_without_profile() {
31497 let plan = LogicalPlan::parse(COVERAGE_SITES).unwrap();
31500 assert!(count_split_arms(&plan).is_none());
31501 }
31502
31503 #[test]
31504 fn count_split_refuses_without_a_storage_countable_arm() {
31505 let profile = count_split_profile(40_000, 600, 700, 37);
31508 let plan = LogicalPlan::parse_with_profile(
31509 r#"SELECT (COUNT(*) AS ?n) WHERE { ?a ?p1 ?k . ?b ?p2 ?k }"#,
31510 Some(&profile),
31511 )
31512 .unwrap();
31513 assert!(count_split_arms(&plan).is_none());
31514 }
31515
31516 #[tokio::test]
31521 async fn count_split_rewrite_matches_the_plain_plan_exactly() {
31522 use crate::error::RetryPolicy;
31523 use crate::query::caches::QueryCaches;
31524 use crate::query::fixtures::{CountingStore, NullResolve, count_split_quads};
31525 use oxsdatatypes::Integer;
31526 use waratah_router::ClusterConfig;
31527 use waratah_storage::SnapshotId;
31528
31529 let run = |plan: &LogicalPlan| {
31530 let engine = crate::query::QueryEngine::new(
31531 CountingStore::new(count_split_quads()),
31532 NullResolve,
31533 ClusterConfig::local_dev().router(16).unwrap(),
31534 RetryPolicy::none(),
31535 );
31536 let ctx = QueryContext::from_snapshot(SnapshotId::latest());
31537 let mut cache = QueryCaches::new();
31538 let root = plan.root.clone();
31539 async move {
31540 engine
31541 .execute_node(&root, &ctx, &mut cache, None)
31542 .await
31543 .unwrap()
31544 }
31545 };
31546
31547 let split = LogicalPlan::parse_with_profile(
31548 COVERAGE_SITES,
31549 Some(&count_split_profile(40_000, 600, 700, 37)),
31550 )
31551 .unwrap();
31552 assert!(
31553 count_split_arms(&split).is_some(),
31554 "the firing profile must actually fire, got {:?}",
31555 split.root
31556 );
31557 let plain = LogicalPlan::parse(COVERAGE_SITES).unwrap();
31558 assert!(count_split_arms(&plain).is_none(), "no profile, no split");
31559
31560 let split_rows = run(&split).await.optional_rows().unwrap();
31561 let plain_rows = run(&plain).await.optional_rows().unwrap();
31562 assert_eq!(split_rows.len(), 1);
31563 assert_eq!(
31564 split_rows, plain_rows,
31565 "the count-split answer must equal the plain join's answer"
31566 );
31567 assert_eq!(
31568 split_rows[0][0],
31569 Some(EncodedTerm::IntegerLiteral(Integer::from(23)))
31570 );
31571 }
31572
31573 #[test]
31579 fn group_count_on_subject_head_lowers_to_predicate_subjects() {
31580 const QUERY: &str = "SELECT ?s (COUNT(*) AS ?n) WHERE { ?s <http://ex/p> ?o } GROUP BY ?s";
31581 let plan = LogicalPlan::parse(QUERY).unwrap();
31582 let Some((kind, head, alias)) = domain_counts_root(&plan) else {
31583 panic!("expected DomainCounts under alias, got {:?}", plan.root);
31584 };
31585 assert_eq!(*kind, DomainScanKind::PredicateSubjects);
31586 assert_eq!(head.as_str(), "s");
31587 assert_eq!(alias.as_str(), "n");
31588 assert!(
31589 explain_est(QUERY, None).contains("predicate_subjects@psog"),
31590 "EXPLAIN must name the new kind and its axis"
31591 );
31592 }
31593
31594 #[test]
31595 fn distinct_subject_head_lowers_to_predicate_subjects_stamp() {
31596 let text = explain_est("SELECT DISTINCT ?s WHERE { ?s <http://ex/p> ?o }", None);
31597 assert!(
31598 text.contains("domain_scan predicate_subjects@psog"),
31599 "unexpected explain: {text}"
31600 );
31601 }
31602
31603 #[tokio::test]
31608 async fn predicate_subjects_counts_execute_on_psog_walk() {
31609 use crate::error::RetryPolicy;
31610 use crate::query::caches::QueryCaches;
31611 use crate::query::fixtures::{CountingStore, NullResolve};
31612 use oxsdatatypes::Integer;
31613 use waratah_router::ClusterConfig;
31614 use waratah_storage::{GraphName, Quad, SnapshotId};
31615
31616 let p = NamedNode::new("http://ex/p").unwrap();
31617 let quad = |s: &str, o: &str| {
31618 Quad::new(
31619 NamedNode::new(s).unwrap(),
31620 p.clone(),
31621 NamedNode::new(o).unwrap(),
31622 GraphName::DefaultGraph,
31623 )
31624 };
31625 let store = CountingStore::new(vec![
31626 quad("http://ex/a1", "http://ex/x1"),
31627 quad("http://ex/a1", "http://ex/x2"),
31628 quad("http://ex/a2", "http://ex/x1"),
31629 ]);
31630 let engine = crate::query::QueryEngine::new(
31631 store,
31632 NullResolve,
31633 ClusterConfig::local_dev().router(16).unwrap(),
31634 RetryPolicy::none(),
31635 );
31636 let plan = LogicalPlan::parse(
31637 "SELECT ?s (COUNT(*) AS ?n) WHERE { ?s <http://ex/p> ?o } GROUP BY ?s",
31638 )
31639 .unwrap();
31640 let root = plan.root.clone();
31641 let ctx = QueryContext::from_snapshot(SnapshotId::latest());
31642 let mut cache = QueryCaches::new();
31643 let solutions = engine
31644 .execute_node(&root, &ctx, &mut cache, None)
31645 .await
31646 .unwrap();
31647 let rows = solutions.optional_rows().unwrap();
31648 assert_eq!(rows.len(), 2, "one row per distinct subject head");
31649 let a1 = EncodedTerm::from(&NamedNode::new("http://ex/a1").unwrap());
31650 let a2 = EncodedTerm::from(&NamedNode::new("http://ex/a2").unwrap());
31651 let mut got: Vec<_> = rows
31652 .iter()
31653 .map(|row| (row[0].clone().unwrap(), row[1].clone().unwrap()))
31654 .collect();
31655 got.sort_by_key(|(subject, _)| if *subject == a1 { 0 } else { 1 });
31656 assert_eq!(
31657 got,
31658 [
31659 (a1, EncodedTerm::IntegerLiteral(Integer::from(2))),
31660 (a2, EncodedTerm::IntegerLiteral(Integer::from(1))),
31661 ]
31662 );
31663 }
31664
31665 #[test]
31669 fn count_split_uses_predicate_subjects_for_s_head_arms() {
31670 let mut live = LiveQuadsProfile::default();
31671 let mut observe = |s: &str, p: &NamedNode, o: &str| {
31672 let quad = waratah_storage::Quad::new(
31673 NamedNode::new(s).unwrap(),
31674 p.clone(),
31675 NamedNode::new(o).unwrap(),
31676 waratah_storage::GraphName::DefaultGraph,
31677 );
31678 observe_quad(&mut live, &encode_quad(&quad).unwrap(), StorageOp::Put);
31679 };
31680 let p1 = NamedNode::new("http://ex/p1").unwrap();
31681 let p2 = NamedNode::new("http://ex/p2").unwrap();
31682 let p3 = NamedNode::new("http://ex/p3").unwrap();
31683 for i in 0..20_000 {
31684 observe(
31685 &format!("http://ex/s{}", i % 40),
31686 &p1,
31687 &format!("http://ex/o{i}"),
31688 );
31689 }
31690 for i in 0..2_000 {
31691 observe(
31692 &format!("http://ex/s{}", i % 40),
31693 &p2,
31694 &format!("http://ex/v{i}"),
31695 );
31696 observe(&format!("http://ex/v{i}"), &p3, &format!("http://ex/w{i}"));
31697 }
31698 let profile = StatsProfile::from(live);
31699 let plan = LogicalPlan::parse_with_profile(
31700 r#"SELECT (COUNT(*) AS ?n) WHERE {
31701 ?s <http://ex/p1> ?o . ?s <http://ex/p2> ?v . ?v <http://ex/p3> ?w
31702 }"#,
31703 Some(&profile),
31704 )
31705 .unwrap();
31706 let Some((left, right)) = count_split_arms(&plan) else {
31707 panic!("expected a count-split plan, got {:?}", plan.root);
31708 };
31709 let stored = [left, right].into_iter().find(|arm| {
31710 matches!(
31711 arm,
31712 PlanNode::DomainCounts {
31713 kind: DomainScanKind::PredicateSubjects,
31714 ..
31715 }
31716 )
31717 });
31718 assert!(
31719 stored.is_some(),
31720 "expected a PSOG DomainCounts relation, got {left:?} and {right:?}"
31721 );
31722 }
31723
31724 fn head_counts_root(plan: &LogicalPlan) -> Option<(&HeadScanKind, bool, &Variable, &Variable)> {
31727 let PlanNode::Extend {
31728 inner,
31729 variable: _alias,
31730 expression: Expression::Variable(copy),
31731 ..
31732 } = &plan.root
31733 else {
31734 return None;
31735 };
31736 let PlanNode::HeadCounts {
31737 kind,
31738 total,
31739 counted,
31740 count,
31741 ..
31742 } = inner.as_ref()
31743 else {
31744 return None;
31745 };
31746 debug_assert_eq!(copy, count);
31748 Some((kind, *total, counted, count))
31749 }
31750
31751 #[test]
31755 fn flagship_type_distinct_count_rewrites_to_tsg_head_counts() {
31756 let plan = LogicalPlan::parse(
31757 "SELECT ?cls (COUNT(DISTINCT ?f) AS ?n) WHERE { ?f a ?cls } GROUP BY ?cls",
31758 )
31759 .unwrap();
31760 let Some((kind, total, counted, _)) = head_counts_root(&plan) else {
31761 panic!("expected a HeadCounts root: {:?}", plan.root);
31762 };
31763 assert_eq!(*kind, HeadScanKind::Classes);
31764 assert!(!total, "grouped shape is PER_HEAD");
31765 assert_eq!(counted.as_str(), "f");
31766 assert!(domain_counts_root(&plan).is_none(), "head pass wins");
31767 }
31768
31769 #[test]
31771 fn ungrouped_class_distinct_count_rewrites_to_tsg_total() {
31772 let plan =
31773 LogicalPlan::parse("SELECT (COUNT(DISTINCT ?cls) AS ?c) WHERE { ?f a ?cls }").unwrap();
31774 let Some((kind, total, counted, _)) = head_counts_root(&plan) else {
31775 panic!("expected a HeadCounts root: {:?}", plan.root);
31776 };
31777 assert_eq!(*kind, HeadScanKind::Classes);
31778 assert!(total);
31779 assert_eq!(counted.as_str(), "cls");
31780 }
31781
31782 #[test]
31784 fn bare_patterns_rewrite_per_head_counts_by_axis() {
31785 let plan = LogicalPlan::parse(
31787 "SELECT ?s (COUNT(DISTINCT ?p) AS ?n) WHERE { ?s ?p ?o } GROUP BY ?s",
31788 )
31789 .unwrap();
31790 let Some((kind, total, counted, _)) = head_counts_root(&plan) else {
31791 panic!("expected a HeadCounts root: {:?}", plan.root);
31792 };
31793 assert_eq!(*kind, HeadScanKind::Subjects);
31794 assert!(!total);
31795 assert_eq!(counted.as_str(), "p");
31796
31797 let plan =
31799 LogicalPlan::parse("SELECT (COUNT(DISTINCT ?o) AS ?c) WHERE { ?s ?p ?o }").unwrap();
31800 let Some((kind, total, counted, _)) = head_counts_root(&plan) else {
31801 panic!("expected a HeadCounts root: {:?}", plan.root);
31802 };
31803 assert_eq!(*kind, HeadScanKind::Objects);
31804 assert!(total);
31805 assert_eq!(counted.as_str(), "o");
31806
31807 let plan = LogicalPlan::parse(
31809 "SELECT ?p (COUNT(DISTINCT ?s) AS ?n) WHERE { ?s ?p ?o } GROUP BY ?p",
31810 )
31811 .unwrap();
31812 let Some((kind, total, counted, _)) = head_counts_root(&plan) else {
31813 panic!("expected a HeadCounts root: {:?}", plan.root);
31814 };
31815 assert_eq!(*kind, HeadScanKind::Predicates);
31816 assert!(!total);
31817 assert_eq!(counted.as_str(), "s");
31818 }
31819
31820 #[test]
31825 fn ungrouped_subject_distinct_count_over_types_stays_generic() {
31826 let plan =
31827 LogicalPlan::parse("SELECT (COUNT(DISTINCT ?f) AS ?c) WHERE { ?f a ?cls }").unwrap();
31828 assert!(head_counts_root(&plan).is_none());
31829 assert!(domain_counts_root(&plan).is_none());
31830 assert!(matches!(find_group(&plan.root), PlanNode::Group { .. }));
31831 }
31832
31833 #[test]
31836 fn head_counts_rewrite_refusals() {
31837 let plan =
31839 LogicalPlan::parse("SELECT ?cls (COUNT(?f) AS ?n) WHERE { ?f a ?cls } GROUP BY ?cls")
31840 .unwrap();
31841 assert!(head_counts_root(&plan).is_none());
31842 let plan =
31844 LogicalPlan::parse("SELECT ?cls (COUNT(*) AS ?n) WHERE { ?f a ?cls } GROUP BY ?cls")
31845 .unwrap();
31846 assert!(head_counts_root(&plan).is_none());
31847 let plan = LogicalPlan::parse(
31849 "SELECT ?cls (COUNT(DISTINCT *) AS ?n) WHERE { ?f a ?cls } GROUP BY ?cls",
31850 )
31851 .unwrap();
31852 assert!(head_counts_root(&plan).is_none());
31853 let plan = LogicalPlan::parse(
31856 "SELECT ?cls (COUNT(DISTINCT ?f) AS ?n) (COUNT(DISTINCT ?f) AS ?m) WHERE { ?f a ?cls } GROUP BY ?cls",
31857 )
31858 .unwrap();
31859 assert!(head_counts_root(&plan).is_none());
31860 let plan =
31862 LogicalPlan::parse("SELECT (COUNT(DISTINCT ?f) AS ?c) WHERE { ?f a <http://ex/C> }")
31863 .unwrap();
31864 assert!(head_counts_root(&plan).is_none());
31865 }
31866
31867 #[test]
31868 fn count_distinct_dead_slot_elimminates_to_domain_counts() {
31869 let plan = LogicalPlan::parse(
31873 "SELECT ?o (COUNT(DISTINCT ?s) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31874 )
31875 .unwrap();
31876 match domain_counts_root(&plan) {
31877 Some((_, _, _)) => {}
31878 other => panic!("expected a DomainCounts root, got {other:?}"),
31879 }
31880 let PlanNode::Extend { inner, .. } = &plan.root else {
31881 unreachable!()
31882 };
31883 let PlanNode::DomainCounts { count_distinct, .. } = inner.as_ref() else {
31884 unreachable!()
31885 };
31886 assert!(count_distinct, "the rewrite must carry the distinct mode");
31887 }
31888
31889 #[test]
31894 fn multi_agg_distinct_count_arms_tsg_head_counts_fold() {
31895 let plan = LogicalPlan::parse(
31896 "SELECT ?cls (COUNT(DISTINCT ?f) AS ?n) (SAMPLE(?cls) AS ?s) WHERE { ?f a ?cls } GROUP BY ?cls",
31897 )
31898 .unwrap();
31899 assert!(
31900 head_counts_root(&plan).is_none(),
31901 "shortcut refuses 2 aggregates"
31902 );
31903 let mut scans = Vec::new();
31904 collect_scans(&plan.root, &mut scans);
31905 assert_eq!(scans.len(), 1);
31906 let scan = scans[0];
31907 assert_eq!(
31908 scan.head_scan_counts,
31909 Some(HeadScanKind::Classes),
31910 "TSG head-count annotation arms the PER_HEAD fold"
31911 );
31912 assert!(
31913 scan.domain_counts.is_none(),
31914 "head-count annotation precedes domain counts"
31915 );
31916 assert!(scan.is_counted_distinct(scan.subject.as_ref().unwrap()));
31917 assert_eq!(
31919 scan.bag_mark(scan.object.as_ref().unwrap()),
31920 Some(BagMark::Insensitive)
31921 );
31922 let plan = LogicalPlan::parse(
31927 "SELECT ?cls (COUNT(DISTINCT ?f) AS ?n) (MIN(?cls) AS ?m) WHERE { ?f a ?cls } GROUP BY ?cls",
31928 )
31929 .unwrap();
31930 let mut min_scans = Vec::new();
31931 collect_scans(&plan.root, &mut min_scans);
31932 assert_eq!(min_scans.len(), 1);
31933 assert_eq!(
31934 min_scans[0].head_scan_counts,
31935 Some(HeadScanKind::Classes),
31936 "MIN over the head folds from the same TSG hits"
31937 );
31938 }
31939
31940 #[test]
31944 fn dual_agg_bag_shape_never_arms_head_counts() {
31945 let plan = LogicalPlan::parse(
31946 "SELECT ?class (COUNT(?s) AS ?n) (COUNT(*) AS ?all) WHERE { ?s a ?class } GROUP BY ?class",
31947 )
31948 .unwrap();
31949 let mut scans = Vec::new();
31950 collect_scans(&plan.root, &mut scans);
31951 assert_eq!(scans.len(), 1);
31952 let scan = scans[0];
31953 assert!(scan.head_scan_counts.is_none());
31954 assert!(scan.head_scan.is_none());
31955 assert_eq!(
31956 scan.domain_counts,
31957 Some(DomainScanKind::PredicateDomain),
31958 "POSG domain counts supply the bag"
31959 );
31960 }
31961
31962 #[test]
31963 fn count_distinct_star_stays_on_the_group_path() {
31964 let plan = LogicalPlan::parse(
31968 "SELECT ?o (COUNT(DISTINCT *) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31969 )
31970 .unwrap();
31971 assert!(domain_counts_root(&plan).is_none());
31972 assert!(
31973 matches!(find_group(&plan.root), PlanNode::Group { .. }),
31974 "Group must survive"
31975 );
31976 }
31977
31978 #[test]
31979 fn group_count_of_the_key_does_not_distinct_scan() {
31980 let plan = LogicalPlan::parse(
31983 "SELECT ?o (COUNT(?o) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31984 )
31985 .unwrap();
31986 assert!(domain_counts_root(&plan).is_none());
31987 let mut scans = Vec::new();
31988 collect_scans(&plan.root, &mut scans);
31989 assert_eq!(scans.len(), 1);
31990 let scan = scans[0];
31991 assert_eq!(
31992 scan.bag_mark(scan.object.as_ref().unwrap()),
31993 Some(BagMark::Sensitive)
31994 );
31995 assert!(scan.domain_scan.is_none() && scan.head_scan.is_none());
31996 }
31997
31998 #[test]
31999 fn sum_aggregate_stays_on_the_group_path() {
32000 let plan = LogicalPlan::parse(
32001 "SELECT ?o (SUM(?s) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
32002 )
32003 .unwrap();
32004 assert!(domain_counts_root(&plan).is_none());
32005 }
32006
32007 #[test]
32008 fn count_expression_argument_stays_on_the_group_path() {
32009 let plan = LogicalPlan::parse(
32010 "SELECT ?o (COUNT(?s + 1) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
32011 )
32012 .unwrap();
32013 assert!(domain_counts_root(&plan).is_none());
32014 }
32015
32016 #[test]
32017 fn repeated_count_variable_stays_on_the_group_path() {
32018 let plan = LogicalPlan::parse(
32021 "SELECT ?p (COUNT(?x) AS ?n) WHERE { ?x <http://ex/p> ?x } GROUP BY ?p",
32022 )
32023 .unwrap();
32024 assert!(domain_counts_root(&plan).is_none());
32025 }
32026
32027 #[test]
32028 fn count_star_repeated_slot_stays_on_the_group_path() {
32029 let plan = LogicalPlan::parse(
32032 "SELECT ?o (COUNT(*) AS ?n) WHERE { ?o <http://ex/p> ?o } GROUP BY ?o",
32033 )
32034 .unwrap();
32035 assert!(domain_counts_root(&plan).is_none());
32036 }
32037
32038 #[test]
32039 fn unbound_constraint_slot_stays_on_the_group_path() {
32040 let plan = LogicalPlan::parse("SELECT ?o (COUNT(?s) AS ?n) WHERE { ?s ?p ?o } GROUP BY ?o")
32042 .unwrap();
32043 assert!(domain_counts_root(&plan).is_none());
32044 }
32045
32046 #[test]
32047 fn group_key_on_subject_slot_rewrites_via_predicate_subjects() {
32048 let plan = LogicalPlan::parse(
32052 "SELECT ?s (COUNT(?o) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?s",
32053 )
32054 .unwrap();
32055 let Some((kind, head, _)) = domain_counts_root(&plan) else {
32056 panic!("expected DomainCounts under alias, got {:?}", plan.root);
32057 };
32058 assert_eq!(*kind, DomainScanKind::PredicateSubjects);
32059 assert_eq!(head.as_str(), "s");
32060 }
32061
32062 fn find_domain_counts_node(node: &PlanNode) -> Option<&PlanNode> {
32063 match node {
32064 PlanNode::DomainCounts { .. } => Some(node),
32065 PlanNode::Extend { inner, .. }
32066 | PlanNode::Filter { inner, .. }
32067 | PlanNode::Distinct { inner, .. }
32068 | PlanNode::Sort { inner, .. }
32069 | PlanNode::Slice { inner, .. }
32070 | PlanNode::Group { inner, .. } => find_domain_counts_node(inner),
32071 PlanNode::Join { left, right, .. } => {
32072 find_domain_counts_node(left).or_else(|| find_domain_counts_node(right))
32073 }
32074 _ => None,
32075 }
32076 }
32077
32078 #[test]
32079 fn values_two_key_group_lowers_to_domain_counts() {
32080 let plan = LogicalPlan::parse(
32081 "SELECT ?p ?o (COUNT(?s) AS ?c) WHERE {
32082 VALUES ?p { <http://ex/colour> <http://ex/height> <http://ex/condition> <http://ex/width> }
32083 ?s ?p ?o
32084 } GROUP BY ?p ?o",
32085 )
32086 .unwrap();
32087 let node = find_domain_counts_node(&plan.root).expect("DomainCounts shortcut");
32088 let PlanNode::DomainCounts {
32089 constraints,
32090 constraint_var,
32091 ..
32092 } = node
32093 else {
32094 unreachable!();
32095 };
32096 assert_eq!(constraints.len(), 4);
32097 assert_eq!(constraint_var.as_ref().map(|v| v.as_str()), Some("p"));
32098 let PlanNode::DomainCounts {
32099 constraint_multiplicity,
32100 ..
32101 } = node
32102 else {
32103 unreachable!();
32104 };
32105 assert_eq!(constraint_multiplicity.as_slice(), &[1, 1, 1, 1]);
32106 }
32107
32108 #[test]
32109 fn values_duplicate_constraint_keeps_row_multiplicity() {
32110 let plan = LogicalPlan::parse(
32111 "SELECT ?p ?o (COUNT(?s) AS ?c) WHERE {
32112 VALUES ?p { <http://ex/colour> <http://ex/colour> <http://ex/height> }
32113 ?s ?p ?o
32114 } GROUP BY ?p ?o",
32115 )
32116 .unwrap();
32117 let node = find_domain_counts_node(&plan.root).expect("DomainCounts shortcut");
32118 let PlanNode::DomainCounts {
32119 constraints,
32120 constraint_multiplicity,
32121 ..
32122 } = node
32123 else {
32124 unreachable!();
32125 };
32126 assert_eq!(constraints.len(), 2);
32127 let colour =
32130 waratah_storage::EncodedTerm::from(&NamedNode::new("http://ex/colour").unwrap());
32131 let height =
32132 waratah_storage::EncodedTerm::from(&NamedNode::new("http://ex/height").unwrap());
32133 let want: Vec<(waratah_storage::EncodedTerm, u64)> =
32134 if waratah_storage::encode_term_bytes(&colour)
32135 < waratah_storage::encode_term_bytes(&height)
32136 {
32137 vec![(colour, 2), (height, 1)]
32138 } else {
32139 vec![(height, 1), (colour, 2)]
32140 };
32141 let want_terms: Vec<_> = want.iter().map(|(term, _)| term.clone()).collect();
32142 let want_mults: Vec<_> = want.iter().map(|(_, mult)| *mult).collect();
32143 assert_eq!(constraints.as_slice(), want_terms.as_slice());
32144 assert_eq!(constraint_multiplicity.as_slice(), want_mults.as_slice());
32145 }
32146
32147 #[test]
32148 fn values_extra_non_join_column_counts_as_row_multiplicity() {
32149 let plan = LogicalPlan::parse(
32150 "SELECT ?p ?o (COUNT(*) AS ?c) WHERE {
32151 VALUES (?p ?tag) { (<http://ex/colour> 1) (<http://ex/colour> 2) }
32152 ?s ?p ?o
32153 } GROUP BY ?p ?o",
32154 )
32155 .unwrap();
32156 let node = find_domain_counts_node(&plan.root).expect("DomainCounts shortcut");
32157 let PlanNode::DomainCounts {
32158 constraints,
32159 constraint_multiplicity,
32160 ..
32161 } = node
32162 else {
32163 unreachable!();
32164 };
32165 assert_eq!(constraints.len(), 1);
32166 assert_eq!(constraint_multiplicity.as_slice(), &[2]);
32167 }
32168
32169 #[test]
32170 fn values_undef_constraint_does_not_eliminate_group() {
32171 let plan = LogicalPlan::parse(
32172 "SELECT ?p ?o (COUNT(?s) AS ?c) WHERE {
32173 VALUES ?p { UNDEF <http://ex/colour> }
32174 ?s ?p ?o
32175 } GROUP BY ?p ?o",
32176 )
32177 .unwrap();
32178 assert!(
32179 find_domain_counts_node(&plan.root).is_none(),
32180 "UNDEF on the constraint column must stay on the Group path"
32181 );
32182 }
32183
32184 #[test]
32185 fn values_binding_the_head_does_not_eliminate_group() {
32186 let plan = LogicalPlan::parse(
32187 "SELECT ?p ?o (COUNT(?s) AS ?c) WHERE {
32188 VALUES (?p ?o) { (<http://ex/colour> \"red\") (<http://ex/colour> \"red\") }
32189 ?s ?p ?o
32190 } GROUP BY ?p ?o",
32191 )
32192 .unwrap();
32193 assert!(
32194 find_domain_counts_node(&plan.root).is_none(),
32195 "a VALUES column that is also the head is a join key, not a scalar multiplier"
32196 );
32197 }
32198
32199 #[test]
32200 fn group_with_extra_triple_keeps_group_and_annotates_domain_counts() {
32201 let plan = LogicalPlan::parse(
32202 "SELECT ?p ?o (COUNT(?s) AS ?c) WHERE {
32203 VALUES ?p { <http://ex/colour> <http://ex/height> }
32204 ?s ?p ?o .
32205 ?s <http://ex/tag> ?t
32206 } GROUP BY ?p ?o",
32207 )
32208 .unwrap();
32209 assert!(
32210 matches!(find_group(&plan.root), PlanNode::Group { .. }),
32211 "extra triple must block the DomainCounts shortcut"
32212 );
32213 }
32214
32215 #[test]
32216 fn type_count_dual_agg_refuses_classes_head_scan() {
32217 let plan = LogicalPlan::parse(
32220 "SELECT ?class (COUNT(?s) AS ?n) (COUNT(*) AS ?all) WHERE { ?s a ?class } GROUP BY ?class",
32221 )
32222 .unwrap();
32223 assert!(
32224 matches!(find_group(&plan.root), PlanNode::Group { .. }),
32225 "a second aggregate must keep Group"
32226 );
32227 let mut scans = Vec::new();
32228 collect_scans(&plan.root, &mut scans);
32229 assert_eq!(scans.len(), 1);
32230 let scan = scans[0];
32231 let s = scan.subject.as_ref().unwrap();
32232 assert!(
32233 scan.is_counted(s),
32234 "COUNT(?s) / COUNT(*) must count the subject"
32235 );
32236 assert!(
32237 scan.head_scan.is_none(),
32238 "Classes skip-scan has no multiplicity: {scan:?}"
32239 );
32240 assert_eq!(
32241 scan.domain_counts,
32242 Some(DomainScanKind::PredicateDomain),
32243 "type COUNT must fall through to POSG domain counts: {scan:?}"
32244 );
32245 }
32246
32247 #[test]
32248 fn count_group_by_counted_var_is_live_not_counted() {
32249 let plan = LogicalPlan::parse(
32250 "SELECT ?s (COUNT(?s) AS ?n) WHERE { ?s <http://ex/p> ?o } GROUP BY ?s",
32251 )
32252 .unwrap();
32253 let PlanNode::Extend { inner, .. } = &plan.root else {
32254 panic!("expected Extend over Group");
32255 };
32256 let PlanNode::Group { inner, .. } = inner.as_ref() else {
32257 panic!("expected Group");
32258 };
32259 let PlanNode::Scan(scan) = inner.as_ref() else {
32260 panic!("expected Scan");
32261 };
32262 let s = scan.subject.as_ref().unwrap();
32263 assert!(scan.is_live(s));
32264 assert!(!scan.is_counted(s));
32265 assert!(domain_counts_root(&plan).is_none());
32266 }
32267
32268 fn bag_counts_profile(predicate: &str, triples: u64, distinct_heads: u128) -> StatsProfile {
32272 let mut profile = StatsProfile::default();
32273 let hash = waratah_storage::StrHash::new(predicate);
32274 profile.total_puts = triples;
32275 profile.predicate_counts.insert(hash, triples);
32276 profile
32277 .objects_per_predicate
32278 .insert(hash, hll_with_n(distinct_heads));
32279 profile
32280 }
32281
32282 #[test]
32283 fn bag_sensitive_head_annotates_domain_counts() {
32284 let profile = bag_counts_profile("http://ex/p", 100, 10);
32285 let plan = LogicalPlan::parse_with_profile(
32286 "SELECT ?o WHERE { ?s <http://ex/p> ?o }",
32287 Some(&profile),
32288 )
32289 .unwrap();
32290 let scans = plan.scans().unwrap();
32291 assert_eq!(scans.len(), 1);
32292 assert!(
32293 scans[0].domain_counts.is_some(),
32294 "bag head over a constrained scan should annotate the counts walk"
32295 );
32296 assert!(scans[0].domain_scan.is_none() && scans[0].head_scan.is_none());
32297 }
32298
32299 #[test]
32300 fn bag_counts_annotation_needs_a_loaded_profile() {
32301 let plan = LogicalPlan::parse("SELECT ?o WHERE { ?s <http://ex/p> ?o }").unwrap();
32302 let scans = plan.scans().unwrap();
32303 assert_eq!(scans.len(), 1);
32304 assert!(
32305 scans[0].domain_counts.is_none(),
32306 "no profile must keep the plain scan"
32307 );
32308 }
32309
32310 #[test]
32311 fn bag_counts_annotation_skips_short_runs() {
32312 let profile = bag_counts_profile("http://ex/p", 10, 10);
32314 let plan = LogicalPlan::parse_with_profile(
32315 "SELECT ?o WHERE { ?s <http://ex/p> ?o }",
32316 Some(&profile),
32317 )
32318 .unwrap();
32319 let scans = plan.scans().unwrap();
32320 assert!(scans[0].domain_counts.is_none());
32321 }
32322
32323 #[test]
32324 fn distinct_head_beats_the_bag_counts_annotation() {
32325 let plan = LogicalPlan::parse("SELECT DISTINCT ?o WHERE { ?s <http://ex/p> ?o }").unwrap();
32326 let scans = plan.scans().unwrap();
32327 assert_eq!(scans.len(), 1);
32328 assert!(scans[0].domain_scan.is_some() || scans[0].head_scan.is_some());
32329 assert!(scans[0].domain_counts.is_none());
32330 }
32331
32332 fn find_first_scan(node: &PlanNode) -> Option<&ScanOp> {
32336 match node {
32337 PlanNode::Scan(scan) => Some(scan),
32338 PlanNode::Join { left, right, .. }
32339 | PlanNode::LeftJoin { left, right, .. }
32340 | PlanNode::Union { left, right } => {
32341 find_first_scan(left).or_else(|| find_first_scan(right))
32342 }
32343 PlanNode::Filter { inner, .. }
32344 | PlanNode::Extend { inner, .. }
32345 | PlanNode::Slice { inner, .. }
32346 | PlanNode::Distinct { inner, .. }
32347 | PlanNode::Sort { inner, .. }
32348 | PlanNode::Group { inner, .. }
32349 | PlanNode::JoinGraphVar { inner, .. } => find_first_scan(inner),
32350 PlanNode::SubSelect(sub) => find_first_scan(&sub.inner),
32351 PlanNode::CustomNode(op) => op.children.iter().find_map(find_first_scan),
32352 _ => None,
32353 }
32354 }
32355
32356 fn two_predicate_profile() -> StatsProfile {
32363 let mut profile = StatsProfile {
32364 total_puts: 2_000_000,
32365 ..StatsProfile::default()
32366 };
32367 for predicate in ["http://ex/p1", "http://ex/p2"] {
32368 let hash = waratah_storage::StrHash::new(predicate);
32369 profile.predicate_counts.insert(hash, 1_000_000);
32370 profile.objects_per_predicate.insert(hash, hll_with_n(50));
32371 }
32372 profile
32373 }
32374
32375 #[test]
32382 fn values_constrained_distinct_head_takes_domain_scan() {
32383 let profile = two_predicate_profile();
32384 let plan = LogicalPlan::parse_with_profile(
32385 "SELECT DISTINCT ?o WHERE { VALUES ?p { <http://ex/p1> <http://ex/p2> <http://ex/p2> } ?s ?p ?o }",
32386 Some(&profile),
32387 )
32388 .unwrap();
32389 let scan = find_first_scan(&plan.root).expect("scan must survive planning");
32390 assert!(
32391 scan.domain_scan.is_some(),
32392 "VALUES-constrained DISTINCT head must take the domain scan"
32393 );
32394 assert!(scan.broadcasted.is_some());
32395 }
32396
32397 #[test]
32401 fn values_constrained_plain_select_keeps_bag_rows() {
32402 let profile = two_predicate_profile();
32403 let plan = LogicalPlan::parse_with_profile(
32404 "SELECT ?o WHERE { VALUES ?p { <http://ex/p1> <http://ex/p2> } ?s ?p ?o }",
32405 Some(&profile),
32406 )
32407 .unwrap();
32408 let scan = find_first_scan(&plan.root).expect("scan must survive planning");
32409 assert!(
32410 scan.broadcasted.is_some(),
32411 "the stamp must land for this pin"
32412 );
32413 assert!(scan.domain_scan.is_none());
32414 assert!(scan.domain_counts.is_none());
32415 }
32416
32417 #[test]
32420 fn values_constrained_count_keeps_row_multiplicity() {
32421 let profile = two_predicate_profile();
32422 let plan = LogicalPlan::parse_with_profile(
32423 "SELECT (COUNT(*) AS ?n) WHERE { VALUES ?p { <http://ex/p1> <http://ex/p2> <http://ex/p2> } ?s ?p ?o }",
32424 Some(&profile),
32425 )
32426 .unwrap();
32427 assert!(find_first_scan(&plan.root).is_none_or(|scan| scan.domain_scan.is_none()));
32430 }
32431
32432 #[test]
32436 fn values_constrained_slice_head_stays_sensitive() {
32437 let profile = two_predicate_profile();
32438 let plan = LogicalPlan::parse_with_profile(
32439 "SELECT DISTINCT ?o WHERE { { SELECT ?o WHERE { VALUES ?p { <http://ex/p1> } ?s ?p ?o } LIMIT 3 } }",
32440 Some(&profile),
32441 )
32442 .unwrap();
32443 let scan = find_first_scan(&plan.root).expect("scan must survive planning");
32444 assert!(scan.domain_scan.is_none());
32445 }
32446
32447 #[test]
32448 fn bag_counts_annotation_survives_a_bare_limit() {
32449 let profile = bag_counts_profile("http://ex/p", 100, 10);
32453 let plan = LogicalPlan::parse_with_profile(
32454 "SELECT ?o WHERE { ?s <http://ex/p> ?o } LIMIT 10",
32455 Some(&profile),
32456 )
32457 .unwrap();
32458 let scans = plan.scans().unwrap();
32459 assert_eq!(scans.len(), 1);
32460 assert!(scans[0].domain_counts.is_some());
32461 for sparql in [
32462 "SELECT ?o WHERE { ?s <http://ex/p> ?o } LIMIT 10",
32463 "SELECT ?o WHERE { ?s <http://ex/p> ?o } ORDER BY ?o LIMIT 10",
32464 "SELECT ?o WHERE { ?s <http://ex/p> ?o }",
32465 ] {
32466 let text = explain_est(sparql, Some(&profile));
32467 assert!(
32468 !text.contains("domain_counts_bag"),
32469 "the scan leaf does not print the count RPC: {text}"
32470 );
32471 }
32472 }
32473
32474 #[test]
32475 fn bag_counts_under_default_union_stays_on_the_scan() {
32476 let profile = bag_counts_profile("http://ex/p", 1_000, 1);
32477 let query =
32478 crate::rephrase_error::parse_query("SELECT ?o WHERE { ?s <http://ex/p> ?o }").unwrap();
32479 let Query::Select {
32480 pattern, dataset, ..
32481 } = query
32482 else {
32483 panic!("select");
32484 };
32485 let dataset = QueryDataset::resolve(&[], &[], dataset.as_ref(), true).unwrap();
32486 let ctx = QueryContext::from_snapshot(SnapshotId::latest()).with_dataset(dataset);
32487 let plan = LogicalPlan::from_algebra_with_ctx(pattern, Some(&profile), &ctx).unwrap();
32488 let scans = plan.scans().unwrap();
32489 assert!(scans[0].domain_counts.is_some());
32490 assert!(scans[0].merge_default_graph);
32491 }
32492
32493 #[test]
32494 fn grouped_estimate_names_domain_counts_on_the_group() {
32495 let text = explain_est(
32496 "SELECT ?o (COUNT(?s) AS ?n) (COUNT(*) AS ?all) WHERE { ?s <http://ex/p> ?o } GROUP BY ?o",
32497 None,
32498 );
32499 assert!(
32500 text.contains("(weighted_counts domain_counts_bag "),
32501 "{text}"
32502 );
32503 assert_eq!(
32504 text.matches("domain_counts_bag").count(),
32505 1,
32506 "the scan leaf must not repeat the count RPC: {text}"
32507 );
32508 }
32509
32510 #[test]
32511 fn having_is_iri_stamps_domain_counts() {
32512 let plan = LogicalPlan::parse(
32513 "SELECT ?o (COUNT(?s) AS ?n) WHERE { ?s <http://ex/p> ?o } GROUP BY ?o HAVING (isIRI(?o))",
32514 )
32515 .unwrap();
32516 let PlanNode::DomainCounts { iri_only, .. } =
32517 find_domain_counts(&plan.root).expect("DomainCounts under HAVING")
32518 else {
32519 unreachable!()
32520 };
32521 assert!(
32522 *iri_only,
32523 "isIRI(?o) on the group key must stamp the count node"
32524 );
32525 }
32526
32527 fn find_domain_counts(node: &PlanNode) -> Option<&PlanNode> {
32528 match node {
32529 PlanNode::DomainCounts { .. } => Some(node),
32530 PlanNode::Extend { inner, .. }
32531 | PlanNode::Filter { inner, .. }
32532 | PlanNode::Slice { inner, .. }
32533 | PlanNode::Group { inner, .. }
32534 | PlanNode::Distinct { inner, .. }
32535 | PlanNode::Sort { inner, .. } => find_domain_counts(inner),
32536 _ => None,
32537 }
32538 }
32539
32540 #[test]
32546 fn probe_key_domains_stamp_from_the_probe_arm_not_the_driver() {
32547 let mut profile = StatsProfile::default();
32548 let niche = StrHash::new("http://ex/niche");
32549 let wide = StrHash::new("http://ex/wide");
32550 profile.predicate_counts.insert(niche, 400);
32551 profile.predicate_counts.insert(wide, 5_000_000);
32552 profile
32553 .subjects_per_predicate
32554 .insert(niche, hll_with_n(400));
32555 profile
32556 .subjects_per_predicate
32557 .insert(wide, hll_with_n(1_000_000));
32558 profile.total_puts = 5_000_400;
32559
32560 let left = PlanNode::Scan(var_scan(Some("s"), "http://ex/niche", Some("flag"), 400));
32563 let right = PlanNode::Scan(var_scan(Some("s"), "http://ex/wide", Some("o"), 5_000_000));
32564 let join = join_nodes(left, right, Some(&profile));
32565 let PlanNode::Join {
32566 hash_keys,
32567 probe_key_domains,
32568 probe_key_overlap_milli: _,
32569 ..
32570 } = join
32571 else {
32572 panic!("expected Join, got {join:?}");
32573 };
32574 assert_eq!(hash_keys, vec![var("s")]);
32575 assert_eq!(probe_key_domains.len(), 1);
32576 let stamped = probe_key_domains[0];
32579 assert!(
32580 (900_000..=1_100_000).contains(&stamped),
32581 "stamp must be the probe arm's domain (~1M), got {stamped}"
32582 );
32583 }
32584
32585 #[test]
32605 fn seat_by_total_cost_flips_the_legacy_swap() {
32606 let member_of = StrHash::new("http://ex/memberOf");
32607 let degree_from = StrHash::new("http://ex/degreeFrom");
32608 let mut profile = StatsProfile::default();
32609 profile.predicate_counts.insert(member_of, 1_048_532);
32610 profile.predicate_counts.insert(degree_from, 652_374);
32611 profile
32612 .subjects_per_predicate
32613 .insert(member_of, hll_with_n(1_500));
32614 profile
32615 .subjects_per_predicate
32616 .insert(degree_from, hll_with_n(3_000));
32617 profile
32618 .objects_per_predicate
32619 .insert(member_of, hll_with_n(326_526));
32620 profile
32621 .objects_per_predicate
32622 .insert(degree_from, hll_with_n(10_000));
32623 profile.total_puts = 1_048_532 + 652_374;
32624 let member_of_term = Some(EncodedTerm::from(
32625 &NamedNode::new("http://ex/memberOf").unwrap(),
32626 ));
32627 let degree_from_term = Some(EncodedTerm::from(
32628 &NamedNode::new("http://ex/degreeFrom").unwrap(),
32629 ));
32630 let join_of = || {
32631 join_nodes(
32632 PlanNode::Scan(var_scan(
32633 Some("x"),
32634 "http://ex/memberOf",
32635 Some("y"),
32636 1_048_532,
32637 )),
32638 PlanNode::Scan(var_scan(
32639 Some("x"),
32640 "http://ex/degreeFrom",
32641 Some("y"),
32642 652_374,
32643 )),
32644 Some(&profile),
32645 )
32646 };
32647 let driving_predicate = |node: &PlanNode| {
32648 let PlanNode::Join { left, .. } = node else {
32649 panic!("expected Join, got {node:?}");
32650 };
32651 let PlanNode::Scan(scan) = left.as_ref() else {
32652 panic!("driver arm should stay a scan, got {left:?}");
32653 };
32654 scan.pattern.predicate.clone()
32655 };
32656
32657 let mut legacy = join_of();
32659 refinalize_joins(&mut legacy, Some(&profile), None);
32660 assert_eq!(
32661 driving_predicate(&legacy),
32662 member_of_term,
32663 "the legacy comparator must keep the small-domain big arm driving"
32664 );
32665
32666 let seat_ctx =
32669 QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
32670 let mut promoted = join_of();
32671 refinalize_joins(&mut promoted, Some(&profile), Some(&seat_ctx));
32672 assert_eq!(
32673 driving_predicate(&promoted),
32674 degree_from_term,
32675 "the seat-by-total-cost comparator must invert the seating here"
32676 );
32677 }
32678
32679 #[test]
32688 fn t1_facet_shape_seats_union_left_and_promotes_semi() {
32689 use spargebra::Query;
32690 use waratah_stats::term_key;
32691
32692 let sparql = r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
32693 ?r <http://ex/isRecord> <http://ex/record> .
32694 { ?r <http://ex/kindA> ?v . BIND(<http://ex/dimA> AS ?dim) }
32695 UNION
32696 { ?r <http://ex/kindB> ?v . BIND(<http://ex/dimB> AS ?dim) }
32697 UNION
32698 { ?r <http://ex/kindC> ?v . BIND(<http://ex/dimC> AS ?dim) }
32699 } GROUP BY ?dim ?v"#;
32700
32701 let mut profile = StatsProfile::default();
32702 for (predicate, rows, subjects, objects) in [
32703 ("http://ex/isRecord", 500_000u64, 500_000u128, 1u128),
32704 ("http://ex/kindA", 1_000_000, 500_000, 4),
32705 ("http://ex/kindB", 1_000_000, 500_000, 4),
32706 ("http://ex/kindC", 1_000_000, 500_000, 4),
32707 ] {
32708 profile
32709 .predicate_counts
32710 .insert(StrHash::new(predicate), rows);
32711 profile
32712 .subjects_per_predicate
32713 .insert(StrHash::new(predicate), hll_with_n(subjects));
32714 profile
32715 .objects_per_predicate
32716 .insert(StrHash::new(predicate), hll_with_n(objects));
32717 }
32718 profile.total_puts = 3_500_000;
32719 let record = EncodedTerm::from(&NamedNode::new("http://ex/record").unwrap());
32720 profile.object_cms.add(term_key(&record), 500_000);
32721
32722 let Query::Select { pattern, .. } = crate::rephrase_error::parse_query(sparql).unwrap()
32723 else {
32724 panic!("expected SELECT");
32725 };
32726 let ctx = QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
32727 let plan = LogicalPlan::from_algebra_with_ctx(pattern, Some(&profile), &ctx).unwrap();
32728
32729 let group = match &plan.root {
32730 PlanNode::Group { .. } => &plan.root,
32731 PlanNode::Extend { inner, .. } => inner.as_ref(),
32732 other => panic!("expected the alias Extend over the Group, got {other:?}"),
32733 };
32734 let PlanNode::Group {
32735 inner,
32736 variables,
32737 aggregates,
32738 ..
32739 } = group
32740 else {
32741 panic!("expected Group, got {group:?}");
32742 };
32743 let PlanNode::Join {
32744 left, right, meta, ..
32745 } = inner.as_ref()
32746 else {
32747 panic!("expected the Join under the Group, got {inner:?}");
32748 };
32749 assert!(
32750 matches!(left.as_ref(), PlanNode::Union { .. }),
32751 "the union must be the driver, got {left:?}"
32752 );
32753 let PlanNode::Scan(scan) = right.as_ref() else {
32754 panic!("expected the record scan as the probe, got {right:?}");
32755 };
32756 assert_eq!(
32757 scan.pattern.object,
32758 Some(record),
32759 "the probe must be ?r isRecord <record>"
32760 );
32761 assert!(
32762 scan.fetch_once.is_some(),
32763 "the benchmark shape needs the whole-read verdict, got {scan:?}"
32764 );
32765 assert_eq!(
32766 meta.strategy,
32767 JoinStrategy::SemiScan,
32768 "the key-unique whole-read record scan must be a semi probe"
32769 );
32770 let modes = count_mode_plan(inner, variables, aggregates)
32774 .expect("the three single-pattern arms must qualify");
32775 assert_eq!(modes.dim.as_str(), "dim");
32776 assert_eq!(modes.by_dim.len(), 3);
32777 assert!(
32778 modes
32779 .by_dim
32780 .values()
32781 .all(|mode| *mode == CountMode::CountRows),
32782 "all three single-pattern arms must count rows: {modes:?}"
32783 );
32784
32785 let mixed_sparql = r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
32790 ?r <http://ex/isRecord> <http://ex/record> .
32791 { ?r <http://ex/kindA> ?v . BIND(<http://ex/dimA> AS ?dim) }
32792 UNION
32793 { ?r <http://ex/kindB> ?v . BIND(<http://ex/dimB> AS ?dim) }
32794 UNION
32795 { ?r <http://ex/kindC> ?v . BIND(<http://ex/dimC> AS ?dim) }
32796 UNION
32797 { ?r <http://ex/kindD> ?v . ?r <http://ex/other> ?w . BIND(<http://ex/dimD> AS ?dim) }
32798 } GROUP BY ?dim ?v"#;
32799 let Query::Select { pattern, .. } =
32800 crate::rephrase_error::parse_query(mixed_sparql).unwrap()
32801 else {
32802 panic!("expected SELECT");
32803 };
32804 let mut mixed_profile = profile.clone();
32805 for (predicate, rows, subjects, objects) in [
32806 ("http://ex/kindD", 1_000_000u64, 500_000u128, 4u128),
32807 ("http://ex/other", 1_000_000, 500_000, 500_000),
32808 ] {
32809 mixed_profile
32810 .predicate_counts
32811 .insert(StrHash::new(predicate), rows);
32812 mixed_profile
32813 .subjects_per_predicate
32814 .insert(StrHash::new(predicate), hll_with_n(subjects));
32815 mixed_profile
32816 .objects_per_predicate
32817 .insert(StrHash::new(predicate), hll_with_n(objects));
32818 }
32819 mixed_profile.total_puts += 2_000_000;
32820 let mixed_plan =
32821 LogicalPlan::from_algebra_with_ctx(pattern, Some(&mixed_profile), &ctx).unwrap();
32822 let mixed_group = match &mixed_plan.root {
32823 PlanNode::Group { .. } => &mixed_plan.root,
32824 PlanNode::Extend { inner, .. } => inner.as_ref(),
32825 other => panic!("expected the alias Extend over the Group, got {other:?}"),
32826 };
32827 let PlanNode::Group {
32828 inner,
32829 variables,
32830 aggregates,
32831 ..
32832 } = mixed_group
32833 else {
32834 panic!("expected Group, got {mixed_group:?}");
32835 };
32836 let PlanNode::Join { left, meta, .. } = inner.as_ref() else {
32837 panic!("expected the semi Join under the mixed Group, got {inner:?}");
32838 };
32839 assert!(
32840 matches!(left.as_ref(), PlanNode::Union { .. }),
32841 "the mixed union must stay on the driver side, got {left:?}"
32842 );
32843 assert_eq!(
32844 meta.strategy,
32845 JoinStrategy::SemiScan,
32846 "the mixed shape must keep the key-unique semi probe"
32847 );
32848 let mixed_modes = count_mode_plan(inner, variables, aggregates)
32849 .expect("the three single-pattern arms still qualify");
32850 assert_eq!(
32851 mixed_modes.summary(),
32852 "dim=?dim arms_count_rows=3 arms_distinct=1"
32853 );
32854
32855 let duplicate_sparql = r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
32859 ?r <http://ex/isRecord> <http://ex/record> .
32860 { ?r <http://ex/kindA> ?v . BIND(<http://ex/dimA> AS ?dim) }
32861 UNION
32862 { ?r <http://ex/kindB> ?v . BIND(<http://ex/dimB> AS ?dim) }
32863 UNION
32864 { ?r <http://ex/kindC> ?v . BIND(<http://ex/dimC> AS ?dim) }
32865 UNION
32866 { ?r <http://ex/kindD> ?v . BIND(<http://ex/dimA> AS ?dim) }
32867 } GROUP BY ?dim ?v"#;
32868 let Query::Select { pattern, .. } =
32869 crate::rephrase_error::parse_query(duplicate_sparql).unwrap()
32870 else {
32871 panic!("expected SELECT");
32872 };
32873 let duplicate_plan =
32874 LogicalPlan::from_algebra_with_ctx(pattern, Some(&mixed_profile), &ctx).unwrap();
32875 let duplicate_group = match &duplicate_plan.root {
32876 PlanNode::Group { .. } => &duplicate_plan.root,
32877 PlanNode::Extend { inner, .. } => inner.as_ref(),
32878 other => panic!("expected the alias Extend over the Group, got {other:?}"),
32879 };
32880 let PlanNode::Group {
32881 inner,
32882 variables,
32883 aggregates,
32884 ..
32885 } = duplicate_group
32886 else {
32887 panic!("expected Group, got {duplicate_group:?}");
32888 };
32889 let duplicate_modes = count_mode_plan(inner, variables, aggregates)
32890 .expect("the single-pattern arms still build the map");
32891 assert_eq!(
32892 duplicate_modes.summary(),
32893 "dim=?dim arms_count_rows=2 arms_distinct=1",
32894 "a shared discriminator must keep the seen-set"
32895 );
32896
32897 let dead_slot_sparql = r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
32902 ?r <http://ex/isRecord> <http://ex/record> .
32903 { ?r <http://ex/kindA> ?v . BIND(<http://ex/dimA> AS ?dim) }
32904 UNION
32905 { ?r <http://ex/kindB> ?v . BIND(<http://ex/dimB> AS ?dim) }
32906 UNION
32907 { ?r ?pc ?v . BIND(<http://ex/dimC> AS ?dim) }
32908 } GROUP BY ?dim ?v"#;
32909 let Query::Select { pattern, .. } =
32910 crate::rephrase_error::parse_query(dead_slot_sparql).unwrap()
32911 else {
32912 panic!("expected SELECT");
32913 };
32914 let dead_slot_plan =
32915 LogicalPlan::from_algebra_with_ctx(pattern, Some(&profile), &ctx).unwrap();
32916 let dead_slot_group = match &dead_slot_plan.root {
32917 PlanNode::Group { .. } => &dead_slot_plan.root,
32918 PlanNode::Extend { inner, .. } => inner.as_ref(),
32919 other => panic!("expected the alias Extend over the Group, got {other:?}"),
32920 };
32921 let PlanNode::Group {
32922 inner,
32923 variables,
32924 aggregates,
32925 ..
32926 } = dead_slot_group
32927 else {
32928 panic!("expected Group, got {dead_slot_group:?}");
32929 };
32930 let dead_slot_modes = count_mode_plan(inner, variables, aggregates)
32931 .expect("the two constant-predicate arms still qualify");
32932 assert_eq!(
32933 dead_slot_modes.summary(),
32934 "dim=?dim arms_count_rows=2 arms_distinct=1",
32935 "the arm with a dropped slot variable must keep the seen-set"
32936 );
32937 }
32938
32939 #[test]
32945 fn count_mode_plan_refuses_specialized_domain_counts_arms() {
32946 use spargebra::Query;
32947
32948 let sparql = r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
32949 { ?r <http://ex/kindA> ?v . BIND(<http://ex/dimA> AS ?dim) }
32950 UNION
32951 { ?r <http://ex/kindB> ?v . BIND(<http://ex/dimB> AS ?dim) }
32952 UNION
32953 { ?r <http://ex/kindD> ?v . ?r <http://ex/other> ?w . BIND(<http://ex/dimD> AS ?dim) }
32954 } GROUP BY ?dim ?v"#;
32955 let Query::Select { pattern, .. } = crate::rephrase_error::parse_query(sparql).unwrap()
32956 else {
32957 panic!("expected SELECT");
32958 };
32959 let ctx = QueryContext::from_snapshot(SnapshotId::latest());
32960 let plan = LogicalPlan::from_algebra_with_ctx(pattern, None, &ctx).unwrap();
32961 let group = match &plan.root {
32962 PlanNode::Group { .. } => &plan.root,
32963 PlanNode::Extend { inner, .. } => inner.as_ref(),
32964 other => panic!("expected the alias Extend over the Group, got {other:?}"),
32965 };
32966 let PlanNode::Group {
32967 inner,
32968 variables,
32969 aggregates,
32970 ..
32971 } = group
32972 else {
32973 panic!("expected Group, got {group:?}");
32974 };
32975 assert!(
32976 matches!(inner.as_ref(), PlanNode::Union { .. }),
32977 "expected the union under the Group, got {inner:?}"
32978 );
32979 let modes = count_mode_plan(inner, variables, aggregates)
32980 .expect("the dim map is still built; the specialized arms just refuse CountRows");
32981 assert_eq!(
32982 modes.summary(),
32983 "dim=?dim arms_count_rows=0 arms_distinct=3"
32984 );
32985 }
32986
32987 #[test]
32991 fn count_mode_plan_refuses_the_negative_gates() {
32992 let var = |name: &str| Variable::new(name).unwrap();
32993 let count_distinct = |name: &str| AggregateExpression::FunctionCall {
32994 name: AggregateFunction::Count,
32995 expr: Expression::Variable(var(name)),
32996 distinct: true,
32997 };
32998 let keys = vec![var("dim"), var("v")];
32999 let aggregates = vec![(var("n"), count_distinct("r"))];
33000 let arm = |scan: ScanOp, dim_iri: &str| PlanNode::Extend {
33001 inner: Box::new(PlanNode::Scan(scan)),
33002 variable: var("dim"),
33003 expression: Expression::NamedNode(NamedNode::new(dim_iri).unwrap()),
33004 const_strings: Vec::new(),
33005 const_blobs: Vec::new(),
33006 };
33007 let union = |left: PlanNode, right: PlanNode| PlanNode::Union {
33008 left: Box::new(left),
33009 right: Box::new(right),
33010 };
33011 let scan =
33012 |predicate: &str| var_scan(Some("r"), &format!("http://ex/{predicate}"), Some("v"), 10);
33013 let summary = |inner: &PlanNode| {
33014 count_mode_plan(inner, &keys, &aggregates)
33015 .expect("the dim map is built")
33016 .summary()
33017 };
33018
33019 let baseline = union(
33020 arm(scan("kindA"), "http://ex/dimA"),
33021 arm(scan("kindB"), "http://ex/dimB"),
33022 );
33023 assert_eq!(
33024 summary(&baseline),
33025 "dim=?dim arms_count_rows=2 arms_distinct=0"
33026 );
33027
33028 let one_arm_refused = |scan_b: ScanOp| {
33029 union(
33030 arm(scan("kindA"), "http://ex/dimA"),
33031 arm(scan_b, "http://ex/dimB"),
33032 )
33033 };
33034 for (label, scan_b) in [
33035 ("merge_default_graph", {
33036 let mut scan = scan("kindB");
33037 scan.merge_default_graph = true;
33038 scan
33039 }),
33040 ("graph variable", {
33041 let mut scan = scan("kindB");
33042 scan.graph = Some(var("g"));
33043 scan
33044 }),
33045 ("graph filter", {
33046 let mut scan = scan("kindB");
33047 scan.graph_filter = Some(GraphFilter::exclude_default());
33048 scan
33049 }),
33050 ("grounded counted", {
33051 let mut scan = scan("kindB");
33052 scan.grounded.push((var("r"), PatternSlot::Subject));
33053 scan
33054 }),
33055 ("second ungrouped variable", {
33056 let mut scan = scan("kindB");
33057 scan.predicate = Some(var("pc"));
33058 scan.pattern.predicate = None;
33059 scan
33060 }),
33061 ] {
33062 let plan = one_arm_refused(scan_b);
33063 assert_eq!(
33064 summary(&plan),
33065 "dim=?dim arms_count_rows=1 arms_distinct=1",
33066 "{label} must keep the seen-set"
33067 );
33068 }
33069
33070 let star = vec![(
33071 var("n"),
33072 AggregateExpression::CountSolutions { distinct: true },
33073 )];
33074 assert!(
33075 count_mode_plan(&baseline, &keys, &star).is_none(),
33076 "COUNT(DISTINCT *) is not a bare-variable count"
33077 );
33078
33079 let expression = vec![(
33080 var("n"),
33081 AggregateExpression::FunctionCall {
33082 name: AggregateFunction::Count,
33083 expr: Expression::Bound(var("r")),
33084 distinct: true,
33085 },
33086 )];
33087 assert!(
33088 count_mode_plan(&baseline, &keys, &expression).is_none(),
33089 "an expression argument keeps the Encoded seen-set"
33090 );
33091
33092 let two_extend = |dim_iri: &str, dim2_iri: &str| PlanNode::Extend {
33093 inner: Box::new(PlanNode::Extend {
33094 inner: Box::new(PlanNode::Scan(scan("kindA"))),
33095 variable: var("dim2"),
33096 expression: Expression::NamedNode(NamedNode::new(dim2_iri).unwrap()),
33097 const_strings: Vec::new(),
33098 const_blobs: Vec::new(),
33099 }),
33100 variable: var("dim"),
33101 expression: Expression::NamedNode(NamedNode::new(dim_iri).unwrap()),
33102 const_strings: Vec::new(),
33103 const_blobs: Vec::new(),
33104 };
33105 let multi = union(
33106 two_extend("http://ex/dimA", "http://ex/dimA2"),
33107 two_extend("http://ex/dimB", "http://ex/dimB2"),
33108 );
33109 let multi_keys = vec![var("dim"), var("dim2"), var("v")];
33110 assert!(
33111 count_mode_plan(&multi, &multi_keys, &aggregates).is_none(),
33112 "a second arm-discriminating key must refuse the map"
33113 );
33114
33115 let non_key_unique_right = PlanNode::Join {
33116 left: Box::new(baseline),
33117 right: Box::new(PlanNode::Scan(var_scan(
33118 Some("r"),
33119 "http://ex/isRecord",
33120 Some("o"),
33121 10,
33122 ))),
33123 hash_keys: vec![var("r")],
33124 probe_key_domains: vec![0],
33125 probe_key_overlap_milli: vec![1000],
33126 rhs_hostable_keys: Arc::from(vec![var("r")]),
33127 meta: JoinMeta {
33128 semi_gate: None,
33129 strategy: JoinStrategy::SemiScan,
33130 produced_row_count_estimate: 10,
33131 own_push_removed_row_count_estimate: 10,
33132 star_arms: None,
33133 },
33134 };
33135 assert!(
33136 count_mode_plan(&non_key_unique_right, &keys, &aggregates).is_none(),
33137 "a non-key-unique right must refuse the semi count mode"
33138 );
33139 }
33140
33141 #[test]
33147 fn t4_values_move_to_the_union_and_ground_the_selector_scans() {
33148 use spargebra::Query;
33149
33150 let sparql = r#"PREFIX sdo: <https://schema.org/>
33151PREFIX scr: <https://koenigsnet/scraper-vocab/>
33152PREFIX kn: <https://koenigsnet/ont/>
33153SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
33154 VALUES ?selCommodity { <https://koenigsnet/scraper-vocab/concept/commodity/gold> }
33155 VALUES ?selDocType { <https://koenigsnet/scraper-vocab/concept/record-type/report> }
33156 VALUES ?word { "report" }
33157 ?r scr:datasetKind <https://koenigsnet/scraper-vocab/concept/dataset-kind/record> .
33158 ?r sdo:name|sdo:abstract|scr:searchKeyword ?_lit .
33159 FILTER(CONTAINS(LCASE(STR(?_lit)), LCASE("report")))
33160 { ?r scr:documentType ?selDocType . { ?r scr:commodity ?v . BIND(scr:commodity AS ?dim) } }
33161 UNION
33162 { ?r scr:commodity ?selCommodity . { ?r scr:documentType ?v . BIND(scr:documentType AS ?dim) } }
33163 UNION
33164 { ?r scr:commodity ?selCommodity ; scr:documentType ?selDocType .
33165 { ?r sdo:isPartOf ?v . ?v a sdo:DataCatalog . BIND(kn:catalog AS ?dim) }
33166 UNION
33167 { ?r scr:documentType ?v . BIND(scr:documentType AS ?dim) }
33168 UNION
33169 { ?r scr:commodity ?v . BIND(scr:commodity AS ?dim) }
33170 UNION
33171 { ?r scr:subject ?v . BIND(scr:subject AS ?dim) }
33172 UNION
33173 { ?r scr:workCategory ?v . BIND(scr:workCategory AS ?dim) }
33174 UNION
33175 { ?r scr:geologicAge ?v . BIND(scr:geologicAge AS ?dim) }
33176 UNION
33177 { ?r scr:tenement|scr:mineralClaim|scr:mineralOccurrence ?_h . ?_h scr:jurisdiction ?v . ?v a scr:AdministrativeArea . BIND(scr:jurisdiction AS ?dim) }
33178 }
33179} GROUP BY ?dim ?v"#;
33180 let Query::Select { pattern, .. } = crate::rephrase_error::parse_query(sparql).unwrap()
33181 else {
33182 panic!("expected SELECT");
33183 };
33184 let ctx = QueryContext::from_snapshot(SnapshotId::latest());
33185 let plan = LogicalPlan::from_algebra_with_ctx(pattern, None, &ctx).unwrap();
33186
33187 let mut scans = Vec::new();
33188 collect_scans(&plan.root, &mut scans);
33189 let doc = var("selDocType");
33190 let commodity = var("selCommodity");
33191 let doc_term = EncodedTerm::from(
33192 &NamedNode::new("https://koenigsnet/scraper-vocab/concept/record-type/report").unwrap(),
33193 );
33194 let commodity_term = EncodedTerm::from(
33195 &NamedNode::new("https://koenigsnet/scraper-vocab/concept/commodity/gold").unwrap(),
33196 );
33197 let doc_scans: Vec<&ScanOp> = scans
33198 .iter()
33199 .copied()
33200 .filter(|scan| !scan.slot_of(&doc).is_empty())
33201 .collect();
33202 let commodity_scans: Vec<&ScanOp> = scans
33203 .iter()
33204 .copied()
33205 .filter(|scan| !scan.slot_of(&commodity).is_empty())
33206 .collect();
33207 assert!(
33208 !doc_scans.is_empty(),
33209 "the document-type selector scans must survive lowering"
33210 );
33211 assert!(
33212 doc_scans
33213 .iter()
33214 .all(|scan| scan.pattern.object.as_ref() == Some(&doc_term)),
33215 "every document-type selector scan must be grounded to the report term: {doc_scans:?}"
33216 );
33217 assert!(
33218 !commodity_scans.is_empty(),
33219 "the commodity selector scans must survive lowering"
33220 );
33221 assert!(
33222 commodity_scans
33223 .iter()
33224 .all(|scan| scan.pattern.object.as_ref() == Some(&commodity_term)),
33225 "every commodity selector scan must be grounded to the gold term: {commodity_scans:?}"
33226 );
33227
33228 let values = values_in_plan(&plan.root);
33229 assert!(
33230 values
33231 .iter()
33232 .all(|values| !values.variables.contains(&var("word"))),
33233 "the unused ?word column must be dropped: {values:?}"
33234 );
33235 }
33236
33237 fn select_region(pattern: &GraphPattern) -> &GraphPattern {
33241 match pattern {
33242 GraphPattern::Project { inner, .. }
33243 | GraphPattern::Extend { inner, .. }
33244 | GraphPattern::Group { inner, .. }
33245 | GraphPattern::Filter { inner, .. } => select_region(inner),
33246 other => other,
33247 }
33248 }
33249
33250 type AlgebraValues<'a> = (Vec<usize>, &'a [Variable], &'a [Vec<Option<GroundTerm>>]);
33252
33253 fn collect_algebra_values<'a>(
33256 pattern: &'a GraphPattern,
33257 path: &mut Vec<usize>,
33258 out: &mut Vec<AlgebraValues<'a>>,
33259 ) {
33260 match pattern {
33261 GraphPattern::Values {
33262 variables,
33263 bindings,
33264 } => out.push((path.clone(), variables, bindings)),
33265 GraphPattern::Join { left, right }
33266 | GraphPattern::Union { left, right }
33267 | GraphPattern::Minus { left, right } => {
33268 path.push(0);
33269 collect_algebra_values(left, path, out);
33270 path.pop();
33271 path.push(1);
33272 collect_algebra_values(right, path, out);
33273 path.pop();
33274 }
33275 GraphPattern::LeftJoin { left, right, .. } => {
33276 path.push(0);
33277 collect_algebra_values(left, path, out);
33278 path.pop();
33279 path.push(1);
33280 collect_algebra_values(right, path, out);
33281 path.pop();
33282 }
33283 GraphPattern::Filter { inner, .. }
33284 | GraphPattern::Extend { inner, .. }
33285 | GraphPattern::Group { inner, .. }
33286 | GraphPattern::Project { inner, .. }
33287 | GraphPattern::OrderBy { inner, .. }
33288 | GraphPattern::Distinct { inner }
33289 | GraphPattern::Reduced { inner }
33290 | GraphPattern::Slice { inner, .. }
33291 | GraphPattern::Graph { inner, .. }
33292 | GraphPattern::Service { inner, .. } => {
33293 path.push(0);
33294 collect_algebra_values(inner, path, out);
33295 path.pop();
33296 }
33297 GraphPattern::Bgp { .. } | GraphPattern::Path { .. } => {}
33298 }
33299 }
33300
33301 fn parse_select_pattern(sparql: &str) -> GraphPattern {
33302 let Query::Select { pattern, .. } = crate::rephrase_error::parse_query(sparql).unwrap()
33303 else {
33304 panic!("expected SELECT");
33305 };
33306 pattern
33307 }
33308
33309 fn placed_values(sparql: &str) -> GraphPattern {
33310 place_values_at_lca_with_live(parse_select_pattern(sparql), &[])
33311 }
33312
33313 fn report_term() -> GroundTerm {
33314 GroundTerm::NamedNode(NamedNode::new("http://ex/report").unwrap())
33315 }
33316
33317 fn datasheet_term() -> GroundTerm {
33318 GroundTerm::NamedNode(NamedNode::new("http://ex/datasheet").unwrap())
33319 }
33320
33321 #[test]
33325 fn multi_row_values_move_whole_and_drop_a_dead_unbound_column() {
33326 let placed = placed_values(
33327 r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
33328 VALUES (?selDocType ?word ?extra) {
33329 (<http://ex/report> "report" UNDEF)
33330 (<http://ex/datasheet> "data" UNDEF)
33331 }
33332 ?r <http://ex/datasetKind> <http://ex/record> .
33333 ?r <http://ex/documentType> ?selDocType .
33334 ?r <http://ex/searchKeyword> ?word .
33335 { ?r <http://ex/commodity> ?v . BIND(<http://ex/commodity> AS ?dim) }
33336 UNION
33337 { ?r <http://ex/subject> ?v . BIND(<http://ex/subject> AS ?dim) }
33338 } GROUP BY ?dim ?v"#,
33339 );
33340 let region = select_region(&placed);
33341 let mut values = Vec::new();
33342 collect_algebra_values(region, &mut Vec::new(), &mut values);
33343 assert_eq!(
33344 values.len(),
33345 1,
33346 "the multi-row table must stay one unit, got {values:?}"
33347 );
33348 let (path, variables, rows) = &values[0];
33349 assert_eq!(
33350 variables,
33351 &[var("selDocType"), var("word")],
33352 "the always-unbound unused ?extra column must be dropped, and the bound columns kept"
33353 );
33354 let report_row = vec![
33355 Some(report_term()),
33356 Some(GroundTerm::Literal(Literal::new_simple_literal("report"))),
33357 ];
33358 let datasheet_row = vec![
33359 Some(datasheet_term()),
33360 Some(GroundTerm::Literal(Literal::new_simple_literal("data"))),
33361 ];
33362 assert_eq!(rows, &[report_row, datasheet_row], "row multiplicity lost");
33363 assert!(
33364 path.len() > 1,
33365 "the table must move below the region root, got {path:?}"
33366 );
33367 }
33368
33369 #[test]
33373 fn multi_row_values_with_an_expression_only_column_keep_their_original_seat() {
33374 let parsed = parse_select_pattern(
33375 r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
33376 VALUES (?selDocType ?word ?extra) {
33377 (<http://ex/report> "report" UNDEF)
33378 (<http://ex/datasheet> "data" UNDEF)
33379 }
33380 ?r <http://ex/documentType> ?selDocType .
33381 FILTER(CONTAINS(?word, "rep"))
33382 { ?r <http://ex/commodity> ?v . BIND(<http://ex/commodity> AS ?dim) }
33383 UNION
33384 { ?r <http://ex/subject> ?v . BIND(<http://ex/subject> AS ?dim) }
33385 } GROUP BY ?dim ?v"#,
33386 );
33387 let mut before = Vec::new();
33388 collect_algebra_values(select_region(&parsed), &mut Vec::new(), &mut before);
33389 let origin = before
33390 .iter()
33391 .find(|(_, variables, _)| variables.contains(&var("word")))
33392 .map(|(path, _, _)| path.clone())
33393 .expect("the original table must contain ?word");
33394 let placed = place_values_at_lca_with_live(parsed, &[]);
33395 let region = select_region(&placed);
33396 let mut values = Vec::new();
33397 collect_algebra_values(region, &mut Vec::new(), &mut values);
33398 assert_eq!(values.len(), 1, "got {values:?}");
33399 let (path, variables, rows) = &values[0];
33400 let expected: Vec<usize> = origin.iter().copied().chain([0]).collect();
33403 assert_eq!(
33404 path, &expected,
33405 "the table must keep its original seat so the FILTER can read ?word"
33406 );
33407 assert_eq!(
33408 variables,
33409 &[var("selDocType"), var("word")],
33410 "?extra is dropped, ?word stays for the FILTER expression"
33411 );
33412 assert_eq!(rows.len(), 2);
33413 }
33414
33415 #[test]
33418 fn multi_row_values_inside_a_union_arm_stay_in_that_arm() {
33419 let placed = placed_values(
33420 r#"SELECT * WHERE {
33421 { VALUES ?x { <http://ex/a> <http://ex/b> } . ?s <http://ex/p> ?x }
33422 UNION
33423 { ?s <http://ex/q> ?y }
33424 }"#,
33425 );
33426 let region = select_region(&placed);
33427 let mut values = Vec::new();
33428 collect_algebra_values(region, &mut Vec::new(), &mut values);
33429 assert_eq!(values.len(), 1, "got {values:?}");
33430 let (path, variables, rows) = &values[0];
33431 assert_eq!(variables, &[var("x")]);
33432 assert_eq!(rows.len(), 2);
33433 assert_eq!(
33434 path.first(),
33435 Some(&0),
33436 "the table must stay in the left UNION arm, got {path:?}"
33437 );
33438 }
33439
33440 #[test]
33444 fn values_column_read_only_by_order_by_survives_placement() {
33445 let plan = LogicalPlan::parse(
33446 r#"SELECT ?s ?y WHERE {
33447 VALUES (?x ?y) { (2 "a") (1 "b") }
33448 ?s <http://ex/p> ?o .
33449 } ORDER BY ?x"#,
33450 )
33451 .unwrap();
33452 let values = values_in_plan(&plan.root);
33453 assert_eq!(values.len(), 1, "{:?}", plan.root);
33454 assert!(
33455 values[0].variables.contains(&var("x")),
33456 "the ORDER BY key column must survive placement: {:?}",
33457 values[0]
33458 );
33459 assert_eq!(values[0].rows.len(), 2);
33460 }
33461
33462 #[test]
33467 fn values_column_read_only_by_an_exists_body_survives_placement() {
33468 let plan = LogicalPlan::parse(
33469 r#"SELECT ?s WHERE {
33470 VALUES ?s { <http://ex/s1> }
33471 VALUES ?x { <http://ex/a> }
33472 FILTER EXISTS { VALUES ?q { 1 } FILTER(?x = <http://ex/a>) }
33473 }"#,
33474 )
33475 .unwrap();
33476 let values = values_in_plan(&plan.root);
33477 assert!(
33478 values.iter().any(|v| v.variables.contains(&var("x"))),
33479 "the VALUES column read only inside EXISTS must survive: {:?}",
33480 plan.root
33481 );
33482 }
33483
33484 #[test]
33487 fn one_row_values_split_seats_each_column_at_its_branch() {
33488 let plan = LogicalPlan::parse(
33489 r#"SELECT ?s ?t WHERE {
33490 VALUES (?x ?y) { ( <http://ex/a> 7 ) }
33491 { ?s <http://ex/p> ?x }
33492 { ?t <http://ex/q> ?y }
33493 }"#,
33494 )
33495 .unwrap();
33496 let values = values_in_plan(&plan.root);
33497 let x: Vec<_> = values
33498 .iter()
33499 .filter(|values| values.variables == vec![var("x")])
33500 .collect();
33501 let y: Vec<_> = values
33502 .iter()
33503 .filter(|values| values.variables == vec![var("y")])
33504 .collect();
33505 assert_eq!(x.len(), 1, "one Values node for ?x: {values:?}");
33506 assert_eq!(y.len(), 1, "one Values node for ?y: {values:?}");
33507 assert_eq!(x[0].rows.len(), 1);
33508 assert_eq!(y[0].rows.len(), 1);
33509 }
33510
33511 #[test]
33515 fn multi_row_values_never_enter_an_optional_right() {
33516 let plan = LogicalPlan::parse(
33517 r#"SELECT ?s ?x WHERE {
33518 VALUES ?s { <http://ex/s1> }
33519 VALUES ?x { <http://ex/a> <http://ex/b> }
33520 OPTIONAL { ?s <http://ex/p> ?x }
33521 }"#,
33522 )
33523 .unwrap();
33524 let mut saw_left_join = false;
33525 walk_plan(&plan.root, &mut |node| {
33526 if let PlanNode::LeftJoin { right, .. } = node {
33527 saw_left_join = true;
33528 assert!(
33529 !values_in_plan(right)
33530 .iter()
33531 .any(|values| values.variables.contains(&var("x"))),
33532 "the multi-row ?x table must stay out of the OPTIONAL right: {right:?}"
33533 );
33534 }
33535 });
33536 assert!(saw_left_join, "expected a LeftJoin: {:?}", plan.root);
33537 }
33538
33539 #[test]
33542 fn mention_walk_counts_bound_and_graph_and_service_names() {
33543 let empty = || GraphPattern::Bgp {
33544 patterns: Vec::new(),
33545 };
33546
33547 let mut bound = Vec::new();
33548 collect_mentions(
33549 &GraphPattern::Filter {
33550 expr: Expression::Bound(var("bound")),
33551 inner: Box::new(empty()),
33552 },
33553 &mut bound,
33554 );
33555 assert_eq!(mention_count(&bound, &var("bound")), 1);
33556
33557 let mut graph = Vec::new();
33558 collect_mentions(
33559 &GraphPattern::Graph {
33560 name: NamedNodePattern::Variable(var("g")),
33561 inner: Box::new(empty()),
33562 },
33563 &mut graph,
33564 );
33565 assert_eq!(mention_count(&graph, &var("g")), 1);
33566
33567 let mut service = Vec::new();
33568 collect_mentions(
33569 &GraphPattern::Service {
33570 name: NamedNodePattern::Variable(var("svc")),
33571 inner: Box::new(empty()),
33572 silent: false,
33573 },
33574 &mut service,
33575 );
33576 assert_eq!(mention_count(&service, &var("svc")), 1);
33577 }
33578
33579 #[test]
33580 fn exists_bearing_expressions_are_detected_for_the_pin_guard() {
33581 let body = GraphPattern::Bgp {
33582 patterns: Vec::new(),
33583 };
33584 let nested = Expression::If(
33585 Box::new(Expression::Exists(Box::new(body))),
33586 Box::new(Expression::Variable(var("x"))),
33587 Box::new(Expression::Literal(Literal::new_simple_literal("fallback"))),
33588 );
33589 assert!(expression_contains_exists(&nested));
33590 assert!(!expression_contains_exists(&Expression::Variable(var("x"))));
33591 assert!(!expression_contains_exists(&Expression::Literal(
33592 Literal::new_simple_literal("fallback")
33593 )));
33594 }
33595
33596 #[test]
33621 fn stamped_custom_driver_and_probe_price_regime_work() {
33622 let stamped = |rows: u64| {
33629 PlanNode::CustomNode(cost_test_op(
33630 rows,
33631 Some(CustomOpCost {
33632 drain_rows: 90,
33633 per_key_unit: 8,
33634 inline_point_unit: 1,
33635 direct_probe: true,
33636 probe_keyed_columns: 0b1,
33637 probe_filter_unit: 8,
33638 probe_memo_entry_rows: 0,
33639 }),
33640 ))
33641 };
33642 let scan = || PlanNode::Scan(var_scan(Some("s"), "http://ex/p", Some("o"), 7_000));
33643
33644 let op_drives = seat_cost_total(None, &stamped(1_000), &scan(), &[], None, None);
33645 assert_eq!(op_drives.rows, 8_090 + 7_000);
33646 assert_eq!(op_drives.seeks, 0);
33647
33648 let op_probes = seat_cost_total(None, &scan(), &stamped(1_000), &[], None, None);
33649 assert_eq!(op_probes.rows, 7_000 + 8_090);
33650 assert_eq!(op_probes.seeks, 0);
33651 }
33652
33653 #[test]
33654 fn unstamped_custom_arms_still_price_at_the_row_estimate() {
33655 let op = PlanNode::CustomNode(cost_test_op(1_000, None));
33658 let scan = PlanNode::Scan(var_scan(Some("s"), "http://ex/p", Some("o"), 7_000));
33659 let seat = seat_cost_total(None, &op, &scan, &[], None, None);
33660 assert_eq!(seat.rows, 1_000 + 7_000);
33661 }
33662
33663 #[test]
33664 fn stamped_custom_probe_keyed_road_is_regime_work_per_page() {
33665 let mut profile = StatsProfile::default();
33673 profile
33674 .predicate_counts
33675 .insert(StrHash::new("http://ex/p"), 100_000);
33676 profile
33677 .subjects_per_predicate
33678 .insert(StrHash::new("http://ex/p"), hll_with_n(100_000));
33679 profile
33680 .objects_per_predicate
33681 .insert(StrHash::new("http://ex/p"), hll_with_n(50_000));
33682 profile.total_puts = 100_000;
33683 let driver = PlanNode::Scan(var_scan(None, "http://ex/p", Some("g"), 100_000));
33684 let op = cost_test_op(
33685 500_000,
33686 Some(CustomOpCost {
33687 drain_rows: 90,
33688 per_key_unit: 8,
33689 inline_point_unit: 1,
33690 direct_probe: true,
33691 probe_keyed_columns: 0b1,
33692 probe_filter_unit: 8,
33693 probe_memo_entry_rows: 0,
33694 }),
33695 );
33696 let probe = PlanNode::CustomNode(op.clone());
33697 let keys = hash_keys_for(&driver.output_vars(), &probe.output_vars());
33698 let seat = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
33699 let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
33703 let dom = profile
33704 .objects_per_predicate
33705 .get(&StrHash::new("http://ex/p"))
33706 .expect("object HLL")
33707 .cardinality();
33708 let list = clustered_page_distinct(100_000, dom, page);
33709 let pages = 100_000u64.div_ceil(page);
33710 let keyed = op
33711 .keyed_cost(list, Some(0))
33712 .expect("stamped op prices keyed_cost");
33713 assert_eq!(seat.rows, 100_000 + pages * keyed);
33714 assert_eq!(seat.seeks, 0);
33715 }
33716
33717 #[test]
33718 fn stamped_custom_probe_coverage_road_prices_one_sweep() {
33719 let mut profile = StatsProfile::default();
33725 profile
33726 .predicate_counts
33727 .insert(StrHash::new("http://ex/p"), 100_000);
33728 profile
33729 .subjects_per_predicate
33730 .insert(StrHash::new("http://ex/p"), hll_with_n(100_000));
33731 profile
33732 .objects_per_predicate
33733 .insert(StrHash::new("http://ex/p"), hll_with_n(50_000));
33734 profile.total_puts = 100_000;
33735 let driver = PlanNode::Scan(var_scan(None, "http://ex/p", Some("g"), 100_000));
33736 let probe = PlanNode::CustomNode(cost_test_op(
33737 300,
33738 Some(CustomOpCost {
33739 drain_rows: 90,
33740 per_key_unit: 8,
33741 inline_point_unit: 1,
33742 direct_probe: true,
33743 probe_keyed_columns: 0b1,
33744 probe_filter_unit: 8,
33745 probe_memo_entry_rows: 0,
33746 }),
33747 ));
33748 let keys = hash_keys_for(&driver.output_vars(), &probe.output_vars());
33749 let seat = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
33750 assert_eq!(seat.rows, 100_000 + 90 + 300 * 8);
33752 assert_eq!(seat.seeks, 0);
33753 }
33754
33755 fn custom_cluster_facts(node: &PlanNode) -> Option<(usize, u64, bool)> {
33762 fn walk(node: &PlanNode, joins_above: usize) -> Option<(usize, u64, bool)> {
33763 match node {
33764 PlanNode::Join { left, right, .. } => match (&**left, &**right) {
33765 (PlanNode::CustomNode(op), other) | (other, PlanNode::CustomNode(op)) => {
33766 Some((
33767 joins_above,
33768 other.produced_row_count_estimate(),
33769 op.cost.is_some(),
33770 ))
33771 }
33772 _ => walk(left, joins_above + 1).or_else(|| walk(right, joins_above + 1)),
33773 },
33774 _ => None,
33775 }
33776 }
33777 walk(node, 0)
33778 }
33779
33780 fn test_join(left: PlanNode, right: PlanNode) -> PlanNode {
33785 let keys = hash_keys_for(&left.output_vars(), &right.output_vars());
33786 let (strategy, produced, own_push_removed) =
33787 finalize_inner_join_meta(&left, &right, &keys, None);
33788 PlanNode::Join {
33789 left: Box::new(left),
33790 right: Box::new(right),
33791 hash_keys: keys,
33792 probe_key_domains: Vec::new(),
33793 probe_key_overlap_milli: Vec::new(),
33794 rhs_hostable_keys: Vec::new().into(),
33795 meta: JoinMeta {
33796 semi_gate: None,
33797 star_arms: None,
33798 strategy,
33799 produced_row_count_estimate: produced,
33800 own_push_removed_row_count_estimate: own_push_removed,
33801 },
33802 }
33803 }
33804
33805 fn sydney_shaped_tree(cluster: PlanNode) -> PlanNode {
33806 let union = PlanNode::Union {
33809 left: Box::new(PlanNode::Scan(var_scan(
33810 Some("f"),
33811 "http://ex/hasGeom",
33812 Some("g"),
33813 8_000_000,
33814 ))),
33815 right: Box::new(PlanNode::Scan(var_scan(
33816 Some("f"),
33817 "http://ex/hasDefault",
33818 Some("g"),
33819 1,
33820 ))),
33821 };
33822 let feature = PlanNode::Scan(var_scan(
33823 Some("f"),
33824 "http://ex/aFeature",
33825 Some("ft"),
33826 7_900_000,
33827 ));
33828 let cls = PlanNode::Scan(var_scan(Some("f"), "http://ex/aCls", Some("c"), 39_000_000));
33829 test_join(test_join(test_join(union, feature), cls), cluster)
33830 }
33831
33832 fn geo_cluster_profile() -> StatsProfile {
33833 let mut profile = StatsProfile::default();
33834 for (p, rows) in [
33835 ("http://ex/hasGeom", 8_000_000u64),
33836 ("http://ex/hasDefault", 1),
33837 ("http://ex/aFeature", 7_900_000),
33838 ("http://ex/aCls", 39_000_000),
33839 ("http://ex/asWKT", 5_000_000),
33840 ] {
33841 profile.predicate_counts.insert(StrHash::new(p), rows);
33842 }
33843 for (p, rows) in [
33848 ("http://ex/hasGeom", 8_000_000u64),
33849 ("http://ex/aFeature", 7_900_000),
33850 ("http://ex/aCls", 39_000_000),
33851 ("http://ex/asWKT", 5_000_000),
33852 ] {
33853 profile
33854 .subjects_per_predicate
33855 .insert(StrHash::new(p), hll_with_n(rows as u128));
33856 profile
33857 .objects_per_predicate
33858 .insert(StrHash::new(p), hll_with_n(rows as u128));
33859 }
33860 profile.total_puts = 59_900_001;
33861 profile
33862 }
33863
33864 #[test]
33865 fn stamped_custom_cluster_pools_and_seats_first() {
33866 let cluster = test_join(
33872 PlanNode::CustomNode(cost_test_op(
33873 500,
33874 Some(CustomOpCost {
33875 drain_rows: 90,
33876 per_key_unit: 8,
33877 inline_point_unit: 1,
33878 direct_probe: true,
33879 probe_keyed_columns: 0b1,
33880 probe_filter_unit: 8,
33881 probe_memo_entry_rows: 0,
33882 }),
33883 )),
33884 PlanNode::Scan(var_scan(
33885 Some("gm"),
33886 "http://ex/asWKT",
33887 Some("g"),
33888 5_000_000,
33889 )),
33890 );
33891 let mut tree = sydney_shaped_tree(cluster);
33892 let profile = geo_cluster_profile();
33893 assert_eq!(custom_cluster_facts(&tree), Some((1, 5_000_000, true)));
33896 reassociate_inner_joins(&mut tree, Some(&profile), None);
33897 assert_eq!(custom_cluster_facts(&tree), Some((3, 5_000_000, true)));
33902 let once = tree.clone();
33905 reassociate_inner_joins(&mut tree, Some(&profile), None);
33906 assert_eq!(tree, once);
33907 }
33908
33909 #[test]
33910 fn unpriced_custom_cluster_keeps_the_spine_frozen() {
33911 let cluster = test_join(
33916 PlanNode::CustomNode(cost_test_op(500, None)),
33917 PlanNode::Scan(var_scan(
33918 Some("gm"),
33919 "http://ex/asWKT",
33920 Some("g"),
33921 5_000_000,
33922 )),
33923 );
33924 let mut tree = sydney_shaped_tree(cluster);
33925 assert_eq!(custom_cluster_facts(&tree), Some((1, 5_000_000, false)));
33926 reassociate_inner_joins(&mut tree, Some(&geo_cluster_profile()), None);
33927 assert_eq!(custom_cluster_facts(&tree), Some((1, 5_000_000, false)));
33928 }
33929
33930 #[test]
33931 fn pinned_custom_cluster_keeps_the_spine_frozen() {
33932 let mut op = cost_test_op(
33937 500,
33938 Some(CustomOpCost {
33939 drain_rows: 90,
33940 per_key_unit: 8,
33941 inline_point_unit: 1,
33942 direct_probe: true,
33943 probe_keyed_columns: 0b1,
33944 probe_filter_unit: 8,
33945 probe_memo_entry_rows: 0,
33946 }),
33947 );
33948 op.pinned
33949 .push((var("g"), EncodedTerm::from(&Literal::from(1))));
33950 let cluster = test_join(
33951 PlanNode::CustomNode(op),
33952 PlanNode::Scan(var_scan(
33953 Some("gm"),
33954 "http://ex/asWKT",
33955 Some("g"),
33956 5_000_000,
33957 )),
33958 );
33959 let mut tree = sydney_shaped_tree(cluster);
33960 assert_eq!(custom_cluster_facts(&tree), Some((1, 5_000_000, true)));
33961 reassociate_inner_joins(&mut tree, Some(&geo_cluster_profile()), None);
33962 assert_eq!(custom_cluster_facts(&tree), Some((1, 5_000_000, true)));
33963 }
33964
33965 fn scan_row_order(node: &PlanNode, out: &mut Vec<u64>) {
33969 match node {
33970 PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
33971 scan_row_order(left, out);
33972 scan_row_order(right, out);
33973 }
33974 PlanNode::Scan(scan) => out.push(scan.produced_row_count_estimate),
33975 _ => {}
33976 }
33977 }
33978
33979 fn chained_union_profile() -> StatsProfile {
33983 let mut profile = StatsProfile::default();
33984 for (p, rows) in [
33985 ("http://ex/hasOwner", 5_000_000u64),
33986 ("http://ex/inAgency", 4_000_000),
33987 ("http://ex/flagged", 2_000),
33988 ("http://ex/underReview", 500),
33989 ("http://ex/asWKT", 5_000_000),
33990 ("http://ex/tagOne", 2_000),
33991 ("http://ex/tagTwo", 3_000),
33992 ("http://ex/agencyName", 1_000),
33993 ] {
33994 profile.predicate_counts.insert(StrHash::new(p), rows);
33995 profile
33996 .subjects_per_predicate
33997 .insert(StrHash::new(p), hll_with_n(rows as u128));
33998 profile
33999 .objects_per_predicate
34000 .insert(StrHash::new(p), hll_with_n(rows as u128));
34001 }
34002 profile
34003 }
34004
34005 #[test]
34013 fn pooled_union_operand_interior_associates_cost_based() {
34014 let profile = chained_union_profile();
34015 let has_owner = PlanNode::Scan(var_scan(
34018 Some("parcel"),
34019 "http://ex/hasOwner",
34020 Some("owner"),
34021 5_000_000,
34022 ));
34023 let in_agency = PlanNode::Scan(var_scan(
34024 Some("owner"),
34025 "http://ex/inAgency",
34026 Some("agency"),
34027 4_000_000,
34028 ));
34029 let flagged = PlanNode::Scan(var_scan(
34030 Some("parcel"),
34031 "http://ex/flagged",
34032 Some("v"),
34033 2_000,
34034 ));
34035 let chain = test_join(test_join(has_owner, in_agency), flagged);
34036 let union = PlanNode::Union {
34037 left: Box::new(chain),
34038 right: Box::new(PlanNode::Scan(var_scan(
34039 Some("parcel"),
34040 "http://ex/underReview",
34041 Some("r"),
34042 500,
34043 ))),
34044 };
34045 let cluster = test_join(
34046 PlanNode::CustomNode(cost_test_op(
34047 500,
34048 Some(CustomOpCost {
34049 drain_rows: 90,
34050 per_key_unit: 8,
34051 inline_point_unit: 1,
34052 direct_probe: true,
34053 probe_keyed_columns: 0b1,
34054 probe_filter_unit: 8,
34055 probe_memo_entry_rows: 0,
34056 }),
34057 )),
34058 PlanNode::Scan(var_scan(
34059 Some("gm"),
34060 "http://ex/asWKT",
34061 Some("g"),
34062 5_000_000,
34063 )),
34064 );
34065 let mut tree = test_join(union, cluster);
34066 reassociate_inner_joins(&mut tree, Some(&profile), None);
34067 let PlanNode::Join { left, right, .. } = &tree else {
34071 panic!("expected the spine root Join, got {tree:?}")
34072 };
34073 let (union, other) = match (left.as_ref(), right.as_ref()) {
34074 (union @ PlanNode::Union { .. }, other) => (union, other),
34075 (other, union @ PlanNode::Union { .. }) => (union, other),
34076 _ => panic!("expected the Union as a root operand, got {tree:?}"),
34077 };
34078 assert!(
34079 custom_cluster_facts(other).is_some(),
34080 "the cluster must remain the pool's other operand: {other:?}"
34081 );
34082 let PlanNode::Union { left: chain, .. } = union else {
34083 unreachable!("matched a Union above")
34084 };
34085
34086 let mut order = Vec::new();
34092 scan_row_order(chain, &mut order);
34093 let position = |rows: u64| {
34094 order
34095 .iter()
34096 .position(|&row| row == rows)
34097 .unwrap_or_else(|| panic!("scan {rows} missing from the rebuilt chain: {order:?}"))
34098 };
34099 assert!(
34100 position(2_000) < position(4_000_000),
34101 "flagged (2K) must be joined before inAgency (4M), \
34102 inverting the written order: {order:?}"
34103 );
34104
34105 let once = tree.clone();
34107 reassociate_inner_joins(&mut tree, Some(&profile), None);
34108 assert_eq!(tree, once);
34109 }
34110
34111 #[test]
34119 fn pooled_cluster_operand_descends_into_the_key_arm() {
34120 let profile = chained_union_profile();
34121 let wkt = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("w"), 5_000_000));
34122 let tag_two = PlanNode::Scan(var_scan(Some("g"), "http://ex/tagTwo", Some("t2"), 3_000));
34123 let tag_one = PlanNode::Scan(var_scan(Some("g"), "http://ex/tagOne", Some("t1"), 2_000));
34124 let key_arm = test_join(test_join(wkt, tag_two), tag_one);
34126 let mut tree = test_join(
34127 PlanNode::CustomNode(cost_test_op(
34128 500,
34129 Some(CustomOpCost {
34130 drain_rows: 90,
34131 per_key_unit: 8,
34132 inline_point_unit: 1,
34133 direct_probe: true,
34134 probe_keyed_columns: 0b1,
34135 probe_filter_unit: 8,
34136 probe_memo_entry_rows: 0,
34137 }),
34138 )),
34139 key_arm,
34140 );
34141 assert_eq!(
34142 custom_cluster_facts(&tree).map(|(joins_above, _, stamped)| (joins_above, stamped)),
34143 Some((0, true)),
34144 "as built: the cluster is the whole spine, key arm in parse order"
34145 );
34146 reassociate_inner_joins(&mut tree, Some(&profile), None);
34147 assert_eq!(
34150 custom_cluster_facts(&tree).map(|(joins_above, _, stamped)| (joins_above, stamped)),
34151 Some((0, true)),
34152 "the descent must not dissolve the cluster from its key arm"
34153 );
34154 let PlanNode::Join { right: key_arm, .. } = &tree else {
34155 panic!("expected the cluster Join, got {tree:?}")
34156 };
34157
34158 let mut order = Vec::new();
34164 scan_row_order(key_arm, &mut order);
34165 let position = |rows: u64| {
34166 order
34167 .iter()
34168 .position(|&row| row == rows)
34169 .unwrap_or_else(|| {
34170 panic!("scan {rows} missing from the rebuilt key arm: {order:?}")
34171 })
34172 };
34173 assert!(
34174 position(2_000) < position(3_000),
34175 "tagOne (2K) must be joined before tagTwo (3K), \
34176 inverting the written order: {order:?}"
34177 );
34178
34179 let once = tree.clone();
34180 reassociate_inner_joins(&mut tree, Some(&profile), None);
34181 assert_eq!(tree, once);
34182 }
34183
34184 #[test]
34190 fn cluster_free_pooled_spine_visits_union_interiors() {
34191 let profile = chained_union_profile();
34192 let has_owner = PlanNode::Scan(var_scan(
34193 Some("parcel"),
34194 "http://ex/hasOwner",
34195 Some("owner"),
34196 5_000_000,
34197 ));
34198 let in_agency = PlanNode::Scan(var_scan(
34199 Some("owner"),
34200 "http://ex/inAgency",
34201 Some("agency"),
34202 4_000_000,
34203 ));
34204 let flagged = PlanNode::Scan(var_scan(
34205 Some("parcel"),
34206 "http://ex/flagged",
34207 Some("v"),
34208 2_000,
34209 ));
34210 let chain = test_join(test_join(has_owner, in_agency), flagged);
34211 let union = PlanNode::Union {
34212 left: Box::new(chain),
34213 right: Box::new(PlanNode::Scan(var_scan(
34214 Some("parcel"),
34215 "http://ex/underReview",
34216 Some("r"),
34217 500,
34218 ))),
34219 };
34220 let mut tree = test_join(
34221 union,
34222 PlanNode::Scan(var_scan(
34223 Some("agency"),
34224 "http://ex/agencyName",
34225 Some("name"),
34226 1_000,
34227 )),
34228 );
34229 reassociate_inner_joins(&mut tree, Some(&profile), None);
34230
34231 let PlanNode::Join { left, right, .. } = &tree else {
34235 panic!("expected the spine root Join, got {tree:?}")
34236 };
34237 let union = if matches!(**left, PlanNode::Union { .. }) {
34238 left
34239 } else if matches!(**right, PlanNode::Union { .. }) {
34240 right
34241 } else {
34242 panic!("expected the Union as a root operand, got {tree:?}");
34243 };
34244 let PlanNode::Union { left: chain, .. } = &**union else {
34245 unreachable!("matched a Union above")
34246 };
34247
34248 fn one_scan_rows(node: &PlanNode) -> u64 {
34249 let mut rows = Vec::new();
34250 scan_row_order(node, &mut rows);
34251 assert_eq!(rows.len(), 1, "expected a single scan, got {node:?}");
34252 rows[0]
34253 }
34254
34255 let PlanNode::Join {
34261 left: inner,
34262 right: outer_probe,
34263 ..
34264 } = chain.as_ref()
34265 else {
34266 panic!("expected the rebuilt chain, got {chain:?}");
34267 };
34268 assert_eq!(
34269 one_scan_rows(outer_probe),
34270 4_000_000,
34271 "inAgency must be attached last, not left in written order"
34272 );
34273 let PlanNode::Join {
34274 left: pair_a,
34275 right: pair_b,
34276 ..
34277 } = inner.as_ref()
34278 else {
34279 panic!("expected the inner pair, got {inner:?}");
34280 };
34281 let mut pair = [one_scan_rows(pair_a), one_scan_rows(pair_b)];
34282 pair.sort_unstable();
34283 assert_eq!(
34284 pair,
34285 [2_000, 5_000_000],
34286 "the inner pair must be flagged + hasOwner"
34287 );
34288 }
34289
34290 #[test]
34291 fn union_domain_binds_an_unknown_hosting_arm_by_its_rows() {
34292 let profile = geo_cluster_profile();
34299 let sketched = PlanNode::Scan(var_scan(
34300 Some("f"),
34301 "http://ex/hasGeom",
34302 Some("g"),
34303 8_000_000,
34304 ));
34305 let sketchless = PlanNode::Scan(var_scan(Some("f"), "http://ex/hasDefault", Some("g"), 1));
34306 let union = PlanNode::Union {
34307 left: Box::new(sketched.clone()),
34308 right: Box::new(sketchless),
34309 };
34310 let dom = |node: &PlanNode| join_key_domain_for_node(Some(&profile), node, &var("g"));
34311 let sketched_dom = dom(&sketched).expect("hasGeom objects HLL");
34312 let got = dom(&union).expect("union domain is bound by the rows");
34313 assert_eq!(got, sketched_dom.saturating_add(1));
34315 let foreign = PlanNode::Scan(var_scan(Some("x"), "http://ex/aCls", Some("c"), 39_000_000));
34319 let foreign_union = PlanNode::Union {
34320 left: Box::new(sketched),
34321 right: Box::new(foreign),
34322 };
34323 assert_eq!(dom(&foreign_union), None);
34324 let both = PlanNode::Union {
34326 left: Box::new(PlanNode::Scan(var_scan(
34327 Some("f"),
34328 "http://ex/none1",
34329 Some("g"),
34330 10,
34331 ))),
34332 right: Box::new(PlanNode::Scan(var_scan(
34333 Some("f"),
34334 "http://ex/none2",
34335 Some("g"),
34336 20,
34337 ))),
34338 };
34339 assert_eq!(dom(&both), None);
34340 }
34341
34342 #[test]
34343 fn union_domain_merges_arm_sketches_instead_of_summing() {
34344 let mut profile = StatsProfile::default();
34348 let mut first = waratah_stats::HyperLogLog::default_params();
34349 for i in 0..1_000u128 {
34350 first.add(i);
34351 }
34352 let mut second = waratah_stats::HyperLogLog::default_params();
34353 for i in 500..1_500u128 {
34354 second.add(i);
34355 }
34356 profile.total_puts = 2_000;
34357 profile
34358 .subjects_per_predicate
34359 .insert(StrHash::new("http://ex/p1"), first);
34360 profile
34361 .subjects_per_predicate
34362 .insert(StrHash::new("http://ex/p2"), second);
34363 let union = PlanNode::Union {
34364 left: Box::new(PlanNode::Scan(var_scan(
34365 Some("s"),
34366 "http://ex/p1",
34367 Some("o1"),
34368 1_000,
34369 ))),
34370 right: Box::new(PlanNode::Scan(var_scan(
34371 Some("s"),
34372 "http://ex/p2",
34373 Some("o2"),
34374 1_000,
34375 ))),
34376 };
34377 let domain = join_key_domain_for_node(Some(&profile), &union, &var("s"))
34378 .expect("the merged sketch supplies the domain");
34379 assert!(
34380 (1_300..=1_700).contains(&domain),
34381 "merged union domain, got {domain}"
34382 );
34383 assert!(
34384 domain < 1_900,
34385 "the two-arm sum (2,000) must not be the domain: {domain}"
34386 );
34387 }
34388
34389 #[test]
34390 fn union_domain_adds_the_exact_class_count() {
34391 let mut profile = StatsProfile::default();
34394 let mut subjects = waratah_stats::HyperLogLog::default_params();
34395 for i in 0..1_000u128 {
34396 subjects.add(i);
34397 }
34398 profile
34399 .subjects_per_predicate
34400 .insert(StrHash::new("http://ex/p1"), subjects);
34401 profile
34402 .class_counts
34403 .insert(StrHash::new("http://ex/Cls"), 250);
34404 let plain = PlanNode::Scan(var_scan(Some("s"), "http://ex/p1", Some("o"), 1_000));
34405 let mut typed = var_scan(None, "http://ex/placeholder", None, 250);
34406 typed.pattern.predicate = Some(RDF_TYPE.clone());
34407 typed.pattern.object = Some(EncodedTerm::from(&NamedNode::new("http://ex/Cls").unwrap()));
34408 typed.subject = Some(var("s"));
34409 typed.object = None;
34410 let union = PlanNode::Union {
34411 left: Box::new(plain),
34412 right: Box::new(PlanNode::Scan(typed)),
34413 };
34414 let domain = join_key_domain_for_node(Some(&profile), &union, &var("s"))
34415 .expect("merged sketch plus the exact class count");
34416 assert!(
34417 (1_150..=1_350).contains(&domain),
34418 "merged sketch plus the exact class count, got {domain}"
34419 );
34420 }
34421
34422 #[test]
34423 fn union_domain_counts_the_class_universe_once() {
34424 let mut profile = StatsProfile::default();
34427 for class in ["http://ex/C1", "http://ex/C2", "http://ex/C3"] {
34428 profile.class_counts.insert(StrHash::new(class), 100);
34429 }
34430 let type_object = |subject: &str| {
34431 let mut scan = var_scan(Some(subject), "http://ex/placeholder", None, 300);
34432 scan.pattern.predicate = Some(RDF_TYPE.clone());
34433 scan.object = Some(var("c"));
34434 PlanNode::Scan(scan)
34435 };
34436 let union = PlanNode::Union {
34437 left: Box::new(type_object("s1")),
34438 right: Box::new(type_object("s2")),
34439 };
34440 let domain = join_key_domain_for_node(Some(&profile), &union, &var("c"))
34441 .expect("the class universe is exact");
34442 assert_eq!(domain, 3, "the class universe is one set, not one per arm");
34443 }
34444
34445 #[test]
34446 fn facet_union_join_estimates_the_containment_output() {
34447 let mut profile = StatsProfile::default();
34452 let mut subjects = waratah_stats::HyperLogLog::default_params();
34453 for i in 0..1_000u128 {
34454 subjects.add(i);
34455 }
34456 profile.total_puts = 4_000;
34457 profile
34458 .subjects_per_predicate
34459 .insert(StrHash::new("http://ex/facetA"), subjects.clone());
34460 profile
34461 .subjects_per_predicate
34462 .insert(StrHash::new("http://ex/facetB"), subjects.clone());
34463 profile
34464 .subjects_per_predicate
34465 .insert(StrHash::new("http://ex/datasetKind"), subjects);
34466 let union = PlanNode::Union {
34467 left: Box::new(PlanNode::Scan(var_scan(
34468 Some("r"),
34469 "http://ex/facetA",
34470 Some("v1"),
34471 2_000,
34472 ))),
34473 right: Box::new(PlanNode::Scan(var_scan(
34474 Some("r"),
34475 "http://ex/facetB",
34476 Some("v2"),
34477 2_000,
34478 ))),
34479 };
34480 let mut record_scan = var_scan(Some("r"), "http://ex/datasetKind", None, 1_000);
34481 record_scan.pattern.object = Some(EncodedTerm::from(
34482 &NamedNode::new("http://ex/record").unwrap(),
34483 ));
34484 let record = PlanNode::Scan(record_scan);
34485 let keys = hash_keys_for(&union.output_vars(), &record.output_vars());
34486 let (_, produced, _) = finalize_inner_join_meta(&union, &record, &keys, Some(&profile));
34487 assert!(
34488 produced >= 3_500,
34489 "containment-aware union join output, got {produced}"
34490 );
34491 }
34492
34493 #[test]
34494 fn union_domain_bound_lets_the_cluster_drive() {
34495 let profile = geo_cluster_profile();
34503 let union = PlanNode::Union {
34504 left: Box::new(PlanNode::Scan(var_scan(
34505 Some("f"),
34506 "http://ex/hasGeom",
34507 Some("g"),
34508 8_000_000,
34509 ))),
34510 right: Box::new(PlanNode::Scan(var_scan(
34511 Some("f"),
34512 "http://ex/hasDefault",
34513 Some("g"),
34514 1,
34515 ))),
34516 };
34517 let feature = PlanNode::Scan(var_scan(
34518 Some("f"),
34519 "http://ex/aFeature",
34520 Some("ft"),
34521 7_900_000,
34522 ));
34523 let subtree = test_join(union, feature);
34524 let cluster = test_join(
34525 PlanNode::CustomNode(cost_test_op(
34526 500,
34527 Some(CustomOpCost {
34528 drain_rows: 90,
34529 per_key_unit: 8,
34530 inline_point_unit: 1,
34531 direct_probe: true,
34532 probe_keyed_columns: 0b1,
34533 probe_filter_unit: 8,
34534 probe_memo_entry_rows: 0,
34535 }),
34536 )),
34537 PlanNode::Scan(var_scan(
34538 Some("gm"),
34539 "http://ex/asWKT",
34540 Some("g"),
34541 5_000_000,
34542 )),
34543 );
34544 let mut join = test_join(subtree, cluster);
34546 refinalize_joins_without_ctx(&mut join, Some(&profile));
34547 let PlanNode::Join { left, .. } = &join else {
34548 panic!("still a join")
34549 };
34550 let PlanNode::Join {
34553 left: cluster_lead, ..
34554 } = &**left
34555 else {
34556 panic!("the driver side is the cluster join")
34557 };
34558 assert!(
34559 matches!(&**cluster_lead, PlanNode::CustomNode(_)),
34560 "the geo cluster drives"
34561 );
34562 }
34563
34564 #[test]
34565 fn assoc_ranks_by_the_seating_the_arm_swap_keeps() {
34566 let mut profile = StatsProfile::default();
34567 profile
34568 .predicate_counts
34569 .insert(StrHash::new("http://ex/pS"), 100_000);
34570 profile
34571 .predicate_counts
34572 .insert(StrHash::new("http://ex/pB"), 50_000);
34573 profile
34574 .predicate_counts
34575 .insert(StrHash::new("http://ex/pC"), 40_000);
34576 profile
34577 .subjects_per_predicate
34578 .insert(StrHash::new("http://ex/pS"), hll_with_n(100_000));
34579 profile
34580 .subjects_per_predicate
34581 .insert(StrHash::new("http://ex/pB"), hll_with_n(100));
34582 profile
34583 .subjects_per_predicate
34584 .insert(StrHash::new("http://ex/pC"), hll_with_n(80_000));
34585 profile
34586 .objects_per_predicate
34587 .insert(StrHash::new("http://ex/pS"), hll_with_n(10_000));
34588 profile
34589 .objects_per_predicate
34590 .insert(StrHash::new("http://ex/pB"), hll_with_n(2_000));
34591 profile
34592 .objects_per_predicate
34593 .insert(StrHash::new("http://ex/pC"), hll_with_n(1_000));
34594 profile.total_puts = 190_000;
34595 let seed = PlanNode::Scan(var_scan(Some("x"), "http://ex/pS", Some("z"), 100_000));
34596 let cand_b = PlanNode::Scan(var_scan(Some("x"), "http://ex/pB", Some("w"), 50_000));
34597 let cand_c = PlanNode::Scan(var_scan(Some("x"), "http://ex/pC", Some("v"), 40_000));
34598
34599 let price = |driver: &PlanNode, probe: &PlanNode| {
34603 let keys = hash_keys_for(&driver.output_vars(), &probe.output_vars());
34604 seat_cost_total(Some(&profile), driver, probe, &keys, None, None)
34605 };
34606 let b_seed_drives = price(&seed, &cand_b);
34607 let seed_b = price(&cand_b, &seed);
34608 let c_seed_drives = price(&seed, &cand_c);
34609 let seed_c = price(&cand_c, &seed);
34610 let dom = |p: &str| {
34617 profile
34618 .subjects_per_predicate
34619 .get(&StrHash::new(p))
34620 .expect("subject HLL")
34621 .cardinality()
34622 };
34623 let (seed_dom, b_dom) = (dom("http://ex/pS"), dom("http://ex/pB"));
34624 let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
34628 assert_eq!(b_seed_drives.rows, 150_000);
34635 assert_eq!(b_seed_drives.seeks, 0);
34636 let b_list = clustered_page_distinct(50_000, b_dom, page);
34642 assert_eq!(
34643 seed_b.rows,
34644 50_000 + 3 * (100_000 * b_list.min(seed_dom) / seed_dom)
34645 );
34646 assert_eq!(seed_b.seeks, 3 * b_list);
34647 assert_eq!(c_seed_drives.seeks, b_seed_drives.seeks);
34648 assert_eq!(c_seed_drives.rows, 179_620);
34653 assert_eq!(seed_c.seeks, 0);
34660 assert_eq!(seed_c.rows, 140_000);
34661
34662 let seat_ctx =
34663 QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
34664 let canonical = |mut candidates: Vec<JoinableSpineNode>| {
34667 candidates.sort_by(|a, b| {
34668 crate::explain::plan_node_tag(a.as_plan())
34669 .cmp(&crate::explain::plan_node_tag(b.as_plan()))
34670 });
34671 candidates
34672 };
34673 let candidates = canonical(vec![
34674 JoinableSpineNode::Bare(cand_b.clone()),
34675 JoinableSpineNode::Bare(cand_c.clone()),
34676 ]);
34677 let picked = |idx: usize| crate::explain::plan_node_tag(candidates[idx].as_plan());
34678 let b_tag = crate::explain::plan_node_tag(&cand_b);
34679 let c_tag = crate::explain::plan_node_tag(&cand_c);
34680
34681 let (idx, produced_c, _) = pick_attachment(&seed, &candidates, Some(&profile), None, false);
34684 assert_eq!(picked(idx), c_tag);
34685 let keys_b = hash_keys_for(&seed.output_vars(), &cand_b.output_vars());
34686 let produced_b = finalize_inner_join_meta(&seed, &cand_b, &keys_b, Some(&profile)).1;
34687 assert!(
34688 produced_c < produced_b,
34689 "C's join output ({produced_c}) must be below B's ({produced_b})"
34690 );
34691
34692 let (idx, _, cost) =
34698 pick_attachment(&seed, &candidates, Some(&profile), Some(&seat_ctx), true);
34699 assert_eq!(picked(idx), b_tag);
34700 assert_eq!((cost.rows, cost.seeks), (seed_b.rows, seed_b.seeks));
34701 assert_ne!(
34702 (cost.rows, cost.seeks),
34703 (b_seed_drives.rows, b_seed_drives.seeks)
34704 );
34705 }
34706
34707 #[test]
34719 fn seat_mode_two_start_picks_the_pair_start_when_it_differs_from_the_seed_start() {
34720 fn one_scan_rows(node: &PlanNode) -> u64 {
34721 let mut rows = Vec::new();
34722 scan_row_order(node, &mut rows);
34723 assert_eq!(rows.len(), 1, "expected a single scan, got {node:?}");
34724 rows[0]
34725 }
34726 let mut profile = StatsProfile::default();
34727 for (predicate, rows) in [
34728 ("http://ex/pA", 10u64),
34729 ("http://ex/pB", 10_000),
34730 ("http://ex/pC", 5_000),
34731 ] {
34732 profile
34733 .predicate_counts
34734 .insert(StrHash::new(predicate), rows);
34735 profile
34736 .subjects_per_predicate
34737 .insert(StrHash::new(predicate), hll_with_n(rows as u128));
34738 profile
34739 .objects_per_predicate
34740 .insert(StrHash::new(predicate), hll_with_n(rows as u128));
34741 }
34742 let a = PlanNode::Scan(var_scan(Some("a"), "http://ex/pA", Some("va"), 10));
34745 let b = PlanNode::Scan(var_scan(Some("x"), "http://ex/pB", Some("vb"), 10_000));
34746 let c = PlanNode::Scan(var_scan(Some("x"), "http://ex/pC", Some("vc"), 5_000));
34747 let mut tree = test_join(test_join(a, b), c);
34748 let seat_ctx =
34749 QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
34750 reassociate_inner_joins(&mut tree, Some(&profile), Some(&seat_ctx));
34751
34752 let PlanNode::Join { left, right, .. } = &tree else {
34755 panic!("expected the spine root Join, got {tree:?}");
34756 };
34757 assert_eq!(
34758 one_scan_rows(right),
34759 10,
34760 "the 10-row A scan must be attached last, not first: {tree:?}"
34761 );
34762 let PlanNode::Join {
34763 left: pair_a,
34764 right: pair_b,
34765 ..
34766 } = left.as_ref()
34767 else {
34768 panic!("expected the pair start's inner join, got {left:?}");
34769 };
34770 let mut pair = [one_scan_rows(pair_a), one_scan_rows(pair_b)];
34771 pair.sort_unstable();
34772 assert_eq!(
34773 pair,
34774 [5_000, 10_000],
34775 "the inner pair must be B and C: {tree:?}"
34776 );
34777 }
34778
34779 #[test]
34798 fn seat_mode_association_work_is_bounded_by_pairs_and_attachments() {
34799 let a = PlanNode::Scan(var_scan(Some("a"), "http://ex/pA", Some("va"), 10));
34800 let b = PlanNode::Scan(var_scan(Some("x"), "http://ex/pB", Some("vb"), 10_000));
34801 let c = PlanNode::Scan(var_scan(Some("x"), "http://ex/pC", Some("vc"), 5_000));
34802 let d = PlanNode::Scan(var_scan(Some("x"), "http://ex/pD", Some("vd"), 2_000));
34803 let mut tree = test_join(test_join(test_join(a, b), c), d);
34804 let seat_ctx =
34805 QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
34806 super::SEAT_CALLS.with(|counter| counter.set(0));
34807 reassociate_inner_joins(&mut tree, None, Some(&seat_ctx));
34808 let seat_calls = super::SEAT_CALLS.with(|counter| counter.get());
34809 assert_eq!(
34810 seat_calls, 37,
34811 "the pair pre-pass and both association runs must price 37 seats, got {seat_calls}"
34812 );
34813 }
34814
34815 #[test]
34819 fn pair_start_dedup_follows_the_built_orientation() {
34820 let other = "scan(?u <#1> ?t *)";
34821 let seed = "scan(?s <#2> ?t *)";
34822 assert!(
34823 pair_start_matches_seed_start(0, 0, Some(other), other),
34824 "the seed is the pair's left arm and start a attaches the pair's other arm"
34825 );
34826 assert!(
34827 !pair_start_matches_seed_start(1, 0, Some(other), other),
34828 "a pair built with the other arm on the left is a different seating"
34829 );
34830 assert!(
34831 !pair_start_matches_seed_start(0, 0, Some(seed), other),
34832 "start a's first attachment is not the pair's other arm"
34833 );
34834 }
34835
34836 #[test]
34842 fn seat_mode_pair_start_is_not_deduped_when_its_orientation_differs() {
34843 let mut profile = StatsProfile::default();
34844 profile
34845 .predicate_counts
34846 .insert(StrHash::new("http://ex/pS"), 10_000);
34847 profile
34848 .predicate_counts
34849 .insert(StrHash::new("http://ex/pB"), 20_000);
34850 profile
34851 .predicate_counts
34852 .insert(StrHash::new("http://ex/pC"), 200_000);
34853 profile
34854 .subjects_per_predicate
34855 .insert(StrHash::new("http://ex/pS"), hll_with_n(10_000));
34856 profile
34857 .subjects_per_predicate
34858 .insert(StrHash::new("http://ex/pB"), hll_with_n(20_000));
34859 profile
34864 .subjects_per_predicate
34865 .insert(StrHash::new("http://ex/pC"), hll_with_n(10_000));
34866 profile
34867 .objects_per_predicate
34868 .insert(StrHash::new("http://ex/pS"), hll_with_n(10_000));
34869 profile
34870 .objects_per_predicate
34871 .insert(StrHash::new("http://ex/pB"), hll_with_n(100));
34872 profile.total_puts = 230_000;
34873
34874 let seed = PlanNode::Scan(var_scan(Some("s"), "http://ex/pS", Some("t"), 10_000));
34876 let other = PlanNode::Scan(var_scan(Some("u"), "http://ex/pB", Some("t"), 20_000));
34879 let third = PlanNode::Scan(var_scan(Some("t"), "http://ex/pC", Some("v"), 200_000));
34884
34885 let mut tree = test_join(test_join(seed, other.clone()), third.clone());
34886 let seat_ctx =
34887 QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
34888 reassociate_inner_joins(&mut tree, Some(&profile), Some(&seat_ctx));
34889
34890 fn scan_with(node: &PlanNode, iri: &str) -> bool {
34891 matches!(
34892 node,
34893 PlanNode::Scan(scan)
34894 if scan.pattern.predicate.as_ref()
34895 == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
34896 )
34897 }
34898 let PlanNode::Join { left, right, .. } = &tree else {
34899 panic!("expected the spine root, got {tree:?}");
34900 };
34901 let PlanNode::Join {
34902 left: inner_left,
34903 right: inner_right,
34904 ..
34905 } = left.as_ref()
34906 else {
34907 panic!("expected the pair join, got {left:?}");
34908 };
34909 assert!(
34910 scan_with(inner_left, "http://ex/pB"),
34911 "the pair must be built with its cheaper driver (pB) on the left, got {tree:?}"
34912 );
34913 assert!(scan_with(inner_right, "http://ex/pS"));
34914 assert!(scan_with(right, "http://ex/pC"));
34915 }
34916
34917 #[test]
34927 fn seat_pages_price_the_ownership_aware_driver_read() {
34928 let mut profile = StatsProfile::default();
34929 profile
34930 .predicate_counts
34931 .insert(StrHash::new("http://ex/drv"), 50_000);
34932 profile
34933 .subjects_per_predicate
34934 .insert(StrHash::new("http://ex/drv"), hll_with_n(50_000));
34935 profile
34936 .objects_per_predicate
34937 .insert(StrHash::new("http://ex/drv"), hll_with_n(40_000));
34938 profile
34939 .predicate_counts
34940 .insert(StrHash::new("http://ex/prb"), 40_000);
34941 profile
34942 .subjects_per_predicate
34943 .insert(StrHash::new("http://ex/prb"), hll_with_n(40_000));
34944 profile.total_puts = 90_000;
34945 let key = var("k");
34946 let keys = [key.clone()];
34947 let probe = PlanNode::Scan(var_scan(Some("k"), "http://ex/prb", Some("o"), 40_000));
34948 let intrinsic = estimate_unclamped_scan_rows(
34955 Some(&profile),
34956 &var_scan(Some("k"), "http://ex/drv", Some("o"), 1),
34957 );
34958 let mut own_claimed = var_scan(Some("k"), "http://ex/drv", Some("o"), 80);
34967 own_claimed.broadcasted = Some((key.clone(), PatternSlot::Subject));
34968 let unmarked = var_scan(Some("k"), "http://ex/drv", Some("o"), intrinsic);
34969 let mut foreign_claimed = var_scan(Some("k"), "http://ex/drv", Some("o"), 1_500);
34970 foreign_claimed.broadcasted = Some((var("zzz"), PatternSlot::Subject));
34971 let own_driver = PlanNode::Scan(own_claimed);
34972 let plain_driver = PlanNode::Scan(unmarked);
34973 let foreign_driver = PlanNode::Scan(foreign_claimed);
34974
34975 let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
34981 let own = seat_probe_shape(Some(&profile), &own_driver, &probe, &keys, None, None);
34982 assert_eq!(
34983 own.pages,
34984 intrinsic.div_ceil(page),
34985 "own claim: the page count prices the intrinsic whole read"
34986 );
34987 let plain = seat_probe_shape(Some(&profile), &plain_driver, &probe, &keys, None, None);
34988 assert_eq!(
34989 plain.pages, own.pages,
34990 "an own-claim clamp on the driver must not change the page count"
34991 );
34992 let foreign = seat_probe_shape(Some(&profile), &foreign_driver, &probe, &keys, None, None);
34993 assert_eq!(
34994 foreign.pages,
34995 1_500u64.div_ceil(page),
34996 "foreign claim: the ancestor-bounded cell is the whole read"
34997 );
34998
34999 let seat_claimed = seat_cost_total(Some(&profile), &own_driver, &probe, &keys, None, None);
35006 let seat_plain = seat_cost_total(Some(&profile), &plain_driver, &probe, &keys, None, None);
35007 assert_eq!(
35008 seat_claimed, seat_plain,
35009 "an own-claim clamp on the driver must not change the cost estimate"
35010 );
35011 }
35012
35013 #[test]
35024 fn missing_driver_domain_never_covers_and_prices_a_full_page() {
35025 let mut profile = StatsProfile::default();
35026 profile
35027 .predicate_counts
35028 .insert(StrHash::new("http://ex/pA"), 100_000);
35029 profile
35030 .predicate_counts
35031 .insert(StrHash::new("http://ex/pB"), 60_000);
35032 profile
35035 .subjects_per_predicate
35036 .insert(StrHash::new("http://ex/pB"), hll_with_n(6_000));
35037 profile.total_puts = 160_000;
35038 let driver = PlanNode::Scan(var_scan(Some("x"), "http://ex/pA", Some("z"), 100_000));
35039 let probe = PlanNode::Scan(var_scan(Some("x"), "http://ex/pB", Some("w"), 60_000));
35040 let keys = hash_keys_for(&driver.output_vars(), &probe.output_vars());
35041 let seat = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
35042 let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
35052 assert_eq!((seat.rows, seat.seeks), (400_000, 5 * page));
35053 }
35054
35055 #[test]
35063 fn assoc_explosion_guard_blocks_read_cheap_product_huge_cartesian() {
35064 let mut profile = StatsProfile::default();
35065 profile
35066 .predicate_counts
35067 .insert(StrHash::new("http://ex/pS"), 200_000);
35068 profile
35069 .predicate_counts
35070 .insert(StrHash::new("http://ex/pK"), 1_000_000);
35071 profile
35072 .predicate_counts
35073 .insert(StrHash::new("http://ex/pQ"), 500_000);
35074 profile
35075 .subjects_per_predicate
35076 .insert(StrHash::new("http://ex/pS"), hll_with_n(200_000));
35077 profile
35078 .subjects_per_predicate
35079 .insert(StrHash::new("http://ex/pK"), hll_with_n(100_000));
35080 profile
35081 .subjects_per_predicate
35082 .insert(StrHash::new("http://ex/pQ"), hll_with_n(400_000));
35083 profile.total_puts = 1_700_000;
35084 let seed = PlanNode::Scan(var_scan(Some("s"), "http://ex/pS", Some("t"), 200_000));
35085 let keyed = PlanNode::Scan(var_scan(Some("s"), "http://ex/pK", Some("u"), 1_000_000));
35086 let cart = PlanNode::Scan(var_scan(Some("q"), "http://ex/pQ", Some("r"), 500_000));
35087
35088 let price = |cand: &PlanNode| {
35089 let keys = hash_keys_for(&seed.output_vars(), &cand.output_vars());
35090 (
35091 finalize_inner_join_meta(&seed, cand, &keys, Some(&profile)).1,
35092 seat_cost_total(Some(&profile), &seed, cand, &keys, None, None),
35093 )
35094 };
35095 let (produced_k, seat_k) = price(&keyed);
35096 let (produced_cart, seat_cart) = price(&cart);
35097 assert_eq!((seat_cart.rows, seat_cart.seeks), (700_000, 0));
35100 assert_eq!((seat_k.rows, seat_k.seeks), (1_200_000, 0));
35107 assert!(seat_cart.rows < seat_k.rows);
35108 assert_eq!(produced_k, 1_000_000);
35110 assert_eq!(produced_cart, 100_000_000_000);
35111
35112 let p_k = Some(EncodedTerm::from(&NamedNode::new("http://ex/pK").unwrap()));
35113 let first_attached = |tree: &PlanNode| -> Option<EncodedTerm> {
35114 let mut node = tree;
35115 while let PlanNode::Join { left, right, .. } = node {
35116 if !matches!(**left, PlanNode::Join { .. }) {
35117 let PlanNode::Scan(scan) = right.as_ref() else {
35118 panic!("expected a scan probe, got {right:?}")
35119 };
35120 return scan.pattern.predicate.clone();
35121 }
35122 node = left;
35123 }
35124 panic!("expected a join spine, got {tree:?}");
35125 };
35126 let associate = |seat_ctx: Option<QueryContext>| {
35127 let mut tree = join_nodes(
35128 join_nodes(seed.clone(), keyed.clone(), Some(&profile)),
35129 cart.clone(),
35130 Some(&profile),
35131 );
35132 reassociate_inner_joins(&mut tree, Some(&profile), seat_ctx.as_ref());
35133 tree
35134 };
35135
35136 assert_eq!(
35141 first_attached(&associate(Some(
35142 QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true)
35143 ))),
35144 p_k
35145 );
35146 assert_eq!(first_attached(&associate(None)), p_k);
35147 }
35148
35149 #[test]
35157 fn assoc_guard_admits_small_product_cartesian() {
35158 let mut profile = StatsProfile::default();
35159 profile
35160 .predicate_counts
35161 .insert(StrHash::new("http://ex/pS"), 200_000);
35162 profile
35163 .predicate_counts
35164 .insert(StrHash::new("http://ex/pK"), 1_000_000);
35165 profile
35166 .predicate_counts
35167 .insert(StrHash::new("http://ex/pQ2"), 5);
35168 profile
35169 .predicate_counts
35170 .insert(StrHash::new("http://ex/pQ2b"), 100);
35171 profile
35172 .subjects_per_predicate
35173 .insert(StrHash::new("http://ex/pS"), hll_with_n(200_000));
35174 profile
35175 .subjects_per_predicate
35176 .insert(StrHash::new("http://ex/pK"), hll_with_n(100_000));
35177 profile
35178 .subjects_per_predicate
35179 .insert(StrHash::new("http://ex/pQ2"), hll_with_n(5));
35180 profile
35181 .subjects_per_predicate
35182 .insert(StrHash::new("http://ex/pQ2b"), hll_with_n(100));
35183 profile.total_puts = 1_200_105;
35184 let seed = PlanNode::Scan(var_scan(Some("s"), "http://ex/pS", Some("t"), 200_000));
35185 let keyed = PlanNode::Scan(var_scan(Some("s"), "http://ex/pK", Some("u"), 1_000_000));
35186 let cart_small = PlanNode::Scan(var_scan(Some("q2"), "http://ex/pQ2", Some("r2"), 5));
35187 let cart_huge = PlanNode::Scan(var_scan(Some("q3"), "http://ex/pQ2b", Some("r3"), 100));
35188
35189 let price = |cand: &PlanNode| {
35191 let keys = hash_keys_for(&seed.output_vars(), &cand.output_vars());
35192 (
35193 finalize_inner_join_meta(&seed, cand, &keys, Some(&profile)).1,
35194 seat_cost_total(Some(&profile), &seed, cand, &keys, None, None),
35195 )
35196 };
35197 let (produced_k, seat_k) = price(&keyed);
35198 let (produced_cart, seat_cart) = price(&cart_small);
35199 let (produced_huge, seat_huge) = price(&cart_huge);
35200 assert_eq!(produced_k, 1_000_000);
35201 assert_eq!(produced_cart, 1_000_000);
35202 assert_eq!((seat_cart.rows, seat_cart.seeks), (200_005, 0));
35203 assert_eq!((seat_k.rows, seat_k.seeks), (1_200_000, 0));
35204 assert_eq!(produced_huge, 20_000_000);
35207 assert_eq!((seat_huge.rows, seat_huge.seeks), (200_100, 0));
35208
35209 let seat_ctx =
35210 QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
35211 let canonical = |mut candidates: Vec<JoinableSpineNode>| {
35214 candidates.sort_by(|a, b| {
35215 crate::explain::plan_node_tag(a.as_plan())
35216 .cmp(&crate::explain::plan_node_tag(b.as_plan()))
35217 });
35218 candidates
35219 };
35220 let candidates = |a: &PlanNode, b: &PlanNode| {
35221 canonical(vec![
35222 JoinableSpineNode::Bare(a.clone()),
35223 JoinableSpineNode::Bare(b.clone()),
35224 ])
35225 };
35226 let picked = |candidates: &[JoinableSpineNode], idx: usize| {
35227 crate::explain::plan_node_tag(candidates[idx].as_plan())
35228 };
35229 let cart_tag = crate::explain::plan_node_tag(&cart_small);
35230 let keyed_tag = crate::explain::plan_node_tag(&keyed);
35231
35232 let admitted = candidates(&keyed, &cart_small);
35235 let (idx, _, _) = pick_attachment(&seed, &admitted, Some(&profile), Some(&seat_ctx), true);
35236 assert_eq!(picked(&admitted, idx), cart_tag);
35237
35238 let (idx, _, _) = pick_attachment(&seed, &admitted, Some(&profile), None, false);
35241 assert_eq!(picked(&admitted, idx), cart_tag);
35242
35243 let blocked = candidates(&keyed, &cart_huge);
35248 let (idx, produced, _) =
35249 pick_attachment(&seed, &blocked, Some(&profile), Some(&seat_ctx), true);
35250 assert_eq!(picked(&blocked, idx), keyed_tag);
35251 assert_eq!(produced, produced_k);
35252 }
35253
35254 #[test]
35260 fn scan_memo_key_distinguishes_graph_identity() {
35261 use crate::query::caches::ScanMemoKey;
35262 let default_scan = var_scan(Some("s"), "http://ex/p", Some("o"), 100);
35263 let named = |iri: &str| {
35264 let mut scan = var_scan(Some("s"), "http://ex/p", Some("o"), 100);
35265 scan.pattern.graph_name = Some(EncodedTerm::from(&NamedNode::new(iri).unwrap()));
35266 scan
35267 };
35268 let g1 = named("http://ex/g1");
35269 let g2 = named("http://ex/g2");
35270 assert_ne!(
35271 ScanMemoKey::of(&default_scan, 7),
35272 ScanMemoKey::of(&g1, 7),
35273 "default-graph and GRAPH <g1> scans must not share a memo entry"
35274 );
35275 assert_ne!(
35276 ScanMemoKey::of(&g1, 7),
35277 ScanMemoKey::of(&g2, 7),
35278 "two named graphs must not share a memo entry"
35279 );
35280 assert_ne!(
35281 ScanMemoKey::of(&default_scan, 7),
35282 ScanMemoKey::of(&default_scan, 8),
35283 "snapshot is part of the identity"
35284 );
35285 assert_eq!(
35286 ScanMemoKey::of(&g1, 7),
35287 ScanMemoKey::of(&g1, 7),
35288 "same identity (graph included) is stable"
35289 );
35290 }
35291
35292 #[test]
35298 fn scan_memo_key_distinguishes_repeat_structure() {
35299 use crate::query::caches::ScanMemoKey;
35300 let repeat = var_scan(Some("a"), "http://ex/p", Some("a"), 100);
35301 let mut dead = var_scan(Some("a"), "http://ex/p", Some("dead"), 100);
35302 dead.marks.push((
35304 Variable::new("dead").unwrap(),
35305 Liveness::Dead,
35306 BagMark::Sensitive,
35307 ));
35308
35309 assert_eq!(
35312 repeat.materialized_variables(),
35313 dead.materialized_variables()
35314 );
35315 assert_eq!(repeat.repeat_slot_pairs(), vec![(0, 2)]);
35316 assert!(dead.repeat_slot_pairs().is_empty());
35317 assert_ne!(
35318 ScanMemoKey::of(&repeat, 7),
35319 ScanMemoKey::of(&dead, 7),
35320 "a repeat-filtered scan and a same-shaped unfiltered scan must not share a memo entry"
35321 );
35322 }
35323
35324 #[test]
35335 fn scan_output_slots_single_derivation_agreement() {
35336 let so = var_scan(Some("a"), "http://ex/p", Some("a"), 100);
35338 assert_eq!(so.repeat_slot_pairs(), vec![(0, 2)]);
35339 assert_eq!(
35340 so.materialized_variables(),
35341 vec![Variable::new("a").unwrap()]
35342 );
35343
35344 let mut sp_o = var_scan(Some("a"), "http://ex/p", Some("a"), 100);
35348 sp_o.predicate = Some(Variable::new("p").unwrap());
35349 let out = sp_o.output_slots();
35350 assert_eq!(
35351 out.slots,
35352 [
35353 Some(Variable::new("a").unwrap()),
35354 Some(Variable::new("p").unwrap()),
35355 Some(Variable::new("a").unwrap()),
35356 None
35357 ]
35358 );
35359 assert_eq!(out.repeats, vec![(0, 2)]);
35360 assert_eq!(
35361 out.materialized,
35362 vec![
35363 (0, Variable::new("a").unwrap()),
35364 (1, Variable::new("p").unwrap())
35365 ]
35366 );
35367 assert_eq!(
35368 sp_o.materialized_variables(),
35369 out.materialized
35370 .iter()
35371 .map(|(_, v)| v.clone())
35372 .collect::<Vec<_>>()
35373 );
35374 assert_eq!(sp_o.repeat_slot_pairs(), out.repeats);
35375
35376 let mut graph_repeat = var_scan(Some("a"), "http://ex/p", None, 100);
35380 graph_repeat.graph = Some(Variable::new("a").unwrap());
35381 let out = graph_repeat.output_slots();
35382 assert_eq!(out.repeats, vec![(0, 3)]);
35383 assert_eq!(out.materialized, vec![(0, Variable::new("a").unwrap())]);
35384
35385 let mut dead_repeat = var_scan(Some("a"), "http://ex/p", Some("a"), 100);
35389 dead_repeat.marks.push((
35390 Variable::new("a").unwrap(),
35391 Liveness::Dead,
35392 BagMark::Sensitive,
35393 ));
35394 let out = dead_repeat.output_slots();
35395 assert_eq!(out.repeats, vec![(0, 2)]);
35396 assert!(out.materialized.is_empty());
35397 assert!(dead_repeat.materialized_variables().is_empty());
35398
35399 let dict = waratah_exec::TermDict::new_shared();
35404 let term =
35405 |local: &str| EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap());
35406 let quad = |object: EncodedTerm| {
35407 waratah_storage::EncodedQuad::new(
35408 term("a"),
35409 term("p"),
35410 object,
35411 EncodedTerm::DefaultGraph,
35412 )
35413 };
35414 let solutions = crate::solutions::EncodedSolutions::from_scan(
35415 Arc::clone(&dict),
35416 &sp_o,
35417 vec![quad(term("a")), quad(term("b"))],
35418 )
35419 .unwrap();
35420 assert_eq!(solutions.variables(), sp_o.materialized_variables());
35421 assert_eq!(solutions.len(), 1);
35422 assert_eq!(
35423 solutions.get(0, &Variable::new("a").unwrap()).unwrap(),
35424 Some(term("a"))
35425 );
35426 assert_eq!(
35427 solutions.get(0, &Variable::new("p").unwrap()).unwrap(),
35428 Some(term("p"))
35429 );
35430
35431 let dead_solutions = crate::solutions::EncodedSolutions::from_scan(
35434 dict,
35435 &dead_repeat,
35436 vec![quad(term("a")), quad(term("b"))],
35437 )
35438 .unwrap();
35439 assert!(dead_solutions.variables().is_empty());
35440 assert_eq!(dead_solutions.len(), 1);
35441 }
35442
35443 #[test]
35454 fn scan_omitted_slots_producer_table() {
35455 let bound_p = || Some(EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()));
35456 let eff = |subject: Option<EncodedTerm>,
35457 predicate: Option<EncodedTerm>,
35458 object: Option<EncodedTerm>,
35459 graph_name: Option<EncodedTerm>| EncodedTriplePattern {
35460 subject,
35461 predicate,
35462 object,
35463 graph_name,
35464 };
35465 let live = var_scan(Some("a"), "http://ex/p", Some("b"), 100);
35466 let mut dead = var_scan(Some("a"), "http://ex/p", Some("b"), 100);
35467 dead.marks.push((
35468 Variable::new("b").unwrap(),
35469 Liveness::Dead,
35470 BagMark::Sensitive,
35471 ));
35472 let mut dead_repeat = var_scan(Some("a"), "http://ex/p", Some("a"), 100);
35473 dead_repeat.marks.push((
35474 Variable::new("a").unwrap(),
35475 Liveness::Dead,
35476 BagMark::Sensitive,
35477 ));
35478 let mut pinned = live.clone();
35481 pinned.pattern.subject = Some(EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()));
35482 let free_scan = var_scan(None, "http://ex/p", None, 100);
35483
35484 let cases: &[(&str, &ScanOp, EncodedTriplePattern, u8, u8)] = &[
35485 (
35487 "bound predicate only",
35488 &live,
35489 eff(None, bound_p(), None, None),
35490 OMIT_PREDICATE,
35491 OMIT_PREDICATE | OMIT_GRAPH,
35492 ),
35493 (
35494 "broadcast-pinned subject omits like any bound slot",
35495 &pinned,
35496 eff(pinned.pattern.subject.clone(), bound_p(), None, None),
35497 OMIT_SUBJECT | OMIT_PREDICATE,
35498 OMIT_SUBJECT | OMIT_PREDICATE | OMIT_GRAPH,
35499 ),
35500 (
35501 "dead object omits only under allow_dead",
35502 &dead,
35503 eff(None, bound_p(), None, None),
35504 OMIT_PREDICATE,
35505 OMIT_PREDICATE | OMIT_OBJECT | OMIT_GRAPH,
35506 ),
35507 (
35508 "dead repeated name never omits (row filter compares both)",
35509 &dead_repeat,
35510 eff(None, bound_p(), None, None),
35511 OMIT_PREDICATE,
35512 OMIT_PREDICATE | OMIT_GRAPH,
35513 ),
35514 (
35515 "bound graph omits at either flag",
35516 &live,
35517 eff(None, bound_p(), None, Some(EncodedTerm::DefaultGraph)),
35518 OMIT_PREDICATE | OMIT_GRAPH,
35519 OMIT_PREDICATE | OMIT_GRAPH,
35520 ),
35521 (
35522 "free pattern on named live slots: only nameless slots omit",
35523 &live,
35524 eff(None, None, None, None),
35525 0,
35526 OMIT_PREDICATE | OMIT_GRAPH,
35527 ),
35528 (
35529 "fully free scan: every slot is dead by definition",
35530 &free_scan,
35531 eff(None, None, None, None),
35532 0,
35533 OMIT_SUBJECT | OMIT_PREDICATE | OMIT_OBJECT | OMIT_GRAPH,
35534 ),
35535 ];
35536 for (label, scan, effective, expect_strict, expect_allow) in cases {
35537 assert_eq!(
35538 scan.omitted_slots(effective, false),
35539 *expect_strict,
35540 "{label}: allow_dead=false"
35541 );
35542 assert_eq!(
35543 scan.omitted_slots(effective, true),
35544 *expect_allow,
35545 "{label}: allow_dead=true"
35546 );
35547 }
35548 }
35549
35550 #[test]
35564 fn leaf_walk_prices_kept_key_subtree_per_page() {
35565 let mut profile = StatsProfile::default();
35566 for (pred, rows, subjects) in [
35573 ("http://ex/p0", 100_000_u64, 100_000_u128),
35574 ("http://ex/p1", 8_000_000, 8_000_000),
35575 ("http://ex/p2", 300, 1_000),
35576 ] {
35577 profile.predicate_counts.insert(StrHash::new(pred), rows);
35578 profile
35579 .subjects_per_predicate
35580 .insert(StrHash::new(pred), hll_with_n(subjects));
35581 profile
35582 .objects_per_predicate
35583 .insert(StrHash::new(pred), hll_with_n(subjects));
35584 }
35585 profile.total_puts = 8_100_300;
35586 let subtree = PlanNode::Join {
35590 left: Box::new(PlanNode::Scan(var_scan(
35591 Some("s"),
35592 "http://ex/p1",
35593 None,
35594 8_000_000,
35595 ))),
35596 right: Box::new(PlanNode::Scan(var_scan(
35597 Some("g"),
35598 "http://ex/p2",
35599 Some("z"),
35600 300,
35601 ))),
35602 hash_keys: vec![var("g")],
35603 probe_key_domains: Vec::new(),
35604 probe_key_overlap_milli: Vec::new(),
35605 rhs_hostable_keys: Vec::new().into(),
35606 meta: JoinMeta {
35607 semi_gate: None,
35608 star_arms: None,
35609 strategy: JoinStrategy::Broadcast,
35610 produced_row_count_estimate: 24_000,
35611 own_push_removed_row_count_estimate: 24_000,
35612 },
35613 };
35614 let a1 = PlanNode::Scan(var_scan(Some("g"), "http://ex/p2", Some("z"), 300));
35615 let d1 = PlanNode::Scan(var_scan(Some("s"), "http://ex/p1", None, 8_000_000));
35616 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/p0", Some("o"), 100_000));
35617 let keys = hash_keys_for(&driver.output_vars(), &subtree.output_vars());
35618
35619 super::SEAT_CALLS.with(|c| c.set(0));
35620 super::WALK_VISITS.with(|c| c.set(0));
35621 let seat = seat_cost_total(Some(&profile), &driver, &subtree, &keys, None, None);
35622 let seat_calls = super::SEAT_CALLS.with(|c| c.get());
35623 let walk_visits = super::WALK_VISITS.with(|c| c.get());
35624
35625 let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
35633 let dom_s0 = profile
35634 .subjects_per_predicate
35635 .get(&StrHash::new("http://ex/p0"))
35636 .expect("p0 subjects HLL")
35637 .cardinality();
35638 let pushed_val_count = pushed_val_count(Some(&profile), &driver, &var("s")).min(page);
35644 assert_eq!(pushed_val_count, dom_s0.min(page));
35645 let inner_driver =
35646 containing_push_driver_bound(Some(&profile), &d1, &var("s"), pushed_val_count)
35647 .expect("D1's ?s domain is known");
35648 let a1_whole = estimate_unclamped_scan_rows(
35649 Some(&profile),
35650 match &a1 {
35651 PlanNode::Scan(scan) => scan,
35652 _ => unreachable!("a1 is a scan"),
35653 },
35654 );
35655 let a1_domain = profile
35656 .subjects_per_predicate
35657 .get(&StrHash::new("http://ex/p2"))
35658 .expect("p2 subjects HLL")
35659 .cardinality();
35660 let a1_scan = match &a1 {
35661 PlanNode::Scan(scan) => scan,
35662 _ => unreachable!("a1 is a scan"),
35663 };
35664 let inner_driver_domain = join_key_domain_for_node(Some(&profile), &d1, &var("g"));
35670 let (cover_len, inner_list, domains_known) = match inner_driver_domain {
35671 Some(d) => {
35672 let clustered = clustered_page_distinct(inner_driver, d, page);
35673 (clustered, clustered, true)
35674 }
35675 None => (1, page.min(inner_driver.max(1)), false),
35676 };
35677 let covered = crate::query::pushdown::push_list_covers_domain(
35678 usize::try_from(cover_len).unwrap_or(usize::MAX),
35679 a1_domain,
35680 1_000,
35681 );
35682 let drop = crate::query::pushdown::source_coverage_drop(&d1, &a1, page);
35683 let inner = seat_cost_arithmetic(
35687 inner_driver,
35688 a1_whole,
35689 crate::query::scan_memo_eligible(a1_scan)
35690 && a1_whole <= crate::query::caches::SCAN_MEMO_MAX_ENTRY_ROWS as u64,
35691 inner_driver.div_ceil(page),
35692 &[(covered, inner_list, a1_domain, 1_000)],
35693 drop,
35694 fetch_once_stampable(a1_scan),
35695 whole_read_rows_known(Some(&profile), a1_scan),
35696 domains_known,
35697 false,
35698 None,
35699 );
35700 let inner_rows = inner.rows;
35701 let inner_seeks = inner.seeks;
35702 let j0_pages = 100_000u64.div_ceil(page);
35703 assert_eq!(
35704 seat,
35705 SeatCost {
35706 rows: 100_000 + j0_pages * inner_rows,
35707 seeks: j0_pages * inner_seeks,
35708 },
35709 "the subtree must price per-page with the driver keyed to ~{pushed_val_count}, not 8M"
35710 );
35711 assert_eq!(seat_calls, 2, "top seat + one inner seat");
35714 assert_eq!(walk_visits, 1, "one Join arm walked");
35715 }
35716
35717 #[test]
35724 fn leaf_walk_recursion_is_linear_in_subtree_joins() {
35725 let mut profile = StatsProfile::default();
35726 profile
35727 .predicate_counts
35728 .insert(StrHash::new("http://ex/chain"), 50_000);
35729 profile
35730 .subjects_per_predicate
35731 .insert(StrHash::new("http://ex/chain"), hll_with_n(50_000));
35732 profile
35733 .objects_per_predicate
35734 .insert(StrHash::new("http://ex/chain"), hll_with_n(50_000));
35735 profile.total_puts = 50_000;
35736 const SEGMENTS: usize = 24;
35737 let mut node = PlanNode::Scan(var_scan(
35742 Some(&format!("s{}", SEGMENTS - 1)),
35743 "http://ex/chain",
35744 Some(&format!("s{SEGMENTS}")),
35745 50_000,
35746 ));
35747 for i in (1..SEGMENTS).rev() {
35748 node = PlanNode::Join {
35749 left: Box::new(PlanNode::Scan(var_scan(
35750 Some(&format!("s{}", i - 1)),
35751 "http://ex/chain",
35752 Some(&format!("s{i}")),
35753 50_000,
35754 ))),
35755 right: Box::new(node),
35756 hash_keys: vec![var(&format!("s{i}"))],
35757 probe_key_domains: Vec::new(),
35758 probe_key_overlap_milli: Vec::new(),
35759 rhs_hostable_keys: Vec::new().into(),
35760 meta: JoinMeta {
35761 semi_gate: None,
35762 star_arms: None,
35763 strategy: JoinStrategy::Broadcast,
35764 produced_row_count_estimate: 50_000,
35765 own_push_removed_row_count_estimate: 50_000,
35766 },
35767 };
35768 }
35769 let driver = PlanNode::Scan(var_scan(
35770 Some("s0"),
35771 "http://ex/chain",
35772 Some("head"),
35773 50_000,
35774 ));
35775 let keys = hash_keys_for(&driver.output_vars(), &node.output_vars());
35776 super::SEAT_CALLS.with(|c| c.set(0));
35777 super::WALK_VISITS.with(|c| c.set(0));
35778 let seat = seat_cost_total(Some(&profile), &driver, &node, &keys, None, None);
35779 let seat_calls = super::SEAT_CALLS.with(|c| c.get());
35780 let walk_visits = super::WALK_VISITS.with(|c| c.get());
35781 assert!(seat.rows > 0);
35782 assert!(
35783 (SEGMENTS as u64..=2 * SEGMENTS as u64).contains(&seat_calls),
35784 "one seat per join ({SEGMENTS}), ±headroom — got {seat_calls}"
35785 );
35786 assert!(
35787 ((SEGMENTS - 1) as u64..=2 * SEGMENTS as u64).contains(&walk_visits),
35788 "one walk visit per Join arm, ±headroom — got {walk_visits}"
35789 );
35790
35791 let plain = PlanNode::Scan(var_scan(Some("s0"), "http://ex/chain", Some("x"), 50_000));
35793 let plain_keys = hash_keys_for(&driver.output_vars(), &plain.output_vars());
35794 super::SEAT_CALLS.with(|c| c.set(0));
35795 super::WALK_VISITS.with(|c| c.set(0));
35796 let _ = seat_cost_total(Some(&profile), &driver, &plain, &plain_keys, None, None);
35797 assert_eq!(super::SEAT_CALLS.with(|c| c.get()), 1, "no recursion");
35798 assert_eq!(super::WALK_VISITS.with(|c| c.get()), 0, "no walk");
35799 }
35800
35801 #[test]
35806 fn leaf_walk_budget_degrades_wide_subtrees_to_the_coarse_price() {
35807 let mut profile = StatsProfile::default();
35808 profile
35809 .predicate_counts
35810 .insert(StrHash::new("http://ex/u"), 100_000);
35811 profile
35812 .subjects_per_predicate
35813 .insert(StrHash::new("http://ex/u"), hll_with_n(100_000));
35814 profile
35815 .objects_per_predicate
35816 .insert(StrHash::new("http://ex/u"), hll_with_n(50_000));
35817 profile.total_puts = 100_000;
35818 let mut node = PlanNode::Scan(var_scan(None, "http://ex/u", Some("g"), 1_000));
35821 for _ in 0..80 {
35822 node = PlanNode::Union {
35823 left: Box::new(PlanNode::Scan(var_scan(
35824 None,
35825 "http://ex/u",
35826 Some("g"),
35827 1_000,
35828 ))),
35829 right: Box::new(node),
35830 };
35831 }
35832 let driver = PlanNode::Scan(var_scan(None, "http://ex/u", Some("g"), 100_000));
35833 let keys = hash_keys_for(&driver.output_vars(), &node.output_vars());
35834 super::SEAT_CALLS.with(|c| c.set(0));
35835 super::WALK_VISITS.with(|c| c.set(0));
35836 let seat = seat_cost_total(Some(&profile), &driver, &node, &keys, None, None);
35837 assert_eq!(
35838 super::WALK_VISITS.with(|c| c.get()),
35839 SUBTREE_WALK_NODE_BUDGET,
35840 "the budget const is the exact visit count — raising it is a deliberate trade"
35841 );
35842 assert_eq!(
35843 super::SEAT_CALLS.with(|c| c.get()),
35844 1,
35845 "no joins, no nested seats"
35846 );
35847 assert!(seat.rows > 0, "a degraded walk still prices the arm");
35848 }
35849
35850 #[test]
35855 fn leaf_walk_once_roads_do_not_walk() {
35856 let mut profile = StatsProfile::default();
35857 for (pred, rows, subjects) in [
35864 ("http://ex/p0", 100_000_u64, 300_u128),
35865 ("http://ex/p1", 5_000, 8),
35866 ("http://ex/p2", 1_000, 8),
35867 ] {
35868 profile.predicate_counts.insert(StrHash::new(pred), rows);
35869 profile
35870 .subjects_per_predicate
35871 .insert(StrHash::new(pred), hll_with_n(subjects));
35872 profile
35873 .objects_per_predicate
35874 .insert(StrHash::new(pred), hll_with_n(subjects));
35875 }
35876 profile.total_puts = 106_000;
35877 let subtree = PlanNode::Join {
35878 left: Box::new(PlanNode::Scan(var_scan(
35879 Some("s"),
35880 "http://ex/p1",
35881 None,
35882 5_000,
35883 ))),
35884 right: Box::new(PlanNode::Scan(var_scan(
35885 Some("s"),
35886 "http://ex/p2",
35887 Some("z"),
35888 1_000,
35889 ))),
35890 hash_keys: vec![var("s")],
35891 probe_key_domains: Vec::new(),
35892 probe_key_overlap_milli: Vec::new(),
35893 rhs_hostable_keys: Vec::new().into(),
35894 meta: JoinMeta {
35895 semi_gate: None,
35896 star_arms: None,
35897 strategy: JoinStrategy::Broadcast,
35898 produced_row_count_estimate: 4_000,
35899 own_push_removed_row_count_estimate: 4_000,
35900 },
35901 };
35902 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/p0", Some("o"), 100_000));
35903 let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
35904 assert!(crate::query::pushdown::source_coverage_drop(
35908 &driver, &subtree, page
35909 ));
35910 let keys = hash_keys_for(&driver.output_vars(), &subtree.output_vars());
35911 super::SEAT_CALLS.with(|c| c.set(0));
35912 super::WALK_VISITS.with(|c| c.set(0));
35913 let seat = seat_cost_total(Some(&profile), &driver, &subtree, &keys, None, None);
35914 assert_eq!(super::SEAT_CALLS.with(|c| c.get()), 1);
35916 assert_eq!(super::WALK_VISITS.with(|c| c.get()), 0);
35917 assert_eq!(
35918 seat,
35919 SeatCost {
35920 rows: 100_000 + 4_000,
35921 seeks: 0
35922 }
35923 );
35924 super::SEAT_CALLS.with(|c| c.set(0));
35926 super::WALK_VISITS.with(|c| c.set(0));
35927 let seat = seat_cost_total(Some(&profile), &driver, &subtree, &[], None, None);
35928 assert_eq!(
35929 seat,
35930 SeatCost {
35931 rows: 100_000 + 4_000,
35932 seeks: 0
35933 }
35934 );
35935 assert_eq!(super::SEAT_CALLS.with(|c| c.get()), 1);
35936 assert_eq!(super::WALK_VISITS.with(|c| c.get()), 0);
35937 }
35938
35939 #[test]
35950 fn transects_seat_repro_diagnostic() {
35951 let mut profile = StatsProfile::default();
35952 for (pred, rows, subjects, objects) in [
35953 ("http://ex/type", 500_u64, 500_u128, 500_u128),
35954 ("http://ex/hasGeom", 816_044, 793_204, 816_044),
35955 ("http://ex/asWKT", 817_201, 817_201, 795_534),
35956 ] {
35957 profile.predicate_counts.insert(StrHash::new(pred), rows);
35958 profile
35959 .subjects_per_predicate
35960 .insert(StrHash::new(pred), hll_with_n(subjects));
35961 profile
35962 .objects_per_predicate
35963 .insert(StrHash::new(pred), hll_with_n(objects));
35964 }
35965 profile.total_puts = 1_633_745;
35966 let geo_scan = PlanNode::CustomNode(CustomOp {
35967 plugin_id: "cost-test",
35968 op_id: "op",
35969 payload: crate::plugin::PluginPayloadBox::new(CostTestPayload),
35970 children: Vec::new(),
35971 variables: vec![var("wkt")],
35972 produced_row_count_estimate: 36_862,
35973 cost: Some(CustomOpCost {
35974 drain_rows: 36_862,
35975 per_key_unit: 8,
35976 inline_point_unit: 1,
35977 direct_probe: true,
35978 probe_keyed_columns: 0b1,
35979 probe_filter_unit: 8,
35980 probe_memo_entry_rows: 0,
35981 }),
35982 pinned: Vec::new(),
35983 });
35984 let cluster = PlanNode::Join {
35985 left: Box::new(geo_scan),
35986 right: Box::new(PlanNode::Scan(var_scan(
35987 Some("g"),
35988 "http://ex/asWKT",
35989 Some("wkt"),
35990 817_201,
35991 ))),
35992 hash_keys: vec![var("wkt")],
35993 probe_key_domains: Vec::new(),
35994 probe_key_overlap_milli: Vec::new(),
35995 rhs_hostable_keys: Vec::new().into(),
35996 meta: JoinMeta {
35997 semi_gate: None,
35998 star_arms: None,
35999 strategy: JoinStrategy::Broadcast,
36000 produced_row_count_estimate: 37_865,
36001 own_push_removed_row_count_estimate: 37_865,
36002 },
36003 };
36004 let transect = PlanNode::Join {
36005 left: Box::new(PlanNode::Scan(var_scan(
36006 Some("tr"),
36007 "http://ex/type",
36008 None,
36009 500,
36010 ))),
36011 right: Box::new(PlanNode::Scan(var_scan(
36012 Some("tr"),
36013 "http://ex/hasGeom",
36014 Some("g"),
36015 816_044,
36016 ))),
36017 hash_keys: vec![var("tr")],
36018 probe_key_domains: Vec::new(),
36019 probe_key_overlap_milli: Vec::new(),
36020 rhs_hostable_keys: Vec::new().into(),
36021 meta: JoinMeta {
36022 semi_gate: None,
36023 star_arms: None,
36024 strategy: JoinStrategy::Broadcast,
36025 produced_row_count_estimate: 515,
36026 own_push_removed_row_count_estimate: 515,
36027 },
36028 };
36029 let keys = hash_keys_for(&transect.output_vars(), &cluster.output_vars());
36030 super::SEAT_CALLS.with(|c| c.set(0));
36031 super::WALK_VISITS.with(|c| c.set(0));
36032 let left = seat_cost_total(Some(&profile), &cluster, &transect, &keys, None, None);
36033 let right = seat_cost_total(Some(&profile), &transect, &cluster, &keys, None, None);
36034 eprintln!(
36035 "DIAG transects-seat: keys={keys:?} left(cluster drives)={left:?} right(transects drive)={right:?} calls={} visits={}",
36036 super::SEAT_CALLS.with(|c| c.get()),
36037 super::WALK_VISITS.with(|c| c.get())
36038 );
36039 }
36040
36041 #[test]
36051 fn push_bound_stamp_and_hypothesis_share_one_derivation() {
36052 let mut profile = StatsProfile::default();
36053 for (pred, rows) in [
36054 ("http://ex/p0", 100_000_u64),
36055 ("http://ex/p1", 817_201),
36056 ("http://ex/p2", 500),
36057 ] {
36058 profile.predicate_counts.insert(StrHash::new(pred), rows);
36059 profile
36060 .subjects_per_predicate
36061 .insert(StrHash::new(pred), hll_with_n(rows as u128));
36062 profile
36063 .objects_per_predicate
36064 .insert(StrHash::new(pred), hll_with_n(rows as u128));
36065 }
36066 profile.total_puts = 917_701;
36067 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/p0", Some("o"), 100_000));
36068 let mut probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/p1", None, 817_201));
36069
36070 let count = pushed_val_count(Some(&profile), &driver, &var("s"));
36075 let dom_s0 = profile
36076 .subjects_per_predicate
36077 .get(&StrHash::new("http://ex/p0"))
36078 .expect("p0 subjects HLL")
36079 .cardinality();
36080 assert_eq!(
36081 count,
36082 dom_s0.clamp(1, 100_000),
36083 "the list size is min(domain, the pusher's OWN rows)"
36084 );
36085 let hypothesis = containing_push_driver_bound(Some(&profile), &probe, &var("s"), count);
36086
36087 let scan = match &mut probe {
36089 PlanNode::Scan(scan) => scan,
36090 _ => unreachable!("probe is a scan"),
36091 };
36092 let slots = scan.slot_of(&var("s"));
36093 assert!(!slots.is_empty(), "the subject slot hosts ?s");
36094 scan.broadcasted = Some((var("s"), slots[0]));
36095 let keys = [var("s")];
36096 clamp_broadcast_probe_estimates(&driver, &mut probe, &keys, Some(&profile));
36097 let stamp = match &probe {
36098 PlanNode::Scan(scan) => scan.ancestor_push_return_bound,
36099 _ => unreachable!("probe is a scan"),
36100 }
36101 .expect("the clamp stamps the bound");
36102
36103 assert_eq!(Some(stamp), hypothesis);
36107
36108 let small_driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/p2", Some("o"), 500));
36113 profile
36117 .subjects_per_predicate
36118 .insert(StrHash::new("http://ex/p2"), hll_with_n(816_044));
36119 let small_count = pushed_val_count(Some(&profile), &small_driver, &var("s"));
36120 let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
36121 assert_eq!(small_count, 500, "the pusher's rows bound the list");
36122 assert_eq!(
36123 small_count.min(page),
36124 500,
36125 "and the per-page context carries the bound"
36126 );
36127 }
36128
36129 #[test]
36135 fn leaf_walk_plan_level_seat_call_bound() {
36136 let mut profile = StatsProfile::default();
36137 for i in 0..6 {
36138 let pred = format!("http://ex/p{i}");
36139 profile.predicate_counts.insert(StrHash::new(&pred), 50_000);
36140 profile
36141 .subjects_per_predicate
36142 .insert(StrHash::new(&pred), hll_with_n(50_000));
36143 profile
36144 .objects_per_predicate
36145 .insert(StrHash::new(&pred), hll_with_n(50_000));
36146 }
36147 profile.total_puts = 300_000;
36148 let sparql = "SELECT ?d WHERE {
36149 ?a <http://ex/p0> ?b . ?b <http://ex/p1> ?c . ?c <http://ex/p2> ?d .
36150 ?a <http://ex/p3> ?e . ?e <http://ex/p4> ?f . ?f <http://ex/p5> ?d }";
36151 super::SEAT_CALLS.with(|c| c.set(0));
36152 let plan =
36153 LogicalPlan::parse_with_profile(sparql, Some(&profile)).expect("reference shape plans");
36154 let seat_calls = super::SEAT_CALLS.with(|c| c.get());
36155 assert!(
36162 (1..=260).contains(&seat_calls),
36163 "planner comparator work for the reference shape: {seat_calls} seat calls"
36164 );
36165 let _ = plan;
36166 }
36167
36168 #[test]
36176 fn planner_time_line_lists_every_bucket_and_resets_parse() {
36177 let lines = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
36178 let ctx = QueryContext::from_snapshot(SnapshotId::latest()).with_log(
36179 crate::LogSink::capture(crate::context::LogLevel::Debug, lines.clone()),
36180 );
36181 LogicalPlan::parse_with_context("SELECT ?s WHERE { ?s ?p ?o } LIMIT 3", &ctx)
36182 .expect("plans");
36183 let captured = lines.lock().expect("capture mutex").clone();
36184 let line = captured
36185 .iter()
36186 .find(|line| line.contains("planner-time:"))
36187 .expect("the planner-time line is captured");
36188 for bucket in ["parse=", "lower=", "rewrite=", "seat=", "stamps=", "total="] {
36189 assert!(line.contains(bucket), "missing `{bucket}` in: {line}");
36190 }
36191 let number_after = |key: &str| -> u64 {
36192 let idx = line.find(key).expect("bucket present") + key.len();
36193 let digits: String = line[idx..]
36194 .chars()
36195 .take_while(|c| c.is_ascii_digit())
36196 .collect();
36197 digits.parse().expect("bucket carries a µs number")
36198 };
36199 let interior: u64 = ["lower=", "rewrite=", "seat=", "stamps="]
36200 .iter()
36201 .map(|key| number_after(key))
36202 .sum();
36203 assert!(
36204 number_after("total=") >= interior,
36205 "total must cover the interior buckets: {line}"
36206 );
36207 assert_eq!(
36208 0,
36209 super::PLANNER_PARSE_US.with(|cell| cell.get()),
36210 "the parse cell resets on emission"
36211 );
36212 }
36213
36214 #[test]
36222 #[ignore = "release timing harness — run explicitly, prints p50/p99"]
36223 fn planner_latency_reference_shape() {
36224 let mut profile = StatsProfile::default();
36225 for i in 0..6 {
36226 let pred = format!("http://ex/p{i}");
36227 profile.predicate_counts.insert(StrHash::new(&pred), 50_000);
36228 profile
36229 .subjects_per_predicate
36230 .insert(StrHash::new(&pred), hll_with_n(50_000));
36231 profile
36232 .objects_per_predicate
36233 .insert(StrHash::new(&pred), hll_with_n(50_000));
36234 }
36235 profile.total_puts = 300_000;
36236 let sparql = "SELECT ?d WHERE {
36237 ?a <http://ex/p0> ?b . ?b <http://ex/p1> ?c . ?c <http://ex/p2> ?d .
36238 ?a <http://ex/p3> ?e . ?e <http://ex/p4> ?f . ?f <http://ex/p5> ?d }";
36239 let _ = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
36243 const ITERATIONS: usize = 500;
36244 let mut micros = Vec::with_capacity(ITERATIONS);
36245 let mut parse_only = Vec::with_capacity(ITERATIONS);
36246 for _ in 0..ITERATIONS {
36247 super::SEAT_CALLS.with(|c| c.set(0));
36248 let start = std::time::Instant::now();
36249 let _ = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
36250 micros.push(start.elapsed().as_micros());
36251 let start = std::time::Instant::now();
36252 let parsed = spargebra::SparqlParser::new().parse_query(sparql).unwrap();
36253 let _ = parsed;
36254 parse_only.push(start.elapsed().as_micros());
36255 }
36256 micros.sort_unstable();
36257 parse_only.sort_unstable();
36258 let p50 = micros[micros.len() / 2];
36259 let p99 = micros[micros.len() * 99 / 100];
36260 let parse_p50 = parse_only[parse_only.len() / 2];
36261 println!(
36262 "parse+plan over {ITERATIONS}: p50 {p50}µs, p99 {p99}µs (parse alone p50 {parse_p50}µs — the planner's share is the difference)"
36263 );
36264 }
36265}
36266
36267#[cfg(test)]
36273mod shadow_seating_tests {
36274 use super::{
36275 FetchOnceVerdict, clustered_page_distinct, fetch_once_verdict, mixed_page_distinct,
36276 probe_broadcast_price,
36277 };
36278 use super::{SeatCost, seat_beats, seat_cost_arithmetic};
36279 use crate::query::pushdown::push_list_covers_domain;
36280
36281 #[test]
36282 fn clustered_list_is_the_runtime_page_not_the_whole_domain() {
36283 let page = clustered_page_distinct(652_374, 3_000, 24_576);
36288 assert!(
36289 (111..=115).contains(&page),
36290 "expected ~113 subjects per page, got {page}"
36291 );
36292 assert!(!push_list_covers_domain(page as usize, 1_500, 1_000));
36297 assert!(push_list_covers_domain(3_000, 1_500, 1_000));
36298 assert_eq!(clustered_page_distinct(2_007, 2_007, 24_576), 2_007);
36299 }
36300
36301 #[test]
36302 fn mixed_page_sample_never_exceeds_what_a_page_holds() {
36303 let mixed = mixed_page_distinct(100_000, 24_576, 200_000);
36306 assert!(
36307 (21_780..=21_800).contains(&mixed),
36308 "expected ~21,789, got {mixed}"
36309 );
36310 let saturated = mixed_page_distinct(3_000, 24_576, 200_000);
36312 assert!((2_980..=3_000).contains(&saturated));
36313 assert!(mixed_page_distinct(100_000, 24_576, 200_000) <= 24_576);
36314 assert!(mixed_page_distinct(5, 24_576, 200_000) <= 5);
36315 }
36316
36317 #[test]
36318 fn short_driver_pages_hold_at_most_their_own_rows() {
36319 assert_eq!(clustered_page_distinct(1, 2_200_000, 24_576), 1);
36325 assert_eq!(clustered_page_distinct(2, 2_200_000, 24_576), 2);
36326 assert_eq!(mixed_page_distinct(2_200_000, 24_576, 2), 2);
36329 assert_eq!(clustered_page_distinct(652_374, 3_000, 24_576), 113);
36331 }
36332
36333 #[test]
36334 fn q02_walk_prefers_inverting_the_spine() {
36335 let member_of_drives = seat_cost_arithmetic(
36342 1_048_532,
36343 652_374,
36344 false,
36345 53,
36346 &[(false, 190, 326_526, 1_000), (false, 37, 2_007, 1_000)],
36347 true,
36348 false,
36349 true,
36350 true,
36351 false,
36352 None,
36353 );
36354 assert_eq!(
36355 member_of_drives,
36356 SeatCost {
36357 rows: 1_048_532 + 53 * 379,
36358 seeks: 53 * 190
36359 }
36360 );
36361 let subtree_drives = seat_cost_arithmetic(
36366 652_374,
36367 1_048_532,
36368 false,
36369 33,
36370 &[(false, 199, 1_048_532, 1_000), (false, 60, 1_972, 1_000)],
36371 true,
36372 false,
36373 true,
36374 true,
36375 false,
36376 None,
36377 );
36378 assert_eq!(
36379 subtree_drives,
36380 SeatCost {
36381 rows: 652_374 + 33 * 199,
36382 seeks: 33 * 199
36383 }
36384 );
36385 assert!(seat_beats(subtree_drives, member_of_drives));
36387 let old_left = super::driver_cost(1_048_532, Some(1_972));
36391 let old_right = super::driver_cost(652_374, Some(2_007));
36392 assert!(
36393 old_left < old_right,
36394 "the legacy comparator must keep memberOf driving here"
36395 );
36396 }
36397
36398 #[test]
36399 fn all_keys_covered_builds_a_subtree_probe_once() {
36400 let built_once = seat_cost_arithmetic(
36403 100_000,
36404 50_000,
36405 false,
36406 5,
36407 &[(true, 400, 400, 1_000)],
36408 true,
36409 true,
36410 true,
36411 true,
36412 false,
36413 None,
36414 );
36415 assert_eq!(
36416 built_once,
36417 SeatCost {
36418 rows: 150_000,
36419 seeks: 0
36420 }
36421 );
36422 let memoized = seat_cost_arithmetic(
36425 100_000,
36426 20_000,
36427 true,
36428 5,
36429 &[(true, 400, 400, 1_000)],
36430 true,
36431 true,
36432 true,
36433 true,
36434 false,
36435 None,
36436 );
36437 assert_eq!(
36438 memoized,
36439 SeatCost {
36440 rows: 140_000,
36441 seeks: 0
36442 }
36443 );
36444 }
36445
36446 #[test]
36447 fn covered_but_guard_denied_broadcasts_the_list() {
36448 let broadcast = seat_cost_arithmetic(
36453 100_000,
36454 50_000,
36455 false,
36456 5,
36457 &[(true, 2_000, 2_000, 1_000)],
36458 false,
36459 true,
36460 true,
36461 true,
36462 false,
36463 None,
36464 );
36465 assert_eq!(
36472 broadcast,
36473 SeatCost {
36474 rows: 150_000,
36475 seeks: 0
36476 }
36477 );
36478 let unstamped = seat_cost_arithmetic(
36482 100_000,
36483 50_000,
36484 false,
36485 5,
36486 &[(true, 2_000, 2_000, 1_000)],
36487 false,
36488 false,
36489 true,
36490 true,
36491 false,
36492 None,
36493 );
36494 assert_eq!(
36495 unstamped,
36496 SeatCost {
36497 rows: 100_000 + 5 * 50_000,
36498 seeks: 5 * 2_000
36499 }
36500 );
36501 }
36502
36503 #[test]
36504 fn one_list_broadcasts_priced_from_the_first_surviving_key() {
36505 let both = seat_cost_arithmetic(
36512 100_000,
36513 50_000,
36514 false,
36515 5,
36516 &[(false, 10, 100_000, 1_000), (false, 50, 1_000, 1_000)],
36517 true,
36518 true,
36519 true,
36520 true,
36521 false,
36522 None,
36523 );
36524 assert_eq!(
36525 both,
36526 SeatCost {
36527 rows: 100_000 + 5 * 5,
36528 seeks: 5 * 10
36529 }
36530 );
36531 }
36532
36533 #[test]
36534 fn covered_keys_are_skipped_in_the_pick() {
36535 let (seeks, matched) = probe_broadcast_price(
36539 50_000,
36540 &[(true, 10_000, 10_000, 1_000), (false, 50, 1_000, 1_000)],
36541 true,
36542 );
36543 assert_eq!((seeks, matched), (50, 2_500));
36544 }
36545
36546 #[test]
36547 fn arm_estimate_without_a_profile_never_builds() {
36548 assert_eq!(
36556 fetch_once_verdict(
36557 6, 10_000, 0, 3, false, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36558 ),
36559 FetchOnceVerdict::PerPage
36560 );
36561 assert_eq!(
36562 fetch_once_verdict(
36563 6, 10_000, 0, 3, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36564 ),
36565 FetchOnceVerdict::FetchOnce
36566 );
36567 }
36568
36569 #[test]
36570 fn covered_whole_read_prices_the_arm_not_the_clamp() {
36571 let covered = seat_cost_arithmetic(
36580 100_000,
36581 7_659,
36582 false,
36583 5,
36584 &[(true, 400, 400, 1_000)],
36585 true,
36586 true,
36587 true,
36588 true,
36589 false,
36590 None,
36591 );
36592 assert_eq!(
36593 covered,
36594 SeatCost {
36595 rows: 100_000 + 7_659,
36596 seeks: 0
36597 }
36598 );
36599 let memoized = seat_cost_arithmetic(
36600 100_000,
36601 7_659,
36602 true,
36603 5,
36604 &[(true, 400, 400, 1_000)],
36605 true,
36606 true,
36607 true,
36608 true,
36609 false,
36610 None,
36611 );
36612 assert_eq!(
36613 memoized,
36614 SeatCost {
36615 rows: 100_000 + 2 * 7_659,
36616 seeks: 0
36617 }
36618 );
36619 }
36620
36621 #[test]
36622 fn summed_key_lists_do_not_inflate_the_verdict_into_a_build() {
36623 let (seeks, matched) = probe_broadcast_price(
36629 277_000,
36630 &[
36631 (false, 10_000, 1_000_000_000_000, 1_000),
36632 (false, 10_000, 1_000_000_000_000, 1_000),
36633 ],
36634 false,
36635 );
36636 assert_eq!((seeks, matched), (10_000, 0));
36637 assert_eq!(
36638 fetch_once_verdict(
36639 6, seeks, matched, 277_000, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36640 ),
36641 FetchOnceVerdict::PerPage
36642 );
36643 assert_eq!(
36646 fetch_once_verdict(
36647 6, 20_000, matched, 277_000, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36648 ),
36649 FetchOnceVerdict::FetchOnce
36650 );
36651 }
36652
36653 #[test]
36654 fn one_term_list_is_a_point_lookup_never_covered() {
36655 let point = seat_cost_arithmetic(
36659 40_000,
36660 10_000,
36661 true,
36662 2,
36663 &[(false, 1, 500, 1_000)],
36664 true,
36665 true,
36666 true,
36667 true,
36668 false,
36669 None,
36670 );
36671 assert_eq!(
36672 point,
36673 SeatCost {
36674 rows: 40_000 + 2 * 20,
36675 seeks: 2
36676 }
36677 );
36678 assert!(point.rows < 40_000 + 10_000);
36679 }
36680
36681 #[test]
36682 fn unknown_probe_domain_never_covers_and_prices_conservatively() {
36683 let unknown = seat_cost_arithmetic(
36687 40_000,
36688 10_000,
36689 true,
36690 2,
36691 &[(false, 190, 0, 1_000)],
36692 true,
36693 true,
36694 true,
36695 true,
36696 false,
36697 None,
36698 );
36699 assert_eq!(
36705 unknown,
36706 SeatCost {
36707 rows: 50_000,
36708 seeks: 0
36709 }
36710 );
36711 }
36712
36713 #[test]
36714 fn empty_driver_reads_nothing() {
36715 assert_eq!(
36716 seat_cost_arithmetic(
36717 0,
36718 10_000,
36719 true,
36720 1,
36721 &[(false, 5, 100, 1_000)],
36722 false,
36723 true,
36724 true,
36725 true,
36726 false,
36727 None,
36728 ),
36729 SeatCost { rows: 0, seeks: 0 },
36730 );
36731 }
36732
36733 #[test]
36734 fn seat_beats_rows_decide_and_seeks_only_break_statistical_ties() {
36735 let incumbent = SeatCost {
36736 rows: 1_000,
36737 seeks: 500,
36738 };
36739 assert!(!seat_beats(
36744 SeatCost {
36745 rows: 1_001,
36746 seeks: 0
36747 },
36748 incumbent
36749 ));
36750 assert!(!seat_beats(
36753 SeatCost {
36754 rows: 990,
36755 seeks: 600
36756 },
36757 incumbent
36758 ));
36759 assert!(seat_beats(
36760 SeatCost {
36761 rows: 990,
36762 seeks: 400
36763 },
36764 incumbent
36765 ));
36766 assert!(seat_beats(
36768 SeatCost {
36769 rows: 1_000,
36770 seeks: 499
36771 },
36772 incumbent
36773 ));
36774 assert!(!seat_beats(
36775 SeatCost {
36776 rows: 1_000,
36777 seeks: 501
36778 },
36779 incumbent
36780 ));
36781 assert!(seat_beats(
36784 SeatCost {
36785 rows: 900,
36786 seeks: 9_999
36787 },
36788 incumbent
36789 ));
36790 }
36791
36792 #[test]
36793 fn fetch_once_predicate_priced_in_row_equivalents() {
36794 assert_eq!(
36802 fetch_once_verdict(
36803 6, 24_576, 24_576, 277_711, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36804 ),
36805 FetchOnceVerdict::FetchOnce
36806 );
36807 assert_eq!(
36811 fetch_once_verdict(
36812 6, 674, 674, 7_694, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36813 ),
36814 FetchOnceVerdict::FetchOnce
36815 );
36816 assert_eq!(
36822 fetch_once_verdict(
36823 6, 100, 100, 1_000_000, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36824 ),
36825 FetchOnceVerdict::PerPage
36826 );
36827 assert_eq!(
36832 fetch_once_verdict(
36833 50, 24_576, 0, 1_000, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36834 ),
36835 FetchOnceVerdict::FetchOnce
36836 );
36837 assert_eq!(
36844 fetch_once_verdict(
36845 11, 6_141, 6_141, 7_659, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36846 ),
36847 FetchOnceVerdict::FetchOnce
36848 );
36849 assert_eq!(
36850 fetch_once_verdict(
36851 11, 6_141, 6_141, 686, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36852 ),
36853 FetchOnceVerdict::FetchOnce
36854 );
36855 assert_eq!(
36858 fetch_once_verdict(
36859 0, 100, 100, 1_000, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36860 ),
36861 FetchOnceVerdict::PerPage
36862 );
36863 assert_eq!(
36864 fetch_once_verdict(
36865 6, 100, 100, 0, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36866 ),
36867 FetchOnceVerdict::PerPage
36868 );
36869 assert_eq!(
36871 fetch_once_verdict(
36872 u64::MAX,
36873 u64::MAX,
36874 u64::MAX,
36875 1,
36876 true,
36877 true,
36878 false,
36879 3_600,
36880 1_000,
36881 1_200,
36882 1_000,
36883 1_500
36884 ),
36885 FetchOnceVerdict::FetchOnce
36886 );
36887 assert_eq!(
36891 fetch_once_verdict(
36892 6, 24_576, 24_576, 277_711, true, false, false, 3_600, 1_000, 1_200, 1_000, 1_500
36893 ),
36894 FetchOnceVerdict::PerPage
36895 );
36896 }
36897
36898 #[test]
36905 fn a_degenerate_probe_match_builds_on_pages_not_on_the_bound() {
36906 const WHOLE: u64 = 44_804_238;
36907 assert_eq!(
36910 fetch_once_verdict(
36911 1, 16, WHOLE, WHOLE, true, true, true, 4_200, 1_400, 1_200, 1_000, 1_400
36912 ),
36913 FetchOnceVerdict::PerPage
36914 );
36915 assert_eq!(
36919 fetch_once_verdict(
36920 2, 16, WHOLE, WHOLE, true, true, true, 4_200, 1_400, 1_200, 1_000, 1_400
36921 ),
36922 FetchOnceVerdict::FetchOnce
36923 );
36924 assert_eq!(
36930 fetch_once_verdict(
36931 2, 0, 550, 1_000, true, true, false, 4_200, 1_400, 1_200, 1_000, 1_400
36932 ),
36933 FetchOnceVerdict::FetchOnce
36934 );
36935 assert_eq!(
36938 fetch_once_verdict(
36939 1, 24_576, 10, 10, true, true, true, 4_200, 1_400, 1_200, 1_000, 1_400
36940 ),
36941 FetchOnceVerdict::FetchOnce
36942 );
36943 }
36944}
36945
36946#[cfg(test)]
36947mod const_seed_tests {
36948 use super::*;
36953 use waratah_storage::Variable;
36954
36955 fn var(name: &str) -> Expression {
36956 Expression::Variable(Variable::new(name).unwrap())
36957 }
36958
36959 fn node(iri: &str) -> Expression {
36960 Expression::NamedNode(waratah_storage::NamedNode::new(iri).unwrap())
36961 }
36962
36963 #[test]
36964 fn collect_expression_consts_including_nested_positions() {
36965 let expression = Expression::Coalesce(vec![
36966 var("missing"),
36967 node("urn:ex:const-fallback"),
36968 Expression::If(
36969 Box::new(var("flag")),
36970 Box::new(node("urn:ex:branch-then")),
36971 Box::new(Expression::Literal(
36972 waratah_storage::Literal::new_simple_literal("a long lexical form"),
36973 )),
36974 ),
36975 ]);
36976 let mut strings = Vec::new();
36977 let mut blobs = Vec::new();
36978 collect_expression_const_seeds(&expression, &mut strings, &mut blobs);
36979 let fallback = waratah_storage::StrHash::new("urn:ex:const-fallback");
36982 assert!(
36983 strings
36984 .iter()
36985 .any(|(hash, raw)| *hash == fallback && raw == "urn:ex:const-fallback"),
36986 "the COALESCE fallback IRI must be collected"
36987 );
36988 let branch = waratah_storage::StrHash::new("urn:ex:branch-then");
36989 assert!(strings.iter().any(|(hash, _)| *hash == branch));
36990 assert_eq!(
36991 strings.len(),
36992 3,
36993 "two IRIs + one big-string lexical, deduped"
36994 );
36995 assert!(blobs.is_empty(), "no plugin-owned datatype in this shape");
36996 }
36997
36998 #[test]
36999 fn attach_fills_extend_and_group_nodes_only() {
37000 let mut tree = PlanNode::Extend {
37001 inner: Box::new(PlanNode::Group {
37002 inner: Box::new(PlanNode::Unit),
37003 variables: Vec::new(),
37004 aggregates: vec![(
37005 Variable::new("m").unwrap(),
37006 AggregateExpression::FunctionCall {
37007 name: spargebra::algebra::AggregateFunction::Min,
37008 expr: node("urn:ex:agg-const"),
37009 distinct: false,
37010 },
37011 )],
37012 const_strings: Vec::new(),
37013 const_blobs: Vec::new(),
37014 }),
37015 variable: Variable::new("y").unwrap(),
37016 expression: Expression::Coalesce(vec![var("missing"), node("urn:ex:const-fallback")]),
37017 const_strings: Vec::new(),
37018 const_blobs: Vec::new(),
37019 };
37020 attach_const_seeds(&mut tree);
37021 let PlanNode::Extend {
37022 const_strings,
37023 inner,
37024 ..
37025 } = &tree
37026 else {
37027 panic!("expected Extend root");
37028 };
37029 assert_eq!(const_strings.len(), 1, "the COALESCE fallback IRI");
37030 let PlanNode::Group { const_strings, .. } = inner.as_ref() else {
37031 panic!("expected Group inner");
37032 };
37033 assert_eq!(const_strings.len(), 1, "the aggregate argument IRI");
37034 }
37035
37036 #[test]
37037 fn duplicate_consts_dedup_per_node() {
37038 let expression = Expression::Coalesce(vec![
37039 var("a"),
37040 node("urn:ex:same"),
37041 Expression::Coalesce(vec![var("b"), node("urn:ex:same")]),
37042 ]);
37043 let mut strings = Vec::new();
37044 let mut blobs = Vec::new();
37045 collect_expression_const_seeds(&expression, &mut strings, &mut blobs);
37046 assert_eq!(strings.len(), 1);
37047 }
37048
37049 #[test]
37054 fn attach_descends_custom_op_children() {
37055 #[derive(Debug)]
37056 struct WalkTestPayload;
37057 impl crate::plugin::PluginPayload for WalkTestPayload {
37058 fn plugin_id(&self) -> &'static str {
37059 "const-seed-test"
37060 }
37061 fn memo_content(&self) -> Vec<u8> {
37062 Vec::new()
37063 }
37064 }
37065 let mut tree = PlanNode::CustomNode(CustomOp {
37066 plugin_id: "const-seed-test",
37067 op_id: "op",
37068 payload: crate::plugin::PluginPayloadBox::new(WalkTestPayload),
37069 children: vec![PlanNode::Extend {
37070 inner: Box::new(PlanNode::Unit),
37071 variable: Variable::new("y").unwrap(),
37072 expression: Expression::Coalesce(vec![var("missing"), node("urn:ex:under-custom")]),
37073 const_strings: Vec::new(),
37074 const_blobs: Vec::new(),
37075 }],
37076 variables: vec![Variable::new("y").unwrap()],
37077 produced_row_count_estimate: 1,
37078 cost: None,
37079 pinned: Vec::new(),
37080 });
37081 attach_const_seeds(&mut tree);
37082 let PlanNode::CustomNode(op) = &tree else {
37083 panic!("expected CustomNode root");
37084 };
37085 let PlanNode::Extend { const_strings, .. } = &op.children[0] else {
37086 panic!("expected Extend child");
37087 };
37088 assert_eq!(
37089 const_strings.len(),
37090 1,
37091 "the const under the custom child must be collected"
37092 );
37093 }
37094}
37095
37096#[cfg(test)]
37100mod fetch_once_stamp_tests {
37101 use super::FetchOnceVerdict;
37102 use super::{fetch_once_verdict, probe_seek_concurrency_milli};
37103
37104 use super::restamp_fetch_once;
37105 use super::stamp_semi_join_strategy;
37106 use super::{BagMark, DomainScanKind, Liveness};
37107 use super::{GraphFilter, scan_is_key_unique};
37108 use super::{JoinMeta, JoinStrategy, LeftJoinMeta, PlanNode, ScanOp, StatsProfile};
37109 use super::{bound_constraint_count_scan, fetch_once_stampable};
37110 use crate::ValuesOp;
37111 use waratah_storage::{EncodedTerm, EncodedTriplePattern, NamedNode, Variable};
37112
37113 fn var_scan(subject: Option<&str>, predicate: &str, object: Option<&str>, rows: u64) -> ScanOp {
37114 ScanOp {
37115 ancestor_push_return_bound: None,
37116 fetch_once: None,
37117 pattern: EncodedTriplePattern {
37118 subject: None,
37119 predicate: Some(EncodedTerm::from(&NamedNode::new(predicate).unwrap())),
37120 object: None,
37121 graph_name: None,
37122 },
37123 subject: subject.map(|v| Variable::new(v).unwrap()),
37124 predicate: None,
37125 object: object.map(|v| Variable::new(v).unwrap()),
37126 graph: None,
37127 produced_row_count_estimate: rows,
37128 broadcasted: None,
37129 graph_filter: None,
37130 grounded: Vec::new(),
37131 merge_default_graph: false,
37132 marks: Vec::new(),
37133 domain_scan: None,
37134 head_scan: None,
37135 head_scan_counts: None,
37136 domain_counts: None,
37137 iri_only: Vec::new(),
37138 eager: Vec::new(),
37139 join_domains: Default::default(),
37140 }
37141 }
37142
37143 fn join(left: PlanNode, right: PlanNode, produced: u64) -> PlanNode {
37144 PlanNode::Join {
37145 left: Box::new(left),
37146 right: Box::new(right),
37147 hash_keys: vec![Variable::new("s").unwrap()],
37148 probe_key_domains: Vec::new(),
37149 probe_key_overlap_milli: Vec::new(),
37150 rhs_hostable_keys: Vec::new().into(),
37151 meta: JoinMeta {
37152 semi_gate: None,
37153 star_arms: None,
37154 strategy: JoinStrategy::Broadcast,
37155 produced_row_count_estimate: produced,
37156 own_push_removed_row_count_estimate: produced,
37157 },
37158 }
37159 }
37160
37161 fn stamp_of(node: &PlanNode) -> Option<Option<u64>> {
37162 node.as_scan().map(|scan| scan.fetch_once)
37163 }
37164
37165 fn is_stamped(node: &PlanNode) -> bool {
37166 node.as_scan().is_some_and(|scan| scan.fetch_once.is_some())
37167 }
37168
37169 fn strategy_of(node: &PlanNode) -> JoinStrategy {
37170 match node {
37171 PlanNode::Join { meta, .. } => meta.strategy,
37172 other => panic!("expected Join, got {other:?}"),
37173 }
37174 }
37175
37176 fn var(name: &str) -> Variable {
37177 Variable::new(name).unwrap()
37178 }
37179
37180 fn known_profile(driver_keys: u128) -> StatsProfile {
37184 let mut profile = StatsProfile::default();
37185 for (pred, rows, keys) in [
37188 ("http://ex/driver", 200_000u64, driver_keys),
37189 ("http://ex/probe", 50_000, 50_000),
37190 ("http://ex/a", 50_000, 50_000),
37191 ("http://ex/b", 50_000, 50_000),
37192 ("http://ex/il", 60_000, 5_000),
37193 ("http://ex/ir", 3_000, 3_000),
37194 ] {
37195 let mut hll = waratah_stats::HyperLogLog::default_params();
37196 for i in 0..keys {
37197 hll.add(i);
37198 }
37199 profile
37200 .subjects_per_predicate
37201 .insert(waratah_storage::StrHash::new(pred), hll);
37202 profile
37203 .predicate_counts
37204 .insert(waratah_storage::StrHash::new(pred), rows);
37205 }
37206 profile.total_puts = 400_000;
37207 profile
37208 }
37209
37210 #[test]
37219 fn star_divisor_flips_only_with_the_batch_credit() {
37220 assert_eq!(
37223 fetch_once_verdict(
37224 115, 24_576, 24_576, 7_635_119, true, true, false, 3_600, 1_000, 1_200, 1_000,
37225 1_500
37226 ),
37227 FetchOnceVerdict::FetchOnce
37228 );
37229 assert_eq!(
37232 fetch_once_verdict(
37233 115, 24_576, 24_576, 7_635_119, true, true, false, 3_600, 1_000, 1_200, 1_500,
37234 1_500
37235 ),
37236 FetchOnceVerdict::PerPage
37237 );
37238 assert_eq!(
37240 fetch_once_verdict(
37241 115, 24_576, 24_576, 2_822_319, true, true, false, 3_600, 1_000, 1_200, 1_500,
37242 1_500
37243 ),
37244 FetchOnceVerdict::FetchOnce
37245 );
37246 }
37247
37248 #[test]
37264 fn single_arm_batch_prices_the_fetch_concurrency() {
37265 assert_eq!(probe_seek_concurrency_milli(false, 115, 24_576, 3), 1000);
37267 assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 3), 2_420);
37270 assert_eq!(probe_seek_concurrency_milli(true, 1, 24_576, 3), 1000);
37272 assert_eq!(
37274 fetch_once_verdict(
37275 115, 24_576, 24_576, 7_635_119, true, true, false, 3_600, 1_000, 1_200, 1_000,
37276 1_500
37277 ),
37278 FetchOnceVerdict::FetchOnce
37279 );
37280 assert_eq!(
37281 fetch_once_verdict(
37282 115, 24_576, 24_576, 7_635_119, true, true, false, 3_600, 1_000, 1_200, 3_000,
37283 1_500
37284 ),
37285 FetchOnceVerdict::PerPage
37286 );
37287 }
37288
37289 #[test]
37290 fn star_concurrency_milli_is_the_fetch_concurrency_not_the_spine_size() {
37291 assert_eq!(probe_seek_concurrency_milli(false, 115, 24_576, 3), 1000);
37293 assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 3), 2_420);
37297 assert_eq!(probe_seek_concurrency_milli(true, 1, 24_576, 3), 1000);
37300 assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 3), 2_420);
37308 assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 8), 4_050);
37310 }
37311
37312 #[test]
37313 fn seek_concurrency_engine_off_floor_and_large_fetch_concurrency() {
37314 assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 0), 1000);
37317 assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 1), 1000);
37318 assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 2), 1_820);
37320 assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 8), 4_050);
37324 assert_eq!(probe_seek_concurrency_milli(true, 0, 24_576, 3), 1000);
37327 assert_eq!(probe_seek_concurrency_milli(true, 115, 0, 3), 1000);
37328 }
37329
37330 #[test]
37331 fn firing_scan_probe_is_stamped_driver_is_not() {
37332 let _fc = crate::context::FetchConcurrencyPin::set(crate::context::QUERY_FETCH_CONCURRENCY);
37337 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 200_000));
37338 let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/probe", Some("v"), 50_000));
37339 let mut tree = join(driver, probe, 200_000);
37340 let profile = known_profile(200_000);
37341 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37342 let PlanNode::Join { left, right, .. } = &tree else {
37343 panic!("expected Join, got {tree:?}")
37344 };
37345 assert!(
37346 is_stamped(right),
37347 "the firing probe stamps (carrying its arm estimate)"
37348 );
37349 assert!(!is_stamped(left), "the driver never stamps");
37350 }
37351
37352 #[test]
37369 fn sliced_stamp_suppresses_the_divisor_star_included() {
37370 let _fc = crate::context::FetchConcurrencyPin::set(crate::context::QUERY_FETCH_CONCURRENCY);
37374 let mut profile = StatsProfile::default();
37375 for (pred, rows, keys) in [
37376 ("http://ex/driver", 2_826_240u64, 2_826_240u128),
37377 ("http://ex/probe", 9_500_000, 9_500_000),
37378 ] {
37379 let mut hll = waratah_stats::HyperLogLog::default_params();
37380 for i in 0..keys {
37381 hll.add(i);
37382 }
37383 profile
37384 .subjects_per_predicate
37385 .insert(waratah_storage::StrHash::new(pred), hll);
37386 profile
37387 .predicate_counts
37388 .insert(waratah_storage::StrHash::new(pred), rows);
37389 }
37390 profile.total_puts = 12_326_240;
37391 let make_tree = |star_arms: Option<u8>| {
37392 let driver = PlanNode::Scan(var_scan(
37393 Some("s"),
37394 "http://ex/driver",
37395 Some("o"),
37396 2_826_240,
37397 ));
37398 let probe =
37399 PlanNode::Scan(var_scan(Some("s"), "http://ex/probe", Some("v"), 9_500_000));
37400 let mut tree = join(driver, probe, 9_500_000);
37401 if let PlanNode::Join { meta, .. } = &mut tree {
37402 meta.star_arms = star_arms;
37403 }
37404 tree
37405 };
37406 let probe_is_stamped = |tree: &PlanNode| match tree {
37407 PlanNode::Join { right, .. } => is_stamped(right),
37408 _ => panic!("expected Join, got {tree:?}"),
37409 };
37410
37411 let mut tree = make_tree(None);
37413 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37414 assert!(
37415 !probe_is_stamped(&tree),
37416 "eager single-arm: the single-arm share flips the verdict to PerPage"
37417 );
37418
37419 let mut tree = make_tree(Some(2));
37421 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37422 assert!(
37423 !probe_is_stamped(&tree),
37424 "eager star: the two-arm share flips the verdict to PerPage"
37425 );
37426
37427 let mut tree = make_tree(None);
37430 restamp_fetch_once(&mut tree, Some(&profile), None, true);
37431 assert!(
37432 probe_is_stamped(&tree),
37433 "sliced single-arm: sequential price, the divisor must not fire"
37434 );
37435
37436 let mut tree = make_tree(Some(2));
37439 restamp_fetch_once(&mut tree, Some(&profile), None, true);
37440 assert!(
37441 probe_is_stamped(&tree),
37442 "sliced star: sequential price, the star stamp must not restore the divisor"
37443 );
37444 }
37445
37446 #[test]
37454 fn build_verdict_writes_the_mark_at_any_arm_size() {
37455 let _fc = crate::context::FetchConcurrencyPin::set(crate::context::QUERY_FETCH_CONCURRENCY);
37460 let driver = PlanNode::Scan(var_scan(
37477 Some("s"),
37478 "http://ex/driver",
37479 Some("o"),
37480 1_000_000,
37481 ));
37482 let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/huge", Some("v"), 2_000_000));
37483 let mut tree = join(driver, probe, 1_000_000);
37484 let mut profile = StatsProfile::default();
37485 for (pred, rows, keys) in [
37486 ("http://ex/driver", 1_000_000u64, 1_000_000u128),
37487 ("http://ex/huge", 2_000_000, 200_000),
37488 ] {
37489 let mut hll = waratah_stats::HyperLogLog::default_params();
37490 for i in 0..keys {
37491 hll.add(i);
37492 }
37493 profile
37494 .subjects_per_predicate
37495 .insert(waratah_storage::StrHash::new(pred), hll);
37496 profile
37497 .predicate_counts
37498 .insert(waratah_storage::StrHash::new(pred), rows);
37499 }
37500 profile.total_puts = 3_000_000;
37501 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37502 let PlanNode::Join { right, .. } = &tree else {
37503 panic!("expected Join, got {tree:?}")
37504 };
37505 let stamp = stamp_of(right).expect("scan arm").expect("stamped");
37510 assert!(
37511 stamp > 1_572_864,
37512 "a FetchOnce verdict writes the mark whatever the arm size; the executor picks residency (got {stamp})"
37513 );
37514 }
37515
37516 fn join_on(left: PlanNode, right: PlanNode, produced: u64, key: &str) -> PlanNode {
37519 PlanNode::Join {
37520 left: Box::new(left),
37521 right: Box::new(right),
37522 hash_keys: vec![Variable::new(key).unwrap()],
37523 probe_key_domains: Vec::new(),
37524 probe_key_overlap_milli: Vec::new(),
37525 rhs_hostable_keys: Vec::new().into(),
37526 meta: JoinMeta {
37527 semi_gate: None,
37528 star_arms: None,
37529 strategy: JoinStrategy::Broadcast,
37530 produced_row_count_estimate: produced,
37531 own_push_removed_row_count_estimate: produced,
37532 },
37533 }
37534 }
37535
37536 fn push_conditioned_profile() -> StatsProfile {
37544 let mut profile = StatsProfile::default();
37545 for (pred, rows, subject_keys, object_keys) in [
37546 (
37547 "http://ex/hasGeom",
37548 8_000_000u64,
37549 7_950_000u128,
37550 Some(8_000_000u128),
37551 ),
37552 ("http://ex/type", 7_900_000, 7_900_000, None),
37553 ("http://ex/cluster", 360_000, 360_000, Some(350_000u128)),
37554 ("http://ex/other", 8_000_000, 7_950_000, None),
37555 ] {
37556 let mut subjects = waratah_stats::HyperLogLog::default_params();
37557 for i in 0..subject_keys {
37558 subjects.add(i);
37559 }
37560 profile
37561 .subjects_per_predicate
37562 .insert(waratah_storage::StrHash::new(pred), subjects);
37563 if let Some(object_keys) = object_keys {
37564 let mut objects = waratah_stats::HyperLogLog::default_params();
37565 for i in 0..object_keys {
37566 objects.add(i);
37567 }
37568 profile
37569 .objects_per_predicate
37570 .insert(waratah_storage::StrHash::new(pred), objects);
37571 }
37572 profile
37573 .predicate_counts
37574 .insert(waratah_storage::StrHash::new(pred), rows);
37575 }
37576 profile.total_puts = 16_260_000;
37577 profile
37578 }
37579
37580 fn contained_type_join() -> PlanNode {
37583 let driver = PlanNode::Scan(var_scan(
37584 Some("feature"),
37585 "http://ex/hasGeom",
37586 Some("geom"),
37587 8_000_000,
37588 ));
37589 let probe = PlanNode::Scan(var_scan(
37590 Some("feature"),
37591 "http://ex/type",
37592 Some("v"),
37593 7_900_000,
37594 ));
37595 join_on(driver, probe, 8_000_000, "feature")
37596 }
37597
37598 #[test]
37605 fn contained_type_join_stamps_build_standalone() {
37606 let mut tree = contained_type_join();
37607 let profile = push_conditioned_profile();
37608 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37609 let PlanNode::Join { right, .. } = &tree else {
37610 panic!("expected Join, got {tree:?}")
37611 };
37612 assert!(
37613 is_stamped(right),
37614 "standalone geometry: the many-page driver verdict stamps FetchOnce"
37615 );
37616 }
37617
37618 #[test]
37626 fn containing_push_unstamps_the_hosting_contained_join() {
37627 let cluster = PlanNode::Scan(var_scan(None, "http://ex/cluster", Some("geom"), 360_000));
37628 let mut tree = join_on(cluster, contained_type_join(), 360_000, "geom");
37629 let profile = push_conditioned_profile();
37630 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37631 let PlanNode::Join { right: subtree, .. } = &tree else {
37632 panic!("expected Join, got {tree:?}")
37633 };
37634 let PlanNode::Join {
37635 right: inner_probe, ..
37636 } = &**subtree
37637 else {
37638 panic!("expected subtree Join, got {subtree:?}")
37639 };
37640 assert!(
37641 !is_stamped(inner_probe),
37642 "the containing push re-geometries the inner driver: no Build stamp, the keyed probe road runs"
37643 );
37644 }
37645
37646 #[test]
37654 fn non_hosting_contained_driver_keeps_the_stamp() {
37655 let cluster = PlanNode::Scan(var_scan(None, "http://ex/cluster", Some("geom"), 360_000));
37656 let driver = PlanNode::Scan(var_scan(
37657 Some("feature"),
37658 "http://ex/other",
37659 Some("x"),
37660 8_000_000,
37661 ));
37662 let probe = PlanNode::Scan(var_scan(
37663 Some("feature"),
37664 "http://ex/type",
37665 Some("v"),
37666 7_900_000,
37667 ));
37668 let subtree = join_on(driver, probe, 8_000_000, "feature");
37669 let mut tree = join_on(cluster, subtree, 360_000, "geom");
37670 let profile = push_conditioned_profile();
37671 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37672 let PlanNode::Join { right: subtree, .. } = &tree else {
37673 panic!("expected Join, got {tree:?}")
37674 };
37675 let PlanNode::Join {
37676 right: inner_probe, ..
37677 } = &**subtree
37678 else {
37679 panic!("expected subtree Join, got {subtree:?}")
37680 };
37681 assert!(
37682 is_stamped(inner_probe),
37683 "a containing push the driver cannot host never conditions: the standalone Build stands"
37684 );
37685 }
37686
37687 #[test]
37699 fn selective_tail_subtree_keeps_the_honest_driver_bound() {
37700 let mut profile = push_conditioned_profile();
37701 let mut rare_subjects = waratah_stats::HyperLogLog::default_params();
37702 for i in 0..1_000_000u128 {
37703 rare_subjects.add(i);
37704 }
37705 profile.subjects_per_predicate.insert(
37706 waratah_storage::StrHash::new("http://ex/rare"),
37707 rare_subjects,
37708 );
37709 profile
37710 .predicate_counts
37711 .insert(waratah_storage::StrHash::new("http://ex/rare"), 1_000_000);
37712 let mut dense_geoms = waratah_stats::HyperLogLog::default_params();
37715 for i in 0..98_000u128 {
37716 dense_geoms.add(i);
37717 }
37718 profile.objects_per_predicate.insert(
37719 waratah_storage::StrHash::new("http://ex/hasGeom"),
37720 dense_geoms,
37721 );
37722
37723 let has_geom = PlanNode::Scan(var_scan(
37724 Some("feature"),
37725 "http://ex/hasGeom",
37726 Some("geom"),
37727 8_000_000,
37728 ));
37729 let type_scan = PlanNode::Scan(var_scan(
37730 Some("feature"),
37731 "http://ex/type",
37732 Some("v"),
37733 7_900_000,
37734 ));
37735 let rare_scan = PlanNode::Scan(var_scan(
37736 Some("feature"),
37737 "http://ex/rare",
37738 Some("r"),
37739 1_000_000,
37740 ));
37741 let cluster = PlanNode::Scan(var_scan(None, "http://ex/cluster", Some("geom"), 360_000));
37742 let inner = join_on(has_geom, type_scan, 7_900_000, "feature");
37743 let subtree = join_on(inner, rare_scan, 30_000, "feature");
37746 let mut tree = join_on(cluster, subtree, 360_000, "geom");
37747 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37748 let PlanNode::Join { right: subtree, .. } = &tree else {
37749 panic!("expected Join, got {tree:?}")
37750 };
37751 let PlanNode::Join { right: rare, .. } = &**subtree else {
37752 panic!("expected subtree Join, got {subtree:?}")
37753 };
37754 assert!(
37755 is_stamped(rare),
37756 "the honest ~2M per-page bound prices the keyed road above the margin: the Build stamp stands"
37757 );
37758 }
37759
37760 #[test]
37773 fn values_driver_with_known_domain_keeps_the_stamp() {
37774 let values = PlanNode::Values(ValuesOp {
37775 variables: vec![Variable::new("g").unwrap()],
37776 rows: (0..60_000)
37777 .map(|i| {
37778 vec![Some(EncodedTerm::from(
37779 &NamedNode::new(format!("http://ex/g{i}")).unwrap(),
37780 ))]
37781 })
37782 .collect(),
37783 strings: Vec::new(),
37784 blobs: Vec::new(),
37785 });
37786 let mut profile = push_conditioned_profile();
37787 let mut vtype_subjects = waratah_stats::HyperLogLog::default_params();
37788 for i in 0..30_000u128 {
37789 vtype_subjects.add(i);
37790 }
37791 profile.subjects_per_predicate.insert(
37792 waratah_storage::StrHash::new("http://ex/vtype"),
37793 vtype_subjects,
37794 );
37795 profile
37796 .predicate_counts
37797 .insert(waratah_storage::StrHash::new("http://ex/vtype"), 30_000);
37798 let vtype = PlanNode::Scan(var_scan(Some("g"), "http://ex/vtype", Some("v"), 30_000));
37799 let subtree = join_on(values, vtype, 30_000, "g");
37800 let cluster = PlanNode::Scan(var_scan(None, "http://ex/cluster", Some("geom"), 360_000));
37801 let mut tree = join_on(cluster, subtree, 360_000, "g");
37802 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37803 let PlanNode::Join { right: subtree, .. } = &tree else {
37804 panic!("expected Join, got {tree:?}")
37805 };
37806 let PlanNode::Join { right: vtype, .. } = &**subtree else {
37807 panic!("expected subtree Join, got {subtree:?}")
37808 };
37809 assert!(
37810 is_stamped(vtype),
37811 "a Values driver cannot be push-filtered: the standalone Build stamp stands on the gate alone"
37812 );
37813 }
37814
37815 #[test]
37826 fn containing_push_crosses_an_optional_required_arm() {
37827 let has_geom = PlanNode::Scan(var_scan(
37828 Some("feature"),
37829 "http://ex/hasGeom",
37830 Some("geom"),
37831 8_000_000,
37832 ));
37833 let type_scan = PlanNode::Scan(var_scan(
37834 Some("feature"),
37835 "http://ex/type",
37836 Some("v"),
37837 7_900_000,
37838 ));
37839 let label = PlanNode::Scan(var_scan(
37840 Some("feature"),
37841 "http://ex/label",
37842 Some("l"),
37843 1_000,
37844 ));
37845 let required = join_on(has_geom, type_scan, 7_900_000, "feature");
37846 let leftjoin = PlanNode::LeftJoin {
37847 left: Box::new(required),
37848 right: Box::new(label),
37849 hash_keys: vec![Variable::new("feature").unwrap()],
37850 early_filter: None,
37851 residual_filter: None,
37852 probe_key_domains: Vec::new(),
37853 probe_key_overlap_milli: Vec::new(),
37854 meta: LeftJoinMeta {
37855 produced_row_count_estimate: 7_900_000,
37856 own_push_removed_row_count_estimate: 7_900_000,
37857 },
37858 };
37859 let cluster = PlanNode::Scan(var_scan(None, "http://ex/cluster", Some("geom"), 360_000));
37860 let mut tree = join_on(cluster, leftjoin, 360_000, "geom");
37861 restamp_fetch_once(&mut tree, Some(&push_conditioned_profile()), None, false);
37862 let PlanNode::Join { right: subtree, .. } = &tree else {
37863 panic!("expected Join, got {tree:?}")
37864 };
37865 let PlanNode::LeftJoin { left: required, .. } = &**subtree else {
37866 panic!("expected subtree LeftJoin, got {subtree:?}")
37867 };
37868 let PlanNode::Join {
37869 right: type_arm, ..
37870 } = &**required
37871 else {
37872 panic!("expected required-side Join, got {required:?}")
37873 };
37874 assert!(
37875 !is_stamped(type_arm),
37876 "the containing push reaches the OPTIONAL's required arm: the keyed road runs, no whole-read stamp"
37877 );
37878 }
37879
37880 #[test]
37883 fn optional_arms_never_stamp() {
37884 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 200_000));
37885 let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/probe", Some("v"), 50_000));
37886 let mut tree = PlanNode::LeftJoin {
37887 left: Box::new(driver),
37888 right: Box::new(probe),
37889 hash_keys: vec![Variable::new("s").unwrap()],
37890 early_filter: None,
37891 residual_filter: None,
37892 probe_key_domains: Vec::new(),
37893 probe_key_overlap_milli: Vec::new(),
37894 meta: LeftJoinMeta {
37895 produced_row_count_estimate: 0,
37896 own_push_removed_row_count_estimate: 0,
37897 },
37898 };
37899 restamp_fetch_once(&mut tree, None, None, false);
37900 let PlanNode::LeftJoin { right, .. } = &tree else {
37901 panic!("expected LeftJoin, got {tree:?}")
37902 };
37903 assert!(
37904 !is_stamped(right),
37905 "an OPTIONAL arm has no built slot — never stamped"
37906 );
37907 }
37908
37909 #[test]
37920 fn unbroadcastable_graph_key_joins_are_never_stamped() {
37921 let driver = PlanNode::Values(ValuesOp {
37922 variables: vec![Variable::new("g").unwrap()],
37923 rows: (0..30)
37924 .map(|i| {
37925 vec![Some(EncodedTerm::from(
37926 &NamedNode::new(format!("http://ex/g{i}")).unwrap(),
37927 ))]
37928 })
37929 .collect(),
37930 strings: Vec::new(),
37931 blobs: Vec::new(),
37932 });
37933 let mut probe = var_scan(Some("s"), "http://ex/a", Some("v"), 200_000);
37934 probe.graph = Some(Variable::new("g").unwrap());
37935 let mut tree = PlanNode::Join {
37936 left: Box::new(driver),
37937 right: Box::new(PlanNode::Scan(probe)),
37938 hash_keys: vec![Variable::new("g").unwrap()],
37939 probe_key_domains: Vec::new(),
37940 probe_key_overlap_milli: Vec::new(),
37941 rhs_hostable_keys: Vec::new().into(),
37942 meta: JoinMeta {
37943 semi_gate: None,
37944 star_arms: None,
37945 strategy: JoinStrategy::Broadcast,
37946 produced_row_count_estimate: 200_000,
37947 own_push_removed_row_count_estimate: 200_000,
37948 },
37949 };
37950 let profile = known_profile(200_000);
37951 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37952 let PlanNode::Join { right, .. } = &tree else {
37953 panic!("expected Join, got {tree:?}")
37954 };
37955 assert!(
37956 !is_stamped(right),
37957 "a graph-position key can never broadcast a list: no stamp"
37958 );
37959 }
37960
37961 #[test]
37965 fn hosted_keys_still_stamp_through_a_values_driver() {
37966 let driver = PlanNode::Values(ValuesOp {
37967 variables: vec![Variable::new("s").unwrap()],
37968 rows: (0..60_000)
37969 .map(|i| {
37970 vec![Some(EncodedTerm::from(
37971 &NamedNode::new(format!("http://ex/s{i}")).unwrap(),
37972 ))]
37973 })
37974 .collect(),
37975 strings: Vec::new(),
37976 blobs: Vec::new(),
37977 });
37978 let probe = var_scan(Some("s"), "http://ex/a", Some("v"), 50_000);
37979 let mut tree = PlanNode::Join {
37980 left: Box::new(driver),
37981 right: Box::new(PlanNode::Scan(probe)),
37982 hash_keys: vec![Variable::new("s").unwrap()],
37983 probe_key_domains: Vec::new(),
37984 probe_key_overlap_milli: Vec::new(),
37985 rhs_hostable_keys: Vec::new().into(),
37986 meta: JoinMeta {
37987 semi_gate: None,
37988 star_arms: None,
37989 strategy: JoinStrategy::Broadcast,
37990 produced_row_count_estimate: 50_000,
37991 own_push_removed_row_count_estimate: 50_000,
37992 },
37993 };
37994 let profile = known_profile(200_000);
37995 restamp_fetch_once(&mut tree, Some(&profile), None, false);
37996 let PlanNode::Join { right, .. } = &tree else {
37997 panic!("expected Join, got {tree:?}")
37998 };
37999 assert!(
38000 is_stamped(right),
38001 "a hosted key stamps through a Values driver"
38002 );
38003 }
38004
38005 #[test]
38016 fn all_dropped_probe_arms_are_never_stamped() {
38017 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 24_000));
38023 let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/tiny", Some("v"), 2_000));
38024 let mut tree = join(driver, probe, 24_000);
38025 let mut profile = StatsProfile::default();
38026 for (pred, rows, keys) in [
38033 ("http://ex/driver", 24_000u64, 2_000u128),
38034 ("http://ex/tiny", 2_000, 2_000),
38035 ] {
38036 let mut hll = waratah_stats::HyperLogLog::default_params();
38037 for i in 0..keys {
38038 hll.add(i);
38039 }
38040 profile
38041 .subjects_per_predicate
38042 .insert(waratah_storage::StrHash::new(pred), hll);
38043 profile
38044 .predicate_counts
38045 .insert(waratah_storage::StrHash::new(pred), rows);
38046 }
38047 profile.total_puts = 80_000;
38048 restamp_fetch_once(&mut tree, Some(&profile), None, false);
38049 let PlanNode::Join { right, .. } = &tree else {
38050 panic!("expected Join, got {tree:?}")
38051 };
38052 assert!(
38053 !is_stamped(right),
38054 "an all-dropped probe executes once via the built slot: no stamp"
38055 );
38056 }
38057
38058 #[test]
38066 fn sparse_profile_without_this_predicate_never_stamps() {
38067 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 200_000));
38068 let probe = PlanNode::Scan(var_scan(
38070 Some("s"),
38071 "http://ex/unsketched",
38072 Some("v"),
38073 50_000,
38074 ));
38075 let mut tree = join(driver, probe, 200_000);
38076 let profile = known_profile(200_000);
38077 restamp_fetch_once(&mut tree, Some(&profile), None, false);
38078 let PlanNode::Join { right, .. } = &tree else {
38079 panic!("expected Join, got {tree:?}")
38080 };
38081 assert!(
38082 !is_stamped(right),
38083 "a never-observed predicate estimates as 1 row: the gate must refuse the stamp"
38084 );
38085 }
38086
38087 #[test]
38094 fn semi_promotion_requires_key_unique_and_the_fetch_once_verdict() {
38095 let left = || PlanNode::Scan(var_scan(Some("s"), "http://ex/union", Some("v"), 2_000_000));
38096
38097 let ground_right = |stamped: bool, bag: BagMark| {
38100 let mut scan = var_scan(Some("s"), "http://ex/datasetKind", None, 328_500);
38101 scan.pattern.object = Some(EncodedTerm::from(
38102 &NamedNode::new("http://ex/record").unwrap(),
38103 ));
38104 scan.fetch_once = stamped.then_some(328_500);
38105 scan.marks = vec![(var("s"), Liveness::Live, bag)];
38106 PlanNode::Scan(scan)
38107 };
38108
38109 let variable_right = |stamped: bool, bag: BagMark, object_liveness: Liveness| {
38113 let mut scan = var_scan(Some("s"), "http://ex/datasetKind", Some("o"), 328_500);
38114 scan.fetch_once = stamped.then_some(328_500);
38115 scan.marks = vec![
38116 (var("s"), Liveness::Live, bag),
38117 (var("o"), object_liveness, BagMark::Insensitive),
38118 ];
38119 PlanNode::Scan(scan)
38120 };
38121
38122 let mut key_unique = join(left(), ground_right(true, BagMark::Sensitive), 328_500);
38126 stamp_semi_join_strategy(&mut key_unique, None, false, None, &[]);
38127 assert_eq!(
38128 strategy_of(&key_unique),
38129 JoinStrategy::SemiScan,
38130 "a key-unique stamped right is the safe promotion"
38131 );
38132
38133 let mut unstamped = join(left(), ground_right(false, BagMark::Insensitive), 328_500);
38134 stamp_semi_join_strategy(&mut unstamped, None, false, None, &[]);
38135 assert_eq!(
38136 strategy_of(&unstamped),
38137 JoinStrategy::Broadcast,
38138 "the promotion must read the fetch-once verdict, not invent one"
38139 );
38140
38141 let mut payload = join(
38142 left(),
38143 variable_right(true, BagMark::Insensitive, Liveness::Live),
38144 328_500,
38145 );
38146 stamp_semi_join_strategy(&mut payload, None, false, None, &[]);
38147 assert_eq!(
38148 strategy_of(&payload),
38149 JoinStrategy::Broadcast,
38150 "a live right column cannot be replaced by a filter"
38151 );
38152
38153 let mut sensitive = join(
38154 left(),
38155 variable_right(true, BagMark::Sensitive, Liveness::Dead),
38156 328_500,
38157 );
38158 stamp_semi_join_strategy(&mut sensitive, None, false, None, &[]);
38159 assert_eq!(
38160 strategy_of(&sensitive),
38161 JoinStrategy::Broadcast,
38162 "a dead variable object still repeats the key across rows: a plain count sees it"
38163 );
38164
38165 let mut insensitive = join(
38166 left(),
38167 variable_right(true, BagMark::Insensitive, Liveness::Dead),
38168 328_500,
38169 );
38170 stamp_semi_join_strategy(&mut insensitive, None, false, None, &[]);
38171 assert_eq!(
38172 strategy_of(&insensitive),
38173 JoinStrategy::Broadcast,
38174 "a repeated key is not key-unique; a bag-insensitive key alone cannot preserve left row multiplicity"
38175 );
38176
38177 let mut count_star_payload = join(
38182 left(),
38183 variable_right(true, BagMark::Sensitive, Liveness::Counted),
38184 328_500,
38185 );
38186 stamp_semi_join_strategy(&mut count_star_payload, None, false, None, &[]);
38187 assert_eq!(
38188 strategy_of(&count_star_payload),
38189 JoinStrategy::Broadcast,
38190 "a COUNT(*) payload is not key-unique; the Counted mark must not admit it"
38191 );
38192
38193 let mut specialized_right = ground_right(true, BagMark::Insensitive);
38196 if let PlanNode::Scan(scan) = &mut specialized_right {
38197 scan.domain_counts = Some(DomainScanKind::PredicateDomain);
38198 }
38199 let mut specialized = join(left(), specialized_right, 328_500);
38200 stamp_semi_join_strategy(&mut specialized, None, false, None, &[]);
38201 assert_eq!(
38202 strategy_of(&specialized),
38203 JoinStrategy::Broadcast,
38204 "a specialized scan must never become a semi-join key set"
38205 );
38206
38207 let mut one_graph_right = ground_right(true, BagMark::Sensitive);
38209 if let PlanNode::Scan(scan) = &mut one_graph_right {
38210 scan.graph_filter = Some(GraphFilter::allow([EncodedTerm::from(
38211 &NamedNode::new("http://ex/g1").unwrap(),
38212 )]));
38213 }
38214 let mut one_graph = join(left(), one_graph_right, 328_500);
38215 stamp_semi_join_strategy(&mut one_graph, None, false, None, &[]);
38216 assert_eq!(
38217 strategy_of(&one_graph),
38218 JoinStrategy::SemiScan,
38219 "a one-term allow-list fixes the graph, so the key is unique"
38220 );
38221
38222 let mut two_graphs_right = ground_right(true, BagMark::Sensitive);
38225 if let PlanNode::Scan(scan) = &mut two_graphs_right {
38226 scan.graph_filter = Some(GraphFilter::allow([
38227 EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap()),
38228 EncodedTerm::from(&NamedNode::new("http://ex/g2").unwrap()),
38229 ]));
38230 }
38231 let mut two_graphs = join(left(), two_graphs_right, 328_500);
38232 stamp_semi_join_strategy(&mut two_graphs, None, false, None, &[]);
38233 assert_eq!(
38234 strategy_of(&two_graphs),
38235 JoinStrategy::Broadcast,
38236 "a multi-term allow-list can expose the key once per graph"
38237 );
38238
38239 let mut blocked_right = ground_right(true, BagMark::Sensitive);
38240 if let PlanNode::Scan(scan) = &mut blocked_right {
38241 scan.graph_filter = Some(GraphFilter::exclude([EncodedTerm::from(
38242 &NamedNode::new("http://ex/g1").unwrap(),
38243 )]));
38244 }
38245 let mut blocked = join(left(), blocked_right, 328_500);
38246 stamp_semi_join_strategy(&mut blocked, None, false, None, &[]);
38247 assert_eq!(
38248 strategy_of(&blocked),
38249 JoinStrategy::Broadcast,
38250 "a block-list leaves every other graph, so the key can repeat"
38251 );
38252 }
38253
38254 #[test]
38258 fn key_unique_requires_a_fixed_graph() {
38259 let mut scan = var_scan(Some("s"), "http://ex/p", None, 10);
38260 scan.pattern.object = Some(EncodedTerm::from(&NamedNode::new("http://ex/o").unwrap()));
38261 let key = vec![var("s")];
38262 assert!(
38263 scan_is_key_unique(&scan, &key),
38264 "default graph: the key determines the triple"
38265 );
38266
38267 scan.graph_filter = Some(GraphFilter::allow([EncodedTerm::from(
38268 &NamedNode::new("http://ex/g1").unwrap(),
38269 )]));
38270 assert!(
38271 scan_is_key_unique(&scan, &key),
38272 "a one-term allow-list is a fixed graph"
38273 );
38274
38275 scan.graph = Some(var("g"));
38276 assert!(
38277 scan_is_key_unique(&scan, &key),
38278 "a graph variable confined by a one-term allow-list is fixed"
38279 );
38280
38281 scan.graph_filter = Some(GraphFilter::allow([
38282 EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap()),
38283 EncodedTerm::from(&NamedNode::new("http://ex/g2").unwrap()),
38284 ]));
38285 assert!(
38286 !scan_is_key_unique(&scan, &key),
38287 "a multi-term allow-list can repeat the key across graphs"
38288 );
38289
38290 scan.graph = None;
38291 scan.graph_filter = Some(GraphFilter::exclude([EncodedTerm::from(
38292 &NamedNode::new("http://ex/g1").unwrap(),
38293 )]));
38294 assert!(
38295 !scan_is_key_unique(&scan, &key),
38296 "a block-list leaves other graphs open"
38297 );
38298
38299 scan.graph_filter = None;
38300 scan.merge_default_graph = true;
38301 assert!(
38302 !scan_is_key_unique(&scan, &key),
38303 "the default-graph merge can surface the triple per graph"
38304 );
38305 }
38306
38307 #[test]
38314 fn uncovered_sibling_of_the_all_dropped_shape_still_stamps() {
38315 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 60_000));
38316 let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/mid", Some("v"), 3_000));
38317 let mut tree = join(driver, probe, 60_000);
38318 let mut profile = StatsProfile::default();
38319 for (pred, rows, keys) in [
38320 ("http://ex/driver", 60_000u64, 5_000u128),
38321 ("http://ex/mid", 3_000, 3_000),
38322 ] {
38323 let mut hll = waratah_stats::HyperLogLog::default_params();
38324 for i in 0..keys {
38325 hll.add(i);
38326 }
38327 profile
38328 .subjects_per_predicate
38329 .insert(waratah_storage::StrHash::new(pred), hll);
38330 profile
38331 .predicate_counts
38332 .insert(waratah_storage::StrHash::new(pred), rows);
38333 }
38334 profile.total_puts = 80_000;
38335 restamp_fetch_once(&mut tree, Some(&profile), None, false);
38336 let PlanNode::Join { right, .. } = &tree else {
38337 panic!("expected Join, got {tree:?}")
38338 };
38339 assert!(
38340 is_stamped(right),
38341 "a not-covered probe prices normally and stamps"
38342 );
38343 }
38344
38345 #[test]
38351 fn subtree_arms_are_descended_not_stamped_wholesale() {
38352 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 200_000));
38353 let inner_left = PlanNode::Scan(var_scan(Some("s"), "http://ex/il", Some("v"), 60_000));
38358 let inner_right = PlanNode::Scan(var_scan(Some("s"), "http://ex/ir", Some("v"), 3_000));
38359 let mut tree = join(driver, join(inner_left, inner_right, 60_000), 200_000);
38360 let profile = known_profile(200_000);
38361 restamp_fetch_once(&mut tree, Some(&profile), None, false);
38362 let PlanNode::Join { right, .. } = &tree else {
38363 panic!("expected Join, got {tree:?}")
38364 };
38365 assert_eq!(stamp_of(right), None, "a subtree probe is not a scan");
38369 let PlanNode::Join {
38370 right: inner_right, ..
38371 } = right.as_ref()
38372 else {
38373 panic!("expected nested Join, got {right:?}")
38374 };
38375 assert!(
38376 is_stamped(inner_right),
38377 "the subtree's own inner join stamps its bare-Scan arm"
38378 );
38379 }
38380
38381 #[test]
38385 fn cheap_lists_against_a_huge_arm_stay_per_page_mode() {
38386 let mut profile = StatsProfile::default();
38387 let driver_p = waratah_storage::StrHash::new("http://ex/driver");
38388 let probe_p = waratah_storage::StrHash::new("http://ex/probe");
38389 profile.predicate_counts.insert(driver_p, 200_000);
38390 profile.predicate_counts.insert(probe_p, 1_000_000);
38391 let mut driver_hll = waratah_stats::HyperLogLog::default_params();
38392 for i in 0..100 {
38393 driver_hll.add(i);
38394 }
38395 profile.subjects_per_predicate.insert(driver_p, driver_hll);
38396 let mut probe_hll = waratah_stats::HyperLogLog::default_params();
38397 for i in 0..1_000_000u128 {
38398 probe_hll.add(i);
38399 }
38400 profile.subjects_per_predicate.insert(probe_p, probe_hll);
38401 profile.total_puts = 1_200_000;
38402
38403 let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 200_000));
38404 let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/probe", Some("v"), 1_000_000));
38405 let mut tree = join(driver, probe, 1_000_000);
38406 restamp_fetch_once(&mut tree, Some(&profile), None, false);
38407 let PlanNode::Join { right, .. } = &tree else {
38408 panic!("expected Join, got {tree:?}")
38409 };
38410 assert!(
38413 !is_stamped(right),
38414 "cheap lists against a huge arm keep per-page mode"
38415 );
38416 }
38417
38418 #[test]
38426 fn a_bound_predicate_count_walk_is_built_once() {
38427 let mut specialized = var_scan(Some("s"), "http://ex/p", Some("k"), 10);
38428 specialized.domain_counts = Some(DomainScanKind::PredicateDomain);
38429 assert!(bound_constraint_count_scan(&specialized));
38430 assert!(fetch_once_stampable(&specialized));
38431
38432 let mut distinct = specialized.clone();
38435 distinct.marks = vec![(
38436 Variable::new("k").unwrap(),
38437 Liveness::Counted,
38438 BagMark::Insensitive,
38439 )];
38440 assert_eq!(
38441 distinct.domain_count_mode(),
38442 waratah_storage::DomainCountMode::DistinctTerms
38443 );
38444 assert!(!bound_constraint_count_scan(&distinct));
38445 assert!(!fetch_once_stampable(&distinct));
38446
38447 let mut unbound = specialized.clone();
38450 unbound.pattern.predicate = None;
38451 assert!(!bound_constraint_count_scan(&unbound));
38452 assert!(!fetch_once_stampable(&unbound));
38453
38454 let mut subject_kind = var_scan(Some("s"), "http://ex/p", Some("o"), 10);
38457 subject_kind.domain_counts = Some(DomainScanKind::SubjectDomain);
38458 assert!(!bound_constraint_count_scan(&subject_kind));
38459
38460 let driver = PlanNode::Scan(var_scan(
38463 Some("site"),
38464 "http://ex/hasSite",
38465 Some("s"),
38466 200_000,
38467 ));
38468 let mut tree = join(driver, PlanNode::Scan(specialized), 200_000);
38469 restamp_fetch_once(&mut tree, None, None, false);
38470 let PlanNode::Join { right, .. } = &tree else {
38471 panic!("expected Join, got {tree:?}")
38472 };
38473 assert!(
38474 is_stamped(right),
38475 "the count walk must build once instead of re-walking per page"
38476 );
38477
38478 let one_page = PlanNode::Scan(var_scan(Some("site"), "http://ex/hasSite", Some("s"), 1));
38481 let mut one_page_arm = var_scan(Some("s"), "http://ex/kind", Some("k"), 10);
38482 one_page_arm.domain_counts = Some(DomainScanKind::PredicateDomain);
38483 let mut tree = join(one_page, PlanNode::Scan(one_page_arm), 1);
38484 restamp_fetch_once(&mut tree, None, None, false);
38485 let PlanNode::Join { right, .. } = &tree else {
38486 panic!("expected Join, got {tree:?}")
38487 };
38488 assert!(
38489 !is_stamped(right),
38490 "a single-page driver is not force-built"
38491 );
38492 }
38493
38494 #[test]
38498 fn a_count_walk_prices_as_one_build_on_more_than_one_page() {
38499 use super::{SeatCost, seat_cost_arithmetic};
38500
38501 let one_page = seat_cost_arithmetic(
38505 1,
38506 1_000,
38507 false,
38508 1,
38509 &[(false, 10, 1_000, 1_000)],
38510 true,
38511 true,
38512 true,
38513 true,
38514 true,
38515 None,
38516 );
38517 assert!(
38518 one_page.rows < 1_000,
38519 "a single page keeps the priced road, not the build: {one_page:?}"
38520 );
38521
38522 let many_pages = seat_cost_arithmetic(
38523 100_000,
38524 1_000,
38525 false,
38526 10,
38527 &[(false, 10, 1_000, 1_000)],
38528 true,
38529 true,
38530 true,
38531 true,
38532 true,
38533 None,
38534 );
38535 assert_eq!(
38536 many_pages,
38537 SeatCost {
38538 rows: 100_000 + 1_000,
38539 seeks: 0
38540 },
38541 "the build is the only road for a multi-page count walk"
38542 );
38543 }
38544}
38545
38546#[cfg(test)]
38547mod pinned_conjunct_tests {
38548 use super::*;
38549 use oxrdf::NamedNode;
38550 use spargebra::algebra::Function;
38551
38552 fn var(name: &str) -> Variable {
38553 Variable::new_unchecked(name)
38554 }
38555
38556 fn triple(subject: &str, predicate: &str, object: &str) -> TriplePattern {
38557 TriplePattern {
38558 subject: TermPattern::Variable(var(subject)),
38559 predicate: NamedNodePattern::NamedNode(NamedNode::new_unchecked(predicate)),
38560 object: TermPattern::Variable(var(object)),
38561 }
38562 }
38563
38564 fn bgp(triple: TriplePattern) -> GraphPattern {
38565 GraphPattern::Bgp {
38566 patterns: vec![triple],
38567 }
38568 }
38569
38570 fn search(variable: &str) -> Expression {
38573 Expression::FunctionCall(
38574 Function::Custom(NamedNode::new_unchecked("http://ex/search")),
38575 vec![Expression::Variable(var(variable))],
38576 )
38577 }
38578
38579 fn is_search(expression: &Expression) -> bool {
38580 matches!(
38581 expression,
38582 Expression::FunctionCall(Function::Custom(iri), _)
38583 if iri.as_str() == "http://ex/search"
38584 )
38585 }
38586
38587 fn filtered(expression: Expression, inner: GraphPattern) -> GraphPattern {
38588 GraphPattern::Filter {
38589 expr: expression,
38590 inner: Box::new(inner),
38591 }
38592 }
38593
38594 fn overlap(left: &str, right: &str) -> Expression {
38597 Expression::FunctionCall(
38598 Function::Custom(NamedNode::new_unchecked("http://ex/overlap")),
38599 vec![
38600 Expression::Variable(var(left)),
38601 Expression::Variable(var(right)),
38602 ],
38603 )
38604 }
38605
38606 fn is_overlap(expression: &Expression) -> bool {
38607 matches!(
38608 expression,
38609 Expression::FunctionCall(Function::Custom(iri), _)
38610 if iri.as_str() == "http://ex/overlap"
38611 )
38612 }
38613
38614 fn optimized(pattern: GraphPattern) -> GraphPattern {
38618 optimized_with(pattern, &is_search)
38619 }
38620
38621 fn optimized_with(
38622 pattern: GraphPattern,
38623 pins_predicate: &dyn Fn(&Expression) -> bool,
38624 ) -> GraphPattern {
38625 let mut pins = Vec::new();
38626 let pinned = pin_candidate_conjuncts(pattern, pins_predicate, &mut pins);
38627 let optimized = optimize_preserving_graph(pinned);
38628 let mut seen = vec![0u32; pins.len()];
38629 let mut stripped = vec![0u32; pins.len()];
38630 let restored = restore_and_sink_conjuncts(optimized, &pins, &mut seen);
38631 let restored = strip_pin_extends(restored, &pins, &mut stripped);
38632 for (conjuncts, anchors) in seen.iter().zip(stripped.iter()) {
38633 assert_eq!(*conjuncts, 1, "a pinned conjunct was lost or duplicated");
38634 assert_eq!(*anchors, 1, "a pin anchor was lost or duplicated");
38635 }
38636 restored
38637 }
38638
38639 fn child_count(pattern: &GraphPattern) -> usize {
38640 match pattern {
38641 GraphPattern::Join { .. }
38642 | GraphPattern::LeftJoin { .. }
38643 | GraphPattern::Union { .. }
38644 | GraphPattern::Minus { .. } => 2,
38645 GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Values { .. } => 0,
38646 _ => 1,
38647 }
38648 }
38649
38650 fn walk(
38651 pattern: &GraphPattern,
38652 path: &mut Vec<usize>,
38653 f: &mut dyn FnMut(&GraphPattern, &[usize]),
38654 ) {
38655 f(pattern, path);
38656 for index in 0..child_count(pattern) {
38657 path.push(index);
38658 walk(algebra_child(pattern, index), path, f);
38659 path.pop();
38660 }
38661 }
38662
38663 fn search_filters(pattern: &GraphPattern) -> Vec<Vec<usize>> {
38664 search_filters_of(pattern, &is_search)
38665 }
38666
38667 fn search_filters_of(
38668 pattern: &GraphPattern,
38669 predicate: &dyn Fn(&Expression) -> bool,
38670 ) -> Vec<Vec<usize>> {
38671 let mut out = Vec::new();
38672 walk(pattern, &mut Vec::new(), &mut |node, path| {
38673 if let GraphPattern::Filter { expr, .. } = node
38674 && flatten_and(expr).iter().any(predicate)
38675 {
38676 out.push(path.to_vec());
38677 }
38678 });
38679 out
38680 }
38681
38682 fn node_at<'a>(pattern: &'a GraphPattern, path: &[usize]) -> &'a GraphPattern {
38683 let mut node = pattern;
38684 for index in path {
38685 node = algebra_child(node, *index);
38686 }
38687 node
38688 }
38689
38690 fn filter_inner<'a>(pattern: &'a GraphPattern, path: &[usize]) -> &'a GraphPattern {
38691 match node_at(pattern, path) {
38692 GraphPattern::Filter { inner, .. } => inner,
38693 other => panic!("expected a FILTER at {path:?}, got {other:?}"),
38694 }
38695 }
38696
38697 #[test]
38698 fn a_candidate_producer_is_not_cloned_into_union_arms() {
38699 let pattern = filtered(
38700 search("r"),
38701 GraphPattern::Join {
38702 left: Box::new(bgp(triple("r", "http://ex/kind", "k"))),
38703 right: Box::new(GraphPattern::Union {
38704 left: Box::new(bgp(triple("r", "http://ex/a", "v"))),
38705 right: Box::new(GraphPattern::Union {
38706 left: Box::new(bgp(triple("r", "http://ex/b", "v"))),
38707 right: Box::new(bgp(triple("r", "http://ex/c", "v"))),
38708 }),
38709 }),
38710 },
38711 );
38712 let unpinned = optimize_preserving_graph(pattern.clone());
38713 assert!(
38714 search_filters(&unpinned).len() > 1,
38715 "the unpinned filter should be cloned by the algebra optimizer, got {:?}",
38716 search_filters(&unpinned)
38717 );
38718 let pinned = optimized(pattern);
38719 assert_eq!(
38720 search_filters(&pinned).len(),
38721 1,
38722 "a pinned candidate producer must appear exactly once"
38723 );
38724 }
38725
38726 #[test]
38727 fn a_single_site_conjunct_sinks_next_to_its_binding_pattern() {
38728 let pattern = filtered(
38732 search("w"),
38733 GraphPattern::Join {
38734 left: Box::new(bgp(triple("r", "http://ex/geometry", "g"))),
38735 right: Box::new(GraphPattern::Path {
38736 subject: TermPattern::Variable(var("g")),
38737 path: PropertyPathExpression::NamedNode(NamedNode::new_unchecked(
38738 "http://ex/wkt",
38739 )),
38740 object: TermPattern::Variable(var("w")),
38741 }),
38742 },
38743 );
38744 let optimized = optimized(pattern);
38745 let filters = search_filters(&optimized);
38746 assert_eq!(filters.len(), 1);
38747 match filter_inner(&optimized, &filters[0]) {
38748 GraphPattern::Path { object, .. } => assert_eq!(
38749 *object,
38750 TermPattern::Variable(var("w")),
38751 "the filter should sit directly above the pattern that binds ?w"
38752 ),
38753 other => panic!("expected the filter above the ?g :wkt ?w path, got {other:?}"),
38754 }
38755 }
38756
38757 #[test]
38758 fn a_conjunct_bound_in_one_union_arm_stays_above_the_union() {
38759 let pattern = filtered(
38760 search("v"),
38761 GraphPattern::Union {
38762 left: Box::new(bgp(triple("v", "http://ex/a", "x"))),
38763 right: Box::new(bgp(triple("s", "http://ex/b", "y"))),
38764 },
38765 );
38766 let optimized = optimized(pattern);
38767 let filters = search_filters(&optimized);
38768 assert_eq!(filters.len(), 1);
38769 assert!(
38770 matches!(
38771 filter_inner(&optimized, &filters[0]),
38772 GraphPattern::Union { .. }
38773 ),
38774 "sinking into the binding arm would let the other arm's rows escape the filter"
38775 );
38776 }
38777
38778 #[test]
38779 fn a_conjunct_bound_in_every_union_arm_sinks_above_the_union() {
38780 let pattern = filtered(
38781 search("v"),
38782 GraphPattern::Join {
38783 left: Box::new(bgp(triple("r", "http://ex/kind", "k"))),
38784 right: Box::new(GraphPattern::Union {
38785 left: Box::new(bgp(triple("v", "http://ex/a", "x"))),
38786 right: Box::new(bgp(triple("v", "http://ex/b", "y"))),
38787 }),
38788 },
38789 );
38790 let optimized = optimized(pattern);
38791 let filters = search_filters(&optimized);
38792 assert_eq!(filters.len(), 1);
38793 assert!(
38794 matches!(
38795 filter_inner(&optimized, &filters[0]),
38796 GraphPattern::Union { .. }
38797 ),
38798 "the union of every arm's bindings is the lowest single covering point"
38799 );
38800 }
38801
38802 #[test]
38803 fn a_slice_boundary_keeps_the_conjunct_above_it() {
38804 let pattern = filtered(
38805 search("r"),
38806 GraphPattern::Slice {
38807 inner: Box::new(GraphPattern::Join {
38808 left: Box::new(bgp(triple("r", "http://ex/a", "v"))),
38809 right: Box::new(bgp(triple("r", "http://ex/b", "v"))),
38810 }),
38811 start: 0,
38812 length: Some(10),
38813 },
38814 );
38815 let optimized = optimized(pattern);
38816 let filters = search_filters(&optimized);
38817 assert_eq!(filters.len(), 1);
38818 assert!(
38819 matches!(
38820 filter_inner(&optimized, &filters[0]),
38821 GraphPattern::Slice { .. }
38822 ),
38823 "a filter below a slice would select different rows"
38824 );
38825 }
38826
38827 #[test]
38828 fn a_projected_variable_lets_the_conjunct_sink_into_the_subselect() {
38829 let pattern = filtered(
38830 search("r"),
38831 GraphPattern::Project {
38832 inner: Box::new(bgp(triple("r", "http://ex/a", "v"))),
38833 variables: vec![var("r"), var("v")],
38834 },
38835 );
38836 let optimized = optimized(pattern);
38837 let filters = search_filters(&optimized);
38838 assert_eq!(filters.len(), 1);
38839 let GraphPattern::Project { inner, .. } = &optimized else {
38840 panic!("expected the projection to survive, got {optimized:?}");
38841 };
38842 assert!(
38843 matches!(inner.as_ref(), GraphPattern::Filter { .. }),
38844 "a filter reading only projected variables may cross the projection"
38845 );
38846 }
38847
38848 #[test]
38849 fn a_hidden_variable_keeps_the_conjunct_above_the_subselect() {
38850 let pattern = filtered(
38851 search("w"),
38852 GraphPattern::Project {
38853 inner: Box::new(bgp(triple("r", "http://ex/a", "w"))),
38854 variables: vec![var("r")],
38855 },
38856 );
38857 let optimized = optimized(pattern);
38858 let filters = search_filters(&optimized);
38859 assert_eq!(filters.len(), 1);
38860 assert!(
38861 matches!(
38862 filter_inner(&optimized, &filters[0]),
38863 GraphPattern::Project { .. }
38864 ),
38865 "a filter may not cross a projection that hides a variable it reads"
38866 );
38867 }
38868
38869 #[test]
38870 fn graph_bindings_are_sites_but_the_sink_never_enters() {
38871 use spargebra::term::NamedNodePattern;
38872 let graph = GraphPattern::Graph {
38873 name: NamedNodePattern::NamedNode(NamedNode::new_unchecked("http://ex/g")),
38874 inner: Box::new(bgp(triple("s", "http://ex/label", "lit"))),
38875 };
38876 let mut sites = Vec::new();
38877 collect_binding_sites(&graph, &[var("lit")], &mut Vec::new(), &mut sites);
38878 assert_eq!(
38879 sites,
38880 vec![vec![0]],
38881 "a GRAPH's bindings flow out to the enclosing solution, so the site exists"
38882 );
38883 let optimized = optimized(filtered(search("lit"), graph));
38884 let filters = search_filters(&optimized);
38885 assert_eq!(filters.len(), 1);
38886 assert!(
38887 matches!(
38888 filter_inner(&optimized, &filters[0]),
38889 GraphPattern::Graph { .. }
38890 ),
38891 "the filter must stay above the GRAPH: entering it would change its graph scope"
38892 );
38893 }
38894
38895 #[test]
38896 fn optional_right_side_bindings_are_sites_but_not_sink_targets() {
38897 let left_join = GraphPattern::LeftJoin {
38898 left: Box::new(bgp(triple("s", "http://ex/kind", "k"))),
38899 right: Box::new(bgp(triple("s", "http://ex/other", "o"))),
38900 expression: None,
38901 };
38902 let mut sites = Vec::new();
38903 collect_binding_sites(&left_join, &[var("o")], &mut Vec::new(), &mut sites);
38904 assert_eq!(
38905 sites,
38906 vec![vec![1]],
38907 "an OPTIONAL's right side binds ?o for matching rows"
38908 );
38909 let optimized = optimized(filtered(search("o"), left_join));
38910 let filters = search_filters(&optimized);
38911 assert_eq!(filters.len(), 1);
38912 assert!(
38913 matches!(
38914 filter_inner(&optimized, &filters[0]),
38915 GraphPattern::LeftJoin { .. }
38916 ),
38917 "the filter must stay above the LeftJoin: inside the right side a miss row would survive"
38918 );
38919 }
38920
38921 fn is_iri_check(expression: &Expression) -> bool {
38922 matches!(expression, Expression::FunctionCall(Function::IsIri, _))
38923 }
38924
38925 fn count_conjuncts(pattern: &GraphPattern, predicate: &dyn Fn(&Expression) -> bool) -> usize {
38926 let mut count = 0;
38927 walk(pattern, &mut Vec::new(), &mut |node, _| {
38928 if let GraphPattern::Filter { expr, .. } = node {
38929 count += flatten_and(expr).iter().filter(|c| predicate(c)).count();
38930 }
38931 });
38932 count
38933 }
38934
38935 #[test]
38936 fn a_minus_left_variable_sinks_into_the_left_but_a_right_one_does_not() {
38937 let minus = || GraphPattern::Minus {
38938 left: Box::new(bgp(triple("s", "http://ex/kind", "k"))),
38939 right: Box::new(bgp(triple("s", "http://ex/other", "o"))),
38940 };
38941 let plan = optimized(filtered(search("k"), minus()));
38943 let filters = search_filters(&plan);
38944 assert_eq!(filters.len(), 1);
38945 match filter_inner(&plan, &filters[0]) {
38946 GraphPattern::Bgp { patterns } => assert_eq!(
38947 patterns[0].object,
38948 TermPattern::Variable(var("k")),
38949 "the filter should sit above the scan that binds ?k"
38950 ),
38951 other => panic!("expected the filter above the left scan, got {other:?}"),
38952 }
38953 let plan = optimized(filtered(search("o"), minus()));
38955 let filters = search_filters(&plan);
38956 assert_eq!(filters.len(), 1);
38957 assert!(
38958 matches!(filter_inner(&plan, &filters[0]), GraphPattern::Minus { .. }),
38959 "a MINUS right side is not a result binding, so it is not a sink target"
38960 );
38961 }
38962
38963 #[test]
38964 fn a_group_key_is_a_sink_barrier_and_a_non_key_has_no_site() {
38965 let group = |keys: Vec<Variable>| GraphPattern::Group {
38966 inner: Box::new(bgp(triple("r", "http://ex/p", "v"))),
38967 variables: keys,
38968 aggregates: vec![],
38969 };
38970 let plan = optimized(filtered(search("v"), group(vec![var("r")])));
38972 let filters = search_filters(&plan);
38973 assert_eq!(filters.len(), 1);
38974 assert!(
38975 matches!(filter_inner(&plan, &filters[0]), GraphPattern::Group { .. }),
38976 "a non-key variable has no site above the Group"
38977 );
38978 let plan = optimized(filtered(search("r"), group(vec![var("r")])));
38981 let filters = search_filters(&plan);
38982 assert_eq!(filters.len(), 1);
38983 assert!(
38984 matches!(filter_inner(&plan, &filters[0]), GraphPattern::Group { .. }),
38985 "the filter must not cross a Group, even for a key"
38986 );
38987 }
38988
38989 #[test]
38990 fn an_extend_that_defines_the_variable_is_not_crossed() {
38991 let extend = |variable: &str| GraphPattern::Extend {
38992 inner: Box::new(bgp(triple("r", "http://ex/p", "w"))),
38993 variable: var(variable),
38994 expression: Expression::Literal(oxrdf::Literal::from("x")),
38995 };
38996 let plan = optimized(filtered(search("v"), extend("v")));
38998 let filters = search_filters(&plan);
38999 assert_eq!(filters.len(), 1);
39000 assert!(
39001 matches!(
39002 filter_inner(&plan, &filters[0]),
39003 GraphPattern::Extend { .. }
39004 ),
39005 "a variable defined by an Extend cannot be evaluated below it"
39006 );
39007 let plan = optimized(filtered(search("w"), extend("v")));
39009 let filters = search_filters(&plan);
39010 assert_eq!(filters.len(), 1);
39011 match filter_inner(&plan, &filters[0]) {
39012 GraphPattern::Bgp { patterns } => assert_eq!(
39013 patterns[0].object,
39014 TermPattern::Variable(var("w")),
39015 "the filter should sit above the scan that binds ?w"
39016 ),
39017 other => panic!("expected the filter inside the Extend, got {other:?}"),
39018 }
39019 }
39020
39021 #[test]
39022 fn two_pins_in_one_filter_both_restore_and_sink() {
39023 let pattern = filtered(
39024 Expression::And(Box::new(search("a")), Box::new(search("b"))),
39025 bgp(triple("a", "http://ex/link", "b")),
39026 );
39027 let optimized = optimized(pattern);
39028 let filters = search_filters(&optimized);
39029 assert_eq!(filters.len(), 2, "both pinned conjuncts are restored");
39030 let deepest = filters
39031 .iter()
39032 .max_by_key(|path| path.len())
39033 .expect("two filters");
39034 assert!(
39035 matches!(filter_inner(&optimized, deepest), GraphPattern::Bgp { .. }),
39036 "both conjuncts sink to the pattern that binds their variables"
39037 );
39038 }
39039
39040 #[test]
39041 fn a_pinned_conjunct_leaves_its_unpinned_sibling_where_the_optimizer_put_it() {
39042 let isiri =
39043 || Expression::FunctionCall(Function::IsIri, vec![Expression::Variable(var("r"))]);
39044 let both = || {
39045 filtered(
39046 Expression::And(Box::new(search("r")), Box::new(isiri())),
39047 GraphPattern::Join {
39048 left: Box::new(bgp(triple("r", "http://ex/kind", "k"))),
39049 right: Box::new(bgp(triple("r", "http://ex/other", "o"))),
39050 },
39051 )
39052 };
39053 let reference = optimize_preserving_graph(both());
39056 let expected = count_conjuncts(&reference, &is_iri_check);
39057 let optimized = optimized(both());
39058 assert_eq!(count_conjuncts(&optimized, &is_iri_check), expected);
39059 let filters = search_filters(&optimized);
39060 assert_eq!(filters.len(), 1);
39061 assert!(
39062 matches!(
39063 filter_inner(&optimized, &filters[0]),
39064 GraphPattern::Join { .. }
39065 ),
39066 "?r is bound in both branches, so the producer stays above the join"
39067 );
39068 }
39069
39070 #[test]
39071 fn a_ground_producer_keeps_its_join_variable() {
39072 let inner = PlanNode::Values(ValuesOp {
39073 variables: vec![var("g")],
39074 rows: vec![vec![Some(EncodedTerm::BooleanLiteral(
39075 oxsdatatypes::Boolean::from(true),
39076 ))]],
39077 strings: Vec::new(),
39078 blobs: Vec::new(),
39079 });
39080 let inner_vars = inner.output_vars();
39081 let mut conjunct = search("g");
39086 ground_residual_conjunct(&mut conjunct, &inner, &inner_vars, &|_| true);
39087 assert_eq!(
39088 conjunct,
39089 search("g"),
39090 "the join variable must survive grounding"
39091 );
39092 let mut conjunct = search("g");
39094 ground_residual_conjunct(&mut conjunct, &inner, &inner_vars, &|_| false);
39095 assert!(
39096 !variables_in_expression(&conjunct).contains(&var("g")),
39097 "an ordinary conjunct still grounds: {conjunct:?}"
39098 );
39099 }
39100
39101 #[test]
39102 fn the_grounding_guard_tests_the_source_shape() {
39103 let inner = PlanNode::Values(ValuesOp {
39109 variables: vec![var("g")],
39110 rows: vec![vec![Some(EncodedTerm::BooleanLiteral(
39111 oxsdatatypes::Boolean::from(true),
39112 ))]],
39113 strings: Vec::new(),
39114 blobs: Vec::new(),
39115 });
39116 let inner_vars = inner.output_vars();
39117 let keeps_only_with_a_variable =
39118 |expression: &Expression| !variables_in_expression(expression).is_empty();
39119 let mut conjunct = search("g");
39120 ground_residual_conjunct(
39121 &mut conjunct,
39122 &inner,
39123 &inner_vars,
39124 &keeps_only_with_a_variable,
39125 );
39126 assert_eq!(
39127 conjunct,
39128 search("g"),
39129 "the guard must ask about the source expression"
39130 );
39131 }
39132
39133 #[test]
39134 fn a_lost_pin_is_counted_not_ignored() {
39135 let pattern = filtered(search("r"), bgp(triple("r", "http://ex/a", "v")));
39136 let mut pins = Vec::new();
39137 let pinned = pin_candidate_conjuncts(pattern.clone(), &is_search, &mut pins);
39138 assert_eq!(pins.len(), 1);
39139 assert!(matches!(
39140 &pinned,
39141 GraphPattern::Filter { expr, .. } if pinned_ghost_variable_of(expr).is_some()
39142 ));
39143 let mut seen = vec![0u32; pins.len()];
39146 let _ = restore_and_sink_conjuncts(pattern, &pins, &mut seen);
39147 assert_eq!(seen, vec![0]);
39148 }
39149
39150 #[test]
39151 fn a_conjunct_bound_only_in_an_optionals_right_side_is_not_sunk() {
39152 let pattern = filtered(
39157 overlap("g", "o"),
39158 GraphPattern::Join {
39159 left: Box::new(bgp(triple("s", "http://ex/geometry", "g"))),
39160 right: Box::new(GraphPattern::LeftJoin {
39161 left: Box::new(bgp(triple("s", "http://ex/kind", "k"))),
39162 right: Box::new(bgp(triple("s", "http://ex/other", "o"))),
39163 expression: None,
39164 }),
39165 },
39166 );
39167 let optimized = optimized_with(pattern, &is_overlap);
39168 let filters = search_filters_of(&optimized, &is_overlap);
39169 assert_eq!(filters.len(), 1);
39170 assert!(
39171 matches!(
39172 filter_inner(&optimized, &filters[0]),
39173 GraphPattern::Join { .. }
39174 ),
39175 "the filter must stay above the join, not sink under the LeftJoin"
39176 );
39177 }
39178
39179 #[test]
39180 fn a_conjunct_bound_only_behind_a_subselect_is_not_sunk() {
39181 let pattern = filtered(
39185 overlap("g", "o"),
39186 GraphPattern::Join {
39187 left: Box::new(GraphPattern::Project {
39188 inner: Box::new(bgp(triple("s", "http://ex/geometry", "g"))),
39189 variables: vec![var("s"), var("g")],
39190 }),
39191 right: Box::new(bgp(triple("s2", "http://ex/other", "o"))),
39192 },
39193 );
39194 let optimized = optimized_with(pattern, &is_overlap);
39195 let filters = search_filters_of(&optimized, &is_overlap);
39196 assert_eq!(filters.len(), 1);
39197 assert!(
39198 matches!(
39199 filter_inner(&optimized, &filters[0]),
39200 GraphPattern::Join { .. }
39201 ),
39202 "the filter must stay above the join that binds both variables"
39203 );
39204 }
39205
39206 #[test]
39207 fn a_provably_empty_scope_absorbs_its_pin() {
39208 let pattern = filtered(
39212 search("x"),
39213 GraphPattern::Values {
39214 variables: vec![var("x")],
39215 bindings: vec![],
39216 },
39217 );
39218 let mut pins = Vec::new();
39219 let pinned = pin_candidate_conjuncts(pattern, &is_search, &mut pins);
39220 let optimized = optimize_preserving_graph(pinned);
39221 assert!(
39222 pattern_is_surely_empty(&optimized),
39223 "the optimizer proves the scope empty: {optimized:?}"
39224 );
39225 let mut seen = vec![0u32; pins.len()];
39226 let mut anchors = vec![0u32; pins.len()];
39227 let restored = restore_and_sink_conjuncts(optimized, &pins, &mut seen);
39228 let restored = strip_pin_extends(restored, &pins, &mut anchors);
39229 assert_eq!(seen, vec![0]);
39230 assert_eq!(anchors, vec![0]);
39231 check_pin_survival(&restored, &pins, &seen, &anchors)
39232 .expect("an optimizer-proved empty scope absorbs its pin");
39233 }
39234
39235 #[test]
39236 fn a_filter_false_scope_absorbs_its_pin() {
39237 use oxrdf::Literal;
39238 let pattern = filtered(
39243 Expression::And(
39244 Box::new(Expression::Literal(Literal::from(false))),
39245 Box::new(search("r")),
39246 ),
39247 bgp(triple("r", "http://ex/a", "v")),
39248 );
39249 let mut pins = Vec::new();
39250 let pinned = pin_candidate_conjuncts(pattern, &is_search, &mut pins);
39251 let optimized = optimize_preserving_graph(pinned);
39252 let folded = crate::expr::fold_constants(optimized, &crate::expr::ExprEvalEnv::for_tests());
39253 assert!(
39254 pattern_is_surely_empty(&folded),
39255 "the fold proves the scope empty: {folded:?}"
39256 );
39257 let mut seen = vec![0u32; pins.len()];
39258 let mut anchors = vec![0u32; pins.len()];
39259 let restored = restore_and_sink_conjuncts(folded, &pins, &mut seen);
39260 let restored = strip_pin_extends(restored, &pins, &mut anchors);
39261 assert_eq!(seen, vec![0], "the fold took the pinned conjunct with it");
39262 assert_eq!(anchors, vec![0], "the fold took the anchor with it");
39263 check_pin_survival(&restored, &pins, &seen, &anchors)
39264 .expect("boolean folding absorbs the pin with the empty table");
39265 }
39266
39267 #[test]
39268 fn surely_empty_covers_the_shapes_the_optimizer_collapses() {
39269 let empty = GraphPattern::Values {
39270 variables: vec![],
39271 bindings: vec![],
39272 };
39273 let non_empty = bgp(triple("s", "http://ex/p", "o"));
39274 assert!(pattern_is_surely_empty(&empty));
39275 assert!(!pattern_is_surely_empty(&non_empty));
39276 assert!(!pattern_is_surely_empty(&GraphPattern::Bgp {
39278 patterns: vec![]
39279 }));
39280 assert!(pattern_is_surely_empty(&GraphPattern::Join {
39282 left: Box::new(empty.clone()),
39283 right: Box::new(non_empty.clone()),
39284 }));
39285 assert!(!pattern_is_surely_empty(&GraphPattern::Union {
39286 left: Box::new(empty.clone()),
39287 right: Box::new(non_empty.clone()),
39288 }));
39289 assert!(pattern_is_surely_empty(&GraphPattern::LeftJoin {
39291 left: Box::new(empty.clone()),
39292 right: Box::new(non_empty.clone()),
39293 expression: None,
39294 }));
39295 assert!(!pattern_is_surely_empty(&GraphPattern::Group {
39297 inner: Box::new(empty.clone()),
39298 variables: vec![],
39299 aggregates: vec![],
39300 }));
39301 assert!(pattern_is_surely_empty(&GraphPattern::Group {
39302 inner: Box::new(empty.clone()),
39303 variables: vec![var("k")],
39304 aggregates: vec![],
39305 }));
39306 assert!(pattern_is_surely_empty(&GraphPattern::Slice {
39308 inner: Box::new(non_empty),
39309 start: 0,
39310 length: Some(0),
39311 }));
39312 }
39313
39314 #[test]
39315 fn a_lost_pin_is_accepted_only_for_a_proved_empty_scope() {
39316 let pins = vec![PinnedConjunct {
39317 ghost: var("__waratah_pin_test"),
39318 expression: search("r"),
39319 }];
39320 let empty = GraphPattern::Values {
39321 variables: vec![],
39322 bindings: vec![],
39323 };
39324 check_pin_survival(&empty, &pins, &[0], &[0]).expect("an empty scope absorbs its pin");
39325 assert!(
39326 check_pin_survival(&bgp(triple("r", "http://ex/a", "v")), &pins, &[0], &[0]).is_err(),
39327 "a lost pin outside a proved-empty scope must fail"
39328 );
39329 assert!(
39330 check_pin_survival(&empty, &pins, &[1], &[0]).is_err(),
39331 "a surviving conjunct with a lost anchor must fail"
39332 );
39333 assert!(
39334 check_pin_survival(&empty, &pins, &[2], &[1]).is_err(),
39335 "a duplicated conjunct must fail"
39336 );
39337 }
39338}
39339
39340#[cfg(test)]
39341mod semi_admission_tests {
39342 use std::collections::HashMap;
39357 use std::sync::{Arc, Mutex};
39358
39359 use super::*;
39360 use crate::context::{LogLevel, LogSink};
39361 use crate::liveness::{annotate_liveness, join_semi_context};
39362 use crate::query::fixtures::test_support::{join, scan, var};
39363 use waratah_storage::NamedNode;
39364
39365 fn profile(rows: u64, driver_subjects: u128, probe_subjects: u128) -> StatsProfile {
39371 let mut profile = StatsProfile::default();
39372 for (predicate, subjects) in [
39373 ("http://ex/datasetKind", driver_subjects),
39374 ("http://ex/kindA", driver_subjects),
39375 ("http://ex/kindB", driver_subjects),
39376 ("http://ex/name", probe_subjects),
39377 ("http://ex/abstract", probe_subjects),
39378 ] {
39379 let mut subject_hll = waratah_stats::HyperLogLog::default_params();
39380 for i in 0..subjects {
39381 subject_hll.add(i);
39382 }
39383 let hash = StrHash::new(predicate);
39384 profile.subjects_per_predicate.insert(hash, subject_hll);
39385 profile.predicate_counts.insert(hash, rows);
39386 }
39387 profile.total_puts = rows.saturating_mul(5);
39388 profile
39389 }
39390
39391 fn record_scan() -> PlanNode {
39392 let mut scan = scan("r", "http://ex/datasetKind", "dim", 1_000_000);
39393 scan.object = None;
39394 scan.pattern.object = Some(EncodedTerm::from(
39395 &NamedNode::new("http://ex/record").unwrap(),
39396 ));
39397 PlanNode::Scan(scan)
39398 }
39399
39400 fn literal_subtree() -> PlanNode {
39401 let left = scan("r", "http://ex/name", "lit", 1_000_000);
39402 let right = scan("r", "http://ex/abstract", "lit", 1_000_000);
39403 PlanNode::Filter {
39404 inner: Box::new(PlanNode::Union {
39405 left: Box::new(PlanNode::Scan(left)),
39406 right: Box::new(PlanNode::Scan(right)),
39407 }),
39408 early: None,
39409 residual: Some(Expression::Variable(var("lit"))),
39410 exists: Vec::new(),
39411 one_to_one: false,
39412 }
39413 }
39414
39415 fn mark_first_scan_specialized(node: &mut PlanNode) -> bool {
39419 match node {
39420 PlanNode::Scan(scan) => {
39421 scan.domain_scan = Some(DomainScanKind::PredicateSubjects);
39422 true
39423 }
39424 PlanNode::Join { left, right, .. }
39425 | PlanNode::LeftJoin { left, right, .. }
39426 | PlanNode::Union { left, right } => {
39427 mark_first_scan_specialized(left) || mark_first_scan_specialized(right)
39428 }
39429 PlanNode::Filter { inner, .. }
39430 | PlanNode::Extend { inner, .. }
39431 | PlanNode::Slice { inner, .. }
39432 | PlanNode::Distinct { inner, .. }
39433 | PlanNode::Sort { inner, .. }
39434 | PlanNode::Group { inner, .. }
39435 | PlanNode::JoinGraphVar { inner, .. } => mark_first_scan_specialized(inner),
39436 _ => false,
39437 }
39438 }
39439
39440 fn ground_record_scan(predicate: &str) -> PlanNode {
39443 let mut scan = scan("r", predicate, "lit", 1_000_000);
39444 scan.object = None;
39445 scan.pattern.object = Some(EncodedTerm::from(
39446 &NamedNode::new("http://ex/record").unwrap(),
39447 ));
39448 PlanNode::Scan(scan)
39449 }
39450
39451 fn semi_top_scan_right(left_rows: u64) -> PlanNode {
39453 let facet = PlanNode::Union {
39454 left: Box::new(PlanNode::Scan(scan(
39455 "r",
39456 "http://ex/kindA",
39457 "dim",
39458 1_000_000,
39459 ))),
39460 right: Box::new(PlanNode::Scan(scan(
39461 "r",
39462 "http://ex/kindB",
39463 "dim",
39464 1_000_000,
39465 ))),
39466 };
39467 let left = join(facet, record_scan(), &["r"], &[200_000], left_rows);
39468 join(
39469 left,
39470 ground_record_scan("http://ex/abstract"),
39471 &["r"],
39472 &[200_000],
39473 left_rows,
39474 )
39475 }
39476
39477 fn semi_top_scan_right_payload(left_rows: u64) -> PlanNode {
39480 let facet = PlanNode::Union {
39481 left: Box::new(PlanNode::Scan(scan(
39482 "r",
39483 "http://ex/kindA",
39484 "dim",
39485 1_000_000,
39486 ))),
39487 right: Box::new(PlanNode::Scan(scan(
39488 "r",
39489 "http://ex/kindB",
39490 "dim",
39491 1_000_000,
39492 ))),
39493 };
39494 let left = join(facet, record_scan(), &["r"], &[200_000], left_rows);
39495 join(
39496 left,
39497 PlanNode::Scan(scan("r", "http://ex/abstract", "lit", 1_000_000)),
39498 &["r"],
39499 &[200_000],
39500 left_rows,
39501 )
39502 }
39503
39504 fn semi_top(left_rows: u64, multi_key: bool) -> PlanNode {
39505 let facet = PlanNode::Union {
39506 left: Box::new(PlanNode::Scan(scan(
39507 "r",
39508 "http://ex/kindA",
39509 "dim",
39510 1_000_000,
39511 ))),
39512 right: Box::new(PlanNode::Scan(scan(
39513 "r",
39514 "http://ex/kindB",
39515 "dim",
39516 1_000_000,
39517 ))),
39518 };
39519 let left = join(facet, record_scan(), &["r"], &[200_000], left_rows);
39520 let keys: &[&str] = if multi_key { &["r", "dim"] } else { &["r"] };
39521 join(left, literal_subtree(), keys, &[200_000], left_rows)
39522 }
39523
39524 fn outer_join(node: &PlanNode) -> &PlanNode {
39526 match node {
39527 PlanNode::Slice { inner, .. } => outer_join(inner),
39528 PlanNode::Filter { exists, .. } => outer_join(&exists[0].body),
39529 PlanNode::Group { inner, .. } => outer_join(inner),
39530 PlanNode::Join { .. } => node,
39531 other => panic!("unexpected fixture node: {other:?}"),
39532 }
39533 }
39534
39535 fn outer_join_mut(node: &mut PlanNode) -> &mut PlanNode {
39536 match node {
39537 PlanNode::Slice { inner, .. } => outer_join_mut(inner.as_mut()),
39538 PlanNode::Filter { exists, .. } => outer_join_mut(exists[0].body.as_mut()),
39539 PlanNode::Group { inner, .. } => outer_join_mut(inner.as_mut()),
39540 PlanNode::Join { .. } => node,
39541 other => panic!("unexpected fixture node: {other:?}"),
39542 }
39543 }
39544
39545 fn semi_group(top: PlanNode, aggregate: AggregateExpression, group_vars: &[&str]) -> PlanNode {
39546 PlanNode::Group {
39547 inner: Box::new(top),
39548 variables: group_vars.iter().map(|name| var(name)).collect(),
39549 aggregates: vec![(var("n"), aggregate)],
39550 const_strings: Vec::new(),
39551 const_blobs: Vec::new(),
39552 }
39553 }
39554
39555 fn semi_shape(
39556 aggregate: AggregateExpression,
39557 group_vars: &[&str],
39558 left_rows: u64,
39559 multi_key: bool,
39560 ) -> PlanNode {
39561 semi_group(semi_top(left_rows, multi_key), aggregate, group_vars)
39562 }
39563
39564 fn count_distinct() -> AggregateExpression {
39565 AggregateExpression::FunctionCall {
39566 name: AggregateFunction::Count,
39567 expr: Expression::Variable(var("r")),
39568 distinct: true,
39569 }
39570 }
39571
39572 fn count_rows() -> AggregateExpression {
39573 AggregateExpression::FunctionCall {
39574 name: AggregateFunction::Count,
39575 expr: Expression::Variable(var("r")),
39576 distinct: false,
39577 }
39578 }
39579
39580 fn count_star() -> AggregateExpression {
39581 AggregateExpression::CountSolutions { distinct: false }
39582 }
39583
39584 fn admission_log(group: &mut PlanNode, profile: Option<&StatsProfile>, sliced: bool) -> String {
39587 admission_log_with_order(group, profile, sliced, &[])
39588 }
39589
39590 fn admission_log_with_order(
39591 group: &mut PlanNode,
39592 profile: Option<&StatsProfile>,
39593 sliced: bool,
39594 order_keys: &[Variable],
39595 ) -> String {
39596 admission_log_top(
39597 group,
39598 &[var("dim"), var("n")],
39599 order_keys,
39600 false,
39601 profile,
39602 sliced,
39603 )
39604 }
39605
39606 fn admission_log_top(
39607 top: &mut PlanNode,
39608 projection: &[Variable],
39609 order_keys: &[Variable],
39610 distinct: bool,
39611 profile: Option<&StatsProfile>,
39612 sliced: bool,
39613 ) -> String {
39614 let lines = Arc::new(Mutex::new(Vec::new()));
39615 let ctx = crate::context::QueryContext::from_snapshot(SnapshotId::latest())
39616 .with_log(LogSink::capture(LogLevel::Debug, Arc::clone(&lines)));
39617 annotate_liveness(top, projection, order_keys, distinct, profile, Some(&ctx));
39618 if !sliced {
39619 stamp_semi_join_strategy(top, profile, sliced, Some(&ctx), &[]);
39620 }
39621 lines
39622 .lock()
39623 .unwrap()
39624 .iter()
39625 .filter(|line| line.contains("semi-admit:") || line.contains("semi-payload:"))
39626 .cloned()
39627 .collect::<Vec<_>>()
39628 .join("\n")
39629 }
39630
39631 fn admit_line(log: &str) -> &str {
39632 log.lines()
39633 .find(|line| line.contains("semi-admit: filter(union)"))
39634 .unwrap_or_else(|| panic!("no filter(union) admission line:\n{log}"))
39635 }
39636
39637 fn verdict_price(
39638 pages: u64,
39639 per_page_price_milli: u128,
39640 build_read_rows: u64,
39641 build_bar_milli: u128,
39642 ) -> SemiBuildPrice {
39643 SemiBuildPrice {
39644 pages,
39645 driver_rows: 1,
39646 page_rows: 1,
39647 seeks_per_page: 0,
39648 matched_per_page: 0,
39649 per_page_filter_cost_milli: 0,
39650 per_page_price_milli,
39651 build_read_rows,
39652 build_source: "test",
39653 build_seek_terms: 0,
39654 build_rpcs: 0,
39655 build_output_rows: 0,
39656 build_keys: 0,
39657 build_price_milli: build_bar_milli,
39658 build_bar_milli,
39659 build_filter_cost_milli: 0,
39660 unpushed_read_rows: None,
39661 unpushed_output_rows: None,
39662 ancestor_keys: 0,
39663 driver_domain: 1,
39664 probe_domain_known: true,
39665 }
39666 }
39667
39668 #[test]
39669 fn unpushed_frames_are_structural_and_ignore_the_join_cells() {
39670 let profile = profile(1_000_000, 200_000, 400_000);
39671 let join = join(
39672 PlanNode::Scan(scan("r", "http://ex/kindA", "v", 1_000_000)),
39673 PlanNode::Scan(scan("r", "http://ex/kindB", "v", 1_000_000)),
39674 &["r"],
39675 &[200_000],
39676 1,
39679 );
39680 let mut budget = SUBTREE_WALK_NODE_BUDGET;
39681 let read = unpushed_read_rows(Some(&profile), &join, &mut budget)
39682 .expect("both scan reads are profile-backed");
39683 assert_eq!(read, 2_000_000, "read is the sum of the two raw scans");
39684
39685 let mut budget = SUBTREE_WALK_NODE_BUDGET;
39686 let output = unpushed_row_count_estimate(Some(&profile), &join, &mut budget)
39687 .expect("the join is structurally priceable");
39688 assert!(
39690 (4_800_000..=5_100_000).contains(&output),
39691 "the join output is the uniform product over the HLL domain, got {output}"
39692 );
39693 }
39694
39695 #[test]
39696 fn an_ancestor_key_list_reduces_the_build_read() {
39697 let profile = profile(1_000_000, 200_000, 400_000);
39698 let right = literal_subtree();
39699 let key = var("r");
39700
39701 let mut budget = SUBTREE_WALK_NODE_BUDGET;
39702 let source = SemiBuildPushSource::AncestorPushesAndDriverDomain {
39703 key: &key,
39704 domain: 200_000,
39705 };
39706 let base = estimate_semi_build_drain(Some(&profile), &right, source, &[], &mut budget)
39707 .expect("the two literal leaves are profile-backed");
39708
39709 let ancestors = [AncestorPushKey {
39710 key: key.clone(),
39711 list: 100_000,
39712 }];
39713 let mut budget = SUBTREE_WALK_NODE_BUDGET;
39714 let reduced =
39715 estimate_semi_build_drain(Some(&profile), &right, source, &ancestors, &mut budget)
39716 .expect("the ancestor list composes with the driver list");
39717
39718 assert!(
39719 reduced.read_rows < base.read_rows,
39720 "the 100k ancestor list must reduce the 200k driver-domain build: \
39721 base={} reduced={}",
39722 base.read_rows,
39723 reduced.read_rows,
39724 );
39725 assert!(
39726 (450_000..600_000).contains(&reduced.read_rows),
39727 "the merged 100k list halves the ~1M no-ancestor build read, got {}",
39728 reduced.read_rows,
39729 );
39730 assert_eq!(
39731 reduced.pushed_terms,
39732 2 * 100_000,
39733 "the merged list is pushed once per hosted leaf"
39734 );
39735 assert_eq!(
39736 reduced.chunk_fetches,
39737 2 * 5,
39738 "two leaves at 100k keys / 24,576"
39739 );
39740 }
39741
39742 #[test]
39743 fn a_filter_without_a_selectivity_model_keeps_the_inner_domain() {
39744 let profile = profile(1_000_000, 200_000, 400_000);
39745 let scan = PlanNode::Scan(scan("r", "http://ex/name", "lit", 1));
39746 let scan_domain =
39747 join_key_domain_for_node(Some(&profile), &scan, &var("r")).expect("subject HLL");
39748 let filter = PlanNode::Filter {
39749 inner: Box::new(scan),
39750 early: None,
39751 residual: Some(Expression::Variable(var("lit"))),
39752 exists: Vec::new(),
39753 one_to_one: false,
39754 };
39755 assert_eq!(
39756 join_key_domain_for_node(Some(&profile), &filter, &var("r")),
39757 Some(scan_domain),
39758 "an absent selectivity model must not clamp a possibly push-clamped row cell"
39759 );
39760 }
39761
39762 #[test]
39763 fn a_filter_selectivity_bounds_the_surviving_key_domain() {
39764 assert_eq!(filter_domain_bound(817_000, 817_000, 500), 408_500);
39765 assert_eq!(filter_domain_bound(100, 1_000, 500), 100);
39767 assert_eq!(filter_domain_bound(817_000, 1_000, 500), 500);
39769 }
39770
39771 #[test]
39772 fn filter_cost_rates_follow_the_capability_split() {
39773 let encoded = Expression::Bound(var("v"));
39774 let maybe = Expression::Greater(
39775 Box::new(Expression::Variable(var("a"))),
39776 Box::new(Expression::Variable(var("b"))),
39777 );
39778 let resolved = Expression::Equal(
39779 Box::new(Expression::Variable(var("v"))),
39780 Box::new(Expression::FunctionCall(
39781 spargebra::algebra::Function::UCase,
39782 vec![Expression::Variable(var("v"))],
39783 )),
39784 );
39785 assert_eq!(classify(&encoded), ExprCapability::AlwaysEncoded);
39786 assert_eq!(classify(&maybe), ExprCapability::MaybeEncoded);
39787 assert_eq!(classify(&resolved), ExprCapability::AlwaysResolve);
39788 assert_eq!(filter_row_cost_milli(Some(&encoded), None), 5);
39789 assert_eq!(filter_row_cost_milli(Some(&maybe), None), 50);
39790 assert_eq!(filter_row_cost_milli(None, Some(&resolved)), 200);
39791 let both = Expression::And(Box::new(encoded), Box::new(resolved));
39793 assert_eq!(filter_row_cost_milli(Some(&both), None), 205);
39794 }
39795
39796 #[test]
39797 fn filter_selectivity_none_keeps_the_input_estimate() {
39798 let inner_rows = 1_000_000;
39799 let filter = PlanNode::Filter {
39800 inner: Box::new(PlanNode::Scan(scan(
39801 "r",
39802 "http://ex/name",
39803 "lit",
39804 inner_rows,
39805 ))),
39806 early: None,
39807 residual: Some(Expression::Variable(var("lit"))),
39808 exists: Vec::new(),
39809 one_to_one: false,
39810 };
39811 assert_eq!(
39812 filter.produced_row_count_estimate(),
39813 inner_rows,
39814 "no selectivity model => pass-through"
39815 );
39816 assert_eq!(
39817 apply_filter_selectivity(
39818 inner_rows,
39819 None,
39820 Some(&Expression::Variable(var("lit"))),
39821 &[],
39822 ),
39823 inner_rows,
39824 );
39825 }
39826
39827 #[test]
39828 fn filter_cost_is_added_to_the_page_and_once_costs() {
39829 let profile = profile(1_000_000, 200_000, 400_000);
39830 let scan = PlanNode::Scan(scan("r", "http://ex/name", "lit", 1_000_000));
39831 let resolved = Expression::Equal(
39832 Box::new(Expression::Variable(var("lit"))),
39833 Box::new(Expression::FunctionCall(
39834 spargebra::algebra::Function::UCase,
39835 vec![Expression::Variable(var("lit"))],
39836 )),
39837 );
39838 let filter = PlanNode::Filter {
39839 inner: Box::new(scan.clone()),
39840 early: None,
39841 residual: Some(resolved),
39842 exists: Vec::new(),
39843 one_to_one: false,
39844 };
39845 let push = ContainingPush {
39846 key: var("r"),
39847 pushed_val_count: 100_000,
39848 };
39849 let mut budget = SUBTREE_WALK_NODE_BUDGET;
39850 let base_page = subtree_page_cost(Some(&profile), &scan, &push, None, &mut budget);
39851 let mut budget = SUBTREE_WALK_NODE_BUDGET;
39852 let filtered_page = subtree_page_cost(Some(&profile), &filter, &push, None, &mut budget);
39853 assert_eq!(
39854 filtered_page.rows - base_page.rows,
39855 base_page.rows * crate::query::tunables::FILTER_RESOLVE_ROW_EQUIV_MILLI / 1000,
39856 "the resolve conjunct adds one rate per matched page row"
39857 );
39858 assert_eq!(filtered_page.seeks, base_page.seeks);
39859
39860 let base_once = driver_once_cost(Some(&profile), &scan, None);
39861 let filtered_once = driver_once_cost(Some(&profile), &filter, None);
39862 assert_eq!(
39863 filtered_once.rows - base_once.rows,
39864 1_000_000 * crate::query::tunables::FILTER_RESOLVE_ROW_EQUIV_MILLI / 1000,
39865 "the once-cost charges the filter over the inner's output rows"
39866 );
39867
39868 let mut budget = SUBTREE_WALK_NODE_BUDGET;
39869 let build = estimate_semi_build_drain(
39870 Some(&profile),
39871 &filter,
39872 SemiBuildPushSource::AncestorPushesOnly,
39873 &[],
39874 &mut budget,
39875 )
39876 .expect("the scan leaf is priceable");
39877 assert!(
39878 build.filter_eval_milli > 0,
39879 "the semijoin build must charge the filter over the pushed read"
39880 );
39881 }
39882
39883 #[test]
39884 fn a_sensitivity_mark_on_a_name_the_join_does_not_produce_is_ignored() {
39885 let left = PlanNode::Scan(scan("a", "http://ex/p", "b", 10_000));
39886 let right = PlanNode::Scan(scan("a", "http://ex/q", "c", 10_000));
39887 let join = join(left, right, &["a"], &[1_000], 10_000);
39888 let mut required = HashMap::new();
39892 required.insert(var("a"), SlotMark::LIVE_INSENSITIVE);
39893 required.insert(var("z"), SlotMark::LIVE_SENSITIVE);
39894 let PlanNode::Join { left, right, .. } = &join else {
39895 unreachable!()
39896 };
39897 let context = join_semi_context(&required, left, right, &HashMap::new(), false, &[], false);
39898 assert!(
39899 !context.row_multiplicity_observed,
39900 "?z belongs to another branch; it cannot observe this join's duplicates"
39901 );
39902 }
39903
39904 #[test]
39905 fn ancestor_pushes_only_equals_the_unpushed_read_without_ancestors() {
39906 let profile = profile(1_000_000, 200_000, 400_000);
39907 let right = literal_subtree();
39908
39909 let mut budget = SUBTREE_WALK_NODE_BUDGET;
39910 let whole = estimate_semi_build_drain(
39911 Some(&profile),
39912 &right,
39913 SemiBuildPushSource::AncestorPushesOnly,
39914 &[],
39915 &mut budget,
39916 )
39917 .expect("the two literal leaves are profile-backed");
39918 let mut budget = SUBTREE_WALK_NODE_BUDGET;
39919 let unpushed = unpushed_read_rows(Some(&profile), &right, &mut budget)
39920 .expect("the two literal leaves are profile-backed");
39921 assert_eq!(
39922 whole.read_rows, unpushed,
39923 "the regular build is the ancestor-pushes-only drain, which is the \
39924 fully unpushed read when there are no ancestors"
39925 );
39926 assert_eq!(whole.pushed_terms, 0, "no current driver list is pushed");
39927 assert_eq!(whole.chunk_fetches, 0);
39928
39929 let key = var("r");
39931 let ancestors = [AncestorPushKey {
39932 key: key.clone(),
39933 list: 100_000,
39934 }];
39935 let mut budget = SUBTREE_WALK_NODE_BUDGET;
39936 let reduced = estimate_semi_build_drain(
39937 Some(&profile),
39938 &right,
39939 SemiBuildPushSource::AncestorPushesOnly,
39940 &ancestors,
39941 &mut budget,
39942 )
39943 .expect("the ancestor list composes with the leaf domains");
39944 assert!(
39945 (450_000..600_000).contains(&reduced.read_rows),
39946 "the ancestor list, not the driver domain, must filter the drain: {}",
39947 reduced.read_rows
39948 );
39949 assert_eq!(reduced.pushed_terms, 2 * 100_000);
39950 assert_eq!(reduced.chunk_fetches, 2 * 5);
39951 }
39952
39953 #[test]
39954 fn the_verdict_needs_work_to_amortize_and_a_build_to_price() {
39955 assert_eq!(
39956 semi_build_verdict(&verdict_price(0, 100, 10, 10)),
39957 SemiBuildVerdict::PerPage,
39958 "no driver pages means nothing to amortize"
39959 );
39960 assert_eq!(
39961 semi_build_verdict(&verdict_price(1, 100, 0, 0)),
39962 SemiBuildVerdict::PerPage,
39963 "an empty build read must not divide by zero"
39964 );
39965 assert_eq!(
39966 semi_build_verdict(&verdict_price(1, 99, 10, 100)),
39967 SemiBuildVerdict::PerPage,
39968 "below the build bar keeps the per-page road"
39969 );
39970 assert_eq!(
39971 semi_build_verdict(&verdict_price(1, 100, 10, 100)),
39972 SemiBuildVerdict::Build,
39973 "equality meets the bar"
39974 );
39975 }
39976
39977 #[test]
39978 fn subtree_right_under_count_distinct_admits() {
39979 let profile = profile(1_000_000, 200_000, 400_000);
39980 let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
39981 let log = admission_log(&mut group, Some(&profile), false);
39982 let line = admit_line(&log);
39983 assert!(
39984 line.contains("-> admit"),
39985 "the t4-shaped boundary must admit the build-once road:\n{line}"
39986 );
39987 let build_read = line
39988 .split("build_read=")
39989 .nth(1)
39990 .expect("build_read field")
39991 .split_whitespace()
39992 .next()
39993 .expect("build_read value")
39994 .parse::<u64>()
39995 .expect("numeric build_read");
39996 assert_eq!(
39997 build_read, 2_000_000,
39998 "the regular build is the ancestor-pushes-only drain: both literal \
39999 scans read whole, with no driver-domain push:\n{line}"
40000 );
40001 assert!(
40002 line.contains("build_source=ancestor-pushes-only"),
40003 "the admission must name the build frame it priced:\n{line}"
40004 );
40005 assert!(
40006 line.contains("build_seeks=0") && line.contains("build_rpcs=0"),
40007 "no driver or ancestor lists reach this build:\n{line}"
40008 );
40009 assert!(
40010 line.contains("unpushed_read=2000000") && line.contains("unpushed_out=2000000"),
40011 "the fully unpushed frame is the two raw literal reads, not the \
40012 driver-pushed build:\n{line}"
40013 );
40014 assert!(
40015 !line.contains("refuse"),
40016 "an admitted candidate must not also name a refusal:\n{line}"
40017 );
40018 }
40019
40020 #[test]
40021 fn the_recorded_facts_are_applied_as_semi_only_after_the_specialized_claim() {
40022 let profile = profile(1_000_000, 200_000, 400_000);
40023 let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40024 let ctx = crate::context::QueryContext::from_snapshot(SnapshotId::latest());
40025
40026 annotate_liveness(
40029 &mut group,
40030 &[var("dim"), var("n")],
40031 &[],
40032 false,
40033 Some(&profile),
40034 Some(&ctx),
40035 );
40036 let PlanNode::Group { inner, .. } = &group else {
40037 unreachable!()
40038 };
40039 let PlanNode::Join { meta, .. } = inner.as_ref() else {
40040 unreachable!()
40041 };
40042 assert!(
40043 meta.semi_gate.is_some(),
40044 "the final liveness round records the gate facts"
40045 );
40046 assert_eq!(meta.strategy, JoinStrategy::Broadcast);
40047
40048 stamp_semi_join_strategy(&mut group, Some(&profile), false, Some(&ctx), &[]);
40049
40050 let PlanNode::Group { inner, .. } = &group else {
40051 unreachable!()
40052 };
40053 let PlanNode::Join { meta, .. } = inner.as_ref() else {
40054 unreachable!()
40055 };
40056 assert_eq!(meta.strategy, JoinStrategy::Semi);
40057 assert!(
40058 meta.semi_gate.is_none(),
40059 "the stamp pass consumes the recorded facts"
40060 );
40061 }
40062
40063 #[test]
40064 fn an_order_key_outside_the_projection_stays_live_and_sensitive() {
40065 let mut root = PlanNode::Scan(scan("s", "http://ex/p", "o", 10_000));
40066 annotate_liveness(&mut root, &[var("s")], &[var("o")], false, None, None);
40067 let PlanNode::Scan(scan) = &root else {
40068 unreachable!()
40069 };
40070 assert!(
40071 scan.is_live(&var("o")),
40072 "a top-level ORDER BY key is read above the projection and must stay live"
40073 );
40074 assert_eq!(
40075 scan.bag_mark(&var("o")),
40076 Some(BagMark::Sensitive),
40077 "a sort key must not become a collapse key"
40078 );
40079 assert!(
40080 scan.domain_scan.is_none() && scan.head_scan.is_none(),
40081 "a live sort-key slot must block the domain/head rewrites"
40082 );
40083 }
40084
40085 #[test]
40086 fn an_order_key_only_live_above_the_join_refuses_as_payload() {
40087 let profile = profile(1_000_000, 200_000, 400_000);
40088 let mut top = semi_top(600_000, false);
40089 let log = admission_log_top(
40093 &mut top,
40094 &[var("r")],
40095 &[var("lit")],
40096 true,
40097 Some(&profile),
40098 false,
40099 );
40100 let line = admit_line(&log);
40101 assert!(
40102 line.contains("right payload above the join"),
40103 "a right-only ORDER BY key is live above the join and must refuse:\n{line}"
40104 );
40105 assert!(
40106 log.contains("semi-payload:") && log.contains("lit"),
40107 "the recording must name the payload column:\n{log}"
40108 );
40109 }
40110
40111 #[test]
40112 fn a_scan_right_is_a_general_semi_candidate() {
40113 let profile = profile(1_000_000, 200_000, 400_000);
40114 let mut top = semi_top_scan_right(600_000);
40115 let log = admission_log_top(
40116 &mut top,
40117 &[var("r"), var("dim")],
40118 &[],
40119 true,
40120 Some(&profile),
40121 false,
40122 );
40123 let PlanNode::Join { meta, .. } = &top else {
40124 unreachable!()
40125 };
40126 assert_eq!(meta.strategy, JoinStrategy::Semi, "{log}");
40127 }
40128
40129 #[test]
40130 fn a_scan_right_payload_refuses() {
40131 let profile = profile(1_000_000, 200_000, 400_000);
40132 let mut top = semi_top_scan_right_payload(600_000);
40133 let log = admission_log_top(
40134 &mut top,
40135 &[var("r"), var("dim"), var("lit")],
40136 &[],
40137 true,
40138 Some(&profile),
40139 false,
40140 );
40141 let PlanNode::Join { meta, .. } = &top else {
40142 unreachable!()
40143 };
40144 assert_ne!(meta.strategy, JoinStrategy::Semi, "{log}");
40145 assert!(
40146 log.contains("right payload above the join") && log.contains("lit"),
40147 "a live right column must refuse the scan-right build:\n{log}"
40148 );
40149 }
40150
40151 #[test]
40152 fn a_semiscan_eligible_scan_right_keeps_semiscan() {
40153 let profile = profile(1_000_000, 200_000, 400_000);
40154 let mut top = semi_top_scan_right(600_000);
40155 let PlanNode::Join { right, .. } = &mut top else {
40158 unreachable!()
40159 };
40160 let PlanNode::Scan(scan) = right.as_mut() else {
40161 unreachable!()
40162 };
40163 scan.fetch_once = Some(1_000_000);
40164 let log = admission_log_top(
40165 &mut top,
40166 &[var("r"), var("dim")],
40167 &[],
40168 true,
40169 Some(&profile),
40170 false,
40171 );
40172 let PlanNode::Join { meta, .. } = &top else {
40173 unreachable!()
40174 };
40175 assert_eq!(meta.strategy, JoinStrategy::SemiScan, "{log}");
40176 assert!(
40177 meta.semi_gate.is_none(),
40178 "the general record is consumed even when the specialized claim wins"
40179 );
40180 }
40181
40182 #[test]
40183 fn the_plan_tree_names_the_general_semi_strategy() {
40184 let left = PlanNode::Scan(scan("r", "http://ex/p", "o", 10));
40185 let right = PlanNode::Scan(scan("r", "http://ex/q", "o", 10));
40186 let mut join = join(left, right, &["r"], &[10], 10);
40187 let PlanNode::Join { meta, .. } = &mut join else {
40188 unreachable!()
40189 };
40190 meta.strategy = JoinStrategy::Semi;
40191 let text = crate::explain::format_star_plan(&join);
40192 assert!(
40193 text.contains("(semi"),
40194 "EXPLAIN must name the strategy:
40195{text}"
40196 );
40197 assert!(
40198 !text.contains("(semi-scan"),
40199 "the general road must not render as the scan special case:
40200{text}"
40201 );
40202 }
40203
40204 #[test]
40205 fn a_star_arm_never_gets_the_general_semi_stamp() {
40206 let profile = profile(1_000_000, 200_000, 400_000);
40207 let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40208 let ctx = crate::context::QueryContext::from_snapshot(SnapshotId::latest());
40209 annotate_liveness(
40210 &mut group,
40211 &[var("dim"), var("n")],
40212 &[],
40213 false,
40214 Some(&profile),
40215 Some(&ctx),
40216 );
40217 let PlanNode::Group { inner, .. } = &mut group else {
40218 unreachable!()
40219 };
40220 let PlanNode::Join { meta, .. } = inner.as_mut() else {
40221 unreachable!()
40222 };
40223 assert!(
40224 meta.semi_gate.is_some(),
40225 "the fixture must record the general gate facts"
40226 );
40227 meta.star_arms = Some(1);
40229 stamp_semi_join_strategy(&mut group, Some(&profile), false, Some(&ctx), &[]);
40230 let PlanNode::Group { inner, .. } = &group else {
40231 unreachable!()
40232 };
40233 let PlanNode::Join { meta, .. } = inner.as_ref() else {
40234 unreachable!()
40235 };
40236 assert_ne!(
40237 meta.strategy,
40238 JoinStrategy::Semi,
40239 "a star arm is not a semi build"
40240 );
40241 assert!(meta.semi_gate.is_none(), "the record is consumed");
40242 }
40243
40244 fn count_distinct_of(variable: &str) -> AggregateExpression {
40245 AggregateExpression::FunctionCall {
40246 name: AggregateFunction::Count,
40247 expr: Expression::Variable(var(variable)),
40248 distinct: true,
40249 }
40250 }
40251
40252 #[test]
40253 fn a_right_only_count_distinct_argument_refuses_as_payload() {
40254 let profile = profile(1_000_000, 200_000, 400_000);
40255 let mut group = semi_shape(count_distinct_of("lit"), &["dim"], 600_000, false);
40258 let log = admission_log(&mut group, Some(&profile), false);
40259 let line = admit_line(&log);
40260 assert!(
40261 line.contains("right payload above the join"),
40262 "a right-only COUNT(DISTINCT ?lit) argument is payload:\n{log}"
40263 );
40264 assert!(
40265 log.contains("semi-payload:") && log.contains("lit"),
40266 "the recording must name the counted column:\n{log}"
40267 );
40268 }
40269
40270 #[test]
40271 fn plain_count_refuses_row_multiplicity() {
40272 let profile = profile(1_000_000, 200_000, 400_000);
40273 let mut group = semi_shape(count_rows(), &["dim"], 600_000, false);
40274 let log = admission_log(&mut group, Some(&profile), false);
40275 assert!(
40276 admit_line(&log).contains("refuse: row multiplicity is observed above the join"),
40277 "plain COUNT(?r) observes the duplicate right rows:\n{log}"
40278 );
40279 }
40280
40281 #[test]
40282 fn count_star_is_refused_explicitly() {
40283 let profile = profile(1_000_000, 200_000, 400_000);
40284 let mut group = semi_shape(count_star(), &["dim"], 600_000, false);
40285 let log = admission_log(&mut group, Some(&profile), false);
40286 assert!(
40287 admit_line(&log).contains("refuse: plain COUNT(*) above the join"),
40288 "COUNT(*) must name its own refusal, not fall through to the bag rule:\n{log}"
40289 );
40290 }
40291
40292 #[test]
40293 fn right_payload_above_the_join_refuses() {
40294 let profile = profile(1_000_000, 200_000, 400_000);
40295 let mut group = semi_shape(count_distinct(), &["dim", "lit"], 600_000, false);
40298 let log = admission_log(&mut group, Some(&profile), false);
40299 let line = admit_line(&log);
40300 assert!(
40301 line.contains("right payload above the join"),
40302 "a right-only live column must be refused as payload:\n{line}"
40303 );
40304 assert!(
40305 log.contains("semi-payload:") && log.contains("lit"),
40306 "the recording must name the payload column:\n{log}"
40307 );
40308 }
40309
40310 #[test]
40311 fn a_specialized_scan_in_the_right_subtree_refuses() {
40312 let profile = profile(1_000_000, 200_000, 400_000);
40313 let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40314 let PlanNode::Group { inner, .. } = &mut group else {
40315 unreachable!()
40316 };
40317 let PlanNode::Join {
40318 left,
40319 right,
40320 hash_keys,
40321 meta,
40322 ..
40323 } = inner.as_mut()
40324 else {
40325 unreachable!()
40326 };
40327 assert!(
40328 mark_first_scan_specialized(right),
40329 "fixture must put a scan under the right"
40330 );
40331 let facts = SemiGateFacts {
40335 right_payload: false,
40336 row_multiplicity_observed: false,
40337 count_star: false,
40338 };
40339 let refusal = semi_join_admission(
40340 left,
40341 right,
40342 hash_keys,
40343 meta,
40344 &facts,
40345 &[],
40346 false,
40347 Some(&profile),
40348 None,
40349 )
40350 .expect_err("a specialized scan under the right must refuse");
40351 assert!(
40352 matches!(refusal, SemiRefusal::SpecializedScan),
40353 "a count/domain rewrite under the right is not the pattern's rows: {}",
40354 refusal.describe()
40355 );
40356 }
40357
40358 #[test]
40359 fn an_unknown_driver_domain_refuses() {
40360 let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40361 let log = admission_log(&mut group, None, false);
40362 assert!(
40363 admit_line(&log).contains("driver key domain unknown"),
40364 "no profile means no honest page geometry:\n{log}"
40365 );
40366 }
40367
40368 #[test]
40369 fn an_unknown_build_estimate_refuses() {
40370 let mut profile = profile(1_000_000, 200_000, 400_000);
40371 profile
40374 .predicate_counts
40375 .remove(&StrHash::new("http://ex/name"));
40376 profile
40377 .predicate_counts
40378 .remove(&StrHash::new("http://ex/abstract"));
40379 let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40380 let log = admission_log(&mut group, Some(&profile), false);
40381 assert!(
40382 admit_line(&log).contains("build read estimate unknown"),
40383 "a missing literal sketch must refuse the build price:\n{log}"
40384 );
40385 }
40386
40387 #[test]
40388 fn a_sliced_subtree_refuses() {
40389 let profile = profile(1_000_000, 200_000, 400_000);
40390 let group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40391 let PlanNode::Group { inner, .. } = &group else {
40392 unreachable!()
40393 };
40394 let PlanNode::Join {
40395 left,
40396 right,
40397 hash_keys,
40398 meta,
40399 ..
40400 } = inner.as_ref()
40401 else {
40402 unreachable!()
40403 };
40404 let facts = SemiGateFacts {
40405 right_payload: false,
40406 row_multiplicity_observed: false,
40407 count_star: false,
40408 };
40409 let refusal = semi_join_admission(
40412 left,
40413 right,
40414 hash_keys,
40415 meta,
40416 &facts,
40417 &[],
40418 true,
40419 Some(&profile),
40420 None,
40421 )
40422 .expect_err("the OpenNode slice path never consults JoinStrategy");
40423 assert!(
40424 matches!(refusal, SemiRefusal::SlicedSubtree),
40425 "{}",
40426 refusal.describe()
40427 );
40428 }
40429
40430 #[test]
40431 fn a_join_below_a_slice_is_not_stamped() {
40432 let profile = profile(1_000_000, 200_000, 400_000);
40433 let mut root = PlanNode::Slice {
40434 inner: Box::new(semi_shape(count_distinct(), &["dim"], 600_000, false)),
40435 start: 0,
40436 length: Some(10),
40437 };
40438 let ctx = crate::context::QueryContext::from_snapshot(SnapshotId::latest());
40439 annotate_liveness(
40440 &mut root,
40441 &[var("dim"), var("n")],
40442 &[],
40443 false,
40444 Some(&profile),
40445 Some(&ctx),
40446 );
40447 let PlanNode::Join { meta, .. } = outer_join(&root) else {
40448 unreachable!()
40449 };
40450 assert!(
40451 meta.semi_gate.is_some(),
40452 "the liveness round records the facts even below a Slice"
40453 );
40454
40455 stamp_semi_join_strategy(&mut root, Some(&profile), false, Some(&ctx), &[]);
40456
40457 let PlanNode::Join { meta, .. } = outer_join_mut(&mut root) else {
40458 unreachable!()
40459 };
40460 assert_ne!(
40461 meta.strategy,
40462 JoinStrategy::Semi,
40463 "the Slice path runs through OpenNode, which ignores JoinStrategy"
40464 );
40465 assert!(meta.semi_gate.is_none(), "the record is consumed");
40466 }
40467
40468 #[test]
40469 fn a_join_in_an_exists_body_is_not_stamped() {
40470 let profile = profile(1_000_000, 200_000, 400_000);
40471 let mut root = PlanNode::Filter {
40472 inner: Box::new(PlanNode::Scan(scan("s", "http://ex/p", "o", 10))),
40473 early: None,
40474 residual: None,
40475 exists: vec![ExistsClause {
40476 negated: false,
40477 body: Box::new(semi_shape(count_distinct(), &["dim"], 600_000, false)),
40478 correlation: Vec::new(),
40479 kind: ExistsKind::Uncorrelated,
40480 }],
40481 one_to_one: false,
40482 };
40483 let ctx = crate::context::QueryContext::from_snapshot(SnapshotId::latest());
40484 annotate_liveness(
40485 &mut root,
40486 &[var("dim"), var("n")],
40487 &[],
40488 false,
40489 Some(&profile),
40490 Some(&ctx),
40491 );
40492 let PlanNode::Join { meta, .. } = outer_join(&root) else {
40493 unreachable!()
40494 };
40495 assert!(
40496 meta.semi_gate.is_some(),
40497 "the liveness round records the facts inside the EXISTS body"
40498 );
40499
40500 stamp_semi_join_strategy(&mut root, Some(&profile), false, Some(&ctx), &[]);
40501
40502 let PlanNode::Join { meta, .. } = outer_join_mut(&mut root) else {
40503 unreachable!()
40504 };
40505 assert_ne!(
40506 meta.strategy,
40507 JoinStrategy::Semi,
40508 "an EXISTS body is evaluated through OpenNode"
40509 );
40510 assert!(meta.semi_gate.is_none(), "the record is consumed");
40511 }
40512
40513 #[test]
40514 fn one_page_keeps_the_per_page_road() {
40515 let profile = profile(1_000_000, 200_000, 400_000);
40516 let mut group = semi_shape(count_distinct(), &["dim"], 1_000, false);
40517 let log = admission_log(&mut group, Some(&profile), false);
40518 let line = admit_line(&log);
40519 assert!(
40520 line.contains("per-page road is cheaper") && line.contains("pages=1"),
40521 "one page of a known list cannot amortize a two-million-row build:\n{line}"
40522 );
40523 }
40524
40525 #[test]
40526 fn a_second_key_is_refused_by_the_first_cut() {
40527 let profile = profile(1_000_000, 200_000, 400_000);
40528 let mut group = semi_shape(count_distinct(), &["dim"], 600_000, true);
40529 let log = admission_log(&mut group, Some(&profile), false);
40530 assert!(
40531 admit_line(&log).contains("2 join keys"),
40532 "the first cut is deliberately one key:\n{log}"
40533 );
40534 }
40535}
40536
40537#[cfg(test)]
40538mod flat_leaf_tests {
40539 use super::*;
40540
40541 #[test]
40547 fn a_pushed_single_triple_filter_is_a_flat_pipeline_leaf() {
40548 let mut profile = StatsProfile::default();
40549 profile
40550 .predicate_counts
40551 .insert(StrHash::new("http://ex/p"), 10);
40552 profile
40553 .predicate_counts
40554 .insert(StrHash::new("http://ex/q"), 1_000);
40555 let plan = LogicalPlan::parse_with_profile(
40556 r#"SELECT ?s ?o ?x WHERE {
40557 ?s <http://ex/p> ?o .
40558 FILTER(STR(?o) != "x")
40559 ?s <http://ex/q> ?x .
40560 }"#,
40561 Some(&profile),
40562 )
40563 .expect("the query plans");
40564 let PlanNode::Join { left, right, .. } = &plan.root else {
40565 panic!(
40566 "the pushed filter must flatten into one pipeline, got {:?}",
40567 plan.root
40568 );
40569 };
40570 let PlanNode::Filter { inner, .. } = left.as_ref() else {
40571 panic!("the smaller filtered scan must be the left leaf, got {left:?}");
40572 };
40573 let PlanNode::Scan(scan) = inner.as_ref() else {
40574 panic!("the filter leaf must wrap its scan, got {inner:?}");
40575 };
40576 assert_eq!(scan.object, Some(Variable::new_unchecked("o")));
40577 let PlanNode::Scan(q) = right.as_ref() else {
40578 panic!("the larger scan must be the right leaf, got {right:?}");
40579 };
40580 assert_eq!(q.object, Some(Variable::new_unchecked("x")));
40581 }
40582}