1use spargebra::algebra::{Expression, Function};
36use waratah_compute::ComputeError;
37use waratah_compute::JoinStrategy;
38use waratah_compute::PlanNode;
39use waratah_compute::QueryContext;
40use waratah_compute::ground_unique_probe_term;
41use waratah_compute::plugin::{PlannerPlugin, PluginPayloadBox};
42use waratah_stats::PUSHDOWN_TERMS_LIMIT;
43use waratah_storage::{EncodedTerm, TextCandidateMode, TextSearchRequest, TextSubjectRequest};
44
45use crate::config::TextPluginConfig;
46use crate::exec::{TEXT_SCAN_OP_ID, TEXT_SUBJECTS_OP_ID, TextScanPayload, TextSubjectsPayload};
47
48pub const TEXT_QUERY_IRI: &str = "http://jena.apache.org/text#query";
50
51const REGEX_METACHARACTERS: &[char] = &[
58 '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '^', '$',
59];
60
61const UNPRICED_DRAIN_SEAT_ESTIMATE: u64 = PUSHDOWN_TERMS_LIMIT * 2;
103
104#[derive(Debug, Clone)]
107pub struct TextPlannerPlugin {
108 config: TextPluginConfig,
109}
110
111impl TextPlannerPlugin {
112 pub fn new(config: TextPluginConfig) -> Self {
114 Self { config }
115 }
116
117 fn trusted(&self, ctx: &QueryContext) -> bool {
122 ctx.text_index_epoch().is_some()
123 && ctx.text_index_fingerprint() == self.config.fingerprint()
124 }
125
126 fn seed_chars(&self) -> usize {
130 self.config.seed_chars
131 }
132}
133
134impl PlannerPlugin for TextPlannerPlugin {
135 fn rewrite(&self, node: &mut PlanNode, ctx: &QueryContext) -> Result<(), ComputeError> {
136 let mut scope = ScopeTrack::default();
139 self.rewrite_scoped(node, ctx, &mut scope)
140 }
141
142 fn pins_through_optimizer(&self, expression: &Expression) -> bool {
155 match expression {
156 Expression::FunctionCall(Function::Custom(iri), _) => iri.as_str() == TEXT_QUERY_IRI,
157 Expression::FunctionCall(Function::StrStarts | Function::StrEnds, args) => {
158 parse_var_and_pattern(args).is_some_and(|(_, pattern)| !pattern.is_empty())
159 }
160 Expression::FunctionCall(Function::Regex, args) => parse_anchored_regex(args).is_some(),
161 _ => false,
162 }
163 }
164
165 fn keeps_variable_when_ground(&self, expression: &Expression) -> bool {
172 matches!(
173 expression,
174 Expression::FunctionCall(Function::Custom(iri), _) if iri.as_str() == TEXT_QUERY_IRI
175 )
176 }
177}
178
179#[derive(Default)]
189struct ScopeTrack {
190 applied_scopes: Vec<waratah_compute::AppliedGraph>,
203 in_graph_scope: bool,
210}
211
212impl TextPlannerPlugin {
213 fn rewrite_scoped(
217 &self,
218 node: &mut PlanNode,
219 ctx: &QueryContext,
220 scope: &mut ScopeTrack,
221 ) -> Result<(), ComputeError> {
222 match node {
223 PlanNode::Filter {
224 inner,
225 early,
226 residual,
227 exists,
228 ..
229 } => {
230 self.rewrite_scoped(inner, ctx, scope)?;
232 for clause in exists.iter_mut() {
233 self.rewrite_scoped(&mut clause.body, ctx, scope)?;
234 }
235 let Some(residual_expr) = residual else {
236 return Ok(());
237 };
238 let conjuncts = waratah_compute::flatten_and(residual_expr);
239 let inner_variables = inner.variables();
244 let mut unsatisfiable = false;
245 let mut remaining: Vec<Expression> = Vec::new();
246 let mut rewritten: Option<PlanNode> = None;
247 for conjunct in conjuncts {
248 match self.match_conjunct(&conjunct, inner, ctx)? {
249 TextMatch::None => remaining.push(conjunct),
250 TextMatch::Terms {
251 request,
252 variable,
253 strip,
254 } => {
255 if !inner_variables.contains(&variable) {
256 unsatisfiable = true;
265 break;
266 }
267 let join = self.join_text_scan(
270 rewritten.take().unwrap_or_else(|| (**inner).clone()),
271 request,
272 variable,
273 ctx,
274 );
275 rewritten = Some(join);
276 if !strip {
277 remaining.push(conjunct);
280 }
281 }
282 TextMatch::Subject {
283 request,
284 variable,
285 predicates,
286 } => {
287 let inner = rewritten.take().unwrap_or_else(|| (**inner).clone());
294 let window = resolve_subject_scopes(scope, ctx)?;
295 let join = self.join_subject_scan(
296 inner,
297 request,
298 variable,
299 &predicates,
300 &window,
301 ctx,
302 )?;
303 rewritten = Some(join);
304 }
305 }
306 }
307 if unsatisfiable {
308 *node = PlanNode::Values(waratah_compute::ValuesOp {
314 variables: inner_variables,
315 rows: Vec::new(),
316 strings: Vec::new(),
317 blobs: Vec::new(),
318 });
319 return Ok(());
320 }
321 *residual = waratah_compute::and_fold(remaining);
324 for expression in [early.as_ref(), residual.as_ref()].into_iter().flatten() {
337 ensure_no_surviving_text_query(expression)?;
338 }
339 if let Some(join) = rewritten {
340 if residual.is_none() && early.is_none() && exists.is_empty() {
341 *node = join;
342 } else {
343 **inner = join;
344 }
345 }
346 Ok(())
347 }
348 PlanNode::Scan(scan) if is_text_query_predicate(scan) => {
352 Err(ComputeError::UnsupportedSparql(
353 "text:query is a FILTER function, not a graph pattern; write \
354 FILTER text:query(?lit, \"terms\") instead"
355 .to_owned(),
356 ))
357 }
358 PlanNode::Join { left, right, .. } => {
368 self.rewrite_scoped(left, ctx, scope)?;
375 self.rewrite_scoped(right, ctx, scope)
376 }
377 PlanNode::Union { left, right } => {
378 let mut left_scope = ScopeTrack {
395 applied_scopes: Vec::new(),
396 in_graph_scope: scope.in_graph_scope,
397 };
398 self.rewrite_scoped(left, ctx, &mut left_scope)?;
399 let mut right_scope = ScopeTrack {
400 applied_scopes: Vec::new(),
401 in_graph_scope: scope.in_graph_scope,
402 };
403 self.rewrite_scoped(right, ctx, &mut right_scope)?;
404 Ok(())
405 }
406 PlanNode::LeftJoin {
407 left,
408 right,
409 early_filter,
410 residual_filter,
411 ..
412 } => {
413 for expression in [early_filter, residual_filter].into_iter().flatten() {
420 ensure_no_surviving_text_query_in_optional(expression)?;
421 }
422 self.rewrite_scoped(left, ctx, scope)?;
423 let mut body_scope = ScopeTrack {
429 applied_scopes: Vec::new(),
430 in_graph_scope: scope.in_graph_scope,
431 };
432 self.rewrite_scoped(right, ctx, &mut body_scope)?;
433 Ok(())
434 }
435 PlanNode::CustomNode(op) => {
436 for child in &mut op.children {
437 self.rewrite_scoped(child, ctx, scope)?;
438 }
439 Ok(())
440 }
441 PlanNode::Extend {
442 expression, inner, ..
443 } => {
444 ensure_no_surviving_text_query(expression)?;
449 self.rewrite_scoped(inner, ctx, scope)
450 }
451 PlanNode::Sort { keys, inner } => {
452 for key in keys {
456 ensure_no_surviving_text_query(&key.expression)?;
457 }
458 self.rewrite_scoped(inner, ctx, scope)
459 }
460 PlanNode::Group {
461 aggregates, inner, ..
462 } => {
463 for (_, aggregate) in aggregates {
468 if let spargebra::algebra::AggregateExpression::FunctionCall { expr, .. } =
469 aggregate
470 {
471 ensure_no_surviving_text_query(expr)?;
472 }
473 }
474 self.rewrite_scoped(inner, ctx, scope)
475 }
476 PlanNode::Slice { inner, .. } | PlanNode::Distinct { inner, .. } => {
477 self.rewrite_scoped(inner, ctx, scope)
478 }
479 PlanNode::JoinGraphVar { inner, .. } => {
480 let outer = std::mem::take(scope);
484 scope.in_graph_scope = true;
485 let result = self.rewrite_scoped(inner, ctx, scope);
486 *scope = outer;
487 result
488 }
489 PlanNode::SubSelect(sub) => {
490 let outer = std::mem::take(scope);
494 let result = self.rewrite_scoped(&mut sub.inner, ctx, scope);
495 *scope = outer;
496 result
497 }
498 PlanNode::Scan(scan) => {
501 let stamp = scan.applied_graph();
509 if !scope
510 .applied_scopes
511 .iter()
512 .any(|known| same_scope(known, &stamp))
513 {
514 scope.applied_scopes.push(stamp);
515 }
516 Ok(())
517 }
518 PlanNode::Path(_)
519 | PlanNode::Unit
520 | PlanNode::Values(_)
521 | PlanNode::NamedGraphs { .. }
522 | PlanNode::NamedGraphExists { .. }
523 | PlanNode::DomainCounts { .. }
524 | PlanNode::HeadCounts { .. }
525 | PlanNode::PatternCount { .. } => Ok(()),
526 }
527 }
528}
529
530fn resolve_subject_scopes(
558 scope: &ScopeTrack,
559 ctx: &QueryContext,
560) -> Result<waratah_compute::AppliedGraph, ComputeError> {
561 let default_window = waratah_compute::applied_default_graph(ctx.dataset());
562 if let Some(sibling) = scope
563 .applied_scopes
564 .iter()
565 .find(|sibling| same_scope(sibling, &default_window))
566 {
567 return Ok(sibling.clone());
568 }
569 if scope.applied_scopes.is_empty() {
570 if scope.in_graph_scope {
571 return Err(ComputeError::UnsupportedSparql(
572 "subject-mode text:query inside GRAPH requires a triple pattern in the \
573 same graph group (the resolve must inherit the group's graph scope)"
574 .to_owned(),
575 ));
576 }
577 return Ok(any_graph_window());
578 }
579 if scope.applied_scopes.len() == 1 {
580 return Ok(scope.applied_scopes[0].clone());
581 }
582 Ok(any_graph_window())
583}
584
585fn any_graph_window() -> waratah_compute::AppliedGraph {
587 waratah_compute::AppliedGraph {
588 graph_name: None,
589 graph: None,
590 graph_filter: None,
591 merge_default_graph: false,
592 }
593}
594
595fn same_scope(a: &waratah_compute::AppliedGraph, b: &waratah_compute::AppliedGraph) -> bool {
605 match (&a.graph_name, &b.graph_name) {
606 (Some(x), Some(y)) => {
607 if waratah_storage::encode_term_bytes(x) != waratah_storage::encode_term_bytes(y) {
608 return false;
609 }
610 }
611 (None, None) => {}
612 _ => return false,
613 }
614 if a.graph != b.graph {
615 return false;
616 }
617 if a.merge_default_graph != b.merge_default_graph {
618 return false;
619 }
620 match (&a.graph_filter, &b.graph_filter) {
621 (None, None) => true,
622 (Some(x), Some(y)) => x.same_allocation(y),
623 _ => false,
624 }
625}
626
627fn ensure_no_surviving_text_query(expression: &Expression) -> Result<(), ComputeError> {
638 if expression_references_text_query(expression) {
639 return Err(ComputeError::UnsupportedSparql(
640 "text:query is only supported as a top-level FILTER conjunct (ANDed with \
641 the other conditions); it cannot be nested inside ||, !, IF, COALESCE, \
642 or an OPTIONAL's condition. Restructure the query so the text:query \
643 call is its own FILTER"
644 .to_owned(),
645 ));
646 }
647 Ok(())
648}
649
650fn ensure_no_surviving_text_query_in_optional(expression: &Expression) -> Result<(), ComputeError> {
657 if expression_references_text_query(expression) {
658 return Err(ComputeError::UnsupportedSparql(
659 "text:query cannot answer inside an OPTIONAL: this query lowered the \
660 body's filter into the OPTIONAL's join condition, where the injected \
661 candidate scan would decide whether outer rows survive. Move the \
662 pattern and its text:query FILTER out of the OPTIONAL (a plain group \
663 pattern), or run the OPTIONAL without the text filter"
664 .to_owned(),
665 ));
666 }
667 Ok(())
668}
669
670fn expression_references_text_query(expression: &Expression) -> bool {
672 match expression {
673 Expression::FunctionCall(spargebra::algebra::Function::Custom(iri), args) => {
674 iri.as_str() == TEXT_QUERY_IRI || args.iter().any(expression_references_text_query)
675 }
676 Expression::Or(l, r)
677 | Expression::And(l, r)
678 | Expression::Equal(l, r)
679 | Expression::SameTerm(l, r)
680 | Expression::Greater(l, r)
681 | Expression::GreaterOrEqual(l, r)
682 | Expression::Less(l, r)
683 | Expression::LessOrEqual(l, r)
684 | Expression::Add(l, r)
685 | Expression::Subtract(l, r)
686 | Expression::Multiply(l, r)
687 | Expression::Divide(l, r) => {
688 expression_references_text_query(l) || expression_references_text_query(r)
689 }
690 Expression::In(first, rest) => {
691 expression_references_text_query(first)
692 || rest.iter().any(expression_references_text_query)
693 }
694 Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) | Expression::Not(inner) => {
695 expression_references_text_query(inner)
696 }
697 Expression::If(condition, then, otherwise) => {
698 expression_references_text_query(condition)
699 || expression_references_text_query(then)
700 || expression_references_text_query(otherwise)
701 }
702 Expression::Coalesce(arms) | Expression::FunctionCall(_, arms) => {
703 arms.iter().any(expression_references_text_query)
704 }
705 Expression::NamedNode(_)
707 | Expression::Literal(_)
708 | Expression::Variable(_)
709 | Expression::Bound(_) => false,
710 Expression::Exists(_) => false,
716 }
717}
718
719enum TextMatch {
721 None,
723 Terms {
728 request: TextSearchRequest,
729 variable: waratah_storage::Variable,
730 strip: bool,
731 },
732 Subject {
734 request: TextSearchRequest,
735 variable: waratah_storage::Variable,
736 predicates: Vec<oxrdf::NamedNode>,
737 },
738}
739
740fn is_text_query_predicate(scan: &waratah_compute::ScanOp) -> bool {
741 scan.pattern.predicate.as_ref().is_some_and(|term| {
744 matches!(term, EncodedTerm::NamedNode { .. })
745 && *term
746 == EncodedTerm::NamedNode {
747 iri_id: waratah_storage::StrHash::new(TEXT_QUERY_IRI),
748 }
749 })
750}
751
752impl TextPlannerPlugin {
753 fn match_conjunct(
755 &self,
756 conjunct: &Expression,
757 inner: &PlanNode,
758 ctx: &QueryContext,
759 ) -> Result<TextMatch, ComputeError> {
760 match conjunct {
761 Expression::FunctionCall(Function::Custom(iri), args)
762 if iri.as_str() == TEXT_QUERY_IRI =>
763 {
764 self.match_text_query(args, inner, ctx)
765 }
766 Expression::FunctionCall(Function::StrStarts, args) => {
767 self.match_string_function(args, inner, ctx, TextCandidateMode::Prefix)
768 }
769 Expression::FunctionCall(Function::StrEnds, args) => {
770 self.match_string_function(args, inner, ctx, TextCandidateMode::Suffix)
771 }
772 Expression::FunctionCall(Function::Regex, args) => {
773 self.match_anchored_regex(args, inner, ctx)
774 }
775 _ => Ok(TextMatch::None),
776 }
777 }
778
779 fn match_text_query(
786 &self,
787 args: &[Expression],
788 inner: &PlanNode,
789 ctx: &QueryContext,
790 ) -> Result<TextMatch, ComputeError> {
791 if !self.trusted(ctx) {
794 return Err(ComputeError::UnsupportedSparql(untrusted_message()));
795 }
796 match args {
797 [Expression::Variable(variable), rest @ ..]
801 if matches!(rest.first(), Some(Expression::Literal(_))) && rest.len() <= 2 =>
802 {
803 let (query, language) = parse_query_and_lang(rest, 0)?;
804 self.check_literal_variable(inner, variable)?;
805 Ok(TextMatch::Terms {
806 request: TextSearchRequest {
807 mode: TextCandidateMode::Fts,
808 query,
809 language,
810 limit: 0,
811 },
812 variable: variable.clone(),
813 strip: true,
814 })
815 }
816 [Expression::Variable(variable), rest @ ..]
818 if rest.len() >= 2 && matches!(rest.first(), Some(Expression::NamedNode(_))) =>
819 {
820 let split = rest
821 .iter()
822 .position(|arg| matches!(arg, Expression::Literal(_)))
823 .ok_or_else(|| {
824 ComputeError::UnsupportedSparql(
825 "text:query subject mode needs a query string after the predicate IRIs"
826 .to_owned(),
827 )
828 })?;
829 if split == 0 {
830 return Err(ComputeError::UnsupportedSparql(
831 "text:query subject mode needs at least one predicate IRI".to_owned(),
832 ));
833 }
834 let mut predicates = Vec::with_capacity(split);
835 for arg in &rest[..split] {
836 match arg {
837 Expression::NamedNode(node) => predicates.push(node.clone()),
838 _ => {
839 return Err(ComputeError::UnsupportedSparql(
840 "text:query subject mode takes predicate IRIs, then the query string"
841 .to_owned(),
842 ));
843 }
844 }
845 }
846 let (query, language) = parse_query_and_lang(&rest[split..], split)?;
847 if let Some(allow) = self.config.predicate_allowlist() {
852 for predicate in &predicates {
853 if !allow.contains(&waratah_storage::StrHash::new(predicate.as_str())) {
854 return Err(ComputeError::UnsupportedSparql(format!(
855 "text:query names {predicate}, which is not an indexed text \
856 predicate; add it to `predicates` in text.toml (and rebuild \
857 the index), or remove it from the query"
858 )));
859 }
860 }
861 }
862 self.check_subject_variable(inner, variable)?;
863 Ok(TextMatch::Subject {
864 request: TextSearchRequest {
865 mode: TextCandidateMode::Fts,
866 query,
867 language,
868 limit: 0,
869 },
870 variable: variable.clone(),
871 predicates,
872 })
873 }
874 _ => Err(ComputeError::UnsupportedSparql(format!(
875 "unsupported text:query form; expected \
876 text:query(?lit, \"query\" [, \"lang:xx\"]) or \
877 text:query(?s, <field>+, \"query\" [, \"lang:xx\"]), got {args:?}"
878 ))),
879 }
880 }
881
882 fn check_literal_variable(
886 &self,
887 inner: &PlanNode,
888 variable: &waratah_storage::Variable,
889 ) -> Result<(), ComputeError> {
890 let slots = variable_slots(inner, variable);
891 if !slots.is_empty() && slots.iter().all(|slot| *slot == SlotKind::Subject) {
892 return Err(ComputeError::UnsupportedSparql(format!(
893 "text:query bound {variable}, which only appears in subject position; \
894 the subject form is text:query({variable}, <predicate>, \"query\")"
895 )));
896 }
897 Ok(())
898 }
899
900 fn check_subject_variable(
903 &self,
904 inner: &PlanNode,
905 variable: &waratah_storage::Variable,
906 ) -> Result<(), ComputeError> {
907 let slots = variable_slots(inner, variable);
908 if !slots.is_empty() && slots.iter().all(|slot| *slot == SlotKind::Object) {
909 return Err(ComputeError::UnsupportedSparql(format!(
910 "text:query bound {variable}, which only appears in object position; \
911 the literal form is text:query({variable}, \"query\")"
912 )));
913 }
914 Ok(())
915 }
916
917 fn match_string_function(
923 &self,
924 args: &[Expression],
925 inner: &PlanNode,
926 ctx: &QueryContext,
927 mode: TextCandidateMode,
928 ) -> Result<TextMatch, ComputeError> {
929 if !self.trusted(ctx) {
930 return Ok(TextMatch::None);
931 }
932 let Some((variable, pattern)) = parse_var_and_pattern(args) else {
933 return Ok(TextMatch::None);
934 };
935 if !self.text_index_applies(inner, &variable) {
940 return Ok(TextMatch::None);
941 }
942 let Some(request) = seed_request(mode, &pattern, self.seed_chars()) else {
943 return Ok(TextMatch::None);
944 };
945 Ok(TextMatch::Terms {
946 request,
947 variable,
948 strip: false,
949 })
950 }
951
952 fn text_index_applies(&self, node: &PlanNode, variable: &waratah_storage::Variable) -> bool {
977 let allow = self.config.predicate_allowlist();
978 let mut applies = true;
979 let mut object_slot_evidence = false;
980 walk_text_index_applies(
981 node,
982 variable,
983 allow.as_ref(),
984 &mut applies,
985 &mut object_slot_evidence,
986 );
987 applies && object_slot_evidence
988 }
989
990 fn match_anchored_regex(
994 &self,
995 args: &[Expression],
996 inner: &PlanNode,
997 ctx: &QueryContext,
998 ) -> Result<TextMatch, ComputeError> {
999 if !self.trusted(ctx) {
1000 return Ok(TextMatch::None);
1001 }
1002 let Some((variable, mode, anchored)) = parse_anchored_regex(args) else {
1003 return Ok(TextMatch::None);
1004 };
1005 if !self.text_index_applies(inner, variable) {
1006 return Ok(TextMatch::None);
1007 }
1008 let Some(request) = seed_request(mode, anchored, self.seed_chars()) else {
1009 return Ok(TextMatch::None);
1010 };
1011 Ok(TextMatch::Terms {
1012 request,
1013 variable: variable.clone(),
1014 strip: false,
1015 })
1016 }
1017
1018 fn join_text_scan(
1022 &self,
1023 inner: PlanNode,
1024 request: TextSearchRequest,
1025 variable: waratah_storage::Variable,
1026 ctx: &QueryContext,
1027 ) -> PlanNode {
1028 let inner_rows = inner.produced_row_count_estimate();
1029 let scan_rows = candidate_estimate(
1030 &request,
1031 ctx.text_seed_sketch().map(|sketch| sketch.as_ref()),
1032 ctx.text_index_epoch(),
1033 );
1034 let fts = request.mode == TextCandidateMode::Fts;
1037 let mut scan = waratah_compute::CustomOp {
1038 plugin_id: crate::PLUGIN_ID,
1039 op_id: TEXT_SCAN_OP_ID,
1040 payload: PluginPayloadBox::new(TextScanPayload {
1041 request,
1042 analyzer: self.config.analyzer.clone(),
1043 seed_chars: self.config.seed_chars,
1044 }),
1045 children: Vec::new(),
1046 variables: vec![variable.clone()],
1047 produced_row_count_estimate: scan_rows,
1048 cost: Some(waratah_compute::CustomOpCost {
1049 drain_rows: scan_rows,
1050 per_key_unit: 1,
1052 inline_point_unit: 1,
1053 direct_probe: !fts,
1054 probe_keyed_columns: 0,
1057 probe_filter_unit: 1,
1058 probe_memo_entry_rows: waratah_compute::text_probe_memo_entry_terms(),
1061 }),
1062 pinned: Vec::new(),
1063 };
1064 let (left, right) = if scan_rows <= inner_rows {
1065 (PlanNode::CustomNode(scan), inner)
1066 } else {
1067 if let Some(term) = ground_unique_probe_term(&inner, &variable) {
1070 scan.pinned.push((variable.clone(), term));
1071 scan.produced_row_count_estimate = 1;
1072 }
1073 (inner, PlanNode::CustomNode(scan))
1074 };
1075 let strategy = if left.produced_row_count_estimate() <= PUSHDOWN_TERMS_LIMIT {
1076 JoinStrategy::Broadcast
1077 } else {
1078 JoinStrategy::Hash
1079 };
1080 let rhs_hostable_keys =
1081 std::sync::Arc::from(waratah_compute::subtree_hostable_variables(&right));
1082 PlanNode::Join {
1083 left: Box::new(left),
1084 right: Box::new(right),
1085 hash_keys: vec![variable],
1086 probe_key_domains: Vec::new(),
1087 probe_key_overlap_milli: Vec::new(),
1088 rhs_hostable_keys,
1089 meta: waratah_compute::JoinMeta {
1090 star_arms: None,
1091 strategy,
1092 semi_gate: None,
1093 produced_row_count_estimate: inner_rows,
1094 own_push_removed_row_count_estimate: inner_rows,
1095 },
1096 }
1097 }
1098
1099 fn join_subject_scan(
1123 &self,
1124 inner: PlanNode,
1125 request: TextSearchRequest,
1126 variable: waratah_storage::Variable,
1127 predicates: &[oxrdf::NamedNode],
1128 scope: &waratah_compute::AppliedGraph,
1129 ctx: &QueryContext,
1130 ) -> Result<PlanNode, ComputeError> {
1131 let encoded_predicates: Vec<EncodedTerm> =
1135 predicates.iter().map(EncodedTerm::from).collect();
1136 let subject_rows = match request.mode {
1143 TextCandidateMode::Fts => {
1144 fts_placeholder_literals(&request.query).saturating_mul(TEXT_SUBJECT_FANOUT)
1145 }
1146 _ => candidate_estimate(
1147 &request,
1148 ctx.text_seed_sketch().map(|sketch| sketch.as_ref()),
1149 ctx.text_index_epoch(),
1150 ),
1151 };
1152 let subject_equals_graph = scope.graph.as_ref() == Some(&variable);
1153 let emit_graph = scope.graph.as_ref().is_some_and(|graph| graph != &variable);
1158 let mut variables = vec![variable.clone()];
1159 if emit_graph {
1160 variables.push(
1161 scope
1162 .graph
1163 .clone()
1164 .expect("emit_graph implies a graph variable"),
1165 );
1166 }
1167 let (graph_filter_terms, graph_filter_allow) =
1168 waratah_compute::GraphFilter::to_wire(scope.graph_filter.as_ref());
1169 let payload = TextSubjectsPayload {
1170 request: TextSubjectRequest {
1171 mode: request.mode,
1172 query: request.query.clone(),
1173 language: request.language.clone(),
1174 limit: request.limit,
1175 predicates: encoded_predicates,
1176 graph_name: scope.graph_name.clone(),
1177 graph_filter_terms: graph_filter_terms.to_vec(),
1178 graph_filter_allow,
1179 merge_default_graph: scope.merge_default_graph,
1180 return_graph: emit_graph,
1181 subject_equals_graph,
1182 },
1183 };
1184 let subjects = PlanNode::CustomNode(waratah_compute::CustomOp {
1185 plugin_id: crate::PLUGIN_ID,
1186 op_id: TEXT_SUBJECTS_OP_ID,
1187 payload: PluginPayloadBox::new(payload),
1188 children: Vec::new(),
1189 variables,
1190 produced_row_count_estimate: subject_rows,
1191 cost: Some(waratah_compute::CustomOpCost {
1192 drain_rows: subject_rows,
1193 per_key_unit: 1,
1194 inline_point_unit: 1,
1195 direct_probe: false,
1198 probe_keyed_columns: 0b1,
1207 probe_filter_unit: 1,
1208 probe_memo_entry_rows: waratah_compute::text_subject_memo_entry_rows(emit_graph),
1213 }),
1214 pinned: Vec::new(),
1215 });
1216 let inner_rows = inner.produced_row_count_estimate();
1217 let strategy = if subjects.produced_row_count_estimate() <= PUSHDOWN_TERMS_LIMIT {
1221 JoinStrategy::Broadcast
1222 } else {
1223 JoinStrategy::Hash
1224 };
1225 let rhs_hostable_keys =
1226 std::sync::Arc::from(waratah_compute::subtree_hostable_variables(&inner));
1227 Ok(PlanNode::Join {
1228 left: Box::new(subjects),
1229 right: Box::new(inner),
1230 hash_keys: vec![variable],
1231 probe_key_domains: Vec::new(),
1232 probe_key_overlap_milli: Vec::new(),
1233 rhs_hostable_keys,
1234 meta: waratah_compute::JoinMeta {
1235 star_arms: None,
1236 strategy,
1237 semi_gate: None,
1238 produced_row_count_estimate: inner_rows,
1239 own_push_removed_row_count_estimate: inner_rows,
1240 },
1241 })
1242 }
1243}
1244
1245fn untrusted_message() -> String {
1247 "text:query requires a trusted text index (no build epoch is stamped, or the partition's \
1248 index was built by different settings); run `waratah text rebuild-index`, or start the \
1249 cluster with the text plugin enabled so the startup build stamps the epoch"
1250 .to_owned()
1251}
1252
1253fn parse_query_and_lang(
1255 args: &[Expression],
1256 offset: usize,
1257) -> Result<(String, Option<String>), ComputeError> {
1258 let query = match args.first() {
1263 Some(Expression::Literal(literal))
1264 if literal.language().is_none()
1265 && literal.datatype().as_str() == "http://www.w3.org/2001/XMLSchema#string" =>
1266 {
1267 literal.value().to_owned()
1268 }
1269 _ => {
1270 return Err(ComputeError::UnsupportedSparql(format!(
1271 "text:query argument {} must be a plain string literal (the query)",
1272 offset + 1
1273 )));
1274 }
1275 };
1276 if query.trim().is_empty() {
1277 return Err(ComputeError::UnsupportedSparql(
1278 "text:query with an empty query is not answerable (every string matches); \
1279 write a real query"
1280 .to_owned(),
1281 ));
1282 }
1283 let language = match args.get(1) {
1284 None => None,
1285 Some(Expression::Literal(literal))
1287 if literal.language().is_none()
1288 && literal.datatype().as_str() == "http://www.w3.org/2001/XMLSchema#string" =>
1289 {
1290 let value = literal.value();
1291 let Some(tag) = value.strip_prefix("lang:") else {
1292 return Err(ComputeError::UnsupportedSparql(format!(
1293 "text:query trailing argument must be \"lang:xx\", got {value:?}"
1294 )));
1295 };
1296 Some(tag.to_owned())
1297 }
1298 Some(other) => {
1299 return Err(ComputeError::UnsupportedSparql(format!(
1300 "text:query trailing argument must be \"lang:xx\", got {other:?}"
1301 )));
1302 }
1303 };
1304 if args.len() > 2 {
1305 return Err(ComputeError::UnsupportedSparql(
1306 "text:query takes at most a query and a \"lang:xx\" argument after the variable / predicates"
1307 .to_owned(),
1308 ));
1309 }
1310 Ok((query, language))
1311}
1312
1313fn parse_var_and_pattern(args: &[Expression]) -> Option<(waratah_storage::Variable, String)> {
1315 let [Expression::Variable(variable), Expression::Literal(pattern)] = args else {
1318 return None;
1319 };
1320 if pattern.language().is_some() {
1321 return None;
1322 }
1323 Some((variable.clone(), pattern.value().to_owned()))
1324}
1325
1326fn parse_anchored_regex(
1335 args: &[Expression],
1336) -> Option<(&waratah_storage::Variable, TextCandidateMode, &str)> {
1337 let [Expression::Variable(variable), Expression::Literal(pattern)] = args else {
1338 return None;
1339 };
1340 let raw = pattern.value();
1341 let (mode, body) = if let Some(body) = raw.strip_prefix('^') {
1342 (TextCandidateMode::Prefix, body)
1343 } else if let Some(body) = raw
1344 .strip_prefix(".*")
1345 .and_then(|rest| rest.strip_suffix('$'))
1346 {
1347 (TextCandidateMode::Suffix, body)
1348 } else {
1349 return None;
1350 };
1351 if body.is_empty() || body.chars().any(|c| REGEX_METACHARACTERS.contains(&c)) {
1352 return None;
1353 }
1354 Some((variable, mode, body))
1355}
1356
1357fn seed_request(
1365 mode: TextCandidateMode,
1366 pattern: &str,
1367 _seed_chars: usize,
1368) -> Option<TextSearchRequest> {
1369 if pattern.is_empty() {
1370 return None;
1371 }
1372 Some(match mode {
1373 TextCandidateMode::Prefix => TextSearchRequest::prefix(pattern.to_owned()),
1374 TextCandidateMode::Suffix => TextSearchRequest::suffix(pattern.to_owned()),
1375 TextCandidateMode::Fts => return None,
1376 })
1377}
1378
1379fn fts_placeholder_literals(query: &str) -> u64 {
1417 match query.trim().chars().count() {
1418 0..=4 => PUSHDOWN_TERMS_LIMIT * 8,
1419 5..=7 => PUSHDOWN_TERMS_LIMIT * 4,
1420 _ => PUSHDOWN_TERMS_LIMIT / 4,
1421 }
1422}
1423
1424const TEXT_SUBJECT_FANOUT: u64 = 4;
1428
1429fn candidate_estimate(
1441 request: &TextSearchRequest,
1442 sketch: Option<&waratah_stats::TextSeedSketch>,
1443 index_epoch: Option<u64>,
1444) -> u64 {
1445 match request.mode {
1446 TextCandidateMode::Fts => UNPRICED_DRAIN_SEAT_ESTIMATE,
1447 TextCandidateMode::Prefix | TextCandidateMode::Suffix => {
1448 if let Some(rows) = match (sketch, request.mode) {
1461 (Some(sketch), _) if sketch.prices_at(index_epoch) => match request.mode {
1462 TextCandidateMode::Prefix => {
1463 sketch.estimate_prefix(&request.query, index_epoch)
1464 }
1465 TextCandidateMode::Suffix => {
1466 sketch.estimate_suffix(&request.query, index_epoch)
1467 }
1468 TextCandidateMode::Fts => None,
1469 },
1470 _ => None,
1471 } {
1472 return rows.max(1);
1473 }
1474 UNPRICED_DRAIN_SEAT_ESTIMATE
1489 }
1490 }
1491}
1492
1493#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1495enum SlotKind {
1496 Subject,
1497 Predicate,
1498 Object,
1499}
1500
1501fn variable_slots(node: &PlanNode, variable: &waratah_storage::Variable) -> Vec<SlotKind> {
1502 let mut out = Vec::new();
1503 collect_variable_slots(node, variable, &mut out);
1504 out
1505}
1506
1507fn collect_variable_slots(
1508 node: &PlanNode,
1509 variable: &waratah_storage::Variable,
1510 out: &mut Vec<SlotKind>,
1511) {
1512 match node {
1513 PlanNode::Scan(scan) => {
1514 if scan.subject.as_ref() == Some(variable) {
1515 out.push(SlotKind::Subject);
1516 }
1517 if scan.predicate.as_ref() == Some(variable) {
1518 out.push(SlotKind::Predicate);
1519 }
1520 if scan.object.as_ref() == Some(variable) {
1521 out.push(SlotKind::Object);
1522 }
1523 }
1524 PlanNode::Path(op) => {
1525 if op.subject.as_ref() == Some(variable) {
1532 out.push(SlotKind::Subject);
1533 }
1534 if op.object.as_ref() == Some(variable) {
1535 out.push(SlotKind::Object);
1536 }
1537 }
1538 PlanNode::Values(values) => {
1539 let Some(column) = values.variables.iter().position(|v| v == variable) else {
1546 return;
1547 };
1548 for row in &values.rows {
1549 if let Some(term) = row.get(column).and_then(|term| term.as_ref()) {
1550 out.push(ground_term_slot(term));
1551 }
1552 }
1553 }
1554 PlanNode::Extend {
1555 inner,
1556 variable: bound,
1557 expression,
1558 ..
1559 } => {
1560 if bound == variable {
1565 match expression {
1566 Expression::Literal(_) => out.push(SlotKind::Object),
1567 Expression::NamedNode(_) => out.push(SlotKind::Subject),
1568 _ => {}
1569 }
1570 }
1571 collect_variable_slots(inner, variable, out);
1572 }
1573 PlanNode::Join { left, right, .. }
1574 | PlanNode::LeftJoin { left, right, .. }
1575 | PlanNode::Union { left, right } => {
1576 collect_variable_slots(left, variable, out);
1577 collect_variable_slots(right, variable, out);
1578 }
1579 PlanNode::CustomNode(op) => {
1580 for child in &op.children {
1581 collect_variable_slots(child, variable, out);
1582 }
1583 }
1584 PlanNode::Filter { inner, .. }
1585 | PlanNode::Slice { inner, .. }
1586 | PlanNode::Distinct { inner, .. }
1587 | PlanNode::Sort { inner, .. }
1588 | PlanNode::Group { inner, .. }
1589 | PlanNode::JoinGraphVar { inner, .. } => collect_variable_slots(inner, variable, out),
1590 PlanNode::SubSelect(sub) => collect_variable_slots(&sub.inner, variable, out),
1591 _ => {}
1592 }
1593}
1594
1595fn walk_text_index_applies(
1601 node: &PlanNode,
1602 variable: &waratah_storage::Variable,
1603 allow: Option<&std::collections::HashSet<waratah_storage::StrHash>>,
1604 applies: &mut bool,
1605 object_slot_evidence: &mut bool,
1606) {
1607 if !*applies {
1608 return;
1609 }
1610 match node {
1611 PlanNode::Scan(scan) => {
1612 if scan.object.as_ref() != Some(variable) {
1613 return;
1614 }
1615 let Some(EncodedTerm::NamedNode { iri_id }) = &scan.pattern.predicate else {
1618 *applies = false;
1619 return;
1620 };
1621 if allow.is_some_and(|allow| !allow.contains(iri_id)) {
1622 *applies = false;
1623 return;
1624 }
1625 *object_slot_evidence = true;
1628 }
1629 PlanNode::Path(op) => {
1630 if op.object.as_ref() == Some(variable) {
1631 *applies = false;
1632 }
1633 }
1634 PlanNode::Values(values) if values.variables.contains(variable) => {
1639 *applies = false;
1640 }
1641 PlanNode::Extend {
1644 variable: bound, ..
1645 } if bound == variable => {
1646 *applies = false;
1647 }
1648 PlanNode::Join { left, right, .. }
1649 | PlanNode::LeftJoin { left, right, .. }
1650 | PlanNode::Union { left, right } => {
1651 walk_text_index_applies(left, variable, allow, applies, object_slot_evidence);
1652 walk_text_index_applies(right, variable, allow, applies, object_slot_evidence);
1653 }
1654 PlanNode::CustomNode(op) => {
1655 for child in &op.children {
1656 walk_text_index_applies(child, variable, allow, applies, object_slot_evidence);
1657 }
1658 }
1659 PlanNode::Filter { inner, .. }
1660 | PlanNode::Slice { inner, .. }
1661 | PlanNode::Distinct { inner, .. }
1662 | PlanNode::Sort { inner, .. }
1663 | PlanNode::Group { inner, .. }
1664 | PlanNode::JoinGraphVar { inner, .. }
1665 | PlanNode::Extend { inner, .. } => {
1666 walk_text_index_applies(inner, variable, allow, applies, object_slot_evidence);
1667 }
1668 PlanNode::SubSelect(sub) => {
1669 walk_text_index_applies(&sub.inner, variable, allow, applies, object_slot_evidence);
1670 }
1671 _ => {}
1672 }
1673}
1674
1675fn ground_term_slot(term: &EncodedTerm) -> SlotKind {
1679 match term {
1680 EncodedTerm::NamedNode { .. }
1681 | EncodedTerm::NumericalBlankNode { .. }
1682 | EncodedTerm::SmallBlankNode(_)
1683 | EncodedTerm::BigBlankNode { .. } => SlotKind::Subject,
1684 _ => SlotKind::Object,
1688 }
1689}
1690
1691#[cfg(test)]
1692mod tests {
1693 use super::*;
1694
1695 #[test]
1696 fn candidate_producers_are_pinned_through_the_optimizer() {
1697 let plugin = TextPlannerPlugin::new(TextPluginConfig::default());
1698 let variable =
1699 |name: &str| Expression::Variable(waratah_storage::Variable::new_unchecked(name));
1700 let literal = |value: &str| Expression::Literal(waratah_storage::Literal::from(value));
1701 let function =
1702 |function: Function, args: Vec<Expression>| Expression::FunctionCall(function, args);
1703 let custom = |iri: &str, args: Vec<Expression>| {
1704 Expression::FunctionCall(
1705 Function::Custom(waratah_storage::NamedNode::new_unchecked(iri)),
1706 args,
1707 )
1708 };
1709
1710 assert!(plugin.pins_through_optimizer(&custom(TEXT_QUERY_IRI, vec![variable("r")])));
1712
1713 assert!(plugin.pins_through_optimizer(&function(
1716 Function::StrStarts,
1717 vec![variable("lit"), literal("abc")]
1718 )));
1719 assert!(!plugin.pins_through_optimizer(&function(
1720 Function::StrStarts,
1721 vec![variable("lit"), variable("needle")]
1722 )));
1723 assert!(!plugin.pins_through_optimizer(&function(
1724 Function::StrEnds,
1725 vec![literal("abc"), literal("abc")]
1726 )));
1727 assert!(plugin.pins_through_optimizer(&function(
1728 Function::Regex,
1729 vec![variable("lit"), literal("^abc")]
1730 )));
1731 assert!(!plugin.pins_through_optimizer(&function(
1732 Function::Regex,
1733 vec![variable("lit"), literal("abc")]
1734 )));
1735 assert!(
1736 !plugin.pins_through_optimizer(&function(
1737 Function::Regex,
1738 vec![variable("lit"), literal("^a.c")]
1739 )),
1740 "a metacharacter body is not a seedable prefix"
1741 );
1742 assert!(!plugin.pins_through_optimizer(&function(
1743 Function::Regex,
1744 vec![variable("lit"), literal("^abc"), literal("i")]
1745 )));
1746
1747 assert!(
1748 !plugin.pins_through_optimizer(&custom(
1749 "http://example.org/not-text",
1750 vec![variable("r")]
1751 )),
1752 "an unrelated custom function is not a text candidate producer"
1753 );
1754 assert!(!plugin.pins_through_optimizer(&variable("r")));
1755
1756 assert!(plugin.keeps_variable_when_ground(&custom(TEXT_QUERY_IRI, vec![variable("r")])));
1760 for kind in [Function::StrStarts, Function::StrEnds, Function::Regex] {
1761 assert!(
1762 !plugin.keeps_variable_when_ground(&function(
1763 kind,
1764 vec![variable("lit"), literal("abc")]
1765 )),
1766 "a string function grounds to an exact per-row predicate"
1767 );
1768 }
1769 assert!(!plugin.keeps_variable_when_ground(&custom(
1770 "http://example.org/not-text",
1771 vec![variable("r")]
1772 )));
1773 }
1774
1775 #[test]
1776 fn seed_requests_skip_empty_patterns_and_fts() {
1777 assert!(seed_request(TextCandidateMode::Prefix, "", 16).is_none());
1778 assert!(seed_request(TextCandidateMode::Fts, "abc", 16).is_none());
1779 let request = seed_request(TextCandidateMode::Prefix, "abc", 16).unwrap();
1780 assert_eq!(request.mode, TextCandidateMode::Prefix);
1781 assert_eq!(request.query, "abc");
1782 assert_eq!(request.limit, 0);
1783 }
1784
1785 #[test]
1786 fn anchored_regex_shapes_parse() {
1787 let prefix = seed_request(TextCandidateMode::Prefix, "abc", 16).unwrap();
1790 let suffix = seed_request(TextCandidateMode::Suffix, "cba", 16).unwrap();
1791 assert_eq!(prefix.mode, TextCandidateMode::Prefix);
1792 assert_eq!(suffix.mode, TextCandidateMode::Suffix);
1793 }
1794
1795 #[test]
1796 fn unpriced_stamp_seats_every_in_band_seed_above_broadcast() {
1797 let fts = TextSearchRequest::fts("word");
1798 assert!(candidate_estimate(&fts, None, None) > PUSHDOWN_TERMS_LIMIT);
1805 for pattern in [
1812 "a",
1813 "ab",
1814 "abc",
1815 "abcd",
1816 "abcde",
1817 "abcdefghij",
1818 "abcdefghijklmnop",
1819 ] {
1820 assert_eq!(
1821 candidate_estimate(&TextSearchRequest::prefix(pattern), None, None),
1822 UNPRICED_DRAIN_SEAT_ESTIMATE,
1823 "in-band prefix {pattern} seats at the flat value"
1824 );
1825 assert_eq!(
1826 candidate_estimate(&TextSearchRequest::suffix(pattern), None, None),
1827 UNPRICED_DRAIN_SEAT_ESTIMATE,
1828 "in-band suffix {pattern} seats at the flat value"
1829 );
1830 }
1831 let past_seed = TextSearchRequest::prefix("abcdefghijklmnopq"); assert_eq!(
1836 candidate_estimate(&past_seed, None, None),
1837 UNPRICED_DRAIN_SEAT_ESTIMATE,
1838 "past the seed the drain is unpriced"
1839 );
1840 assert_eq!(
1841 candidate_estimate(&TextSearchRequest::prefix("abcdefghi"), None, None),
1842 UNPRICED_DRAIN_SEAT_ESTIMATE,
1843 "9 chars is past an 8-char seed"
1844 );
1845 }
1846
1847 #[test]
1848 fn sketched_estimate_prices_from_the_cms() {
1849 use waratah_stats::TextSeedSketch;
1850 const EPOCH: u64 = 1794192803976;
1851 let mut sketch = TextSeedSketch::collector(16);
1855 for i in 0..2000u64 {
1856 for _ in 0..140 {
1857 sketch.record(&format!("eco-watchdataset1{i:08}"));
1858 }
1859 }
1860 sketch.record("windy");
1861 sketch.epoch = EPOCH;
1862 let epoch = Some(EPOCH);
1863 let win = candidate_estimate(&TextSearchRequest::prefix("win"), Some(&sketch), epoch);
1868 assert!(win >= 1, "never under the true family of 1");
1869 assert!(win <= 60, "near-exact on this corpus, got {win}");
1870 let fat = candidate_estimate(
1874 &TextSearchRequest::prefix("eco-watchdataset1submission30"),
1875 Some(&sketch),
1876 epoch,
1877 );
1878 assert!(fat >= 2_000 * 140, "never under the family total");
1879 assert!(
1880 fat <= 2_000 * 140 + 600,
1881 "near-exact (noise ≈ 280k/19k ≈ 15k per cell, row-min far below), got {fat}"
1882 );
1883 assert_eq!(
1886 candidate_estimate(
1887 &TextSearchRequest::prefix("eco-watchdataset1"),
1888 Some(&sketch),
1889 Some(999),
1890 ),
1891 UNPRICED_DRAIN_SEAT_ESTIMATE,
1892 "a stale sketch never prices"
1893 );
1894 assert_eq!(
1895 candidate_estimate(&TextSearchRequest::prefix("x"), Some(&sketch), None),
1896 UNPRICED_DRAIN_SEAT_ESTIMATE,
1897 "no trusted index epoch, no price"
1898 );
1899 let suffix = candidate_estimate(&TextSearchRequest::suffix("dy"), Some(&sketch), epoch);
1903 assert!(suffix >= 1, "the end direction carries the same walk");
1904 }
1905
1906 use waratah_compute::LogicalPlan;
1909 use waratah_storage::SnapshotId;
1910
1911 fn installed() {
1912 crate::install();
1913 }
1914
1915 fn find_text_join(node: &PlanNode) -> Option<&waratah_compute::CustomOp> {
1920 match node {
1921 PlanNode::Filter { inner, .. } => find_text_join(inner),
1922 PlanNode::Join { left, right, .. } => {
1923 find_text_join(left).or_else(|| find_text_join(right))
1924 }
1925 PlanNode::LeftJoin { left, right, .. } => {
1926 find_text_join(left).or_else(|| find_text_join(right))
1927 }
1928 PlanNode::Union { left, right } => {
1929 find_text_join(left).or_else(|| find_text_join(right))
1930 }
1931 PlanNode::Extend { inner, .. }
1932 | PlanNode::Slice { inner, .. }
1933 | PlanNode::Distinct { inner, .. }
1934 | PlanNode::Sort { inner, .. }
1935 | PlanNode::Group { inner, .. }
1936 | PlanNode::JoinGraphVar { inner, .. } => find_text_join(inner),
1937 PlanNode::SubSelect(sub) => find_text_join(&sub.inner),
1938 PlanNode::CustomNode(op) if op.op_id == TEXT_SCAN_OP_ID => Some(op),
1939 _ => None,
1940 }
1941 }
1942
1943 fn find_subject_op(node: &PlanNode) -> Option<&waratah_compute::CustomOp> {
1945 let mut ops = Vec::new();
1946 subject_ops(node, &mut ops);
1947 ops.into_iter().next()
1948 }
1949
1950 fn subject_ops<'a>(node: &'a PlanNode, out: &mut Vec<&'a waratah_compute::CustomOp>) {
1953 match node {
1954 PlanNode::CustomNode(op) if op.op_id == TEXT_SUBJECTS_OP_ID => out.push(op),
1955 PlanNode::Filter { inner, .. }
1956 | PlanNode::Extend { inner, .. }
1957 | PlanNode::Slice { inner, .. }
1958 | PlanNode::Distinct { inner, .. }
1959 | PlanNode::Sort { inner, .. }
1960 | PlanNode::Group { inner, .. }
1961 | PlanNode::JoinGraphVar { inner, .. } => subject_ops(inner, out),
1962 PlanNode::Join { left, right, .. }
1963 | PlanNode::LeftJoin { left, right, .. }
1964 | PlanNode::Union { left, right } => {
1965 subject_ops(left, out);
1966 subject_ops(right, out);
1967 }
1968 PlanNode::SubSelect(sub) => subject_ops(&sub.inner, out),
1969 _ => {}
1970 }
1971 }
1972
1973 fn subject_request(op: &waratah_compute::CustomOp) -> &waratah_storage::TextSubjectRequest {
1975 &op.payload
1976 .downcast_ref::<TextSubjectsPayload>()
1977 .expect("text_subjects payload")
1978 .request
1979 }
1980
1981 fn find_filter(node: &PlanNode) -> bool {
1983 match node {
1984 PlanNode::Filter { .. } => true,
1985 PlanNode::Join { left, right, .. }
1986 | PlanNode::LeftJoin { left, right, .. }
1987 | PlanNode::Union { left, right } => find_filter(left) || find_filter(right),
1988 PlanNode::CustomNode(op) => op.children.iter().any(find_filter),
1989 _ => false,
1990 }
1991 }
1992
1993 fn find_subject_distinct(node: &PlanNode) -> Option<&PlanNode> {
1996 match node {
1997 PlanNode::Join { left, right, .. } => {
1998 find_subject_distinct(left).or_else(|| find_subject_distinct(right))
1999 }
2000 PlanNode::Distinct { inner, .. } => {
2001 let mut ops = Vec::new();
2002 subject_ops(inner, &mut ops);
2003 (!ops.is_empty()).then_some(node)
2004 }
2005 PlanNode::Filter { inner, .. }
2006 | PlanNode::JoinGraphVar { inner, .. }
2007 | PlanNode::Slice { inner, .. } => find_subject_distinct(inner),
2008 _ => None,
2009 }
2010 }
2011
2012 fn trusted_ctx() -> waratah_compute::QueryContext {
2014 waratah_compute::QueryContext::from_snapshot(SnapshotId::latest()).with_text_index_state(
2015 Some(1),
2016 crate::TextPluginConfig {
2017 enabled: true,
2018 predicates: Vec::new(),
2021 ..crate::TextPluginConfig::default()
2022 }
2023 .fingerprint(),
2024 )
2025 }
2026
2027 fn rewrite_plan(sparql: &str) -> Result<LogicalPlan, ComputeError> {
2028 installed();
2029 LogicalPlan::parse_with_context(sparql, &trusted_ctx())
2032 }
2033
2034 const TEXT: &str = "http://jena.apache.org/text#";
2035
2036 #[test]
2037 fn fts_placeholder_bands_all_fit_the_subject_memo() {
2038 let subject_only = waratah_compute::text_subject_memo_entry_rows(false);
2045 let with_graph = waratah_compute::text_subject_memo_entry_rows(true);
2046 for query in [
2047 "zinc",
2048 "data",
2049 "report",
2050 "geology",
2051 "deposit",
2052 "kalgoorlie",
2053 "cache-creek",
2054 "comodoro-rivadavia",
2055 ] {
2056 let subjects = fts_placeholder_literals(query).saturating_mul(TEXT_SUBJECT_FANOUT);
2057 assert!(
2058 subjects <= subject_only,
2059 "{query}: {subjects} subject ids must fit the {subject_only}-id memo"
2060 );
2061 assert!(
2062 subjects <= with_graph,
2063 "{query}: {subjects} rows must fit the {with_graph}-row graph memo"
2064 );
2065 }
2066 assert!(
2069 2_036_197 <= with_graph,
2070 "the measured report window must be memoizable with its graph column"
2071 );
2072 }
2073
2074 #[test]
2075 fn literal_mode_text_query_strips_the_conjunct_and_joins_the_scan() {
2076 let plan = rewrite_plan(&format!(
2077 "PREFIX text: <{TEXT}>
2078 SELECT ?name WHERE {{
2079 ?x <http://ex/name> ?name .
2080 FILTER(text:query(?name, \"laser printer\"))
2081 }}"
2082 ))
2083 .unwrap();
2084 let op = find_text_join(&plan.root).expect("text_scan joined into the plan");
2085 assert_eq!(op.op_id, TEXT_SCAN_OP_ID);
2086 let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
2087 assert_eq!(payload.request.mode, TextCandidateMode::Fts);
2088 assert_eq!(payload.request.query, "laser printer");
2089 assert_eq!(payload.request.language, None);
2090 assert!(
2093 !find_filter(&plan.root),
2094 "a fully-stripped text:query leaves no Filter node"
2095 );
2096 }
2097
2098 #[test]
2099 fn literal_mode_with_a_language_restriction_carries_the_tag() {
2100 let plan = rewrite_plan(&format!(
2101 "PREFIX text: <{TEXT}>
2102 SELECT ?name WHERE {{
2103 ?x <http://ex/name> ?name .
2104 FILTER(text:query(?name, \"bonjour\", \"lang:fr\"))
2105 }}"
2106 ))
2107 .unwrap();
2108 let op = find_text_join(&plan.root).expect("text_scan joined into the plan");
2109 let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
2110 assert_eq!(payload.request.language.as_deref(), Some("fr"));
2111 }
2112
2113 #[test]
2114 fn subject_mode_joins_the_partition_resolve_on_the_subject() {
2115 let plan = rewrite_plan(&format!(
2116 "PREFIX text: <{TEXT}>
2117 SELECT ?person WHERE {{
2118 ?person <http://ex/livesIn> ?city .
2119 FILTER(text:query(?person, <http://ex/bio>, \"mountain\"))
2120 }}"
2121 ))
2122 .unwrap();
2123 let op = find_subject_op(&plan.root).expect("the subject resolve op");
2126 assert_eq!(op.op_id, TEXT_SUBJECTS_OP_ID);
2127 let request = subject_request(op);
2128 assert_eq!(request.mode, TextCandidateMode::Fts);
2129 assert_eq!(request.query, "mountain");
2130 assert_eq!(
2131 request.predicates,
2132 vec![EncodedTerm::from(
2133 &oxrdf::NamedNode::new("http://ex/bio").unwrap()
2134 )],
2135 "the predicate IRI is encoded into the request"
2136 );
2137 assert!(!request.return_graph, "no graph variable is bound");
2138 assert_eq!(
2139 op.variables,
2140 vec![waratah_storage::Variable::new_unchecked("person")]
2141 );
2142 assert!(
2144 !find_filter(&plan.root),
2145 "a fully-stripped text:query leaves no Filter node"
2146 );
2147 assert!(
2148 matches!(&plan.root, PlanNode::Join { hash_keys, .. }
2149 if hash_keys == &vec![waratah_storage::Variable::new_unchecked("person")]),
2150 "the resolve joins the branch on the subject: {:?}",
2151 plan.root
2152 );
2153 }
2154
2155 #[test]
2162 fn subject_op_prices_its_memo_and_its_keyed_probe() {
2163 let plan = rewrite_plan(
2164 "SELECT ?s WHERE {
2165 ?s <http://ex/bio> ?v .
2166 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2167 }",
2168 )
2169 .unwrap();
2170 let op = find_subject_op(&plan.root).expect("dataset-scope resolve op");
2171 let cost = op.cost.expect("the subject op is stamped");
2172 assert!(
2173 !cost.direct_probe,
2174 "a pushed subject cannot be decided without the resolve"
2175 );
2176 assert_eq!(
2177 cost.probe_keyed_columns, 0b1,
2178 "the subject column is keyed (the memoized window is sorted by it)"
2179 );
2180 assert_eq!(
2181 cost.probe_memo_entry_rows,
2182 waratah_compute::text_subject_memo_entry_rows(false),
2183 "the subject-only shape's admission limit"
2184 );
2185 assert!(
2186 op.probe_drain_amortized(),
2187 "the calibration window fits the subject memo"
2188 );
2189 assert_eq!(
2190 op.probe_page_cost(1_000, Some(0)),
2191 Some((1_000, true)),
2192 "one membership decision per pushed subject, not the whole window"
2193 );
2194
2195 let plan = rewrite_plan(
2197 "SELECT ?g ?s WHERE {
2198 GRAPH ?g {
2199 ?s <http://ex/bio> ?v .
2200 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2201 }
2202 }",
2203 )
2204 .unwrap();
2205 let op = find_subject_op(&plan.root).expect("graph-scope resolve op");
2206 let cost = op.cost.expect("the graph-shape op is stamped");
2207 assert_eq!(
2208 cost.probe_keyed_columns, 0b1,
2209 "the graph column is NOT keyed: the window is sorted by subject"
2210 );
2211 assert_eq!(
2212 cost.probe_memo_entry_rows,
2213 waratah_compute::text_subject_memo_entry_rows(true),
2214 "the graph shape's row limit is half the id budget"
2215 );
2216 assert_eq!(
2217 waratah_compute::text_subject_memo_entry_rows(true) * 2,
2218 waratah_compute::text_subject_memo_entry_rows(false),
2219 "two ids per graph row"
2220 );
2221 assert_eq!(op.probe_page_cost(1_000, Some(0)), Some((1_000, true)));
2225 assert_eq!(
2226 op.probe_page_cost(1_000, Some(1)),
2227 Some((op.produced_row_count_estimate, true)),
2228 "a pushed graph has no index in a subject-sorted window"
2229 );
2230 assert_eq!(
2231 op.probe_page_cost(1_000, None),
2232 Some((op.produced_row_count_estimate, true)),
2233 "an unknown pushed column must price as a scan, never as keyed"
2234 );
2235 }
2236
2237 #[test]
2238 fn two_predicates_are_one_resolve_request() {
2239 let plan = rewrite_plan(&format!(
2240 "PREFIX text: <{TEXT}>
2241 SELECT ?person WHERE {{
2242 ?person <http://ex/livesIn> ?city .
2243 FILTER(text:query(?person, <http://ex/bio>, <http://ex/note>, \"mountain\"))
2244 }}"
2245 ))
2246 .unwrap();
2247 let mut ops = Vec::new();
2248 subject_ops(&plan.root, &mut ops);
2249 assert_eq!(
2250 ops.len(),
2251 1,
2252 "the predicate set is one request, not an arm dimension"
2253 );
2254 assert_eq!(
2255 subject_request(ops[0]).predicates,
2256 vec![
2257 EncodedTerm::from(&oxrdf::NamedNode::new("http://ex/bio").unwrap()),
2258 EncodedTerm::from(&oxrdf::NamedNode::new("http://ex/note").unwrap()),
2259 ],
2260 "both predicate IRIs travel in the one request"
2261 );
2262 }
2263
2264 #[test]
2265 fn strstarts_and_strends_inject_candidates_and_keep_the_conjunct() {
2266 let plan = rewrite_plan(
2267 "SELECT ?name WHERE {
2268 ?x <http://ex/name> ?name .
2269 FILTER(STRSTARTS(?name, \"Bel\"))
2270 }",
2271 )
2272 .unwrap();
2273 let op = find_text_join(&plan.root).expect("text_scan joined into the plan");
2274 let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
2275 assert_eq!(payload.request.mode, TextCandidateMode::Prefix);
2276 assert_eq!(payload.request.query, "Bel");
2277 assert!(
2279 format!("{:?}", plan.root).contains("Filter"),
2280 "the Filter node must survive with the exact conjunct"
2281 );
2282 }
2283
2284 #[test]
2285 fn strends_seeds_the_suffix_mode() {
2286 let plan = rewrite_plan(
2287 "SELECT ?name WHERE {
2288 ?x <http://ex/name> ?name .
2289 FILTER(STRENDS(?name, \"lin\"))
2290 }",
2291 )
2292 .unwrap();
2293 let op = find_text_join(&plan.root).expect("text_scan joined into the plan");
2294 let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
2295 assert_eq!(payload.request.mode, TextCandidateMode::Suffix);
2296 assert_eq!(payload.request.query, "lin");
2297 }
2298
2299 fn allowlist_config(predicates: &[&str]) -> TextPluginConfig {
2300 TextPluginConfig {
2301 enabled: true,
2302 predicates: predicates
2303 .iter()
2304 .map(|predicate| (*predicate).to_owned())
2305 .collect(),
2306 ..TextPluginConfig::default()
2307 }
2308 }
2309
2310 #[test]
2311 fn text_index_applies_requires_an_allowed_constant_predicate() {
2312 let variable = waratah_storage::Variable::new_unchecked("l");
2313 let plan = LogicalPlan::parse("SELECT ?l WHERE { ?s <http://ex/name> ?l }").unwrap();
2314 assert!(
2315 TextPlannerPlugin::new(allowlist_config(&["http://ex/name"]))
2316 .text_index_applies(&plan.root, &variable)
2317 );
2318 assert!(
2319 !TextPlannerPlugin::new(allowlist_config(&["https://schema.org/name"]))
2320 .text_index_applies(&plan.root, &variable),
2321 "an excluded predicate is not covered"
2322 );
2323 assert!(
2324 TextPlannerPlugin::new(allowlist_config(&[])).text_index_applies(&plan.root, &variable),
2325 "an explicit empty allowlist indexes every predicate"
2326 );
2327
2328 let wild = LogicalPlan::parse("SELECT ?l WHERE { ?s ?p ?l }").unwrap();
2329 assert!(
2330 !TextPlannerPlugin::new(allowlist_config(&["http://ex/name"]))
2331 .text_index_applies(&wild.root, &variable),
2332 "a variable predicate cannot be proven covered"
2333 );
2334
2335 let path =
2336 LogicalPlan::parse("SELECT ?o WHERE { <http://ex/s> <http://ex/p>+ ?o }").unwrap();
2337 let object = waratah_storage::Variable::new_unchecked("o");
2338 assert!(
2339 !TextPlannerPlugin::new(allowlist_config(&["http://ex/p"]))
2340 .text_index_applies(&path.root, &object),
2341 "a property-path object is conservatively not covered"
2342 );
2343 }
2344
2345 #[test]
2346 fn text_index_applies_needs_an_object_slot_scan_not_just_values_or_bind() {
2347 let variable = waratah_storage::Variable::new_unchecked("l");
2348 let plugin = TextPlannerPlugin::new(allowlist_config(&[]));
2351
2352 let values = LogicalPlan::parse(r#"SELECT ?l WHERE { VALUES ?l { "alba" } }"#).unwrap();
2353 assert!(
2354 !plugin.text_index_applies(&values.root, &variable),
2355 "a VALUES-only binding proves no index coverage"
2356 );
2357
2358 let bind = LogicalPlan::parse(r#"SELECT ?l WHERE { BIND("alba" AS ?l) }"#).unwrap();
2359 assert!(
2360 !plugin.text_index_applies(&bind.root, &variable),
2361 "a BIND-only binding proves no index coverage"
2362 );
2363
2364 let subject =
2367 LogicalPlan::parse("SELECT ?l WHERE { ?l <http://ex/p> <http://ex/o> }").unwrap();
2368 assert!(
2369 !plugin.text_index_applies(&subject.root, &variable),
2370 "a subject-slot binding is not object-slot coverage"
2371 );
2372
2373 let values_arm = LogicalPlan::parse(
2377 r#"SELECT ?l WHERE { { ?s <http://ex/name> ?l } UNION { VALUES ?l { "alba" } } }"#,
2378 )
2379 .unwrap();
2380 assert!(
2381 !plugin.text_index_applies(&values_arm.root, &variable),
2382 "a VALUES arm reaches the filter unindexed"
2383 );
2384
2385 let bind_arm = LogicalPlan::parse(
2386 r#"SELECT ?l WHERE { { ?s <http://ex/name> ?l } UNION { BIND("alba" AS ?l) } }"#,
2387 )
2388 .unwrap();
2389 assert!(
2390 !plugin.text_index_applies(&bind_arm.root, &variable),
2391 "a BIND arm reaches the filter unindexed"
2392 );
2393
2394 let scanned = LogicalPlan::parse("SELECT ?l WHERE { ?s <http://ex/name> ?l }").unwrap();
2396 assert!(plugin.text_index_applies(&scanned.root, &variable));
2397 }
2398
2399 #[test]
2400 fn a_values_only_string_filter_keeps_the_exact_residual() {
2401 let plan = rewrite_plan(
2409 r#"SELECT ?l WHERE { VALUES ?l { "alba" "beta" } FILTER(STRSTARTS(?l, "al")) }"#,
2410 )
2411 .unwrap();
2412 assert!(
2413 find_text_join(&plan.root).is_none(),
2414 "a VALUES-only binding has no coverage evidence, so no text_scan is injected"
2415 );
2416 }
2417
2418 #[test]
2419 fn a_subject_slot_string_filter_keeps_the_exact_residual() {
2420 let plan = rewrite_plan(
2424 r#"SELECT ?s WHERE { ?s <http://ex/p> <http://ex/o> FILTER(STRSTARTS(?s, "ex")) }"#,
2425 )
2426 .unwrap();
2427 assert!(
2428 find_text_join(&plan.root).is_none(),
2429 "a subject-slot binding has no coverage evidence, so no text_scan is injected"
2430 );
2431 }
2432
2433 #[test]
2434 fn text_query_subject_mode_rejects_an_unindexed_predicate() {
2435 let config = allowlist_config(&["http://ex/indexed"]);
2436 let ctx = waratah_compute::QueryContext::from_snapshot(SnapshotId::latest())
2437 .with_text_index_state(Some(1), config.fingerprint());
2438 let plugin = TextPlannerPlugin::new(config);
2439 let plan = LogicalPlan::parse("SELECT ?s WHERE { ?s <http://ex/indexed> ?o }").unwrap();
2440 let args = vec![
2441 Expression::Variable(waratah_storage::Variable::new_unchecked("s")),
2442 Expression::NamedNode(oxrdf::NamedNode::new("http://ex/other").unwrap()),
2443 Expression::Literal(oxrdf::Literal::new_simple_literal("word")),
2444 ];
2445 let error = match plugin.match_text_query(&args, &plan.root, &ctx) {
2446 Ok(_) => panic!("an unindexed predicate is a plan error"),
2447 Err(error) => error,
2448 };
2449 assert!(
2450 error.to_string().contains("not an indexed text predicate"),
2451 "{error}"
2452 );
2453 }
2454
2455 #[test]
2456 fn anchored_regex_rewrites_only_the_two_anchored_shapes() {
2457 let plan = rewrite_plan(
2459 "SELECT ?name WHERE {
2460 ?x <http://ex/name> ?name .
2461 FILTER(REGEX(?name, \"^Bel\"))
2462 }",
2463 )
2464 .unwrap();
2465 let payload = find_text_join(&plan.root)
2466 .expect("anchored ^ prefix rewrite")
2467 .payload
2468 .downcast_ref::<TextScanPayload>()
2469 .unwrap();
2470 assert_eq!(payload.request.mode, TextCandidateMode::Prefix);
2471 let plan = rewrite_plan(
2473 "SELECT ?name WHERE {
2474 ?x <http://ex/name> ?name .
2475 FILTER(REGEX(?name, \".*lin$\"))
2476 }",
2477 )
2478 .unwrap();
2479 let payload = find_text_join(&plan.root)
2480 .expect("anchored .* suffix rewrite")
2481 .payload
2482 .downcast_ref::<TextScanPayload>()
2483 .unwrap();
2484 assert_eq!(payload.request.mode, TextCandidateMode::Suffix);
2485 let plan = rewrite_plan(
2487 "SELECT ?name WHERE {
2488 ?x <http://ex/name> ?name .
2489 FILTER(REGEX(?name, \"Be.*lin\"))
2490 }",
2491 )
2492 .unwrap();
2493 assert!(
2494 find_text_join(&plan.root).is_none(),
2495 "a general regex has no candidate producer"
2496 );
2497 }
2498
2499 #[test]
2500 fn anchored_regex_bodies_with_metacharacters_stay_unindexed() {
2501 for pattern in [
2509 "^a.c", "^a|b", "^a.*", "^Bel$", ".*a.c$", "^a\\\\.c",
2518 "^a[bc]d", ] {
2520 let sparql = format!(
2521 "SELECT ?name WHERE {{
2522 ?x <http://ex/name> ?name .
2523 FILTER(REGEX(?name, \"{pattern}\"))
2524 }}"
2525 );
2526 let plan = rewrite_plan(&sparql).unwrap();
2527 assert!(
2528 find_text_join(&plan.root).is_none(),
2529 "REGEX body {pattern:?} must stay unindexed (not a literal seed)"
2530 );
2531 }
2532 }
2533
2534 #[test]
2535 fn anchored_regex_literal_bodies_with_plain_specials_still_rewrite() {
2536 let plan = rewrite_plan(
2539 "SELECT ?name WHERE {
2540 ?x <http://ex/name> ?name .
2541 FILTER(REGEX(?name, \"^a-b_c\"))
2542 }",
2543 )
2544 .unwrap();
2545 let payload = find_text_join(&plan.root)
2546 .expect("a hyphen is not regex syntax; the body is literal")
2547 .payload
2548 .downcast_ref::<TextScanPayload>()
2549 .unwrap();
2550 assert_eq!(payload.request.mode, TextCandidateMode::Prefix);
2551 }
2552
2553 #[test]
2554 fn untrusted_text_query_fails_the_plan_with_the_repair_hint() {
2555 installed();
2556 let error = LogicalPlan::parse_with_context(
2558 &format!(
2559 "PREFIX text: <{TEXT}>
2560 SELECT ?name WHERE {{
2561 ?x <http://ex/name> ?name .
2562 FILTER(text:query(?name, \"laser\"))
2563 }}"
2564 ),
2565 &waratah_compute::QueryContext::from_snapshot(SnapshotId::latest()),
2566 )
2567 .expect_err("text:query under an untrusted index must fail the plan");
2568 assert!(
2569 error.to_string().contains("waratah text rebuild-index"),
2570 "the failure names the repair command: {error}"
2571 );
2572 }
2573
2574 #[test]
2575 fn an_empty_partition_fingerprint_is_not_trusted() {
2576 installed();
2581 let ctx = waratah_compute::QueryContext::from_snapshot(SnapshotId::latest())
2582 .with_text_index_state(Some(1), "");
2583 let error = LogicalPlan::parse_with_context(
2584 &format!(
2585 "PREFIX text: <{TEXT}>
2586 SELECT ?name WHERE {{
2587 ?x <http://ex/name> ?name .
2588 FILTER(text:query(?name, \"laser\"))
2589 }}"
2590 ),
2591 &ctx,
2592 )
2593 .expect_err("an empty partition fingerprint must not satisfy the trust gate");
2594 assert!(
2595 error.to_string().contains("waratah text rebuild-index"),
2596 "the failure names the repair command: {error}"
2597 );
2598 }
2599
2600 #[test]
2601 fn subject_mode_keys_follow_the_bound_graph_variable() {
2602 let plan = rewrite_plan(
2610 "SELECT ?s WHERE {
2611 ?s <http://ex/bio> ?v .
2612 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2613 }",
2614 )
2615 .unwrap();
2616 let op = find_subject_op(&plan.root).expect("dataset-scope resolve op");
2617 assert_eq!(
2618 op.variables,
2619 vec![waratah_storage::Variable::new_unchecked("s")]
2620 );
2621 assert!(!subject_request(op).return_graph);
2622 assert!(
2623 find_subject_distinct(&plan.root).is_none(),
2624 "a single scope's op needs no Distinct"
2625 );
2626
2627 let plan = rewrite_plan(
2629 "SELECT ?g ?s WHERE {
2630 GRAPH ?g {
2631 ?s <http://ex/bio> ?v .
2632 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2633 }
2634 }",
2635 )
2636 .unwrap();
2637 let op = find_subject_op(&plan.root).expect("graph-scope resolve op");
2638 assert_eq!(
2639 op.variables,
2640 vec![
2641 waratah_storage::Variable::new_unchecked("s"),
2642 waratah_storage::Variable::new_unchecked("g"),
2643 ]
2644 );
2645 assert!(subject_request(op).return_graph);
2646 assert!(
2647 find_subject_distinct(&plan.root).is_none(),
2648 "one scope, even a graph variable, needs no union Distinct"
2649 );
2650
2651 let plan = rewrite_plan(
2657 "SELECT ?s WHERE {
2658 GRAPH ?g { ?s <http://ex/bio> ?v }
2659 ?s <http://ex/note> ?x
2660 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2661 }",
2662 )
2663 .unwrap();
2664 let op = find_subject_op(&plan.root).expect("mixed-group resolve op");
2665 assert_eq!(
2666 op.variables,
2667 vec![waratah_storage::Variable::new_unchecked("s")],
2668 "a mixed group emits the subject alone"
2669 );
2670 assert_eq!(
2671 subject_request(op).graph_name,
2672 Some(EncodedTerm::DefaultGraph),
2673 "the bare sibling's window is the dataset default"
2674 );
2675 assert!(!subject_request(op).return_graph);
2676 assert!(
2677 find_subject_distinct(&plan.root).is_none(),
2678 "one window needs no union Distinct"
2679 );
2680 }
2681
2682 #[test]
2683 fn mixed_group_resolves_the_bgp_siblings_window() {
2684 for graph in ["<http://ex/g1>", "?g"] {
2689 let plan = rewrite_plan(&format!(
2690 "SELECT ?s WHERE {{
2691 GRAPH {graph} {{ ?s <http://ex/bio> ?v }}
2692 ?s <http://ex/note> ?x
2693 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2694 }}"
2695 ))
2696 .unwrap();
2697 let mut ops = Vec::new();
2698 subject_ops(&plan.root, &mut ops);
2699 assert_eq!(
2700 ops.len(),
2701 1,
2702 "GRAPH {graph}: one op, the BGP sibling's window"
2703 );
2704 assert_eq!(
2705 subject_request(ops[0]).graph_name,
2706 Some(EncodedTerm::DefaultGraph),
2707 "GRAPH {graph}: the bare sibling is the default graph"
2708 );
2709 assert!(!subject_request(ops[0]).return_graph);
2710 assert!(
2711 find_subject_distinct(&plan.root).is_none(),
2712 "one window needs no union Distinct"
2713 );
2714 }
2715 }
2716
2717 #[test]
2718 fn a_single_graph_block_keeps_its_window_when_no_bgp_sibling_exists() {
2719 let plan = rewrite_plan(
2726 "SELECT ?s WHERE {
2727 GRAPH ?g { ?s <http://ex/bio> ?v }
2728 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2729 }",
2730 )
2731 .unwrap();
2732 let op = find_subject_op(&plan.root).expect("variable-graph resolve op");
2733 assert_eq!(
2734 op.variables.len(),
2735 2,
2736 "the graph column survives: {:?}",
2737 op.variables
2738 );
2739 assert!(subject_request(op).return_graph);
2740 assert_eq!(subject_request(op).graph_name, None);
2741
2742 let plan = rewrite_plan(
2743 "SELECT ?s WHERE {
2744 GRAPH <http://ex/g1> { ?s <http://ex/bio> ?v }
2745 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2746 }",
2747 )
2748 .unwrap();
2749 let op = find_subject_op(&plan.root).expect("fixed-graph resolve op");
2750 assert_eq!(op.variables.len(), 1);
2751 assert_eq!(
2752 subject_request(op).graph_name,
2753 Some(EncodedTerm::from(
2754 &oxrdf::NamedNode::new("http://ex/g1").unwrap()
2755 ))
2756 );
2757
2758 let plan = rewrite_plan(
2761 "SELECT ?s WHERE {
2762 GRAPH <http://ex/g1> { ?s <http://ex/bio> ?v }
2763 GRAPH <http://ex/g2> { ?s <http://ex/note> ?x }
2764 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2765 }",
2766 )
2767 .unwrap();
2768 let op = find_subject_op(&plan.root).expect("two-graph resolve op");
2769 assert_eq!(subject_request(op).graph_name, None);
2770 assert!(subject_request(op).graph_filter_terms.is_empty());
2771 assert!(!subject_request(op).return_graph);
2772 }
2773
2774 #[test]
2775 fn graph_variable_equal_to_the_subject_emits_one_column() {
2776 let plan = rewrite_plan(
2782 "SELECT ?s WHERE {
2783 GRAPH ?s { ?x <http://ex/p> ?o }
2784 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2785 }",
2786 )
2787 .unwrap();
2788 let op = find_subject_op(&plan.root).expect("resolve op");
2789 assert_eq!(
2790 op.variables,
2791 vec![waratah_storage::Variable::new_unchecked("s")],
2792 "the op declares the subject once"
2793 );
2794 let request = subject_request(op);
2795 assert!(request.subject_equals_graph);
2796 assert!(!request.return_graph);
2797 assert_eq!(request.graph_name, None);
2798 assert!(
2799 request
2800 .graph_filter_terms
2801 .contains(&EncodedTerm::DefaultGraph)
2802 && !request.graph_filter_allow,
2803 "the GRAPH ?s scope still blocks the unnamed graph"
2804 );
2805 }
2806
2807 #[test]
2808 fn belt_fails_bind_order_by_and_aggregate_nesting() {
2809 let error = rewrite_plan(
2815 "SELECT ?x WHERE {
2816 ?s <http://ex/tag> ?l .
2817 BIND(<http://jena.apache.org/text#query>(?l, \"mountain\") AS ?x)
2818 }",
2819 )
2820 .expect_err("BIND of text:query must fail the plan");
2821 assert!(
2822 error.to_string().contains("top-level FILTER conjunct"),
2823 "{error}"
2824 );
2825
2826 let error = rewrite_plan(
2827 "SELECT ?l WHERE {
2828 ?s <http://ex/tag> ?l .
2829 }
2830 ORDER BY <http://jena.apache.org/text#query>(?l, \"mountain\")",
2831 )
2832 .expect_err("ORDER BY text:query must fail the plan");
2833 assert!(
2834 error.to_string().contains("top-level FILTER conjunct"),
2835 "{error}"
2836 );
2837
2838 let error = rewrite_plan(
2839 "SELECT ?s (COUNT(<http://jena.apache.org/text#query>(?l, \"mountain\")) AS ?c) WHERE {
2840 ?s <http://ex/tag> ?l .
2841 }
2842 GROUP BY ?s",
2843 )
2844 .expect_err("an aggregate argument of text:query must fail the plan");
2845 assert!(
2846 error.to_string().contains("top-level FILTER conjunct"),
2847 "{error}"
2848 );
2849 }
2850
2851 #[test]
2852 fn parse_query_and_lang_reject_non_plain_string_arguments() {
2853 let error = rewrite_plan(
2857 "SELECT ?l WHERE {
2858 ?s <http://ex/tag> ?l .
2859 FILTER(<http://jena.apache.org/text#query>(?l, 42))
2860 }",
2861 )
2862 .expect_err("a numeric query literal must fail the plan");
2863 assert!(
2864 error.to_string().contains("must be a plain string literal"),
2865 "{error}"
2866 );
2867
2868 let error = rewrite_plan(
2869 "SELECT ?l WHERE {
2870 ?s <http://ex/tag> ?l .
2871 FILTER(<http://jena.apache.org/text#query>(?l, \"mountain\"@en))
2872 }",
2873 )
2874 .expect_err("a language-tagged query literal must fail the plan");
2875 assert!(
2876 error.to_string().contains("must be a plain string literal"),
2877 "{error}"
2878 );
2879
2880 let error = rewrite_plan(
2881 "SELECT ?l WHERE {
2882 ?s <http://ex/tag> ?l .
2883 FILTER(<http://jena.apache.org/text#query>(?l, \"mountain\", 42))
2884 }",
2885 )
2886 .expect_err("a non-string trailing argument must fail the plan");
2887 assert!(error.to_string().contains("trailing argument"), "{error}");
2888
2889 rewrite_plan(
2892 "SELECT ?l WHERE {
2893 ?s <http://ex/tag> ?l .
2894 FILTER(<http://jena.apache.org/text#query>(?l, \"mountain\"^^<http://www.w3.org/2001/XMLSchema#string>))
2895 }",
2896 )
2897 .expect("an explicit xsd:string query literal is a plain string");
2898 }
2899
2900 #[test]
2901 fn text_query_in_a_hoisted_optional_condition_names_the_boundary() {
2902 let error = rewrite_plan(
2909 "SELECT ?s ?v WHERE { \
2910 GRAPH <http://ex/g1> { ?s <http://ex/note> ?y } \
2911 OPTIONAL { ?s <http://ex/bio> ?v \
2912 FILTER(<http://jena.apache.org/text#query>(?v, \"mountain\")) } \
2913 }",
2914 )
2915 .expect_err("a hoisted OPTIONAL condition cannot run text:query");
2916 assert!(
2917 error
2918 .to_string()
2919 .contains("cannot answer inside an OPTIONAL"),
2920 "the message names the OPTIONAL situation: {error}"
2921 );
2922 }
2923
2924 #[test]
2925 fn literal_mode_over_an_unbound_variable_answers_the_empty_table() {
2926 let plan = rewrite_plan(&format!(
2933 "PREFIX text: <{TEXT}>
2934 SELECT ?l WHERE {{ FILTER(text:query(?l, \"mountain\")) }}"
2935 ))
2936 .expect("the unsatisfiable filter rewrites, not errors");
2937 let PlanNode::Values(values) = &plan.root else {
2938 panic!("the filter rewrites to the empty table: {:?}", plan.root);
2939 };
2940 assert!(values.rows.is_empty(), "zero rows: {values:?}");
2941
2942 let plan = rewrite_plan(&format!(
2945 "PREFIX text: <{TEXT}>
2946 SELECT ?s WHERE {{
2947 ?s <http://ex/note> ?x .
2948 FILTER(text:query(?l, \"mountain\"))
2949 }}"
2950 ))
2951 .unwrap();
2952 let PlanNode::Values(values) = &plan.root else {
2953 panic!("the filter rewrites to the empty table: {:?}", plan.root);
2954 };
2955 assert!(values.rows.is_empty(), "zero rows: {values:?}");
2956 }
2957
2958 #[test]
2959 fn union_arms_do_not_inherit_sibling_arm_scopes() {
2960 let plan = rewrite_plan(
2967 "SELECT ?s ?v WHERE {
2968 { GRAPH <http://ex/g1> { ?x <http://ex/note> ?y } }
2969 UNION
2970 { ?s <http://ex/bio> ?v
2971 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\")) }
2972 }",
2973 )
2974 .unwrap();
2975 let mut ops = Vec::new();
2976 subject_ops(&plan.root, &mut ops);
2977 assert_eq!(
2978 ops.len(),
2979 1,
2980 "exactly one resolve op, from the filter's own branch: {ops:?}"
2981 );
2982 assert_eq!(
2983 subject_request(ops[0]).graph_name,
2984 Some(EncodedTerm::DefaultGraph),
2985 "the op is scoped to the filter's own dataset window, not the \
2986 sibling arm's g1"
2987 );
2988 }
2989
2990 #[test]
2991 fn path_endpoints_are_slot_evidence() {
2992 let error = rewrite_plan(
2998 "SELECT ?s WHERE {
2999 ?s <http://ex/knows>+ ?o .
3000 FILTER(<http://jena.apache.org/text#query>(?s, \"word\"))
3001 }",
3002 )
3003 .expect_err("a path-subject endpoint cannot be a searched literal");
3004 assert!(
3005 error.to_string().contains("subject position"),
3006 "the subject form is named: {error}"
3007 );
3008
3009 let error = rewrite_plan(
3010 "SELECT ?s WHERE {
3011 ?x <http://ex/knows>+ ?s .
3012 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3013 }",
3014 )
3015 .expect_err("a path-object endpoint cannot be a searched subject");
3016 assert!(
3017 error.to_string().contains("object position"),
3018 "the literal form is named: {error}"
3019 );
3020
3021 let plan = rewrite_plan(
3025 "SELECT ?s WHERE {
3026 ?s <http://ex/knows>+ ?o .
3027 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3028 }",
3029 )
3030 .unwrap();
3031 assert!(
3032 find_subject_op(&plan.root).is_some(),
3033 "subject mode over a path-subject endpoint rewrites"
3034 );
3035 }
3036
3037 #[test]
3038 fn subject_mode_ops_emit_only_user_visible_columns() {
3039 let plan = rewrite_plan(
3044 "SELECT ?s WHERE {
3045 ?s <http://ex/p> ?l .
3046 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3047 }",
3048 )
3049 .unwrap();
3050 let op = find_subject_op(&plan.root).expect("the resolve op");
3051 assert_eq!(
3052 op.variables,
3053 vec![waratah_storage::Variable::new_unchecked("s")]
3054 );
3055
3056 let plan = rewrite_plan(
3057 "SELECT ?g ?s WHERE {
3058 GRAPH ?g {
3059 ?s <http://ex/p> ?l .
3060 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3061 }
3062 }",
3063 )
3064 .unwrap();
3065 let op = find_subject_op(&plan.root).expect("the resolve op");
3066 assert_eq!(
3067 op.variables,
3068 vec![
3069 waratah_storage::Variable::new_unchecked("s"),
3070 waratah_storage::Variable::new_unchecked("g"),
3071 ],
3072 "the graph column is the user's variable, not a carrier"
3073 );
3074 assert!(
3075 op.variables
3076 .iter()
3077 .all(|variable| !variable.as_str().starts_with("__text_h")),
3078 "no hidden carrier column exists"
3079 );
3080 }
3081
3082 #[test]
3083 fn values_and_bind_ground_terms_are_slot_evidence() {
3084 let error = rewrite_plan(
3088 "SELECT ?s WHERE {
3089 VALUES ?s { <http://ex/a> <http://ex/b> }
3090 FILTER(<http://jena.apache.org/text#query>(?s, \"word\"))
3091 }",
3092 )
3093 .expect_err("a VALUES-bound IRI cannot be a searched literal");
3094 assert!(
3095 error.to_string().contains("subject position"),
3096 "the literal form is named: {error}"
3097 );
3098
3099 let error = rewrite_plan(
3104 "SELECT ?s WHERE {
3105 VALUES ?s { \"a\" UNDEF }
3106 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3107 }",
3108 )
3109 .expect_err("a VALUES literal row is object evidence; subject mode is contradicted");
3110 assert!(
3111 error.to_string().contains("object position"),
3112 "the subject form is named: {error}"
3113 );
3114
3115 let error = rewrite_plan(
3120 "SELECT ?s WHERE {
3121 VALUES ?s { \"a\" \"b\" }
3122 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3123 }",
3124 )
3125 .expect_err("a VALUES literal column contradicts subject mode");
3126 assert!(
3127 error.to_string().contains("object position"),
3128 "the subject form is named: {error}"
3129 );
3130
3131 let error = rewrite_plan(
3137 "SELECT ?s WHERE {
3138 BIND(\"word\" AS ?s)
3139 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3140 }",
3141 )
3142 .expect_err("a BIND-ground literal subject contradicts subject mode");
3143 assert!(error.to_string().contains("object position"), "{error}");
3144
3145 let plan = rewrite_plan(
3149 "SELECT ?s WHERE {
3150 VALUES ?s { <http://ex/a> UNDEF }
3151 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3152 }",
3153 )
3154 .unwrap();
3155 assert!(
3156 find_subject_op(&plan.root).is_some(),
3157 "subject mode over a VALUES-bound IRI rewrites"
3158 );
3159 }
3160
3161 #[test]
3162 fn a_ground_subject_keeps_its_variable_and_rewrites() {
3163 let plan = rewrite_plan(
3168 "SELECT ?s WHERE {
3169 VALUES ?s { <http://ex/a> }
3170 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
3171 }",
3172 )
3173 .unwrap();
3174 let op = find_subject_op(&plan.root).expect("the subject resolve op");
3175 assert_eq!(
3176 op.pinned.len(),
3177 1,
3178 "the ground subject is pinned into the resolve"
3179 );
3180 assert_eq!(
3181 op.variables,
3182 vec![waratah_storage::Variable::new_unchecked("s")],
3183 "the variable survives; the op still joins back to it"
3184 );
3185 }
3186
3187 #[test]
3188 fn a_ground_literal_pins_its_term_into_the_text_op() {
3189 let plan = rewrite_plan(
3193 "SELECT ?lit WHERE {
3194 VALUES ?lit { \"report\" }
3195 FILTER(<http://jena.apache.org/text#query>(?lit, \"report\"))
3196 }",
3197 )
3198 .unwrap();
3199 let op = find_text_join(&plan.root).expect("text_scan joined into the plan");
3200 assert_eq!(
3201 op.pinned.len(),
3202 1,
3203 "the ground literal is pinned into the op"
3204 );
3205 assert_eq!(op.produced_row_count_estimate, 1);
3206 }
3207
3208 #[test]
3209 fn fingerprint_mismatch_fails_the_plan_like_an_untrusted_index() {
3210 installed();
3211 let ctx = waratah_compute::QueryContext::from_snapshot(SnapshotId::latest())
3212 .with_text_index_state(Some(1), "text-index-v1;analyzer=other;seed_chars=8");
3213 let error = LogicalPlan::parse_with_context(
3214 &format!(
3215 "PREFIX text: <{TEXT}>
3216 SELECT ?name WHERE {{
3217 ?x <http://ex/name> ?name .
3218 FILTER(text:query(?name, \"laser\"))
3219 }}"
3220 ),
3221 &ctx,
3222 )
3223 .expect_err("a fingerprint mismatch must fail the plan");
3224 assert!(error.to_string().contains("waratah text rebuild-index"));
3225 }
3226
3227 #[test]
3228 fn the_jena_reflex_is_the_contradiction_error() {
3229 let error = rewrite_plan(&format!(
3231 "PREFIX text: <{TEXT}>
3232 SELECT ?s WHERE {{
3233 ?s <http://ex/type> <http://ex/Person> .
3234 FILTER(text:query(?s, \"word\"))
3235 }}"
3236 ))
3237 .expect_err("literal mode over a subject-only variable is a plan error");
3238 assert!(
3239 error.to_string().contains("subject position"),
3240 "the error names the subject form: {error}"
3241 );
3242 }
3243
3244 #[test]
3245 fn text_query_as_a_graph_pattern_predicate_is_a_plan_error() {
3246 let error = rewrite_plan(&format!(
3247 "PREFIX text: <{TEXT}>
3248 SELECT ?s WHERE {{
3249 ?s text:query \"word\" .
3250 }}"
3251 ))
3252 .expect_err("text:query in predicate position is a plan error");
3253 assert!(error.to_string().contains("FILTER function"));
3254 }
3255
3256 #[test]
3257 fn untrusted_string_functions_fall_back_to_the_exact_residual() {
3258 installed();
3260 let plan = LogicalPlan::parse_with_context(
3261 "SELECT ?name WHERE {
3262 ?x <http://ex/name> ?name .
3263 FILTER(STRSTARTS(?name, \"Bel\"))
3264 }",
3265 &waratah_compute::QueryContext::from_snapshot(SnapshotId::latest()),
3266 )
3267 .unwrap();
3268 assert!(
3269 find_text_join(&plan.root).is_none(),
3270 "untrusted string functions rewrite nothing (the residual answers exactly)"
3271 );
3272 }
3273
3274 #[test]
3280 fn text_query_rewrites_under_group_by() {
3281 let plan = rewrite_plan(
3282 "SELECT ?name (COUNT(?x) AS ?n) WHERE {
3283 ?x <http://ex/name> ?name .
3284 FILTER(<http://jena.apache.org/text#query>(?name, \"laser\"))
3285 } GROUP BY ?name",
3286 )
3287 .unwrap();
3288 let op = find_text_join(&plan.root).expect("the GROUP BY must not hide the filter");
3289 let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
3290 assert_eq!(payload.request.query, "laser");
3291 }
3292
3293 #[test]
3294 fn text_query_rewrites_under_graph_variable() {
3295 let plan = rewrite_plan(
3296 "SELECT ?g ?name WHERE {
3297 GRAPH ?g {
3298 ?x <http://ex/name> ?name .
3299 FILTER(<http://jena.apache.org/text#query>(?name, \"laser\"))
3300 }
3301 }",
3302 )
3303 .unwrap();
3304 let op = find_text_join(&plan.root).expect("the GRAPH ?g wrapper must not hide the filter");
3305 let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
3306 assert_eq!(payload.request.query, "laser");
3307 }
3308
3309 #[test]
3310 fn text_query_rewrites_inside_a_subselect() {
3311 let plan = rewrite_plan(
3312 "SELECT ?name WHERE {
3313 {
3314 SELECT ?name WHERE {
3315 ?x <http://ex/name> ?name .
3316 FILTER(<http://jena.apache.org/text#query>(?name, \"laser\"))
3317 }
3318 }
3319 }",
3320 )
3321 .unwrap();
3322 let op = find_text_join(&plan.root).expect("the sub-SELECT must not hide the filter");
3323 let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
3324 assert_eq!(payload.request.query, "laser");
3325 }
3326
3327 #[test]
3328 fn text_query_rewrites_wrapped_by_a_later_bind() {
3329 let plan = rewrite_plan(
3332 "SELECT ?name ?shout WHERE {
3333 ?x <http://ex/name> ?name .
3334 FILTER(<http://jena.apache.org/text#query>(?name, \"laser\"))
3335 BIND(CONCAT(?name, \"!\") AS ?shout)
3336 }",
3337 )
3338 .unwrap();
3339 let op = find_text_join(&plan.root).expect("the BIND wrapper must not hide the filter");
3340 let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
3341 assert_eq!(payload.request.query, "laser");
3342 }
3343
3344 #[test]
3345 fn nested_text_query_fails_the_plan() {
3346 let error = rewrite_plan(
3349 "SELECT ?name WHERE {
3350 ?x <http://ex/name> ?name .
3351 FILTER(<http://jena.apache.org/text#query>(?name, \"laser\") || ?name = \"x\")
3352 }",
3353 )
3354 .expect_err("a text:query nested in || must fail the plan");
3355 assert!(
3356 error.to_string().contains("top-level FILTER conjunct"),
3357 "the belt names the supported shape: {error}"
3358 );
3359 }
3360
3361 #[test]
3362 fn negated_text_query_fails_the_plan() {
3363 let error = rewrite_plan(
3364 "SELECT ?name WHERE {
3365 ?x <http://ex/name> ?name .
3366 FILTER(!<http://jena.apache.org/text#query>(?name, \"laser\"))
3367 }",
3368 )
3369 .expect_err("a negated text:query must fail the plan");
3370 assert!(error.to_string().contains("top-level FILTER conjunct"));
3371 }
3372
3373 #[test]
3374 fn text_query_in_an_if_branch_fails_the_plan() {
3375 let error = rewrite_plan(
3376 "SELECT ?name WHERE {
3377 ?x <http://ex/name> ?name .
3378 FILTER(IF(<http://jena.apache.org/text#query>(?name, \"laser\"), true, false))
3379 }",
3380 )
3381 .expect_err("a text:query inside IF must fail the plan");
3382 assert!(error.to_string().contains("top-level FILTER conjunct"));
3383 }
3384
3385 #[test]
3386 fn text_query_inside_an_optional_rewrites_in_the_right_arm() {
3387 let plan = rewrite_plan(
3396 "SELECT ?name ?note WHERE {
3397 ?x <http://ex/name> ?name .
3398 OPTIONAL {
3399 ?x <http://ex/note> ?note .
3400 FILTER(<http://jena.apache.org/text#query>(?note, \"laser\"))
3401 }
3402 }",
3403 )
3404 .expect("a text:query inside the OPTIONAL's right arm rewrites in place");
3405 let op = find_text_join(&plan.root).expect("the LeftJoin right arm must be rewritten");
3406 let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
3407 assert_eq!(payload.request.query, "laser");
3408 }
3409
3410 #[test]
3411 fn text_query_in_a_leftjoin_condition_slot_fails_the_plan() {
3412 let mut plan = rewrite_plan(
3418 "SELECT ?name ?note WHERE {
3419 ?x <http://ex/name> ?name .
3420 OPTIONAL { ?x <http://ex/note> ?note . }
3421 }",
3422 )
3423 .unwrap();
3424 let call = Expression::FunctionCall(
3425 Function::Custom(spargebra::term::NamedNode::new_unchecked(TEXT_QUERY_IRI)),
3426 vec![
3427 Expression::Variable(spargebra::term::Variable::new_unchecked("note")),
3428 Expression::Literal(spargebra::term::Literal::new_simple_literal("laser")),
3429 ],
3430 );
3431 let PlanNode::LeftJoin { early_filter, .. } = &mut plan.root else {
3432 panic!("expected a LeftJoin root for the OPTIONAL");
3433 };
3434 *early_filter = Some(call);
3435 crate::TextPlannerPlugin::new(crate::TextPluginConfig {
3436 enabled: true,
3437 predicates: Vec::new(),
3438 ..crate::TextPluginConfig::default()
3439 })
3440 .rewrite(&mut plan.root, &trusted_ctx())
3441 .expect_err("a text:query in the LeftJoin condition slots must fail the plan");
3442 }
3443
3444 #[test]
3452 fn subject_mode_resolve_inherits_the_default_graph_scope() {
3453 let plan = rewrite_plan(
3454 "SELECT ?s WHERE {
3455 ?s <http://ex/livesIn> ?city .
3456 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
3457 }",
3458 )
3459 .unwrap();
3460 let request = subject_request(find_subject_op(&plan.root).expect("resolve op"));
3461 assert_eq!(request.graph_name, Some(EncodedTerm::DefaultGraph));
3464 assert!(request.graph_filter_terms.is_empty());
3465 assert!(!request.graph_filter_allow);
3466 assert!(!request.merge_default_graph);
3467 assert!(!request.return_graph);
3468 }
3469
3470 #[test]
3471 fn subject_mode_resolve_inherits_a_single_from_graph_scope() {
3472 let plan = rewrite_plan(
3473 "SELECT ?s FROM <http://ex/g> WHERE {
3474 ?s <http://ex/livesIn> ?city .
3475 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
3476 }",
3477 )
3478 .unwrap();
3479 let request = subject_request(find_subject_op(&plan.root).expect("resolve op"));
3480 assert_eq!(
3483 request.graph_name,
3484 Some(EncodedTerm::from(
3485 &spargebra::term::NamedNode::new_unchecked("http://ex/g")
3486 ))
3487 );
3488 }
3489
3490 #[test]
3491 fn subject_mode_resolve_inherits_the_from_allow_scope() {
3492 let plan = rewrite_plan(
3493 "SELECT ?s FROM <http://ex/g1> FROM <http://ex/g2> WHERE {
3494 ?s <http://ex/livesIn> ?city .
3495 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
3496 }",
3497 )
3498 .unwrap();
3499 let request = subject_request(find_subject_op(&plan.root).expect("resolve op"));
3500 assert_eq!(request.graph_name, None);
3503 assert!(!request.graph_filter_terms.is_empty());
3504 assert!(request.graph_filter_allow, "FROM windows are an allow-list");
3505 assert!(request.merge_default_graph);
3506 }
3507
3508 #[test]
3509 fn subject_mode_resolve_inherits_the_graph_variable_scope() {
3510 let plan = rewrite_plan(
3511 "SELECT ?g ?s WHERE {
3512 GRAPH ?g {
3513 ?s <http://ex/bio> ?v .
3514 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
3515 }
3516 }",
3517 )
3518 .unwrap();
3519 let op = find_subject_op(&plan.root).expect("resolve op");
3520 let request = subject_request(op);
3521 assert_eq!(request.graph_name, None);
3525 assert!(
3526 request.return_graph,
3527 "the graph variable asks for the column"
3528 );
3529 assert!(
3530 request
3531 .graph_filter_terms
3532 .contains(&EncodedTerm::DefaultGraph)
3533 && !request.graph_filter_allow,
3534 "the unnamed graph stays blocked"
3535 );
3536 fn sibling_graph_slot(node: &PlanNode) -> Option<&waratah_storage::Variable> {
3539 match node {
3540 PlanNode::Scan(op) => op.graph.as_ref(),
3541 PlanNode::Filter { inner, .. } => sibling_graph_slot(inner),
3542 PlanNode::Join { left, right, .. } => {
3543 sibling_graph_slot(left).or_else(|| sibling_graph_slot(right))
3544 }
3545 PlanNode::Union { left, right } => {
3546 sibling_graph_slot(left).or_else(|| sibling_graph_slot(right))
3547 }
3548 PlanNode::JoinGraphVar { inner, .. } => sibling_graph_slot(inner),
3549 PlanNode::Distinct { inner, .. } => sibling_graph_slot(inner),
3550 _ => None,
3551 }
3552 }
3553 assert_eq!(
3554 op.variables.get(1),
3555 sibling_graph_slot(&plan.root),
3556 "the op and the sibling scan bind the same G slot"
3557 );
3558 }
3559
3560 fn rewrite_bare_subject_filter(
3563 ctx: &waratah_compute::QueryContext,
3564 ) -> Result<PlanNode, ComputeError> {
3565 installed();
3566 let call = Expression::FunctionCall(
3567 Function::Custom(spargebra::term::NamedNode::new_unchecked(TEXT_QUERY_IRI)),
3568 vec![
3569 Expression::Variable(spargebra::term::Variable::new_unchecked("s")),
3570 Expression::NamedNode(spargebra::term::NamedNode::new_unchecked("http://ex/bio")),
3571 Expression::Literal(spargebra::term::Literal::new_simple_literal("mountain")),
3572 ],
3573 );
3574 let mut node = PlanNode::Filter {
3575 inner: Box::new(PlanNode::Unit),
3576 early: None,
3577 residual: Some(call),
3578 exists: Vec::new(),
3579 one_to_one: false,
3580 };
3581 crate::TextPlannerPlugin::new(crate::TextPluginConfig {
3582 enabled: true,
3583 predicates: Vec::new(),
3584 ..crate::TextPluginConfig::default()
3585 })
3586 .rewrite(&mut node, ctx)?;
3587 Ok(node)
3588 }
3589
3590 #[test]
3591 fn subject_mode_without_a_sibling_pattern_leaves_the_graph_unbound() {
3592 let node = rewrite_bare_subject_filter(&trusted_ctx()).unwrap();
3597 let request = subject_request(find_subject_op(&node).expect("resolve op"));
3598 assert_eq!(request.graph_name, None);
3599 assert!(request.graph_filter_terms.is_empty());
3600 assert!(!request.graph_filter_allow);
3601 assert!(!request.merge_default_graph);
3602 assert!(!request.return_graph);
3603 }
3604
3605 #[test]
3606 fn subject_mode_without_a_sibling_pattern_is_unbound_under_all_graphs() {
3607 let ctx = trusted_ctx().with_default_union(true);
3612 let node = rewrite_bare_subject_filter(&ctx).unwrap();
3613 let request = subject_request(find_subject_op(&node).expect("resolve op"));
3614 assert_eq!(request.graph_name, None);
3615 assert!(request.graph_filter_terms.is_empty());
3616 assert!(!request.graph_filter_allow);
3617 assert!(!request.merge_default_graph);
3618 assert!(!request.return_graph);
3619 }
3620
3621 #[test]
3622 fn subject_mode_inside_graph_without_a_pattern_fails_the_plan() {
3623 let call = Expression::FunctionCall(
3627 Function::Custom(spargebra::term::NamedNode::new_unchecked(TEXT_QUERY_IRI)),
3628 vec![
3629 Expression::Variable(spargebra::term::Variable::new_unchecked("s")),
3630 Expression::NamedNode(spargebra::term::NamedNode::new_unchecked("http://ex/bio")),
3631 Expression::Literal(spargebra::term::Literal::new_simple_literal("mountain")),
3632 ],
3633 );
3634 let mut node = PlanNode::JoinGraphVar {
3635 inner: Box::new(PlanNode::Filter {
3636 inner: Box::new(PlanNode::Unit),
3637 early: None,
3638 residual: Some(call),
3639 exists: Vec::new(),
3640 one_to_one: false,
3641 }),
3642 graph_var: spargebra::term::Variable::new_unchecked("g"),
3643 active_var: spargebra::term::Variable::new_unchecked("__active_g"),
3644 };
3645 let error = crate::TextPlannerPlugin::new(crate::TextPluginConfig {
3646 enabled: true,
3647 predicates: Vec::new(),
3648 ..crate::TextPluginConfig::default()
3649 })
3650 .rewrite(&mut node, &trusted_ctx())
3651 .expect_err("an unstampable GRAPH scope must fail the plan");
3652 assert!(
3653 error
3654 .to_string()
3655 .contains("requires a triple pattern in the same graph group"),
3656 "the error names the limitation: {error}"
3657 );
3658 }
3659}