Skip to main content

waratah_compute/
explain.rs

1//! Multi-level SPARQL EXPLAIN (parse / Sparopt / lowered plan / estimates).
2//!
3//! Vendored Jena SSE printers for spargebra 0.4.6 types (`Query`, `GraphPattern`,
4//! expressions, triples, property paths) live here so Level 0/1 do not call
5//! [`Query::to_sse`]. A vendored mirror of spargebra's SPARQL-syntax `Display`
6//! ([`sparql_query_text`]) serves `optimised-sparql` with well-known-prefix
7//! shortening instead of `Query::to_string`. Level 2 / estimate print
8//! [`PlanNode`] with Waratah extensions.
9
10use std::fmt::{self, Write as _};
11use std::str::FromStr;
12
13use spargebra::Query;
14use spargebra::algebra::{
15    AggregateExpression, AggregateFunction, Expression, Function, GraphPattern, OrderExpression,
16    PropertyPathExpression,
17};
18use spargebra::term::{GroundTerm, NamedNode, NamedNodePattern, TermPattern, TriplePattern};
19use waratah_proto::PatternSlot;
20use waratah_stats::{JoinStrategy, StatsProfile};
21use waratah_storage::{
22    CompareOp, EncodedTerm, EncodedTriplePattern, QuadSlot, RDF_TYPE_IRI_ID, SlotComparison,
23    StrHash, Variable, prefixed_iri_name, well_known_prefixed_iri,
24};
25
26use oxsdatatypes::DateTime;
27
28use crate::dataset::QueryDataset;
29use crate::error::ComputeError;
30use crate::expr::ExprEvalEnv;
31use crate::plan::{
32    BagMark, DomainScanKind, ExistsClause, ExistsKind, HeadScanKind, Liveness, LogicalPlan, PathOp,
33    PlanNode, PropertyPath, ScanOp, SlotMark, SortKey, ValuesOp, join_key_domain_for,
34    join_key_domain_for_node, wrap_project_slice,
35};
36
37/// Dataset knobs for [`LogicalPlan::explain_with`].
38///
39/// Execution already reads these from [`crate::context::QueryContext`]. EXPLAIN
40/// is a static formatter, so callers pass the same values here.
41#[derive(Debug, Clone, Default)]
42pub struct ExplainOptions {
43    /// Engine `--default-union`: SPARQL default graph is all named and unnamed graphs.
44    pub default_union: bool,
45    /// Seat inner-join arms by the total seating cost (the `join-seat-shadow`
46    /// comparator promoted to decision) so EXPLAIN shows the seat the
47    /// server would run under `--seat-by-total-cost`.
48    pub seat_by_total_cost: bool,
49    /// SPARQL Protocol `default-graph-uri` values (override query-text `FROM` when any protocol IRI is present).
50    pub protocol_default_graphs: Vec<String>,
51    /// SPARQL Protocol `named-graph-uri` values.
52    pub protocol_named_graphs: Vec<String>,
53}
54
55/// EXPLAIN output kind (`format=` query param / CLI `--format`).
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
57pub enum ExplainFormat {
58    /// Level 0: parse only, Jena SSE (default).
59    #[default]
60    Sse,
61    /// Level 1: Sparopt + VALUES-into-UNION, Jena SSE.
62    Optimised,
63    /// Level 1 as SPARQL syntax.
64    OptimisedSparql,
65    /// Level 2: fully lowered [`PlanNode`], Jena-like SSE with Waratah extensions.
66    Planned,
67    /// Level 2 as best-effort SPARQL.
68    PlannedSparql,
69    /// Level 2 SSE plus row estimates, domains, and broadcast / grounded
70    /// annotations.
71    Estimate,
72}
73
74impl ExplainFormat {
75    /// Whether `pretty` should indent S-expression output.
76    pub fn is_s_expression(self) -> bool {
77        !matches!(self, Self::OptimisedSparql | Self::PlannedSparql)
78    }
79}
80
81impl FromStr for ExplainFormat {
82    type Err = String;
83
84    fn from_str(s: &str) -> Result<Self, Self::Err> {
85        match s.trim().to_ascii_lowercase().as_str() {
86            "sse" => Ok(Self::Sse),
87            "optimised" | "optimized" => Ok(Self::Optimised),
88            "optimised-sparql" | "optimized-sparql" => Ok(Self::OptimisedSparql),
89            "planned" => Ok(Self::Planned),
90            "planned-sparql" => Ok(Self::PlannedSparql),
91            "estimate" | "estimates" => Ok(Self::Estimate),
92            other => Err(format!("unknown explain format '{other}'")),
93        }
94    }
95}
96
97impl LogicalPlan {
98    /// Format a SPARQL query at the requested EXPLAIN level.
99    ///
100    /// `pretty` indents S-expression and `*-sparql` formats.
101    pub fn explain(
102        sparql: &str,
103        format: ExplainFormat,
104        pretty: bool,
105        profile: Option<&StatsProfile>,
106    ) -> Result<String, ComputeError> {
107        Self::explain_with(sparql, format, pretty, profile, &ExplainOptions::default())
108    }
109
110    /// [`Self::explain`] with protocol / `--default-union` dataset knobs.
111    pub fn explain_with(
112        sparql: &str,
113        format: ExplainFormat,
114        pretty: bool,
115        profile: Option<&StatsProfile>,
116        options: &ExplainOptions,
117    ) -> Result<String, ComputeError> {
118        // Store-less planning surface (CLI `waratah explain`): no engine, so
119        // no index epochs — the temporal trust gate honestly reads untrusted.
120        let base =
121            crate::context::QueryContext::from_snapshot(waratah_storage::SnapshotId::latest());
122        Self::explain_with_context(sparql, format, pretty, profile, &base, options)
123    }
124
125    /// [`Self::explain_with`] planning on an already-built engine context.
126    ///
127    /// The §7b delivery invariant: index epochs and the tick histogram ride
128    /// the context into the planner. Serving surfaces that own an engine must
129    /// pass its context here; rebuilding one from (snapshot, dataset) alone
130    /// silently degrades every temporal comparison rewrite to the unindexed
131    /// residual — execution stays correct, EXPLAIN plans lie.
132    pub fn explain_with_context(
133        sparql: &str,
134        format: ExplainFormat,
135        pretty: bool,
136        profile: Option<&StatsProfile>,
137        base_ctx: &crate::context::QueryContext,
138        options: &ExplainOptions,
139    ) -> Result<String, ComputeError> {
140        let parsed = crate::rephrase_error::parse_query(sparql)?;
141        let compact = match format {
142            ExplainFormat::Sse => query_to_sse(&parsed),
143            ExplainFormat::Optimised => query_to_sse(&rebuild_l1_query(parsed)?),
144            ExplainFormat::OptimisedSparql => format_l1_sparql(parsed)?,
145            ExplainFormat::Planned => format_planned(parsed, false, profile, base_ctx, options)?,
146            ExplainFormat::PlannedSparql => {
147                format_planned_sparql(parsed, profile, base_ctx, options)?
148            }
149            ExplainFormat::Estimate => format_planned(parsed, true, profile, base_ctx, options)?,
150        };
151        Ok(if pretty {
152            if format.is_s_expression() {
153                pretty_sse(&compact)
154            } else {
155                pretty_sparql(&compact)
156            }
157        } else {
158            compact
159        })
160    }
161}
162
163fn rebuild_l1_query(parsed: Query) -> Result<Query, ComputeError> {
164    let fold_eval = ExprEvalEnv::new(DateTime::now(), None);
165    match parsed {
166        Query::Select {
167            pattern, dataset, ..
168        } => {
169            let (variables, optimized, slice, distinct, order) =
170                crate::plan::prepare_algebra(pattern, &fold_eval)?;
171            Ok(Query::Select {
172                base_iri: None,
173                dataset,
174                pattern: wrap_project_slice(variables, optimized, slice, distinct, order),
175            })
176        }
177        Query::Ask {
178            pattern, dataset, ..
179        } => {
180            let pattern = crate::plan::cap_ask_slice(crate::plan::flatten_ask_subselect(pattern));
181            let (variables, optimized, slice, distinct, order) =
182                crate::plan::prepare_algebra(pattern, &fold_eval)?;
183            Ok(Query::Ask {
184                base_iri: None,
185                dataset,
186                pattern: wrap_project_slice(variables, optimized, slice, distinct, order),
187            })
188        }
189        Query::Construct {
190            template,
191            pattern,
192            dataset,
193            ..
194        } => {
195            let (variables, optimized, slice, distinct, order) =
196                crate::plan::prepare_algebra(pattern, &fold_eval)?;
197            Ok(Query::Construct {
198                template,
199                base_iri: None,
200                dataset,
201                pattern: wrap_project_slice(variables, optimized, slice, distinct, order),
202            })
203        }
204        Query::Describe {
205            pattern, dataset, ..
206        } => {
207            let (variables, optimized, slice, distinct, order) =
208                crate::plan::prepare_algebra(pattern, &fold_eval)?;
209            Ok(Query::Describe {
210                base_iri: None,
211                dataset,
212                pattern: wrap_project_slice(variables, optimized, slice, distinct, order),
213            })
214        }
215    }
216}
217
218fn fmt_sparql_from_clauses(dataset: Option<&spargebra::algebra::QueryDataset>) -> String {
219    let Some(dataset) = dataset else {
220        return String::new();
221    };
222    let mut out = String::new();
223    for iri in &dataset.default {
224        write!(out, " FROM {iri}").expect("writing to String cannot fail");
225    }
226    if let Some(named) = &dataset.named {
227        for iri in named {
228            write!(out, " FROM NAMED {iri}").expect("writing to String cannot fail");
229        }
230    }
231    out
232}
233
234/// Level 1 as SPARQL syntax (`optimised-sparql`).
235///
236/// Rendering goes through the vendored spargebra-`Display` mirror
237/// ([`sparql_query_text`] / [`sparql_graph_pattern`]), so the output shape
238/// matches what `Query::to_string()` produced while well-known IRIs shorten
239/// (`a` for `rdf:type` predicates, `owl:Class`, …) like the planned-Sparql
240/// printer.
241fn format_l1_sparql(parsed: Query) -> Result<String, ComputeError> {
242    let targets = describe_targets(&parsed);
243    let target_constants = describe_constant_variables(&parsed);
244    match parsed {
245        Query::Describe {
246            pattern, dataset, ..
247        } => {
248            let fold_eval = ExprEvalEnv::new(DateTime::now(), None);
249            let (_, optimized, slice, _, _) = crate::plan::prepare_algebra(pattern, &fold_eval)?;
250            let body = remove_describe_constant_extends(optimized, &target_constants);
251            let from = fmt_sparql_from_clauses(dataset.as_ref());
252            let mut out = format!(
253                "DESCRIBE {}{from} WHERE {{ {} }}",
254                targets.expect("DESCRIBE query has targets"),
255                sparql_graph_pattern(&body)
256            );
257            if let Some(slice) = slice {
258                if slice.start > 0 {
259                    write!(out, " OFFSET {}", slice.start).expect("writing to String cannot fail");
260                }
261                if let Some(length) = slice.length {
262                    write!(out, " LIMIT {length}").expect("writing to String cannot fail");
263                }
264            }
265            Ok(out)
266        }
267        other => {
268            let rebuilt = rebuild_l1_query(other)?;
269            Ok(sparql_query_text(&rebuilt))
270        }
271    }
272}
273
274fn describe_constant_variables(query: &Query) -> Vec<Variable> {
275    let Query::Describe { pattern, .. } = query else {
276        return Vec::new();
277    };
278    describe_projection(pattern)
279        .into_iter()
280        .flatten()
281        .filter(|variable| describe_constant(pattern, variable).is_some())
282        .cloned()
283        .collect()
284}
285
286fn remove_describe_constant_extends(
287    pattern: GraphPattern,
288    target_constants: &[Variable],
289) -> GraphPattern {
290    match pattern {
291        GraphPattern::Extend {
292            inner, variable, ..
293        } if target_constants.contains(&variable) => {
294            remove_describe_constant_extends(*inner, target_constants)
295        }
296        GraphPattern::Extend {
297            inner,
298            variable,
299            expression,
300        } => GraphPattern::Extend {
301            inner: Box::new(remove_describe_constant_extends(*inner, target_constants)),
302            variable,
303            expression,
304        },
305        other => other,
306    }
307}
308
309fn lower_for_explain(
310    parsed: Query,
311    profile: Option<&StatsProfile>,
312    base_ctx: &crate::context::QueryContext,
313    options: &ExplainOptions,
314) -> Result<(QueryKind, LogicalPlan), ComputeError> {
315    let describe_targets = describe_targets(&parsed);
316    let dataset_clause = match &parsed {
317        Query::Ask { dataset, .. }
318        | Query::Select { dataset, .. }
319        | Query::Construct { dataset, .. }
320        | Query::Describe { dataset, .. } => dataset.as_ref(),
321    };
322    let dataset = QueryDataset::resolve(
323        &options.protocol_default_graphs,
324        &options.protocol_named_graphs,
325        dataset_clause,
326        options.default_union,
327    )?;
328    // Plan on the caller's engine context (§7b delivery invariant): index
329    // epochs and the tick histogram must reach the plugin trust gates, or the
330    // temporal rewrite silently falls back to the unindexed residual. The
331    // dataset window overlays the base context per query.
332    let ctx = base_ctx
333        .clone()
334        .with_dataset(dataset)
335        .with_seat_by_total_cost(options.seat_by_total_cost);
336    match parsed {
337        Query::Ask { pattern, .. } => Ok((
338            QueryKind::Ask,
339            LogicalPlan::from_ask_algebra_with_ctx(pattern, profile, &ctx)?,
340        )),
341        Query::Select { pattern, .. } => Ok((
342            QueryKind::Select,
343            LogicalPlan::from_algebra_with_ctx(pattern, profile, &ctx)?,
344        )),
345        Query::Construct {
346            template, pattern, ..
347        } => Ok((
348            QueryKind::Construct { template },
349            LogicalPlan::from_algebra_with_ctx(pattern, profile, &ctx)?,
350        )),
351        Query::Describe { pattern, .. } => Ok((
352            QueryKind::Describe {
353                targets: describe_targets.expect("DESCRIBE query has targets"),
354            },
355            LogicalPlan::from_algebra_with_ctx(pattern, profile, &ctx)?,
356        )),
357    }
358}
359
360fn describe_targets(query: &Query) -> Option<String> {
361    let Query::Describe { pattern, .. } = query else {
362        return None;
363    };
364    let variables = describe_projection(pattern)?;
365    Some(
366        variables
367            .iter()
368            .map(|variable| {
369                describe_constant(pattern, variable)
370                    .map_or_else(|| variable.to_string(), |node| node.to_string())
371            })
372            .collect::<Vec<_>>()
373            .join(" "),
374    )
375}
376
377fn describe_projection(pattern: &GraphPattern) -> Option<&[Variable]> {
378    match pattern {
379        GraphPattern::Project { variables, .. } => Some(variables),
380        GraphPattern::Slice { inner, .. }
381        | GraphPattern::Distinct { inner }
382        | GraphPattern::Reduced { inner }
383        | GraphPattern::OrderBy { inner, .. } => describe_projection(inner),
384        _ => None,
385    }
386}
387
388fn describe_constant<'a>(
389    pattern: &'a GraphPattern,
390    target: &Variable,
391) -> Option<&'a spargebra::term::NamedNode> {
392    match pattern {
393        GraphPattern::Extend {
394            inner,
395            variable,
396            expression,
397        } => {
398            if variable == target
399                && let Expression::NamedNode(node) = expression
400            {
401                Some(node)
402            } else {
403                describe_constant(inner, target)
404            }
405        }
406        GraphPattern::Project { inner, .. }
407        | GraphPattern::Slice { inner, .. }
408        | GraphPattern::Distinct { inner }
409        | GraphPattern::Reduced { inner }
410        | GraphPattern::OrderBy { inner, .. } => describe_constant(inner, target),
411        _ => None,
412    }
413}
414
415enum QueryKind {
416    Select,
417    Ask,
418    Construct { template: Vec<TriplePattern> },
419    Describe { targets: String },
420}
421
422fn format_planned(
423    parsed: Query,
424    estimates: bool,
425    profile: Option<&StatsProfile>,
426    base_ctx: &crate::context::QueryContext,
427    options: &ExplainOptions,
428) -> Result<String, ComputeError> {
429    let (kind, plan) = lower_for_explain(parsed, profile, base_ctx, options)?;
430    let ctx = PrintCtx {
431        estimates,
432        profile,
433        slice_path: false,
434        suppress_star: false,
435        page_rows: crate::concurrent_star::eager_star_page_rows(),
436    };
437    let mut body = String::new();
438    fmt_plan_query(&kind, &plan, &ctx, &mut body).expect("writing SSE to String cannot fail");
439    Ok(body)
440}
441
442fn format_planned_sparql(
443    parsed: Query,
444    profile: Option<&StatsProfile>,
445    base_ctx: &crate::context::QueryContext,
446    options: &ExplainOptions,
447) -> Result<String, ComputeError> {
448    let (kind, plan) = lower_for_explain(parsed, profile, base_ctx, options)?;
449    Ok(fmt_plan_sparql_query(&kind, &plan))
450}
451
452#[derive(Clone, Copy)]
453struct PrintCtx<'a> {
454    estimates: bool,
455    profile: Option<&'a StatsProfile>,
456    /// `true` under a Slice and inside an EXISTS body: those cursors are
457    /// `open_node`. A SubSelect resets it (fresh `execute_node`).
458    slice_path: bool,
459    /// A parent star already absorbed this subtree, so a nested join that
460    /// would also qualify is not marked again.
461    suppress_star: bool,
462    /// Driver page the over-fetch gate prices. Same value the executor for
463    /// this node will pull: the eager transport cut at the root, the slice
464    /// root's first demand under a `Slice`, and a parent's real pull where
465    /// that pull is not caller `n` (`GROUP BY`, non-1:1 `FILTER`,
466    /// `JoinGraphVar`, EXISTS).
467    page_rows: u64,
468}
469
470/// Fresh eager evaluation: `execute_node` on a SubSelect or Sort body.
471fn eager_star_print<'a>(ctx: &PrintCtx<'a>) -> PrintCtx<'a> {
472    PrintCtx {
473        slice_path: false,
474        suppress_star: false,
475        page_rows: crate::concurrent_star::eager_star_page_rows(),
476        ..*ctx
477    }
478}
479
480/// Root print used by concurrent-star tests: eager page, so a `Slice` or
481/// `Group` in the tree has to switch the page itself.
482#[cfg(test)]
483pub(crate) fn format_star_plan(node: &PlanNode) -> String {
484    // Hand-built fixture trees never went through the planning pipeline, so
485    // the star-shape stamp they carry is whatever the builder wrote
486    // (usually none). EXPLAIN renders stars from the stamp — so derive it
487    // the same way the pipeline would, on a clone, and this helper keeps
488    // showing the shape `detect` admits for the fixture.
489    let mut stamped = node.clone();
490    crate::plan::stamp_star_join_shapes(&mut stamped);
491    let ctx = PrintCtx {
492        estimates: false,
493        profile: None,
494        slice_path: false,
495        suppress_star: false,
496        page_rows: crate::concurrent_star::eager_star_page_rows(),
497    };
498    let mut body = String::new();
499    fmt_plan_node(&stamped, &ctx, &mut body).expect("writing SSE to String cannot fail");
500    body
501}
502
503/// Plan-time debug dump of the tree the executor will run.
504///
505/// Takes the already-finalized `PlanNode` instead of a parsed query, so
506/// `LogicalPlan::from_prepared` can log the exact executed shape after the
507/// last structural rewrite. No profile is carried: only estimates already
508/// stamped on the nodes are rendered, never a fresh read of the stats.
509/// Diagnostic only; its one caller is the debug-gated `plan-tree:` log.
510pub(crate) fn format_plan_tree(node: &PlanNode) -> String {
511    let ctx = PrintCtx {
512        estimates: true,
513        profile: None,
514        slice_path: false,
515        suppress_star: false,
516        page_rows: crate::concurrent_star::eager_star_page_rows(),
517    };
518    let mut body = String::new();
519    fmt_plan_node(node, &ctx, &mut body).expect("writing SSE to String cannot fail");
520    body
521}
522
523fn star_child<'a>(ctx: &PrintCtx<'a>, marked: bool) -> PrintCtx<'a> {
524    PrintCtx {
525        suppress_star: ctx.suppress_star || marked,
526        ..*ctx
527    }
528}
529
530fn fmt_plan_query(
531    kind: &QueryKind,
532    plan: &LogicalPlan,
533    ctx: &PrintCtx<'_>,
534    f: &mut String,
535) -> fmt::Result {
536    match kind {
537        QueryKind::Select => {
538            f.write_str("(project ")?;
539            if ctx.estimates {
540                write!(f, "~{} ", plan.root.produced_row_count_estimate())?;
541            }
542            f.write_str("(")?;
543            write_var_list(f, &plan.projection)?;
544            f.write_str(") ")?;
545            fmt_plan_node(&plan.root, ctx, f)?;
546            f.write_str(")")
547        }
548        QueryKind::Ask => {
549            f.write_str("(ask ")?;
550            fmt_plan_node(&plan.root, ctx, f)?;
551            f.write_str(")")
552        }
553        QueryKind::Construct { template } => {
554            f.write_str("(construct (")?;
555            for (i, triple) in template.iter().enumerate() {
556                if i > 0 {
557                    f.write_str(" ")?;
558                }
559                fmt_triple_sse(triple, f)?;
560            }
561            f.write_str(") ")?;
562            fmt_plan_node(&plan.root, ctx, f)?;
563            f.write_str(")")
564        }
565        QueryKind::Describe { .. } => {
566            f.write_str("(describe ")?;
567            fmt_plan_node(&plan.root, ctx, f)?;
568            f.write_str(")")
569        }
570    }
571}
572
573fn write_var_list(f: &mut String, vars: &[Variable]) -> fmt::Result {
574    for (i, v) in vars.iter().enumerate() {
575        if i > 0 {
576            f.write_str(" ")?;
577        }
578        write!(f, "{v}")?;
579    }
580    Ok(())
581}
582
583fn fmt_plan_node(node: &PlanNode, ctx: &PrintCtx<'_>, f: &mut String) -> fmt::Result {
584    if !ctx.estimates
585        && let Some(scans) = collect_scan_spine(node)
586    {
587        return fmt_bgp(node, scans, ctx, f);
588    }
589    match node {
590        PlanNode::CustomNode(op) => {
591            f.write_str("(custom-op ")?;
592            if ctx.estimates {
593                write!(f, "~{} ", op.produced_row_count_estimate)?;
594            }
595            write!(f, "{} {}", op.plugin_id, op.op_id)?;
596            for variable in &op.variables {
597                write!(f, " ?{}", variable.as_str())?;
598            }
599            // Explicit regime cost (see CustomOpCost): the two inputs the
600            // sweep/keyed formulas combine — the drain and the per-key
601            // relate unit. Estimates-gated like every other stamped number.
602            if ctx.estimates
603                && let Some(cost) = &op.cost
604            {
605                write!(
606                    f,
607                    " cost=drain~{},unit~{}",
608                    cost.drain_rows, cost.per_key_unit
609                )?;
610            }
611            for child in &op.children {
612                f.write_str(" ")?;
613                fmt_plan_node(child, ctx, f)?;
614            }
615            f.write_str(")")
616        }
617        PlanNode::Scan(scan) => fmt_scan(scan, ctx, f),
618        PlanNode::Path(path) => fmt_path_op(path, ctx, f),
619        PlanNode::Join {
620            left,
621            right,
622            hash_keys,
623            probe_key_domains,
624            probe_key_overlap_milli,
625            meta,
626            ..
627        } => {
628            f.write_str("(join ")?;
629            if ctx.estimates {
630                write!(f, "~{} ", meta.produced_row_count_estimate)?;
631            }
632            fmt_join_strategy(meta.strategy, hash_keys, f)?;
633            let marked = fmt_concurrent_star_here(node, ctx, f)?;
634            f.write_str(" ")?;
635            if ctx.estimates {
636                fmt_hash_key_domains(
637                    node,
638                    hash_keys,
639                    probe_key_domains,
640                    probe_key_overlap_milli,
641                    ctx.profile,
642                    f,
643                )?;
644                // The recorded own-push-removed estimate beside the
645                // push-aware produced count — how much this join's planned
646                // probe push bought, at a glance. Mirrors the scan
647                // `(price ~N)` pair.
648                write!(f, " (price ~{})", meta.own_push_removed_row_count_estimate)?;
649            }
650            let child = star_child(ctx, marked);
651            if marked {
652                // Star head (plan stamp says so): every spine member is a
653                // scan by the stamp's own construction — `detect` admits
654                // only pageable-scan drivers and scan arms — so print the
655                // driver once and each arm as a sibling. This is the
656                // ESTIMATES view of the star the executor runs as one
657                // concurrent step, instead of the left-deep chain the
658                // plan tree literally is.
659                let mut arms = vec![right.as_ref()];
660                let mut cursor = left.as_ref();
661                while let PlanNode::Join {
662                    left: inner_left,
663                    right: inner_right,
664                    ..
665                } = cursor
666                {
667                    arms.push(inner_right.as_ref());
668                    cursor = inner_left.as_ref();
669                }
670                // `arms` was collected head-first (outermost right, then
671                // inward); the walk ends at the driver scan. Print the
672                // driver, then arm 1 .. arm N in spine order.
673                fmt_plan_node(cursor, &child, f)?;
674                arms.reverse();
675                for arm in arms {
676                    f.write_str(" ")?;
677                    fmt_plan_node(arm, &eager_star_print(&child), f)?;
678                }
679            } else {
680                fmt_plan_node(left, &child, f)?;
681                f.write_str(" ")?;
682                // A non-scan right side never opens as a cursor: Broadcast needs
683                // a scan right, and BuildJoin materializes everything else with
684                // `execute_node` (eager drain). Print the right child at the
685                // eager page so the mark is the path that will run. A marked
686                // join's right is always a Scan, so the reset `suppress_star`
687                // only ever matters where it is already false.
688                fmt_plan_node(right, &eager_star_print(&child), f)?;
689            }
690            f.write_str(")")
691        }
692        PlanNode::LeftJoin {
693            left,
694            right,
695            hash_keys,
696            probe_key_domains,
697            probe_key_overlap_milli,
698            early_filter,
699            residual_filter,
700            meta,
701        } => {
702            f.write_str("(leftjoin ")?;
703            if ctx.estimates {
704                write!(f, "~{} ", node.produced_row_count_estimate())?;
705                fmt_hash_key_domains(
706                    node,
707                    hash_keys,
708                    probe_key_domains,
709                    probe_key_overlap_milli,
710                    ctx.profile,
711                    f,
712                )?;
713                // Recorded pre-push estimate beside the push-aware produced
714                // count — mirrors the join and scan `(price ~N)` pairs.
715                write!(f, " (price ~{})", meta.own_push_removed_row_count_estimate)?;
716            }
717            fmt_plan_node(left, ctx, f)?;
718            f.write_str(" ")?;
719            // Same as join: a non-scan OPTIONAL right materializes with
720            // `execute_node` (eager drain), so its subtree prints at the
721            // eager page. A scan right prints no star either way.
722            fmt_plan_node(right, &eager_star_print(ctx), f)?;
723            fmt_split_filters(early_filter.as_ref(), residual_filter.as_ref(), f)?;
724            f.write_str(")")
725        }
726        PlanNode::Filter {
727            inner,
728            early,
729            residual,
730            exists,
731            one_to_one,
732        } => {
733            f.write_str("(filter ")?;
734            if ctx.estimates {
735                write!(f, "~{} ", node.produced_row_count_estimate())?;
736            }
737            if *one_to_one {
738                f.write_str("(one_to_one) ")?;
739            }
740            fmt_exists_clauses(exists, ctx, f)?;
741            if exists.is_empty() {
742                fmt_filter_head(early.as_ref(), residual.as_ref(), f)?;
743            } else {
744                fmt_split_filters(early.as_ref(), residual.as_ref(), f)?;
745            }
746            f.write_str(" ")?;
747            // A non-1:1 filter pulls its child at `scan_batch`, not caller `n`.
748            let child = if ctx.slice_path && !*one_to_one {
749                PrintCtx {
750                    page_rows: crate::query::tunables::scan_batch() as u64,
751                    ..*ctx
752                }
753            } else {
754                *ctx
755            };
756            fmt_plan_node(inner, &child, f)?;
757            f.write_str(")")
758        }
759        PlanNode::Union { left, right } => {
760            f.write_str("(union ")?;
761            if ctx.estimates {
762                write!(f, "~{} ", node.produced_row_count_estimate())?;
763                fmt_union_domains(node, ctx.profile, f)?;
764            }
765            fmt_plan_node(left, ctx, f)?;
766            f.write_str(" ")?;
767            fmt_plan_node(right, ctx, f)?;
768            f.write_str(")")
769        }
770        PlanNode::Unit | PlanNode::NamedGraphExists { .. } => f.write_str("(table (vars))"),
771        PlanNode::Values(values) => fmt_values(values, ctx, f),
772        PlanNode::NamedGraphs { variable, .. } => {
773            f.write_str("(named_graphs ")?;
774            if ctx.estimates {
775                write!(f, "~{} ", node.produced_row_count_estimate())?;
776            }
777            write!(f, "{variable}")?;
778            f.write_str(")")
779        }
780        PlanNode::DomainCounts {
781            kind,
782            head,
783            count,
784            produced_row_count_estimate,
785            merge_default_graph,
786            count_distinct,
787            ..
788        } => {
789            write!(
790                f,
791                "(domain_counts ~{produced_row_count_estimate} {head} {count} {}@{}",
792                kind.name(),
793                kind.permutation().cf_name()
794            )?;
795            if *count_distinct {
796                f.write_str(" (distinct_terms)")?;
797            }
798            if *merge_default_graph {
799                f.write_str(" (merge_default_graph)")?;
800            }
801            f.write_str(")")
802        }
803        PlanNode::HeadCounts {
804            kind,
805            total,
806            counted,
807            count,
808            produced_row_count_estimate,
809            ..
810        } => {
811            write!(
812                f,
813                "(head_counts ~{produced_row_count_estimate} {counted} {count} {}@{}",
814                kind.name(),
815                kind.permutation().cf_name()
816            )?;
817            f.write_str(if *total { " (total)" } else { " (per_head)" })?;
818            f.write_str(")")
819        }
820        PlanNode::PatternCount {
821            count,
822            count_star,
823            counted,
824            merge_default_graph,
825            produced_row_count_estimate,
826            ..
827        } => {
828            write!(f, "(pattern_count ~{produced_row_count_estimate} {count}")?;
829            if *count_star {
830                f.write_str(" COUNT(*)")?;
831            } else if let Some(counted) = counted {
832                write!(f, " COUNT({counted})")?;
833            }
834            if *merge_default_graph {
835                f.write_str(" (merge_default_graph)")?;
836            }
837            f.write_str(")")
838        }
839        PlanNode::JoinGraphVar {
840            inner, graph_var, ..
841        } => {
842            f.write_str("(join_graph_var ")?;
843            if ctx.estimates {
844                write!(f, "~{} ", node.produced_row_count_estimate())?;
845            }
846            write!(f, "{graph_var} ")?;
847            // Pulls a full scan page, not caller `n`.
848            let child = if ctx.slice_path {
849                PrintCtx {
850                    page_rows: crate::query::tunables::scan_batch() as u64,
851                    ..*ctx
852                }
853            } else {
854                *ctx
855            };
856            fmt_plan_node(inner, &child, f)?;
857            f.write_str(")")
858        }
859        PlanNode::Extend {
860            inner,
861            variable,
862            expression,
863            ..
864        } => {
865            f.write_str("(extend ")?;
866            if ctx.estimates {
867                write!(f, "~{} ", node.produced_row_count_estimate())?;
868            }
869            write!(f, "(({variable} ")?;
870            fmt_expression_sse(expression, f)?;
871            f.write_str(")) ")?;
872            fmt_plan_node(inner, ctx, f)?;
873            f.write_str(")")
874        }
875        PlanNode::Slice {
876            inner,
877            start,
878            length,
879        } => {
880            f.write_str("(slice ")?;
881            if ctx.estimates {
882                write!(f, "~{} ", node.produced_row_count_estimate())?;
883            }
884            match length {
885                Some(n) => write!(f, "{start} {n} ")?,
886                None => write!(f, "{start} _ ")?,
887            }
888            // A slice root is `execute_slice`, which opens its child at
889            // `slice_root_star_page`. A slice already inside a cursor
890            // forwards the caller's `n`, so the page stays.
891            let child = if ctx.slice_path {
892                *ctx
893            } else {
894                PrintCtx {
895                    slice_path: true,
896                    page_rows: crate::concurrent_star::slice_root_star_page(*start, *length),
897                    ..*ctx
898                }
899            };
900            fmt_plan_node(inner, &child, f)?;
901            f.write_str(")")
902        }
903        PlanNode::Distinct { inner, columns } => {
904            f.write_str("(distinct ")?;
905            if ctx.estimates {
906                write!(f, "~{} ", node.produced_row_count_estimate())?;
907            }
908            f.write_str("(")?;
909            write_var_list(f, columns)?;
910            f.write_str(") ")?;
911            // Mirror `open_node`: once the seen-set spills, the Distinct
912            // drain pulls `scan_batch()` pages to EOF regardless of `n`,
913            // so a cursor-priced child is priced at the larger page.
914            let child = if ctx.slice_path {
915                PrintCtx {
916                    page_rows: ctx
917                        .page_rows
918                        .max(crate::query::tunables::scan_batch() as u64),
919                    ..*ctx
920                }
921            } else {
922                *ctx
923            };
924            fmt_plan_node(inner, &child, f)?;
925            f.write_str(")")
926        }
927        PlanNode::Sort { inner, keys } => {
928            f.write_str("(sort ")?;
929            if ctx.estimates {
930                write!(f, "~{} ", node.produced_row_count_estimate())?;
931            }
932            f.write_str("(")?;
933            for (i, key) in keys.iter().enumerate() {
934                if i > 0 {
935                    f.write_str(" ")?;
936                }
937                if key.descending {
938                    write!(f, "(desc {})", key.expression)?;
939                } else {
940                    write!(f, "{}", key.expression)?;
941                }
942            }
943            f.write_str(") ")?;
944            // Sort materializes its child with `execute_node`, even when a
945            // slice cursor opened the Sort.
946            fmt_plan_node(inner, &eager_star_print(ctx), f)?;
947            f.write_str(")")
948        }
949        PlanNode::Group {
950            inner,
951            variables,
952            aggregates,
953            ..
954        } => {
955            f.write_str("(group ")?;
956            if ctx.estimates {
957                write!(f, "~{} ", node.produced_row_count_estimate())?;
958            }
959            f.write_str("(")?;
960            write_var_list(f, variables)?;
961            f.write_str(") (")?;
962            for (i, (v, a)) in aggregates.iter().enumerate() {
963                if i > 0 {
964                    f.write_str(" ")?;
965                }
966                f.write_str("(")?;
967                fmt_aggregate_sse(a, f)?;
968                write!(f, " {v})")?;
969            }
970            f.write_str(") ")?;
971            // The weighted fold is the operator that drains DomainScanCounts.
972            // Name the annotation here. The inner scan does not repeat it.
973            let weighted_kind = inner.as_scan().and_then(|scan| {
974                let kind = scan.domain_counts?;
975                crate::aggregate::domain_counts_weighted_fold_ok(scan, kind, variables, aggregates)
976                    .then_some((kind, scan.domain_count_mode()))
977            });
978            if let Some((kind, mode)) = weighted_kind {
979                if ctx.estimates {
980                    let mode_label = match mode {
981                        waratah_storage::DomainCountMode::Rows => String::new(),
982                        waratah_storage::DomainCountMode::DistinctTerms => {
983                            " (distinct_terms)".to_owned()
984                        }
985                        waratah_storage::DomainCountMode::DistinctGraphs => {
986                            " (distinct_graphs)".to_owned()
987                        }
988                    };
989                    write!(
990                        f,
991                        "(weighted_counts domain_counts_bag {}@{}{mode_label}) ",
992                        kind.name(),
993                        kind.permutation().cf_name()
994                    )?;
995                } else {
996                    f.write_str("(weighted_counts) ")?;
997                }
998            }
999            // The head-count folds drain `AxisHeadScanCounts` the same way:
1000            // name the RPC on the Group, not on the scan.
1001            if let Some(scan) = inner.as_scan()
1002                && let Some(hkind) = scan.head_scan_counts
1003            {
1004                if ctx.estimates {
1005                    let shape = if scan.head_count_is_total(hkind) {
1006                        "total"
1007                    } else {
1008                        "per_head"
1009                    };
1010                    write!(
1011                        f,
1012                        "(weighted_counts head_counts {shape} {}@{}) ",
1013                        hkind.name(),
1014                        hkind.permutation().cf_name()
1015                    )?;
1016                } else {
1017                    f.write_str("(weighted_counts) ")?;
1018                }
1019            }
1020            // Eager `execute_group` materializes the child. Under a slice
1021            // cursor the fold pulls `group_fold_batch`, and a LIMIT above
1022            // the group does not shrink that page.
1023            let child = if ctx.slice_path {
1024                PrintCtx {
1025                    page_rows: crate::query::tunables::group_fold_batch() as u64,
1026                    ..*ctx
1027                }
1028            } else {
1029                *ctx
1030            };
1031            fmt_plan_node(inner, &child, f)?;
1032            f.write_str(")")
1033        }
1034        PlanNode::SubSelect(sub) => {
1035            f.write_str("(subselect ")?;
1036            if ctx.estimates {
1037                write!(f, "~{} ", node.produced_row_count_estimate())?;
1038            }
1039            f.write_str("(")?;
1040            write_var_list(f, &sub.variables)?;
1041            f.write_str(") ")?;
1042            // SubSelect evaluates with `execute_node`. A LIMIT inside the
1043            // sub-plan sets `slice_path` again when that Slice is printed.
1044            let child = eager_star_print(ctx);
1045            fmt_plan_node(&sub.inner, &child, f)?;
1046            f.write_str(")")
1047        }
1048    }
1049}
1050
1051fn collect_scan_spine(node: &PlanNode) -> Option<Vec<&ScanOp>> {
1052    let mut out = Vec::new();
1053    collect_scan_spine_into(node, &mut out)?;
1054    if out.len() >= 2 { Some(out) } else { None }
1055}
1056
1057fn collect_scan_spine_into<'a>(node: &'a PlanNode, out: &mut Vec<&'a ScanOp>) -> Option<()> {
1058    match node {
1059        PlanNode::Scan(scan) => {
1060            out.push(scan);
1061            Some(())
1062        }
1063        PlanNode::Join { left, right, .. } => {
1064            collect_scan_spine_into(left, out)?;
1065            collect_scan_spine_into(right, out)
1066        }
1067        _ => None,
1068    }
1069}
1070
1071fn fmt_bgp(
1072    node: &PlanNode,
1073    scans: Vec<&ScanOp>,
1074    ctx: &PrintCtx<'_>,
1075    f: &mut String,
1076) -> fmt::Result {
1077    f.write_str("(bgp ")?;
1078    if ctx.estimates {
1079        write!(f, "~{} ", node.produced_row_count_estimate())?;
1080    }
1081    if let PlanNode::Join {
1082        hash_keys, meta, ..
1083    } = node
1084    {
1085        fmt_join_strategy(meta.strategy, hash_keys, f)?;
1086    }
1087    // Planned format collapses a pure scan spine and never enters the join
1088    // printer. The mark is the same predicate the executor uses, including
1089    // a star the outermost join refused (over-fetch) whose inner join still
1090    // qualifies.
1091    fmt_concurrent_star_spine(node, ctx, f)?;
1092    if ctx.estimates {
1093        if let PlanNode::Join {
1094            hash_keys,
1095            probe_key_domains,
1096            probe_key_overlap_milli,
1097            meta,
1098            ..
1099        } = node
1100        {
1101            fmt_hash_key_domains(
1102                node,
1103                hash_keys,
1104                probe_key_domains,
1105                probe_key_overlap_milli,
1106                ctx.profile,
1107                f,
1108            )?;
1109            // Recorded pre-push estimate beside the push-aware produced
1110            // count — mirrors the scan `(price ~N)` pair.
1111            write!(f, " (price ~{})", meta.own_push_removed_row_count_estimate)?;
1112        }
1113        if let PlanNode::LeftJoin { meta, .. } = node {
1114            write!(f, " (price ~{})", meta.own_push_removed_row_count_estimate)?;
1115        }
1116    }
1117    for scan in scans {
1118        f.write_str(" ")?;
1119        fmt_scan(scan, ctx, f)?;
1120    }
1121    f.write_str(")")
1122}
1123
1124fn fmt_scan(scan: &ScanOp, ctx: &PrintCtx<'_>, f: &mut String) -> fmt::Result {
1125    let extras = scan.broadcasted.is_some()
1126        || !scan.grounded.is_empty()
1127        || scan.graph_filter.is_some()
1128        || scan.merge_default_graph
1129        || !scan.iri_only.is_empty()
1130        || !scan.eager.is_empty()
1131        || ctx.estimates;
1132    if extras {
1133        f.write_str("(scan ")?;
1134        if ctx.estimates {
1135            write!(f, "~{} ", scan.produced_row_count_estimate)?;
1136        }
1137    }
1138    fmt_encoded_triple(scan, ctx, f)?;
1139    if ctx.estimates {
1140        fmt_scan_domains(scan, ctx.profile, f)?;
1141        // The unpushed pattern price beside the produced count: what the
1142        // bare pattern would yield from the sketches, ignoring every
1143        // planner decision (grounding, push clamp). Computed at render
1144        // time — never stored; `produced_row_count_estimate` is the only
1145        // persisted row count.
1146        write!(
1147            f,
1148            " (price ~{})",
1149            crate::plan::estimate_unclamped_scan_rows(ctx.profile, scan)
1150        )?;
1151    }
1152    if let Some((variable, slot)) = &scan.broadcasted {
1153        write!(f, " (broadcast {variable} {})", format_pattern_slot(*slot))?;
1154    }
1155    if let Some(filter) = &scan.graph_filter {
1156        let kind = if filter.is_exclude() {
1157            "block"
1158        } else {
1159            "allow"
1160        };
1161        write!(f, " (graph_filter {kind}({}))", filter.len())?;
1162    }
1163    if scan.merge_default_graph {
1164        f.write_str(" (merge_default_graph)")?;
1165    }
1166    if !scan.iri_only.is_empty() {
1167        f.write_str(" (iri_only")?;
1168        for variable in &scan.iri_only {
1169            write!(f, " {variable}")?;
1170        }
1171        f.write_str(")")?;
1172    }
1173    // The scan's eager comparison list. `exact` entries are authoritative
1174    // (their Filter conjunct is gone); `pre-filter` entries only drop
1175    // provable failures and their conjunct stays in the plan.
1176    if !scan.eager.is_empty() {
1177        let mut exact = Vec::new();
1178        let mut pre_filter = Vec::new();
1179        for comparison in &scan.eager {
1180            let rendered = format_eager_comparison(comparison);
1181            if crate::scan_eager::is_exact_comparison(comparison) {
1182                exact.push(rendered);
1183            } else {
1184                pre_filter.push(rendered);
1185            }
1186        }
1187        for (label, group) in [("exact", exact), ("pre-filter", pre_filter)] {
1188            if group.is_empty() {
1189                continue;
1190            }
1191            write!(f, " (eager {label}")?;
1192            for comparison in group {
1193                write!(f, " ({comparison})")?;
1194            }
1195            f.write_str(")")?;
1196        }
1197    }
1198    if ctx.estimates {
1199        if let Some(kind) = scan.domain_scan {
1200            write!(
1201                f,
1202                " (domain_scan {}@{})",
1203                kind.name(),
1204                kind.permutation().cf_name()
1205            )?;
1206        }
1207        // `domain_counts` is named on the Group that folds the RPC, not here.
1208        if let Some(kind) = scan.head_scan {
1209            write!(
1210                f,
1211                " (head_scan {}@{})",
1212                kind.name(),
1213                kind.permutation().cf_name()
1214            )?;
1215        }
1216    }
1217    if ctx.estimates {
1218        fmt_scan_marks(scan, f)?;
1219    }
1220    if !scan.grounded.is_empty() {
1221        f.write_str(" (grounded")?;
1222        for (i, (variable, slot)) in scan.grounded.iter().enumerate() {
1223            if i == 0 {
1224                write!(f, " {variable} {}", format_pattern_slot(*slot))?;
1225            } else {
1226                write!(f, ", {variable} {}", format_pattern_slot(*slot))?;
1227            }
1228        }
1229        f.write_str(")")?;
1230    }
1231    if extras {
1232        f.write_str(")")?;
1233    }
1234    Ok(())
1235}
1236
1237/// Render one eager comparison as `SLOT OP TERM` (e.g. `O >= 1967`).
1238fn format_eager_comparison(comparison: &SlotComparison) -> String {
1239    let slot = match comparison.slot {
1240        QuadSlot::Subject => "S",
1241        QuadSlot::Predicate => "P",
1242        QuadSlot::Object => "O",
1243        QuadSlot::Graph => "G",
1244    };
1245    let op = match comparison.op {
1246        CompareOp::Eq => "=",
1247        CompareOp::Ne => "!=",
1248        CompareOp::Lt => "<",
1249        CompareOp::Le => "<=",
1250        CompareOp::Gt => ">",
1251        CompareOp::Ge => ">=",
1252    };
1253    format!("{slot} {op} {}", format_encoded_term(&comparison.term, &[]))
1254}
1255
1256fn fmt_scan_marks(scan: &ScanOp, f: &mut String) -> fmt::Result {
1257    for variable in scan.slot_variables() {
1258        match scan.slot_mark(&variable) {
1259            None => write!(f, " (dead {variable})")?,
1260            Some(SlotMark {
1261                liveness: Liveness::Dead,
1262                ..
1263            }) => write!(f, " (dropped {variable})")?,
1264            Some(SlotMark {
1265                liveness: Liveness::Counted,
1266                bag: BagMark::Sensitive,
1267            }) => write!(f, " (counted {variable})")?,
1268            Some(SlotMark {
1269                liveness: Liveness::Counted,
1270                bag: BagMark::Insensitive,
1271            }) => write!(f, " (counted_distinct {variable})")?,
1272            Some(SlotMark {
1273                liveness: Liveness::Live,
1274                bag: BagMark::Insensitive,
1275            }) => write!(f, " (bag_insensitive {variable})")?,
1276            Some(SlotMark {
1277                liveness: Liveness::Live,
1278                bag: BagMark::Sensitive,
1279            }) => (),
1280        }
1281    }
1282    Ok(())
1283}
1284
1285fn fmt_encoded_triple(scan: &ScanOp, _ctx: &PrintCtx<'_>, f: &mut String) -> fmt::Result {
1286    f.write_str("(triple ")?;
1287    write_scan_slot(f, scan.subject.as_ref(), scan.pattern.subject.as_ref(), &[])?;
1288    f.write_str(" ")?;
1289    write_scan_slot_predicate(
1290        f,
1291        scan.predicate.as_ref(),
1292        scan.pattern.predicate.as_ref(),
1293        &[],
1294    )?;
1295    f.write_str(" ")?;
1296    write_scan_slot(f, scan.object.as_ref(), scan.pattern.object.as_ref(), &[])?;
1297    f.write_str(" ")?;
1298    match (scan.graph.as_ref(), scan.pattern.graph_name.as_ref()) {
1299        (_, Some(EncodedTerm::DefaultGraph)) => f.write_str("DEFAULT")?,
1300        (None, None) => f.write_str("*")?,
1301        (variable, term) => write_scan_slot(f, variable, term, &[])?,
1302    }
1303    f.write_str(")")
1304}
1305
1306fn write_scan_slot(
1307    f: &mut String,
1308    variable: Option<&Variable>,
1309    term: Option<&EncodedTerm>,
1310    strings: &[(StrHash, String)],
1311) -> fmt::Result {
1312    match (variable, term) {
1313        (_, Some(term)) => {
1314            f.write_str(&format_encoded_term(term, strings))?;
1315            Ok(())
1316        }
1317        (Some(variable), None) => write!(f, "{variable}"),
1318        (None, None) => f.write_str("_"),
1319    }
1320}
1321
1322/// [`write_scan_slot`] for the predicate slot of an SSE `(triple …)` — Jena
1323/// SSE shares SPARQL's rule that the `a` shorthand is predicate-only.
1324fn write_scan_slot_predicate(
1325    f: &mut String,
1326    variable: Option<&Variable>,
1327    term: Option<&EncodedTerm>,
1328    strings: &[(StrHash, String)],
1329) -> fmt::Result {
1330    match (variable, term) {
1331        (_, Some(term)) => {
1332            f.write_str(&format_encoded_term_predicate(term, strings))?;
1333            Ok(())
1334        }
1335        (Some(variable), None) => write!(f, "{variable}"),
1336        (None, None) => f.write_str("_"),
1337    }
1338}
1339
1340fn fmt_path_op(path: &PathOp, ctx: &PrintCtx<'_>, f: &mut String) -> fmt::Result {
1341    // Mirrors the scan layout: the produced count leads (the scan's rides
1342    // inside the pattern), then the shape, then domains, the unpushed
1343    // pattern price, and the structural markers last.
1344    f.write_str("(path ")?;
1345    if ctx.estimates {
1346        write!(f, "~{} ", path.produced_row_count_estimate)?;
1347    }
1348    write_scan_slot(
1349        f,
1350        path.subject.as_ref(),
1351        path.subject_term.as_ref(),
1352        &path.strings,
1353    )?;
1354    f.write_str(" ")?;
1355    fmt_waratah_path(&path.path, &path.strings, f)?;
1356    f.write_str(" ")?;
1357    write_scan_slot(
1358        f,
1359        path.object.as_ref(),
1360        path.object_term.as_ref(),
1361        &path.strings,
1362    )?;
1363    f.write_str(" ")?;
1364    match (path.graph.as_ref(), path.graph_name.as_ref()) {
1365        (_, Some(EncodedTerm::DefaultGraph)) => f.write_str("DEFAULT")?,
1366        (None, None) => f.write_str("*")?,
1367        (variable, term) => write_scan_slot(f, variable, term, &path.strings)?,
1368    }
1369    if ctx.estimates {
1370        fmt_path_domains(path, f)?;
1371        // The unpushed pattern price beside the produced count: what the
1372        // bare path would yield, ignoring every planner decision (the
1373        // push-aware probe clamp). Computed at render time — never stored;
1374        // mirrors the scan `(price ~N)` pair.
1375        write!(
1376            f,
1377            " (price ~{})",
1378            crate::plan::estimate_path_size(
1379                path.subject_term.is_some(),
1380                &path.path,
1381                path.object_term.is_some(),
1382            )
1383        )?;
1384    }
1385    if let Some(filter) = &path.graph_filter {
1386        let kind = if filter.is_exclude() {
1387            "block"
1388        } else {
1389            "allow"
1390        };
1391        write!(f, " (graph_filter {kind}({}))", filter.len())?;
1392    }
1393    if path.merge_default_graph {
1394        f.write_str(" (merge_default_graph)")?;
1395    }
1396    f.write_str(")")
1397}
1398
1399fn fmt_waratah_path(
1400    path: &PropertyPath,
1401    strings: &[(StrHash, String)],
1402    f: &mut String,
1403) -> fmt::Result {
1404    match path {
1405        PropertyPath::Predicate(term) => f.write_str(&format_encoded_term_predicate(term, strings)),
1406        PropertyPath::Reverse(inner) => {
1407            f.write_str("(reverse ")?;
1408            fmt_waratah_path(inner, strings, f)?;
1409            f.write_str(")")
1410        }
1411        PropertyPath::Sequence(a, b) => {
1412            f.write_str("(seq ")?;
1413            fmt_waratah_path(a, strings, f)?;
1414            f.write_str(" ")?;
1415            fmt_waratah_path(b, strings, f)?;
1416            f.write_str(")")
1417        }
1418        PropertyPath::Alternative(a, b) => {
1419            f.write_str("(alt ")?;
1420            fmt_waratah_path(a, strings, f)?;
1421            f.write_str(" ")?;
1422            fmt_waratah_path(b, strings, f)?;
1423            f.write_str(")")
1424        }
1425        PropertyPath::ZeroOrMore(inner) => {
1426            f.write_str("(path* ")?;
1427            fmt_waratah_path(inner, strings, f)?;
1428            f.write_str(")")
1429        }
1430        PropertyPath::OneOrMore(inner) => {
1431            f.write_str("(path+ ")?;
1432            fmt_waratah_path(inner, strings, f)?;
1433            f.write_str(")")
1434        }
1435        PropertyPath::ZeroOrOne(inner) => {
1436            f.write_str("(path? ")?;
1437            fmt_waratah_path(inner, strings, f)?;
1438            f.write_str(")")
1439        }
1440        PropertyPath::NegatedPropertySet(terms) => {
1441            f.write_str("(notoneof")?;
1442            for term in terms {
1443                f.write_str(" ")?;
1444                f.write_str(&format_encoded_term(term, strings))?;
1445            }
1446            f.write_str(")")
1447        }
1448    }
1449}
1450
1451/// Mark this join when it heads a concurrent star the runtime will run.
1452/// Returns whether the mark was written, so the caller can suppress the
1453/// same mark on the absorbed left spine.
1454///
1455/// Two truth sources, by context:
1456/// - EAGER context (`slice_path = false`): the plan's star-shape stamp
1457///   ([`crate::plan::JoinMeta::star_arms`], written by
1458///   `stamp_star_join_shapes` under exactly these parameters). One truth
1459///   with the executor — no re-derivation, no drift — and the output is a
1460///   pure function of the finished plan, which the EXPLAIN corpus diff
1461///   gate needs.
1462/// - SLICE context (`slice_path = true`, demand-bounded `page_rows`): a
1463///   live `detect` at this cursor's own page, because slice-star
1464///   viability is demand-priced (a `LIMIT 10` first pull admits spines
1465///   the eager page refuses) and plan time cannot reproduce it. This is
1466///   the same derivation the slice executor itself runs.
1467fn fmt_concurrent_star_here(
1468    node: &PlanNode,
1469    ctx: &PrintCtx<'_>,
1470    f: &mut String,
1471) -> Result<bool, fmt::Error> {
1472    if ctx.suppress_star {
1473        return Ok(false);
1474    }
1475    let PlanNode::Join {
1476        left,
1477        right,
1478        hash_keys,
1479        probe_key_domains,
1480        probe_key_overlap_milli,
1481        meta,
1482        ..
1483    } = node
1484    else {
1485        return Ok(false);
1486    };
1487    if ctx.slice_path {
1488        let Some(star) = crate::concurrent_star::detect(
1489            left,
1490            right,
1491            hash_keys,
1492            probe_key_domains,
1493            probe_key_overlap_milli,
1494            meta.strategy,
1495            true,
1496            ctx.page_rows,
1497        ) else {
1498            return Ok(false);
1499        };
1500        fmt_concurrent_star_token(star.explain_keys, star.probes.len() as u8, f)?;
1501        return Ok(true);
1502    }
1503    match meta.star_arms {
1504        Some(arms) => {
1505            fmt_concurrent_star_token(hash_keys, arms, f)?;
1506            Ok(true)
1507        }
1508        // No stamp in an eager context: the join never went through the
1509        // stamp pass (a raw fixture tree), or it is not a star head under
1510        // eager parameters.
1511        None => Ok(false),
1512    }
1513}
1514
1515/// Topmost concurrent star in a collapsed scan spine.
1516///
1517/// A join whose right is itself a Join drains that right eagerly
1518/// (`BuildJoin` -> `execute_node` -> the eager chunk loop's own `detect`),
1519/// so when the walk's own pricing refuses a join, the right subtree is
1520/// walked once under the eager page before the walk continues left — a
1521/// star seated there runs at runtime and the mark must say so. Reads the
1522/// plan's star-shape stamp ([`crate::plan::JoinMeta::star_arms`]), never a
1523/// live re-derivation — same single-truth rule as
1524/// [`fmt_concurrent_star_here`].
1525fn fmt_concurrent_star_spine(node: &PlanNode, ctx: &PrintCtx<'_>, f: &mut String) -> fmt::Result {
1526    if ctx.suppress_star {
1527        return Ok(());
1528    }
1529    let mut cursor = node;
1530    loop {
1531        let PlanNode::Join {
1532            left,
1533            right,
1534            hash_keys,
1535            probe_key_domains,
1536            probe_key_overlap_milli,
1537            meta,
1538            ..
1539        } = cursor
1540        else {
1541            return Ok(());
1542        };
1543        if ctx.slice_path {
1544            // Slice cursor: demand-priced admission, same as the slice
1545            // executor's own `detect` at this page (see
1546            // `fmt_concurrent_star_here` for the two truth sources).
1547            if let Some(star) = crate::concurrent_star::detect(
1548                left,
1549                right,
1550                hash_keys,
1551                probe_key_domains,
1552                probe_key_overlap_milli,
1553                meta.strategy,
1554                true,
1555                ctx.page_rows,
1556            ) {
1557                return fmt_concurrent_star_token(star.explain_keys, star.probes.len() as u8, f);
1558            }
1559        } else if let Some(arms) = meta.star_arms {
1560            return fmt_concurrent_star_token(hash_keys, arms, f);
1561        }
1562        if let PlanNode::Join { .. } = right.as_ref() {
1563            fmt_concurrent_star_spine(right, &eager_star_print(ctx), f)?;
1564        }
1565        cursor = left;
1566    }
1567}
1568
1569fn fmt_concurrent_star_token(keys: &[Variable], arms: u8, f: &mut String) -> fmt::Result {
1570    f.write_str(" (concurrent-star")?;
1571    for key in keys {
1572        write!(f, " {key}")?;
1573    }
1574    write!(f, " arms={arms})")
1575}
1576
1577fn fmt_join_strategy(
1578    strategy: JoinStrategy,
1579    hash_keys: &[Variable],
1580    f: &mut String,
1581) -> fmt::Result {
1582    if hash_keys.is_empty() {
1583        return f.write_str("(cartesian)");
1584    }
1585    let name = match strategy {
1586        JoinStrategy::Hash => "hash",
1587        JoinStrategy::Broadcast => "broadcast",
1588        JoinStrategy::Shuffle => "shuffle",
1589        JoinStrategy::SemiScan => "semi-scan",
1590        JoinStrategy::Semi => "semi",
1591    };
1592    write!(f, "({name}")?;
1593    for v in hash_keys {
1594        write!(f, " {v}")?;
1595    }
1596    f.write_str(")")
1597}
1598
1599fn fmt_exists_clauses(exists: &[ExistsClause], ctx: &PrintCtx<'_>, f: &mut String) -> fmt::Result {
1600    for clause in exists {
1601        let tag = if clause.negated {
1602            "not-exists"
1603        } else {
1604            "exists"
1605        };
1606        let kind = match clause.kind {
1607            ExistsKind::Uncorrelated => "uncorrelated",
1608            ExistsKind::SemiJoin => "semijoin",
1609            ExistsKind::NestedProbe => "probe",
1610        };
1611        write!(f, "({tag}")?;
1612        for variable in &clause.correlation {
1613            write!(f, " {variable}")?;
1614        }
1615        write!(f, " {kind} ")?;
1616        // EXISTS bodies run through `open_node`, even when the outer query
1617        // is on the eager path. An uncorrelated body is one ASK row.
1618        // SemiJoin and NestedProbe pull `scan_batch` (the hash promotion
1619        // later drains that body with `execute_node`, which prices the
1620        // eager page on its own) — so these prices describe the cursor
1621        // pull; a body promoted to `exists_semijoin_hash` runs eagerly
1622        // and the mark above is the cursor path only.
1623        let page_rows = match clause.kind {
1624            ExistsKind::Uncorrelated => 1,
1625            ExistsKind::SemiJoin | ExistsKind::NestedProbe => {
1626                crate::query::tunables::scan_batch() as u64
1627            }
1628        };
1629        let body_ctx = PrintCtx {
1630            slice_path: true,
1631            suppress_star: false,
1632            page_rows,
1633            ..*ctx
1634        };
1635        fmt_plan_node(&clause.body, &body_ctx, f)?;
1636        f.write_str(") ")?;
1637    }
1638    Ok(())
1639}
1640
1641fn fmt_split_filters(
1642    early: Option<&Expression>,
1643    residual: Option<&Expression>,
1644    f: &mut String,
1645) -> fmt::Result {
1646    match (early, residual) {
1647        (None, None) => Ok(()),
1648        (Some(e), None) => {
1649            f.write_str(" ")?;
1650            fmt_expression_sse(e, f)
1651        }
1652        (None, Some(r)) => {
1653            f.write_str(" (residual ")?;
1654            fmt_expression_sse(r, f)?;
1655            f.write_str(")")
1656        }
1657        (Some(e), Some(r)) => {
1658            f.write_str(" (early ")?;
1659            fmt_expression_sse(e, f)?;
1660            f.write_str(") (residual ")?;
1661            fmt_expression_sse(r, f)?;
1662            f.write_str(")")
1663        }
1664    }
1665}
1666
1667fn fmt_filter_head(
1668    early: Option<&Expression>,
1669    residual: Option<&Expression>,
1670    f: &mut String,
1671) -> fmt::Result {
1672    match (early, residual) {
1673        (None, None) => f.write_str("true"),
1674        (Some(e), None) => fmt_expression_sse(e, f),
1675        (None, Some(r)) => {
1676            f.write_str("(residual ")?;
1677            fmt_expression_sse(r, f)?;
1678            f.write_str(")")
1679        }
1680        (Some(e), Some(r)) => {
1681            f.write_str("(early ")?;
1682            fmt_expression_sse(e, f)?;
1683            f.write_str(") (residual ")?;
1684            fmt_expression_sse(r, f)?;
1685            f.write_str(")")
1686        }
1687    }
1688}
1689
1690fn fmt_values(values: &ValuesOp, ctx: &PrintCtx<'_>, f: &mut String) -> fmt::Result {
1691    f.write_str("(table ")?;
1692    if ctx.estimates {
1693        write!(f, "~{} ", values.produced_row_count_estimate())?;
1694    }
1695    f.write_str("(vars")?;
1696    for v in &values.variables {
1697        write!(f, " {v}")?;
1698    }
1699    f.write_str(")")?;
1700    for row in &values.rows {
1701        f.write_str(" (row")?;
1702        for (cell, var) in row.iter().zip(&values.variables) {
1703            if let Some(term) = cell {
1704                write!(f, " ({var} {})", format_encoded_term(term, &values.strings))?;
1705            }
1706        }
1707        f.write_str(")")?;
1708    }
1709    if ctx.estimates {
1710        fmt_values_domains(values, f)?;
1711    }
1712    f.write_str(")")
1713}
1714
1715fn fmt_hash_key_domains(
1716    node: &PlanNode,
1717    hash_keys: &[Variable],
1718    probe_key_domains: &[u64],
1719    probe_key_overlaps: &[u64],
1720    profile: Option<&StatsProfile>,
1721    f: &mut String,
1722) -> fmt::Result {
1723    if hash_keys.is_empty() {
1724        return Ok(());
1725    }
1726    for (idx, variable) in hash_keys.iter().enumerate() {
1727        // `(domain ?v N)` stays the estimator's node-level view (the
1728        // containment/intersection domain pricing consumes) — it is a
1729        // different quantity from the coverage stamp, which is the PROBE
1730        // arm's key space that the runtime drop compares pushed lists
1731        // against. Show that one separately when settled (non-zero).
1732        let domain = join_key_domain_for_node(profile, node, variable);
1733        fmt_one_domain(variable, domain, f)?;
1734        if let Some(stamped) = probe_key_domains.get(idx).copied().filter(|d| *d > 0) {
1735            write!(f, " (probe {variable} {stamped})")?;
1736        }
1737        // The containment stamp only prints when it DEGRADED the rule —
1738        // unaffected plans keep their EXPLAIN text byte-identical.
1739        if let Some(overlap) = probe_key_overlaps.get(idx).copied().filter(|o| *o < 1_000) {
1740            write!(f, " (overlap {variable} {overlap})")?;
1741        }
1742    }
1743    Ok(())
1744}
1745
1746fn fmt_scan_domains(scan: &ScanOp, profile: Option<&StatsProfile>, f: &mut String) -> fmt::Result {
1747    if let Some(variable) = &scan.subject
1748        && scan.pattern.subject.is_none()
1749        && scan.is_live(variable)
1750    {
1751        fmt_one_domain(
1752            variable,
1753            join_key_domain_for(profile, scan, std::slice::from_ref(variable)),
1754            f,
1755        )?;
1756    }
1757    if let Some(variable) = &scan.predicate
1758        && scan.pattern.predicate.is_none()
1759        && scan.is_live(variable)
1760    {
1761        fmt_one_domain(variable, None, f)?;
1762    }
1763    if let Some(variable) = &scan.object
1764        && scan.pattern.object.is_none()
1765        && scan.is_live(variable)
1766    {
1767        fmt_one_domain(
1768            variable,
1769            join_key_domain_for(profile, scan, std::slice::from_ref(variable)),
1770            f,
1771        )?;
1772    }
1773    Ok(())
1774}
1775
1776fn fmt_values_domains(values: &ValuesOp, f: &mut String) -> fmt::Result {
1777    for variable in &values.variables {
1778        fmt_one_domain(variable, values.distinct_key_count(variable), f)?;
1779    }
1780    Ok(())
1781}
1782
1783fn fmt_union_domains(
1784    node: &PlanNode,
1785    profile: Option<&StatsProfile>,
1786    f: &mut String,
1787) -> fmt::Result {
1788    let out = node.output_vars();
1789    for variable in &out.always_bound {
1790        fmt_one_domain(
1791            variable,
1792            join_key_domain_for_node(profile, node, variable),
1793            f,
1794        )?;
1795    }
1796    for variable in &out.maybe_unbound {
1797        fmt_one_domain(variable, None, f)?;
1798    }
1799    Ok(())
1800}
1801
1802fn fmt_path_domains(path: &PathOp, f: &mut String) -> fmt::Result {
1803    let mut seen: Vec<&Variable> = Vec::new();
1804    if let Some(variable) = &path.subject
1805        && path.subject_term.is_none()
1806    {
1807        fmt_one_domain(variable, None, f)?;
1808        seen.push(variable);
1809    }
1810    if let Some(variable) = &path.object
1811        && path.object_term.is_none()
1812        && !seen.contains(&variable)
1813    {
1814        fmt_one_domain(variable, None, f)?;
1815    }
1816    Ok(())
1817}
1818
1819fn fmt_one_domain(variable: &Variable, domain: Option<u64>, f: &mut String) -> fmt::Result {
1820    match domain {
1821        Some(n) => write!(f, " (domain {variable} {n})"),
1822        None => write!(f, " (domain {variable} ?)"),
1823    }
1824}
1825
1826fn format_pattern_slot(slot: PatternSlot) -> &'static str {
1827    match slot {
1828        PatternSlot::Subject => "subject",
1829        PatternSlot::Predicate => "predicate",
1830        PatternSlot::Object => "object",
1831    }
1832}
1833
1834pub(crate) fn format_encoded_term(term: &EncodedTerm, strings: &[(StrHash, String)]) -> String {
1835    match term {
1836        EncodedTerm::NamedNode { iri_id } => format_iri(iri_id, strings),
1837        EncodedTerm::BigBlankNode { id_id } => format!("_:<#{}>", short_hash(id_id)),
1838        EncodedTerm::SmallBlankNode(id) => format!("_:{id}"),
1839        EncodedTerm::NumericalBlankNode { id } => {
1840            format!("_:{}", u128::from_be_bytes(*id))
1841        }
1842        EncodedTerm::SmallStringLiteral(value) => format!("\"{value}\""),
1843        EncodedTerm::BigStringLiteral { value_id } => {
1844            format!("\"<#{}>\"", short_hash(value_id))
1845        }
1846        EncodedTerm::SmallSmallLangStringLiteral { value, language } => {
1847            format!("\"{value}\"@{language}")
1848        }
1849        EncodedTerm::SmallBigLangStringLiteral { value, language_id } => {
1850            format!("\"{value}\"@<#{}>", short_hash(language_id))
1851        }
1852        EncodedTerm::BigSmallLangStringLiteral { value_id, language } => {
1853            format!("\"<#{}>\"@{language}", short_hash(value_id))
1854        }
1855        EncodedTerm::BigBigLangStringLiteral {
1856            value_id,
1857            language_id,
1858        } => format!(
1859            "\"<#{}>\"@<#{}>",
1860            short_hash(value_id),
1861            short_hash(language_id)
1862        ),
1863        EncodedTerm::SmallTypedLiteral { value, datatype_id } => {
1864            format!("\"{value}\"^^{}", format_iri(datatype_id, strings))
1865        }
1866        EncodedTerm::BigTypedLiteral {
1867            value_id,
1868            datatype_id,
1869        } => format!(
1870            "\"<#{}>\"^^{}",
1871            short_hash(value_id),
1872            format_iri(datatype_id, strings)
1873        ),
1874        EncodedTerm::BooleanLiteral(v) => v.to_string(),
1875        EncodedTerm::FloatLiteral(v) => v.to_string(),
1876        EncodedTerm::DoubleLiteral(v) => v.to_string(),
1877        EncodedTerm::IntegerLiteral(v) => v.to_string(),
1878        EncodedTerm::DecimalLiteral(v) => v.to_string(),
1879        EncodedTerm::DateTimeLiteral(v) => format!("\"{v}\""),
1880        EncodedTerm::TimeLiteral(v) => format!("\"{v}\""),
1881        EncodedTerm::DateLiteral(v) => format!("\"{v}\""),
1882        EncodedTerm::GYearMonthLiteral(v) => format!("\"{v}\""),
1883        EncodedTerm::GYearLiteral(v) => format!("\"{v}\""),
1884        EncodedTerm::GMonthDayLiteral(v) => format!("\"{v}\""),
1885        EncodedTerm::GDayLiteral(v) => format!("\"{v}\""),
1886        EncodedTerm::GMonthLiteral(v) => format!("\"{v}\""),
1887        EncodedTerm::DurationLiteral(v) => format!("\"{v}\""),
1888        EncodedTerm::YearMonthDurationLiteral(v) => format!("\"{v}\""),
1889        EncodedTerm::DayTimeDurationLiteral(v) => format!("\"{v}\""),
1890        EncodedTerm::DefaultGraph => "DEFAULT".into(),
1891        EncodedTerm::Placeholder => "<placeholder>".into(),
1892        // Native geo terms print CRS84-inline facts (the ingest-CRS WKT
1893        // serialization needs PROJ; EXPLAIN shows structure, not output).
1894        EncodedTerm::LiteralPoint { x, y, crs, .. } => {
1895            format!("\"POINT({x} {y})\"^^geo:wktLiteral@{:?}", crs)
1896        }
1897        EncodedTerm::LiteralGeometry {
1898            geom_kind,
1899            crs,
1900            blob_id,
1901            ..
1902        } => format!(
1903            "\"<#{}>\"^^geo:wktLiteral@{:?} ({geom_kind:?})",
1904            short_hash(blob_id),
1905            crs
1906        ),
1907        EncodedTerm::BlobLiteral {
1908            datatype_id,
1909            blob_id,
1910        } => format!(
1911            "\"<#blob:{}>\"^^{}",
1912            short_hash(blob_id),
1913            format_iri(datatype_id, strings)
1914        ),
1915    }
1916}
1917
1918fn format_iri(iri_id: &StrHash, strings: &[(StrHash, String)]) -> String {
1919    if let Some((_, raw)) = strings.iter().find(|(h, _)| h == iri_id) {
1920        return prefixed_iri_name(raw).unwrap_or_else(|| format!("<{raw}>"));
1921    }
1922    if let Some(prefixed) = well_known_prefixed_iri(*iri_id) {
1923        return prefixed;
1924    }
1925    format!("<#{}>", short_hash(iri_id))
1926}
1927
1928/// [`format_iri`] for the predicate position of a triple or a path step —
1929/// the only positions whose grammar allows `rdf:type` to shorten to the `a`
1930/// keyword. Everywhere else the keyword is a syntax error, so those callers
1931/// use [`format_iri`] and get `rdf:type`.
1932fn format_iri_predicate(iri_id: &StrHash, strings: &[(StrHash, String)]) -> String {
1933    if *iri_id == RDF_TYPE_IRI_ID {
1934        return "a".into();
1935    }
1936    format_iri(iri_id, strings)
1937}
1938
1939/// [`format_encoded_term`] for a triple/path predicate term: `rdf:type`
1940/// renders as `a`. Predicates are always IRIs, so any other term falls
1941/// through to the position-neutral formatter.
1942pub(crate) fn format_encoded_term_predicate(
1943    term: &EncodedTerm,
1944    strings: &[(StrHash, String)],
1945) -> String {
1946    if let EncodedTerm::NamedNode { iri_id } = term {
1947        return format_iri_predicate(iri_id, strings);
1948    }
1949    format_encoded_term(term, strings)
1950}
1951
1952fn short_hash(hash: &StrHash) -> String {
1953    let hex = hash.to_string();
1954    hex.get(..8).unwrap_or(&hex).to_owned()
1955}
1956
1957/// One-line pattern identity for scan-fetch debug logs: the scan's S/P/O/G
1958/// slots in the same shape EXPLAIN prints them (variables as `?name`, hashed
1959/// terms as `<#…>`, no strings table), so a fetch line correlates with a
1960/// plan node by eye.
1961pub(crate) fn scan_pattern_tag(scan: &ScanOp) -> String {
1962    fn slot(variable: Option<&Variable>, term: Option<&EncodedTerm>) -> String {
1963        match (variable, term) {
1964            (_, Some(term)) => format_encoded_term(term, &[]),
1965            (Some(variable), None) => format!("{variable}"),
1966            (None, None) => "_".to_owned(),
1967        }
1968    }
1969    let predicate = match (scan.predicate.as_ref(), scan.pattern.predicate.as_ref()) {
1970        (_, Some(term)) => format_encoded_term_predicate(term, &[]),
1971        (Some(variable), None) => format!("{variable}"),
1972        (None, None) => "_".to_owned(),
1973    };
1974    let graph = match (scan.graph.as_ref(), scan.pattern.graph_name.as_ref()) {
1975        (_, Some(EncodedTerm::DefaultGraph)) => "DEFAULT".to_owned(),
1976        (None, None) => "*".to_owned(),
1977        (variable, term) => slot(variable, term),
1978    };
1979    format!(
1980        "{} {} {} {}",
1981        slot(scan.subject.as_ref(), scan.pattern.subject.as_ref()),
1982        predicate,
1983        slot(scan.object.as_ref(), scan.pattern.object.as_ref()),
1984        graph
1985    )
1986}
1987
1988/// Compact one-line identity for a plan node in execution debug logs.
1989///
1990/// A scan is its pattern; a join carries its keys and strategy; containers
1991/// recurse once or twice so an `Extend`/`Filter` wrapper does not hide the
1992/// join underneath. Deeper nodes fall back to their kind, keeping a log line
1993/// bounded even for a large UNION spine.
1994pub(crate) fn plan_node_tag(node: &PlanNode) -> String {
1995    plan_node_tag_at(node, 2)
1996}
1997
1998fn plan_node_tag_at(node: &PlanNode, depth: usize) -> String {
1999    if depth == 0 {
2000        return plan_node_kind(node).to_owned();
2001    }
2002    match node {
2003        PlanNode::Scan(scan) => format!("scan({})", scan_pattern_tag(scan)),
2004        PlanNode::Join {
2005            hash_keys, meta, ..
2006        } => format!("join(keys={hash_keys:?},strategy={:?})", meta.strategy),
2007        PlanNode::LeftJoin { hash_keys, .. } => format!("leftjoin(keys={hash_keys:?})"),
2008        PlanNode::Union { .. } => "union".to_owned(),
2009        PlanNode::Filter { inner, .. } => {
2010            format!("filter({})", plan_node_tag_at(inner, depth - 1))
2011        }
2012        PlanNode::Extend {
2013            inner, variable, ..
2014        } => format!("extend({variable},{})", plan_node_tag_at(inner, depth - 1)),
2015        PlanNode::Path(_) => "path".to_owned(),
2016        PlanNode::Values(_) => "values".to_owned(),
2017        PlanNode::Group { .. } => "group".to_owned(),
2018        PlanNode::SubSelect(_) => "subselect".to_owned(),
2019        PlanNode::Distinct { .. } => "distinct".to_owned(),
2020        PlanNode::Sort { .. } => "sort".to_owned(),
2021        PlanNode::Slice { .. } => "slice".to_owned(),
2022        _ => plan_node_kind(node).to_owned(),
2023    }
2024}
2025
2026fn plan_node_kind(node: &PlanNode) -> &'static str {
2027    match node {
2028        PlanNode::Scan(_) => "scan",
2029        PlanNode::Join { .. } => "join",
2030        PlanNode::LeftJoin { .. } => "leftjoin",
2031        PlanNode::Union { .. } => "union",
2032        PlanNode::Filter { .. } => "filter",
2033        PlanNode::Extend { .. } => "extend",
2034        PlanNode::Path(_) => "path",
2035        PlanNode::Values(_) => "values",
2036        PlanNode::Group { .. } => "group",
2037        PlanNode::SubSelect(_) => "subselect",
2038        PlanNode::Distinct { .. } => "distinct",
2039        PlanNode::Sort { .. } => "sort",
2040        PlanNode::Slice { .. } => "slice",
2041        _ => "plan",
2042    }
2043}
2044
2045fn fmt_plan_sparql_query(kind: &QueryKind, plan: &LogicalPlan) -> String {
2046    let (body, start, length, distinct, order) = peel_slice_sparql(&plan.root);
2047    let mut out = String::new();
2048    match kind {
2049        QueryKind::Select => {
2050            let distinct = if distinct { "DISTINCT " } else { "" };
2051            if let Some((items, keys, inner)) = try_flat_group_select(body, &plan.projection) {
2052                // The whole body is an aggregate spine: one flat SELECT with
2053                // the aggregate aliases inlined, no group subselect.
2054                let _ = write!(
2055                    out,
2056                    "SELECT {distinct}{} WHERE {{ {inner} }}",
2057                    items.join(" ")
2058                );
2059                if !keys.is_empty() {
2060                    let keys_text = keys
2061                        .iter()
2062                        .map(ToString::to_string)
2063                        .collect::<Vec<_>>()
2064                        .join(" ");
2065                    let _ = write!(out, " GROUP BY {keys_text}");
2066                }
2067            } else {
2068                let inner = fmt_plan_sparql_body(body);
2069                let vars = if plan.projection.is_empty() {
2070                    "*".to_string()
2071                } else {
2072                    plan.projection
2073                        .iter()
2074                        .map(Variable::to_string)
2075                        .collect::<Vec<_>>()
2076                        .join(" ")
2077                };
2078                let _ = write!(out, "SELECT {distinct}{vars} WHERE {{ {inner} }}");
2079            }
2080        }
2081        QueryKind::Ask => {
2082            let inner = fmt_plan_sparql_body(body);
2083            let _ = write!(out, "ASK WHERE {{ {inner} }}");
2084        }
2085        QueryKind::Construct { template } => {
2086            let inner = fmt_plan_sparql_body(body);
2087            let triples = template
2088                .iter()
2089                .map(|t| t.to_string())
2090                .collect::<Vec<_>>()
2091                .join(" . ");
2092            let _ = write!(out, "CONSTRUCT {{ {triples} }} WHERE {{ {inner} }}");
2093        }
2094        QueryKind::Describe { targets } => {
2095            let inner = fmt_plan_sparql_body(body);
2096            let _ = write!(out, "DESCRIBE {targets} WHERE {{ {inner} }}");
2097        }
2098    }
2099    if !order.is_empty() {
2100        let keys = order
2101            .iter()
2102            .map(fmt_sort_key_sparql)
2103            .collect::<Vec<_>>()
2104            .join(" ");
2105        let _ = write!(out, " ORDER BY {keys}");
2106    }
2107    if *start > 0 {
2108        let _ = write!(out, " OFFSET {start}");
2109    }
2110    if let Some(n) = length {
2111        let _ = write!(out, " LIMIT {n}");
2112    }
2113    out
2114}
2115
2116/// Absorb an `Extend`-chain-over-`Group` (or `Extend`-over-`DomainCounts`)
2117/// query body into the top-level SELECT: returns the SELECT items in
2118/// projection order (aggregate aliases inlined, internal aggregate variables
2119/// substituted), the GROUP BY keys, and the rendered group body. `None` when
2120/// the body is not a flat aggregate shape or the projection does not match
2121/// the group outputs exactly.
2122fn try_flat_group_select(
2123    body: &PlanNode,
2124    projection: &[Variable],
2125) -> Option<(Vec<String>, Vec<Variable>, String)> {
2126    if projection.is_empty() {
2127        return None;
2128    }
2129    let mut aliases: Vec<(&Variable, &Expression)> = Vec::new();
2130    let mut node = body;
2131    while let PlanNode::Extend {
2132        inner,
2133        variable,
2134        expression,
2135        ..
2136    } = node
2137    {
2138        aliases.push((variable, expression));
2139        node = inner;
2140    }
2141    let (keys, agg_texts, inner) = match node {
2142        PlanNode::Group {
2143            inner: group_inner,
2144            variables: group_keys,
2145            aggregates,
2146            ..
2147        } => (
2148            group_keys.clone(),
2149            group_agg_texts(aggregates, IriStyle::Full),
2150            fmt_plan_sparql_body(group_inner),
2151        ),
2152        PlanNode::DomainCounts {
2153            kind,
2154            constraints,
2155            constraint_var,
2156            head,
2157            count,
2158            dead,
2159            count_star,
2160            ..
2161        } => {
2162            let keys = match constraint_var.as_ref() {
2163                Some(cv) => vec![cv.clone(), head.clone()],
2164                None => vec![head.clone()],
2165            };
2166            (
2167                keys,
2168                vec![(count, domain_counts_agg_text(*count_star, dead.as_ref()))],
2169                domain_counts_where_clause(
2170                    *kind,
2171                    constraints,
2172                    constraint_var.as_ref(),
2173                    head,
2174                    dead.as_ref(),
2175                    &[],
2176                ),
2177            )
2178        }
2179        PlanNode::HeadCounts {
2180            kind,
2181            total: _,
2182            counted,
2183            group,
2184            count,
2185            ..
2186        } => {
2187            let keys = group.as_ref().map(|g| vec![g.clone()]).unwrap_or_default();
2188            (
2189                keys,
2190                vec![(count, format!("COUNT(DISTINCT {counted})"))],
2191                head_counts_where_clause(*kind, counted, group.as_ref()),
2192            )
2193        }
2194        PlanNode::PatternCount {
2195            pattern,
2196            subject,
2197            predicate,
2198            object,
2199            count,
2200            count_star,
2201            counted,
2202            ..
2203        } => (
2204            Vec::new(),
2205            vec![(count, pattern_count_agg_text(*count_star, counted.as_ref()))],
2206            pattern_count_where_clause(
2207                subject.as_ref(),
2208                predicate.as_ref(),
2209                object.as_ref(),
2210                pattern,
2211            ),
2212        ),
2213        _ => return None,
2214    };
2215    // Collected outer-to-inner; hoisting wants application order.
2216    let application_order = aliases.iter().rev().copied().collect::<Vec<_>>();
2217    let (entries, referenced) =
2218        hoist_group_aliases(&keys, &agg_texts, &application_order, IriStyle::Full)?;
2219    // The flat form drops the group's own SELECT list, so every aggregate
2220    // must be consumed by a hoisted alias; anything else keeps the subselect.
2221    if referenced.len() != agg_texts.len() {
2222        return None;
2223    }
2224    let mut items = Vec::new();
2225    for var in projection {
2226        if let Some((_, text)) = entries.iter().find(|(entry, _)| *entry == var) {
2227            items.push(format!("({text} AS {var})"));
2228        } else if keys.contains(var) {
2229            items.push(var.to_string());
2230        } else {
2231            return None;
2232        }
2233    }
2234    Some((items, keys, inner))
2235}
2236
2237/// SPARQL `ORDER BY` key text for the planned-Sparql printer (`ASC` / `DESC`
2238/// always explicit, matching the L1 spargebra-derived output).
2239fn fmt_sort_key_sparql(key: &SortKey) -> String {
2240    if key.descending {
2241        format!("DESC({})", key.expression)
2242    } else {
2243        format!("ASC({})", key.expression)
2244    }
2245}
2246
2247/// Peel the top-level `Slice?(Sort?(Distinct?))` modifier spine, returning the
2248/// body plus the OFFSET / LIMIT / DISTINCT / ORDER BY settings for the SELECT
2249/// header.
2250fn peel_slice_sparql(node: &PlanNode) -> (&PlanNode, &u64, &Option<u64>, bool, &[SortKey]) {
2251    static ZERO: u64 = 0;
2252    static NONE: Option<u64> = None;
2253    static NO_KEYS: &[SortKey] = &[];
2254    let (node, start, length) = match node {
2255        PlanNode::Slice {
2256            inner,
2257            start,
2258            length,
2259        } => (inner.as_ref(), start, length),
2260        other => (other, &ZERO, &NONE),
2261    };
2262    match node {
2263        PlanNode::Distinct { inner, .. } => match inner.as_ref() {
2264            PlanNode::Sort { inner, keys } => (inner.as_ref(), start, length, true, keys),
2265            body => (body, start, length, true, NO_KEYS),
2266        },
2267        PlanNode::Sort { inner, keys } => match inner.as_ref() {
2268            PlanNode::Distinct { inner, .. } => (inner.as_ref(), start, length, true, keys),
2269            body => (body, start, length, false, keys),
2270        },
2271        body => (body, start, length, false, NO_KEYS),
2272    }
2273}
2274
2275fn fmt_plan_sparql_body(node: &PlanNode) -> String {
2276    if let Some(scans) = collect_scan_spine(node) {
2277        return scans
2278            .into_iter()
2279            .map(scan_to_sparql_pattern)
2280            .collect::<Vec<_>>()
2281            .join(" . ");
2282    }
2283    match node {
2284        PlanNode::CustomNode(op) => {
2285            // EXPLAIN-only reconstruction: a plugin op has no SPARQL text —
2286            // print a comment marker naming the op (wrapped children, if a
2287            // future plugin supplies them, would render inside).
2288            let mut out = format!("{{ # custom-op {}/{}", op.plugin_id, op.op_id);
2289            for variable in &op.variables {
2290                out.push_str(&format!(" ?{}", variable.as_str()));
2291            }
2292            out.push_str(" }");
2293            out
2294        }
2295        PlanNode::Scan(scan) => scan_to_sparql_pattern(scan),
2296        PlanNode::Path(path) => {
2297            format!(
2298                "{} {} {}",
2299                path_end_sparql(
2300                    path.subject.as_ref(),
2301                    path.subject_term.as_ref(),
2302                    &path.strings
2303                ),
2304                waratah_path_sparql(&path.path, &path.strings),
2305                path_end_sparql(
2306                    path.object.as_ref(),
2307                    path.object_term.as_ref(),
2308                    &path.strings
2309                ),
2310            )
2311        }
2312        PlanNode::Join { left, right, .. } => {
2313            format!(
2314                "{{ {} }} {{ {} }}",
2315                fmt_plan_sparql_body(left),
2316                fmt_plan_sparql_body(right)
2317            )
2318        }
2319        PlanNode::LeftJoin {
2320            left,
2321            right,
2322            early_filter,
2323            residual_filter,
2324            ..
2325        } => {
2326            let mut opt = fmt_plan_sparql_body(right);
2327            if let Some(expr) = early_filter {
2328                opt = format!("{opt} FILTER({expr})");
2329            }
2330            if let Some(expr) = residual_filter {
2331                opt = format!("{opt} FILTER({expr})");
2332            }
2333            format!("{} OPTIONAL {{ {} }}", fmt_plan_sparql_body(left), opt)
2334        }
2335        PlanNode::Filter {
2336            inner,
2337            early,
2338            residual,
2339            exists,
2340            ..
2341        } => {
2342            let mut s = fmt_plan_sparql_body(inner);
2343            for clause in exists {
2344                let keyword = if clause.negated {
2345                    "NOT EXISTS"
2346                } else {
2347                    "EXISTS"
2348                };
2349                s = format!(
2350                    "{s} FILTER({keyword} {{ {} }})",
2351                    fmt_plan_sparql_body(&clause.body)
2352                );
2353            }
2354            match (early, residual) {
2355                (Some(e), Some(r)) => s = format!("{s} FILTER(({e}) && ({r}))"),
2356                (Some(e), None) => s = format!("{s} FILTER({e})"),
2357                (None, Some(r)) => s = format!("{s} FILTER({r})"),
2358                (None, None) => {}
2359            }
2360            s
2361        }
2362        PlanNode::Union { left, right } => format!(
2363            "{{ {} }} UNION {{ {} }}",
2364            fmt_plan_sparql_body(left),
2365            fmt_plan_sparql_body(right)
2366        ),
2367        PlanNode::Unit | PlanNode::NamedGraphExists { .. } => String::new(),
2368        PlanNode::Values(values) => values_to_sparql(values),
2369        PlanNode::NamedGraphs { variable, .. } => format!("GRAPH {variable} {{ }}"),
2370        // The count scan replaces a single triple plus one COUNT. Rebuild
2371        // that triple from the kind, the constraint term, the head, and the
2372        // dead-slot variable the RPC never returns.
2373        PlanNode::DomainCounts {
2374            kind,
2375            constraints,
2376            constraint_var,
2377            head,
2378            dead,
2379            ..
2380        } => domain_counts_where_clause(
2381            *kind,
2382            constraints,
2383            constraint_var.as_ref(),
2384            head,
2385            dead.as_ref(),
2386            &[],
2387        ),
2388        PlanNode::HeadCounts {
2389            kind,
2390            counted,
2391            group,
2392            ..
2393        } => head_counts_where_clause(*kind, counted, group.as_ref()),
2394        PlanNode::PatternCount {
2395            pattern,
2396            subject,
2397            predicate,
2398            object,
2399            ..
2400        } => pattern_count_where_clause(
2401            subject.as_ref(),
2402            predicate.as_ref(),
2403            object.as_ref(),
2404            pattern,
2405        ),
2406        PlanNode::JoinGraphVar { inner, .. } => fmt_plan_sparql_body(inner),
2407        PlanNode::Extend {
2408            inner,
2409            variable,
2410            expression,
2411            ..
2412        } => {
2413            // `SELECT … (agg AS ?alias) … GROUP BY` lowers to an Extend chain
2414            // over a Group, or over a DomainCounts / PatternCount node when
2415            // the group was a single count of one triple. Hoist the aliases
2416            // into the group's own SELECT list (inner to outer, internal
2417            // aggregate variables substituted) instead of printing a group
2418            // subselect plus a `BIND` over a hash-named internal variable.
2419            let mut aliases = vec![(variable, expression)];
2420            let mut node = inner.as_ref();
2421            while let PlanNode::Extend {
2422                inner: next,
2423                variable,
2424                expression,
2425                ..
2426            } = node
2427            {
2428                aliases.push((variable, expression));
2429                node = next;
2430            }
2431            if let PlanNode::DomainCounts {
2432                kind,
2433                constraints,
2434                constraint_var,
2435                head,
2436                count,
2437                dead,
2438                count_star,
2439                ..
2440            } = node
2441            {
2442                let keys: Vec<Variable> = match constraint_var.as_ref() {
2443                    Some(cv) => vec![cv.clone(), head.clone()],
2444                    None => vec![head.clone()],
2445                };
2446                let agg_texts = vec![(count, domain_counts_agg_text(*count_star, dead.as_ref()))];
2447                // Collected outer-to-inner; hoisting wants application order.
2448                let application_order = aliases.iter().rev().copied().collect::<Vec<_>>();
2449                if let Some((entries, referenced)) =
2450                    hoist_group_aliases(&keys, &agg_texts, &application_order, IriStyle::Full)
2451                {
2452                    let group_body = domain_counts_where_clause(
2453                        *kind,
2454                        constraints,
2455                        constraint_var.as_ref(),
2456                        head,
2457                        dead.as_ref(),
2458                        &[],
2459                    );
2460                    return group_subselect_sparql(
2461                        &keys,
2462                        &agg_texts,
2463                        &group_body,
2464                        &entries,
2465                        &referenced,
2466                    );
2467                }
2468            }
2469            if let PlanNode::PatternCount {
2470                pattern,
2471                subject,
2472                predicate,
2473                object,
2474                count,
2475                count_star,
2476                counted,
2477                ..
2478            } = node
2479            {
2480                let keys: Vec<Variable> = Vec::new();
2481                let agg_texts =
2482                    vec![(count, pattern_count_agg_text(*count_star, counted.as_ref()))];
2483                let application_order = aliases.iter().rev().copied().collect::<Vec<_>>();
2484                if let Some((entries, referenced)) =
2485                    hoist_group_aliases(&keys, &agg_texts, &application_order, IriStyle::Full)
2486                {
2487                    let group_body = pattern_count_where_clause(
2488                        subject.as_ref(),
2489                        predicate.as_ref(),
2490                        object.as_ref(),
2491                        pattern,
2492                    );
2493                    return group_subselect_sparql(
2494                        &keys,
2495                        &agg_texts,
2496                        &group_body,
2497                        &entries,
2498                        &referenced,
2499                    );
2500                }
2501            }
2502            if let PlanNode::Group {
2503                inner: group_inner,
2504                variables: keys,
2505                aggregates,
2506                ..
2507            } = node
2508            {
2509                let agg_texts = group_agg_texts(aggregates, IriStyle::Full);
2510                // Collected outer-to-inner; hoisting wants application order.
2511                let application_order = aliases.iter().rev().copied().collect::<Vec<_>>();
2512                if let Some((entries, referenced)) =
2513                    hoist_group_aliases(keys, &agg_texts, &application_order, IriStyle::Full)
2514                {
2515                    let group_body = fmt_plan_sparql_body(group_inner);
2516                    return group_subselect_sparql(
2517                        keys,
2518                        &agg_texts,
2519                        &group_body,
2520                        &entries,
2521                        &referenced,
2522                    );
2523                }
2524            }
2525            // Not a hoistable group alias chain — nested `BIND`s (the
2526            // historical shape).
2527            let mut out = fmt_plan_sparql_body(node);
2528            for (var, expr) in aliases.iter().rev() {
2529                out = format!("{out} BIND({expr} AS {var})");
2530            }
2531            out
2532        }
2533        PlanNode::Slice {
2534            inner,
2535            start,
2536            length,
2537        } => {
2538            let inner = fmt_plan_sparql_body(inner);
2539            let mut s = format!("{{ SELECT * WHERE {{ {inner} }}");
2540            if *start > 0 {
2541                s = format!("{s} OFFSET {start}");
2542            }
2543            if let Some(n) = length {
2544                s = format!("{s} LIMIT {n}");
2545            }
2546            format!("{s} }}")
2547        }
2548        PlanNode::Distinct { inner, .. } | PlanNode::Sort { inner, .. } => {
2549            fmt_plan_sparql_body(inner)
2550        }
2551        PlanNode::Group {
2552            inner,
2553            variables,
2554            aggregates,
2555            ..
2556        } => {
2557            let inner = fmt_plan_sparql_body(inner);
2558            let agg_texts = group_agg_texts(aggregates, IriStyle::Full);
2559            group_subselect_sparql(variables, &agg_texts, &inner, &[], &[])
2560        }
2561        PlanNode::SubSelect(sub) => {
2562            // The boundary owns the subselect's modifier spine — peel
2563            // `Slice?(Sort?(Distinct?(body)))` and render it in the SELECT
2564            // header, SPARQL-style.
2565            let mut inner: &PlanNode = &sub.inner;
2566            let mut slice: Option<(u64, Option<u64>)> = None;
2567            if let PlanNode::Slice {
2568                inner: s,
2569                start,
2570                length,
2571            } = inner
2572            {
2573                slice = Some((*start, *length));
2574                inner = s;
2575            }
2576            let mut order: &[SortKey] = &[];
2577            if let PlanNode::Sort { inner: s, keys } = inner {
2578                order = keys;
2579                inner = s;
2580            }
2581            let mut distinct = false;
2582            if let PlanNode::Distinct { inner: d, .. } = inner {
2583                distinct = true;
2584                inner = d;
2585            }
2586            let body = fmt_plan_sparql_body(inner);
2587            let vars = sub
2588                .variables
2589                .iter()
2590                .map(Variable::to_string)
2591                .collect::<Vec<_>>()
2592                .join(" ");
2593            let distinct = if distinct { "DISTINCT " } else { "" };
2594            let order_by = if order.is_empty() {
2595                String::new()
2596            } else {
2597                let keys = order
2598                    .iter()
2599                    .map(fmt_sort_key_sparql)
2600                    .collect::<Vec<_>>()
2601                    .join(" ");
2602                format!(" ORDER BY {keys}")
2603            };
2604            let modifiers = match slice {
2605                Some((start, Some(length))) => {
2606                    format!(" OFFSET {start} LIMIT {length}")
2607                }
2608                Some((start, None)) if start > 0 => format!(" OFFSET {start}"),
2609                _ => String::new(),
2610            };
2611            format!("{{ SELECT {distinct}{vars} WHERE {{ {body} }}{order_by}{modifiers} }}")
2612        }
2613    }
2614}
2615
2616fn scan_to_sparql_triple(scan: &ScanOp) -> String {
2617    format!(
2618        "{} {} {}",
2619        slot_sparql(scan.subject.as_ref(), scan.pattern.subject.as_ref(), &[]),
2620        slot_sparql_predicate(
2621            scan.predicate.as_ref(),
2622            scan.pattern.predicate.as_ref(),
2623            &[]
2624        ),
2625        slot_sparql(scan.object.as_ref(), scan.pattern.object.as_ref(), &[]),
2626    )
2627}
2628
2629/// SPARQL reconstruction of one scan: the triple followed by a `FILTER`
2630/// pattern for each **exact** eager comparison.
2631///
2632/// The exact entries have no plan `Filter` node left, so this is the only
2633/// place a backward reconstruction can show them. Eager pre-filter entries
2634/// are deliberately omitted: their conjunct is still in the plan `Filter`,
2635/// which renders itself as a `FILTER` around this body, and printing it here
2636/// too would duplicate the same predicate. The result is best effort, like
2637/// the rest of this format (bound predicates print as hashes).
2638fn scan_to_sparql_pattern(scan: &ScanOp) -> String {
2639    let mut out = scan_to_sparql_triple(scan);
2640    for comparison in &scan.eager {
2641        if !crate::scan_eager::is_exact_comparison(comparison) {
2642            continue;
2643        }
2644        let left = match comparison.slot {
2645            QuadSlot::Subject => {
2646                slot_sparql(scan.subject.as_ref(), scan.pattern.subject.as_ref(), &[])
2647            }
2648            QuadSlot::Predicate => slot_sparql_predicate(
2649                scan.predicate.as_ref(),
2650                scan.pattern.predicate.as_ref(),
2651                &[],
2652            ),
2653            QuadSlot::Object => {
2654                slot_sparql(scan.object.as_ref(), scan.pattern.object.as_ref(), &[])
2655            }
2656            QuadSlot::Graph => continue,
2657        };
2658        if left == "_" {
2659            continue;
2660        }
2661        out.push_str(&format!(
2662            " FILTER({left} {} {})",
2663            sparql_compare_op(comparison.op),
2664            format_encoded_term(&comparison.term, &[])
2665        ));
2666    }
2667    out
2668}
2669
2670fn sparql_compare_op(op: CompareOp) -> &'static str {
2671    match op {
2672        CompareOp::Eq => "=",
2673        CompareOp::Ne => "!=",
2674        CompareOp::Lt => "<",
2675        CompareOp::Le => "<=",
2676        CompareOp::Gt => ">",
2677        CompareOp::Ge => ">=",
2678    }
2679}
2680
2681/// Rebuild the WHERE body a [`PlanNode::DomainCounts`] replaced.
2682fn domain_counts_where_clause(
2683    kind: DomainScanKind,
2684    constraints: &[EncodedTerm],
2685    constraint_var: Option<&Variable>,
2686    head: &Variable,
2687    dead: Option<&Variable>,
2688    strings: &[(StrHash, String)],
2689) -> String {
2690    let constraint = constraints.first();
2691    let triple = domain_counts_triple(kind, constraint, head, dead, strings);
2692    match (constraint_var, constraints.len()) {
2693        (Some(cv), n) if n > 1 => {
2694            let terms = constraints
2695                .iter()
2696                .map(|term| format_encoded_term(term, strings))
2697                .collect::<Vec<_>>()
2698                .join(" ");
2699            format!("VALUES {cv} {{ {terms} }} {triple}")
2700        }
2701        (Some(cv), 1) => {
2702            let term = format_encoded_term(&constraints[0], strings);
2703            format!("{triple} FILTER(sameTerm({cv}, {term}))")
2704        }
2705        _ => triple,
2706    }
2707}
2708
2709/// Rebuild the triple a [`PlanNode::DomainCounts`] replaced.
2710///
2711/// The count RPC never returns the dead slot, so that variable's name lives
2712/// on the node only for this reconstruction. An absent dead slot prints as
2713/// `[]`.
2714fn domain_counts_triple(
2715    kind: DomainScanKind,
2716    constraint: Option<&EncodedTerm>,
2717    head: &Variable,
2718    dead: Option<&Variable>,
2719    strings: &[(StrHash, String)],
2720) -> String {
2721    // Slot layout is `DomainScanKind::{constraint,head,dead}_slot`. Written
2722    // out so the triple positions don't go through a closure that cannot
2723    // store the borrowed terms.
2724    let (subject_var, subject_term, predicate_var, predicate_term, object_var, object_term) =
2725        match kind {
2726            DomainScanKind::PredicateDomain => (dead, None, None, constraint, Some(head), None),
2727            DomainScanKind::PredicateSubjects => (Some(head), None, None, constraint, dead, None),
2728            DomainScanKind::SubjectPreds => (None, constraint, Some(head), None, dead, None),
2729            DomainScanKind::SubjectDomain => (None, constraint, dead, None, Some(head), None),
2730            DomainScanKind::ObjectPreds => (dead, None, Some(head), None, None, constraint),
2731        };
2732    format!(
2733        "{} {} {}",
2734        slot_sparql(subject_var, subject_term, strings),
2735        slot_sparql_predicate(predicate_var, predicate_term, strings),
2736        slot_sparql(object_var, object_term, strings),
2737    )
2738}
2739
2740/// Source spelling of the one aggregate a `DomainCounts` node replaced.
2741fn domain_counts_agg_text(count_star: bool, dead: Option<&Variable>) -> String {
2742    match (count_star, dead) {
2743        (false, Some(dead)) => format!("COUNT({dead})"),
2744        _ => "COUNT(*)".to_string(),
2745    }
2746}
2747
2748/// Rebuild the WHERE body a [`PlanNode::PatternCount`] replaced: the BGP
2749/// triple from the retained slot variables and ground terms.
2750fn pattern_count_where_clause(
2751    subject: Option<&Variable>,
2752    predicate: Option<&Variable>,
2753    object: Option<&Variable>,
2754    pattern: &EncodedTriplePattern,
2755) -> String {
2756    format!(
2757        "{} {} {}",
2758        slot_sparql(subject, pattern.subject.as_ref(), &[]),
2759        slot_sparql_predicate(predicate, pattern.predicate.as_ref(), &[]),
2760        slot_sparql(object, pattern.object.as_ref(), &[]),
2761    )
2762}
2763
2764/// Source spelling of the one aggregate a `PatternCount` node replaced.
2765fn pattern_count_agg_text(count_star: bool, counted: Option<&Variable>) -> String {
2766    match (count_star, counted) {
2767        (false, Some(counted)) => format!("COUNT({counted})"),
2768        _ => "COUNT(*)".to_string(),
2769    }
2770}
2771
2772/// Rebuild the WHERE body a [`PlanNode::HeadCounts`] replaced: the bare
2773/// triple (TSG: `{counted} a {group}`), with lost slots (a head count never
2774/// returns them) printed as existential `[]` — same convention as
2775/// [`domain_counts_triple`]'s absent dead slot.
2776fn head_counts_where_clause(
2777    kind: HeadScanKind,
2778    counted: &Variable,
2779    group: Option<&Variable>,
2780) -> String {
2781    let v = |variable: &Variable| slot_sparql(Some(variable), None, &[]);
2782    let none = || "[]".to_string();
2783    let (s, p, o) = match (kind, group) {
2784        // TSG: slot-0 = class (TOTAL: counted; PER_HEAD: group), slot-1 =
2785        // subject, predicate implicit `rdf:type`.
2786        (HeadScanKind::Classes, Some(group)) => (v(counted), "a".to_string(), v(group)),
2787        (HeadScanKind::Classes, None) => (none(), "a".to_string(), v(counted)),
2788        // Bare families: slot-0 head, slot-1 counted, last slot lost.
2789        (HeadScanKind::Subjects, Some(group)) => (v(group), v(counted), none()),
2790        (HeadScanKind::Subjects, None) => (v(counted), none(), none()),
2791        (HeadScanKind::Predicates, Some(group)) => (v(counted), v(group), none()),
2792        (HeadScanKind::Predicates, None) => (none(), v(counted), none()),
2793        (HeadScanKind::Objects, Some(group)) => (none(), v(counted), v(group)),
2794        (HeadScanKind::Objects, None) => (none(), none(), v(counted)),
2795    };
2796    format!("{s} {p} {o}")
2797}
2798
2799fn slot_sparql(
2800    variable: Option<&Variable>,
2801    term: Option<&EncodedTerm>,
2802    strings: &[(StrHash, String)],
2803) -> String {
2804    match (variable, term) {
2805        (_, Some(term)) => format_encoded_term(term, strings),
2806        (Some(variable), None) => variable.to_string(),
2807        (None, None) => "[]".into(),
2808    }
2809}
2810
2811/// [`slot_sparql`] for the triple predicate slot, where `rdf:type` renders
2812/// as the `a` keyword (subject/object slots must keep `rdf:type`).
2813fn slot_sparql_predicate(
2814    variable: Option<&Variable>,
2815    term: Option<&EncodedTerm>,
2816    strings: &[(StrHash, String)],
2817) -> String {
2818    match (variable, term) {
2819        (_, Some(term)) => format_encoded_term_predicate(term, strings),
2820        (Some(variable), None) => variable.to_string(),
2821        (None, None) => "[]".into(),
2822    }
2823}
2824
2825fn path_end_sparql(
2826    variable: Option<&Variable>,
2827    term: Option<&EncodedTerm>,
2828    strings: &[(StrHash, String)],
2829) -> String {
2830    slot_sparql(variable, term, strings)
2831}
2832
2833fn waratah_path_sparql(path: &PropertyPath, strings: &[(StrHash, String)]) -> String {
2834    match path {
2835        PropertyPath::Predicate(term) => format_encoded_term_predicate(term, strings),
2836        PropertyPath::Reverse(inner) => format!("^({})", waratah_path_sparql(inner, strings)),
2837        PropertyPath::Sequence(a, b) => format!(
2838            "({} / {})",
2839            waratah_path_sparql(a, strings),
2840            waratah_path_sparql(b, strings)
2841        ),
2842        PropertyPath::Alternative(a, b) => format!(
2843            "({} | {})",
2844            waratah_path_sparql(a, strings),
2845            waratah_path_sparql(b, strings)
2846        ),
2847        PropertyPath::ZeroOrMore(inner) => {
2848            format!("({})*", waratah_path_sparql(inner, strings))
2849        }
2850        PropertyPath::OneOrMore(inner) => {
2851            format!("({})+", waratah_path_sparql(inner, strings))
2852        }
2853        PropertyPath::ZeroOrOne(inner) => {
2854            format!("({})?", waratah_path_sparql(inner, strings))
2855        }
2856        PropertyPath::NegatedPropertySet(terms) => {
2857            let inner = terms
2858                .iter()
2859                .map(|t| format_encoded_term(t, strings))
2860                .collect::<Vec<_>>()
2861                .join(" | ");
2862            format!("!({inner})")
2863        }
2864    }
2865}
2866
2867fn values_to_sparql(values: &ValuesOp) -> String {
2868    let vars = values
2869        .variables
2870        .iter()
2871        .map(Variable::to_string)
2872        .collect::<Vec<_>>()
2873        .join(" ");
2874    let rows = values
2875        .rows
2876        .iter()
2877        .map(|row| {
2878            let cells = row
2879                .iter()
2880                .map(|cell| match cell {
2881                    Some(term) => format_encoded_term(term, &values.strings),
2882                    None => "UNDEF".into(),
2883                })
2884                .collect::<Vec<_>>()
2885                .join(" ");
2886            format!("({cells})")
2887        })
2888        .collect::<Vec<_>>()
2889        .join(" ");
2890    format!("VALUES ({vars}) {{ {rows} }}")
2891}
2892
2893// ---------------------------------------------------------------------------
2894// Vendored spargebra 0.4.6 Jena SSE (Query / GraphPattern / Expression / terms)
2895// ---------------------------------------------------------------------------
2896
2897fn query_to_sse(query: &Query) -> String {
2898    let mut buffer = String::new();
2899    fmt_query_sse(query, &mut buffer).expect("write to String");
2900    buffer
2901}
2902
2903fn fmt_query_sse(query: &Query, f: &mut String) -> fmt::Result {
2904    match query {
2905        Query::Select {
2906            dataset,
2907            pattern,
2908            base_iri,
2909        } => {
2910            if let Some(base_iri) = base_iri {
2911                write!(f, "(base <{base_iri}> ")?;
2912            }
2913            if let Some(dataset) = dataset {
2914                f.write_str("(dataset ")?;
2915                fmt_dataset_sse(dataset, f)?;
2916                f.write_str(" ")?;
2917            }
2918            fmt_graph_pattern_sse(pattern, f)?;
2919            if dataset.is_some() {
2920                f.write_str(")")?;
2921            }
2922            if base_iri.is_some() {
2923                f.write_str(")")?;
2924            }
2925            Ok(())
2926        }
2927        Query::Construct {
2928            template,
2929            dataset,
2930            pattern,
2931            base_iri,
2932        } => {
2933            if let Some(base_iri) = base_iri {
2934                write!(f, "(base <{base_iri}> ")?;
2935            }
2936            f.write_str("(construct (")?;
2937            for (i, t) in template.iter().enumerate() {
2938                if i > 0 {
2939                    f.write_str(" ")?;
2940                }
2941                fmt_triple_sse(t, f)?;
2942            }
2943            f.write_str(") ")?;
2944            if let Some(dataset) = dataset {
2945                f.write_str("(dataset ")?;
2946                fmt_dataset_sse(dataset, f)?;
2947                f.write_str(" ")?;
2948            }
2949            fmt_graph_pattern_sse(pattern, f)?;
2950            if dataset.is_some() {
2951                f.write_str(")")?;
2952            }
2953            f.write_str(")")?;
2954            if base_iri.is_some() {
2955                f.write_str(")")?;
2956            }
2957            Ok(())
2958        }
2959        Query::Describe {
2960            dataset,
2961            pattern,
2962            base_iri,
2963        } => {
2964            if let Some(base_iri) = base_iri {
2965                write!(f, "(base <{base_iri}> ")?;
2966            }
2967            f.write_str("(describe ")?;
2968            if let Some(dataset) = dataset {
2969                f.write_str("(dataset ")?;
2970                fmt_dataset_sse(dataset, f)?;
2971                f.write_str(" ")?;
2972            }
2973            fmt_graph_pattern_sse(pattern, f)?;
2974            if dataset.is_some() {
2975                f.write_str(")")?;
2976            }
2977            f.write_str(")")?;
2978            if base_iri.is_some() {
2979                f.write_str(")")?;
2980            }
2981            Ok(())
2982        }
2983        Query::Ask {
2984            dataset,
2985            pattern,
2986            base_iri,
2987        } => {
2988            if let Some(base_iri) = base_iri {
2989                write!(f, "(base <{base_iri}> ")?;
2990            }
2991            f.write_str("(ask ")?;
2992            if let Some(dataset) = dataset {
2993                f.write_str("(dataset ")?;
2994                fmt_dataset_sse(dataset, f)?;
2995                f.write_str(" ")?;
2996            }
2997            fmt_graph_pattern_sse(pattern, f)?;
2998            if dataset.is_some() {
2999                f.write_str(")")?;
3000            }
3001            f.write_str(")")?;
3002            if base_iri.is_some() {
3003                f.write_str(")")?;
3004            }
3005            Ok(())
3006        }
3007    }
3008}
3009
3010fn fmt_dataset_sse(dataset: &spargebra::algebra::QueryDataset, f: &mut String) -> fmt::Result {
3011    f.write_str("(")?;
3012    for (i, graph_name) in dataset.default.iter().enumerate() {
3013        if i > 0 {
3014            f.write_str(" ")?;
3015        }
3016        write!(f, "{graph_name}")?;
3017    }
3018    if let Some(named) = &dataset.named {
3019        for (i, graph_name) in named.iter().enumerate() {
3020            if !dataset.default.is_empty() || i > 0 {
3021                f.write_str(" ")?;
3022            }
3023            write!(f, "(named {graph_name})")?;
3024        }
3025    }
3026    f.write_str(")")
3027}
3028
3029fn fmt_graph_pattern_sse(pattern: &GraphPattern, f: &mut String) -> fmt::Result {
3030    match pattern {
3031        GraphPattern::Bgp { patterns } => {
3032            f.write_str("(bgp")?;
3033            for p in patterns {
3034                f.write_str(" ")?;
3035                fmt_triple_sse(p, f)?;
3036            }
3037            f.write_str(")")
3038        }
3039        GraphPattern::Path {
3040            subject,
3041            path,
3042            object,
3043        } => {
3044            f.write_str("(path ")?;
3045            fmt_term_sse(subject, f)?;
3046            f.write_str(" ")?;
3047            fmt_property_path_sse(path, f)?;
3048            f.write_str(" ")?;
3049            fmt_term_sse(object, f)?;
3050            f.write_str(")")
3051        }
3052        GraphPattern::Join { left, right } => {
3053            f.write_str("(join ")?;
3054            fmt_graph_pattern_sse(left, f)?;
3055            f.write_str(" ")?;
3056            fmt_graph_pattern_sse(right, f)?;
3057            f.write_str(")")
3058        }
3059        GraphPattern::LeftJoin {
3060            left,
3061            right,
3062            expression,
3063        } => {
3064            f.write_str("(leftjoin ")?;
3065            fmt_graph_pattern_sse(left, f)?;
3066            f.write_str(" ")?;
3067            fmt_graph_pattern_sse(right, f)?;
3068            if let Some(expr) = expression {
3069                f.write_str(" ")?;
3070                fmt_expression_sse(expr, f)?;
3071            }
3072            f.write_str(")")
3073        }
3074        GraphPattern::Filter { expr, inner } => {
3075            f.write_str("(filter ")?;
3076            fmt_expression_sse(expr, f)?;
3077            f.write_str(" ")?;
3078            fmt_graph_pattern_sse(inner, f)?;
3079            f.write_str(")")
3080        }
3081        GraphPattern::Union { left, right } => {
3082            f.write_str("(union ")?;
3083            fmt_graph_pattern_sse(left, f)?;
3084            f.write_str(" ")?;
3085            fmt_graph_pattern_sse(right, f)?;
3086            f.write_str(")")
3087        }
3088        GraphPattern::Graph { name, inner } => {
3089            f.write_str("(graph ")?;
3090            write!(f, "{name}")?;
3091            f.write_str(" ")?;
3092            fmt_graph_pattern_sse(inner, f)?;
3093            f.write_str(")")
3094        }
3095        GraphPattern::Extend {
3096            inner,
3097            variable,
3098            expression,
3099        } => {
3100            write!(f, "(extend (({variable} ")?;
3101            fmt_expression_sse(expression, f)?;
3102            f.write_str(")) ")?;
3103            fmt_graph_pattern_sse(inner, f)?;
3104            f.write_str(")")
3105        }
3106        GraphPattern::Minus { left, right } => {
3107            f.write_str("(minus ")?;
3108            fmt_graph_pattern_sse(left, f)?;
3109            f.write_str(" ")?;
3110            fmt_graph_pattern_sse(right, f)?;
3111            f.write_str(")")
3112        }
3113        GraphPattern::Service {
3114            name,
3115            inner,
3116            silent,
3117        } => {
3118            f.write_str("(service ")?;
3119            if *silent {
3120                f.write_str("silent ")?;
3121            }
3122            write!(f, "{name}")?;
3123            f.write_str(" ")?;
3124            fmt_graph_pattern_sse(inner, f)?;
3125            f.write_str(")")
3126        }
3127        GraphPattern::Group {
3128            inner,
3129            variables,
3130            aggregates,
3131        } => {
3132            f.write_str("(group (")?;
3133            write_var_list(f, variables)?;
3134            f.write_str(") (")?;
3135            for (i, (v, a)) in aggregates.iter().enumerate() {
3136                if i > 0 {
3137                    f.write_str(" ")?;
3138                }
3139                f.write_str("(")?;
3140                fmt_aggregate_sse(a, f)?;
3141                write!(f, " {v})")?;
3142            }
3143            f.write_str(") ")?;
3144            fmt_graph_pattern_sse(inner, f)?;
3145            f.write_str(")")
3146        }
3147        GraphPattern::Values {
3148            variables,
3149            bindings,
3150        } => {
3151            f.write_str("(table (vars")?;
3152            for var in variables {
3153                write!(f, " {var}")?;
3154            }
3155            f.write_str(")")?;
3156            for row in bindings {
3157                f.write_str(" (row")?;
3158                for (value, var) in row.iter().zip(variables) {
3159                    if let Some(value) = value {
3160                        write!(f, " ({var} {value})")?;
3161                    }
3162                }
3163                f.write_str(")")?;
3164            }
3165            f.write_str(")")
3166        }
3167        GraphPattern::OrderBy { inner, expression } => {
3168            f.write_str("(order (")?;
3169            for (i, c) in expression.iter().enumerate() {
3170                if i > 0 {
3171                    f.write_str(" ")?;
3172                }
3173                fmt_order_sse(c, f)?;
3174            }
3175            f.write_str(") ")?;
3176            fmt_graph_pattern_sse(inner, f)?;
3177            f.write_str(")")
3178        }
3179        GraphPattern::Project { inner, variables } => {
3180            f.write_str("(project (")?;
3181            write_var_list(f, variables)?;
3182            f.write_str(") ")?;
3183            fmt_graph_pattern_sse(inner, f)?;
3184            f.write_str(")")
3185        }
3186        GraphPattern::Distinct { inner } => {
3187            f.write_str("(distinct ")?;
3188            fmt_graph_pattern_sse(inner, f)?;
3189            f.write_str(")")
3190        }
3191        GraphPattern::Reduced { inner } => {
3192            f.write_str("(reduced ")?;
3193            fmt_graph_pattern_sse(inner, f)?;
3194            f.write_str(")")
3195        }
3196        GraphPattern::Slice {
3197            inner,
3198            start,
3199            length,
3200        } => {
3201            if let Some(length) = length {
3202                write!(f, "(slice {start} {length} ")?;
3203            } else {
3204                write!(f, "(slice {start} _ ")?;
3205            }
3206            fmt_graph_pattern_sse(inner, f)?;
3207            f.write_str(")")
3208        }
3209    }
3210}
3211
3212fn fmt_order_sse(order: &OrderExpression, f: &mut String) -> fmt::Result {
3213    match order {
3214        OrderExpression::Asc(e) => {
3215            f.write_str("(asc ")?;
3216            fmt_expression_sse(e, f)?;
3217            f.write_str(")")
3218        }
3219        OrderExpression::Desc(e) => {
3220            f.write_str("(desc ")?;
3221            fmt_expression_sse(e, f)?;
3222            f.write_str(")")
3223        }
3224    }
3225}
3226
3227fn fmt_triple_sse(triple: &TriplePattern, f: &mut String) -> fmt::Result {
3228    f.write_str("(triple ")?;
3229    fmt_term_sse(&triple.subject, f)?;
3230    f.write_str(" ")?;
3231    fmt_named_sse(&triple.predicate, f)?;
3232    f.write_str(" ")?;
3233    fmt_term_sse(&triple.object, f)?;
3234    f.write_str(")")
3235}
3236
3237fn fmt_named_sse(pattern: &NamedNodePattern, f: &mut String) -> fmt::Result {
3238    match pattern {
3239        NamedNodePattern::NamedNode(node) => write!(f, "{node}"),
3240        NamedNodePattern::Variable(var) => write!(f, "{var}"),
3241    }
3242}
3243
3244fn fmt_term_sse(pattern: &TermPattern, f: &mut String) -> fmt::Result {
3245    match pattern {
3246        TermPattern::NamedNode(term) => write!(f, "{term}"),
3247        TermPattern::BlankNode(term) => write!(f, "{term}"),
3248        TermPattern::Literal(term) => write!(f, "{term}"),
3249        TermPattern::Variable(var) => write!(f, "{var}"),
3250    }
3251}
3252
3253fn fmt_property_path_sse(path: &PropertyPathExpression, f: &mut String) -> fmt::Result {
3254    match path {
3255        PropertyPathExpression::NamedNode(p) => write!(f, "{p}"),
3256        PropertyPathExpression::Reverse(p) => {
3257            f.write_str("(reverse ")?;
3258            fmt_property_path_sse(p, f)?;
3259            f.write_str(")")
3260        }
3261        PropertyPathExpression::Alternative(a, b) => {
3262            f.write_str("(alt ")?;
3263            fmt_property_path_sse(a, f)?;
3264            f.write_str(" ")?;
3265            fmt_property_path_sse(b, f)?;
3266            f.write_str(")")
3267        }
3268        PropertyPathExpression::Sequence(a, b) => {
3269            f.write_str("(seq ")?;
3270            fmt_property_path_sse(a, f)?;
3271            f.write_str(" ")?;
3272            fmt_property_path_sse(b, f)?;
3273            f.write_str(")")
3274        }
3275        PropertyPathExpression::ZeroOrMore(p) => {
3276            f.write_str("(path* ")?;
3277            fmt_property_path_sse(p, f)?;
3278            f.write_str(")")
3279        }
3280        PropertyPathExpression::OneOrMore(p) => {
3281            f.write_str("(path+ ")?;
3282            fmt_property_path_sse(p, f)?;
3283            f.write_str(")")
3284        }
3285        PropertyPathExpression::ZeroOrOne(p) => {
3286            f.write_str("(path? ")?;
3287            fmt_property_path_sse(p, f)?;
3288            f.write_str(")")
3289        }
3290        PropertyPathExpression::NegatedPropertySet(p) => {
3291            f.write_str("(notoneof")?;
3292            for p in p {
3293                write!(f, " {p}")?;
3294            }
3295            f.write_str(")")
3296        }
3297    }
3298}
3299
3300fn fmt_expression_sse(expr: &Expression, f: &mut String) -> fmt::Result {
3301    match expr {
3302        Expression::NamedNode(node) => write!(f, "{node}"),
3303        Expression::Literal(l) => write!(f, "{l}"),
3304        Expression::Variable(var) => write!(f, "{var}"),
3305        Expression::Or(a, b) => fmt_sse_binary(f, "||", a, b),
3306        Expression::And(a, b) => fmt_sse_binary(f, "&&", a, b),
3307        Expression::Equal(a, b) => fmt_sse_binary(f, "=", a, b),
3308        Expression::SameTerm(a, b) => fmt_sse_binary(f, "sameTerm", a, b),
3309        Expression::Greater(a, b) => fmt_sse_binary(f, ">", a, b),
3310        Expression::GreaterOrEqual(a, b) => fmt_sse_binary(f, ">=", a, b),
3311        Expression::Less(a, b) => fmt_sse_binary(f, "<", a, b),
3312        Expression::LessOrEqual(a, b) => fmt_sse_binary(f, "<=", a, b),
3313        Expression::In(a, b) => {
3314            f.write_str("(in ")?;
3315            fmt_expression_sse(a, f)?;
3316            for p in b {
3317                f.write_str(" ")?;
3318                fmt_expression_sse(p, f)?;
3319            }
3320            f.write_str(")")
3321        }
3322        Expression::Add(a, b) => fmt_sse_binary(f, "+", a, b),
3323        Expression::Subtract(a, b) => fmt_sse_binary(f, "-", a, b),
3324        Expression::Multiply(a, b) => fmt_sse_binary(f, "*", a, b),
3325        Expression::Divide(a, b) => fmt_sse_binary(f, "/", a, b),
3326        Expression::UnaryPlus(e) => fmt_sse_unary(f, "+", e),
3327        Expression::UnaryMinus(e) => fmt_sse_unary(f, "-", e),
3328        Expression::Not(e) => fmt_sse_unary(f, "!", e),
3329        Expression::FunctionCall(function, parameters) => {
3330            f.write_str("(")?;
3331            fmt_function_sse(function, f)?;
3332            for p in parameters {
3333                f.write_str(" ")?;
3334                fmt_expression_sse(p, f)?;
3335            }
3336            f.write_str(")")
3337        }
3338        Expression::Exists(p) => {
3339            f.write_str("(exists ")?;
3340            fmt_graph_pattern_sse(p, f)?;
3341            f.write_str(")")
3342        }
3343        Expression::Bound(v) => write!(f, "(bound {v})"),
3344        Expression::If(a, b, c) => {
3345            f.write_str("(if ")?;
3346            fmt_expression_sse(a, f)?;
3347            f.write_str(" ")?;
3348            fmt_expression_sse(b, f)?;
3349            f.write_str(" ")?;
3350            fmt_expression_sse(c, f)?;
3351            f.write_str(")")
3352        }
3353        Expression::Coalesce(parameters) => {
3354            f.write_str("(coalesce")?;
3355            for p in parameters {
3356                f.write_str(" ")?;
3357                fmt_expression_sse(p, f)?;
3358            }
3359            f.write_str(")")
3360        }
3361    }
3362}
3363
3364fn fmt_sse_unary(f: &mut String, name: &str, e: &Expression) -> fmt::Result {
3365    write!(f, "({name} ")?;
3366    fmt_expression_sse(e, f)?;
3367    f.write_str(")")
3368}
3369
3370fn fmt_sse_binary(f: &mut String, name: &str, a: &Expression, b: &Expression) -> fmt::Result {
3371    write!(f, "({name} ")?;
3372    fmt_expression_sse(a, f)?;
3373    f.write_str(" ")?;
3374    fmt_expression_sse(b, f)?;
3375    f.write_str(")")
3376}
3377
3378fn fmt_function_sse(function: &Function, f: &mut String) -> fmt::Result {
3379    match function {
3380        Function::Str => f.write_str("str"),
3381        Function::Lang => f.write_str("lang"),
3382        Function::LangMatches => f.write_str("langmatches"),
3383        Function::Datatype => f.write_str("datatype"),
3384        Function::Iri => f.write_str("iri"),
3385        Function::BNode => f.write_str("bnode"),
3386        Function::Rand => f.write_str("rand"),
3387        Function::Abs => f.write_str("abs"),
3388        Function::Ceil => f.write_str("ceil"),
3389        Function::Floor => f.write_str("floor"),
3390        Function::Round => f.write_str("round"),
3391        Function::Concat => f.write_str("concat"),
3392        Function::SubStr => f.write_str("substr"),
3393        Function::StrLen => f.write_str("strlen"),
3394        Function::Replace => f.write_str("replace"),
3395        Function::UCase => f.write_str("ucase"),
3396        Function::LCase => f.write_str("lcase"),
3397        Function::EncodeForUri => f.write_str("encode_for_uri"),
3398        Function::Contains => f.write_str("contains"),
3399        Function::StrStarts => f.write_str("strstarts"),
3400        Function::StrEnds => f.write_str("strends"),
3401        Function::StrBefore => f.write_str("strbefore"),
3402        Function::StrAfter => f.write_str("strafter"),
3403        Function::Year => f.write_str("year"),
3404        Function::Month => f.write_str("month"),
3405        Function::Day => f.write_str("day"),
3406        Function::Hours => f.write_str("hours"),
3407        Function::Minutes => f.write_str("minutes"),
3408        Function::Seconds => f.write_str("seconds"),
3409        Function::Timezone => f.write_str("timezone"),
3410        Function::Tz => f.write_str("tz"),
3411        Function::Now => f.write_str("now"),
3412        Function::Uuid => f.write_str("uuid"),
3413        Function::StrUuid => f.write_str("struuid"),
3414        Function::Md5 => f.write_str("md5"),
3415        Function::Sha1 => f.write_str("sha1"),
3416        Function::Sha256 => f.write_str("sha256"),
3417        Function::Sha384 => f.write_str("sha384"),
3418        Function::Sha512 => f.write_str("sha512"),
3419        Function::StrLang => f.write_str("strlang"),
3420        Function::StrDt => f.write_str("strdt"),
3421        Function::IsIri => f.write_str("isiri"),
3422        Function::IsBlank => f.write_str("isblank"),
3423        Function::IsLiteral => f.write_str("isliteral"),
3424        Function::IsNumeric => f.write_str("isnumeric"),
3425        Function::Regex => f.write_str("regex"),
3426        Function::Custom(iri) => write!(f, "{iri}"),
3427    }
3428}
3429
3430fn fmt_aggregate_sse(agg: &AggregateExpression, f: &mut String) -> fmt::Result {
3431    match agg {
3432        AggregateExpression::CountSolutions { distinct } => {
3433            f.write_str("(count")?;
3434            if *distinct {
3435                f.write_str(" distinct")?;
3436            }
3437            f.write_str(")")
3438        }
3439        AggregateExpression::FunctionCall {
3440            name:
3441                AggregateFunction::GroupConcat {
3442                    separator: Some(separator),
3443                },
3444            expr,
3445            distinct,
3446        } => {
3447            f.write_str("(group_concat ")?;
3448            if *distinct {
3449                f.write_str("distinct ")?;
3450            }
3451            fmt_expression_sse(expr, f)?;
3452            write!(f, " \"{separator}\")")
3453        }
3454        AggregateExpression::FunctionCall {
3455            name,
3456            expr,
3457            distinct,
3458        } => {
3459            f.write_str("(")?;
3460            fmt_agg_fn_sse(name, f)?;
3461            f.write_str(" ")?;
3462            if *distinct {
3463                f.write_str("distinct ")?;
3464            }
3465            fmt_expression_sse(expr, f)?;
3466            f.write_str(")")
3467        }
3468    }
3469}
3470
3471fn fmt_agg_fn_sse(name: &AggregateFunction, f: &mut String) -> fmt::Result {
3472    match name {
3473        AggregateFunction::Count => f.write_str("count"),
3474        AggregateFunction::Sum => f.write_str("sum"),
3475        AggregateFunction::Avg => f.write_str("avg"),
3476        AggregateFunction::Min => f.write_str("min"),
3477        AggregateFunction::Max => f.write_str("max"),
3478        AggregateFunction::GroupConcat { .. } => f.write_str("group_concat"),
3479        AggregateFunction::Sample => f.write_str("sample"),
3480        AggregateFunction::Custom(iri) => write!(f, "{iri}"),
3481    }
3482}
3483
3484// ---------------------------------------------------------------------------
3485// Vendored spargebra 0.4.6 SPARQL syntax (`optimised-sparql`)
3486// ---------------------------------------------------------------------------
3487
3488/// `rdf:type` — shortens to the `a` keyword in predicate position.
3489const RDF_TYPE_IRI: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
3490
3491/// SPARQL-syntax text for a rebuilt L1 query (SELECT / ASK / CONSTRUCT /
3492/// DESCRIBE), a mirror of spargebra 0.4.6's `Display` implementation so
3493/// `optimised-sparql` output keeps the exact shape `Query::to_string()`
3494/// produced: the same `SparqlGraphRootPattern` modifier peel (including its
3495/// `Extend`-into-projection alias fold), the same per-`GraphPattern`
3496/// rendering, and the same expression syntax.
3497///
3498/// The one deliberate difference is term printing: IRIs under
3499/// `WELL_KNOWN_NAMESPACES` render prefixed (`owl:Class`, `rdfs:label`, …) and
3500/// `rdf:type` in predicate position renders `a`, matching the planned-Sparql
3501/// printer. IRIs outside the well-known namespaces stay full `<…>` so those
3502/// outputs still re-parse without a PREFIX prologue.
3503///
3504/// `base_iri` is never rendered because [`rebuild_l1_query`] always clears it.
3505fn sparql_query_text(query: &Query) -> String {
3506    match query {
3507        Query::Select {
3508            dataset, pattern, ..
3509        } => sparql_root_pattern(pattern, dataset.as_ref()),
3510        Query::Ask {
3511            dataset, pattern, ..
3512        } => format!(
3513            "ASK{} WHERE {{ {} }}",
3514            fmt_sparql_from_clauses(dataset.as_ref()),
3515            sparql_root_pattern(pattern, None)
3516        ),
3517        Query::Construct {
3518            template,
3519            dataset,
3520            pattern,
3521            ..
3522        } => {
3523            let mut triples = String::new();
3524            for triple in template {
3525                triples.push_str(&sparql_triple(triple));
3526                triples.push_str(" . ");
3527            }
3528            format!(
3529                "CONSTRUCT {{ {triples}}}{} WHERE {{ {} }}",
3530                fmt_sparql_from_clauses(dataset.as_ref()),
3531                sparql_root_pattern(pattern, None)
3532            )
3533        }
3534        // Dead path, kept for mirror completeness: `format_l1_sparql`
3535        // matches `Query::Describe` before delegating here and renders the
3536        // real targets itself. If a `Describe` ever reaches this arm it
3537        // prints `DESCRIBE *`, silently dropping the targets — faithful to
3538        // spargebra's own `Display`, which loses them the same way because
3539        // its algebra keeps them only inside the pattern.
3540        Query::Describe {
3541            dataset, pattern, ..
3542        } => format!(
3543            "DESCRIBE *{} WHERE {{ {} }}",
3544            fmt_sparql_from_clauses(dataset.as_ref()),
3545            sparql_root_pattern(pattern, None)
3546        ),
3547    }
3548}
3549
3550/// Mirror of spargebra's `SparqlGraphRootPattern::fmt`: peel the
3551/// `OrderBy` / `Project` / `Distinct` / `Reduced` / `Slice` modifier spine and
3552/// print it as a single SELECT header. `Extend` aliases fold into the
3553/// projection the same way spargebra folds them — only when the extended
3554/// variable is projected and not referenced by another projection expression.
3555///
3556/// One deliberate improvement over spargebra: when the folded body is an
3557/// `Extend` chain over a `Group` (the lowered shape of
3558/// `SELECT … (agg AS ?alias) … GROUP BY`), the aliases hoist into the
3559/// projection (inner to outer, internal aggregate variables substituted) and
3560/// the query prints as one flat SELECT instead of a group subselect.
3561fn sparql_root_pattern(
3562    pattern: &GraphPattern,
3563    dataset: Option<&spargebra::algebra::QueryDataset>,
3564) -> String {
3565    let mut distinct = false;
3566    let mut reduced = false;
3567    let mut order: Option<&[OrderExpression]> = None;
3568    let mut start = 0usize;
3569    let mut length: Option<usize> = None;
3570    let mut project: Vec<(&Variable, Option<&Expression>)> = Vec::new();
3571    let mut child = pattern;
3572    let body = loop {
3573        match child {
3574            GraphPattern::OrderBy { inner, expression } => {
3575                order = Some(expression);
3576                child = inner;
3577            }
3578            GraphPattern::Project { inner, variables } if project.is_empty() => {
3579                project.extend(variables.iter().map(|v| (v, None)));
3580                child = inner;
3581            }
3582            GraphPattern::Distinct { inner } => {
3583                distinct = true;
3584                child = inner;
3585            }
3586            GraphPattern::Reduced { inner } => {
3587                reduced = true;
3588                child = inner;
3589            }
3590            GraphPattern::Slice {
3591                inner,
3592                start: s,
3593                length: l,
3594            } => {
3595                start = *s;
3596                length = *l;
3597                child = inner;
3598            }
3599            GraphPattern::Extend {
3600                inner,
3601                expression,
3602                variable,
3603            } if project.iter().any(|(v, _)| *v == variable)
3604                && !project.iter().any(|(_, expr)| {
3605                    expr.is_some_and(|expr| expression_uses_variable(expr, variable))
3606                }) =>
3607            {
3608                // Same simplification spargebra applies: safe because the
3609                // alias moves verbatim into the projection (same evaluation
3610                // point in the algebra).
3611                if let Some(slot) = project.iter_mut().find(|(v, _)| *v == variable) {
3612                    slot.1 = Some(expression);
3613                }
3614                child = inner;
3615            }
3616            p => break p,
3617        }
3618    };
3619    // `Project` over an `Extend` chain over a `Group` is the lowered shape of
3620    // `SELECT … (agg AS ?alias) … GROUP BY`. Hoist the aliases into the
3621    // projection: keys and alias outputs in projection order, every internal
3622    // aggregate variable substituted away. `None` keeps the spargebra shape
3623    // (alias folded over a group subselect).
3624    let flat_group = match body {
3625        GraphPattern::Group {
3626            inner,
3627            variables: keys,
3628            aggregates,
3629        } if !project.is_empty() => {
3630            let agg_texts = group_agg_texts(aggregates, IriStyle::Prefixed);
3631            // The fold above collects aliases outer-to-inner; hoisting wants
3632            // application order (innermost `Extend` first).
3633            let aliases: Vec<(&Variable, &Expression)> = project
3634                .iter()
3635                .filter_map(|(variable, expr)| expr.map(|expr| (*variable, expr)))
3636                .rev()
3637                .collect();
3638            hoist_group_aliases(keys, &agg_texts, &aliases, IriStyle::Prefixed).and_then(
3639                |(entries, referenced)| {
3640                    // The flat form drops the group's own SELECT list, so
3641                    // every aggregate must be consumed by a hoisted alias.
3642                    if referenced.len() != agg_texts.len() {
3643                        return None;
3644                    }
3645                    let mut items = Vec::new();
3646                    for (variable, expr) in &project {
3647                        match expr {
3648                            None if keys.contains(*variable) => {
3649                                items.push((**variable).to_string());
3650                            }
3651                            None => return None,
3652                            Some(_) => {
3653                                let text = entries
3654                                    .iter()
3655                                    .find(|(entry, _)| *entry == *variable)
3656                                    .map(|(_, text)| text.clone())?;
3657                                items.push(format!("({text} AS {variable})"));
3658                            }
3659                        }
3660                    }
3661                    Some((items, keys, inner))
3662                },
3663            )
3664        }
3665        _ => None,
3666    };
3667    let mut out = String::new();
3668    out.push_str("SELECT");
3669    if distinct {
3670        out.push_str(" DISTINCT");
3671    }
3672    if reduced {
3673        out.push_str(" REDUCED");
3674    }
3675    match flat_group {
3676        Some((items, keys, group_inner)) => {
3677            for item in items {
3678                out.push(' ');
3679                out.push_str(&item);
3680            }
3681            out.push_str(&fmt_sparql_from_clauses(dataset));
3682            let _ = write!(out, " WHERE {{ {} }}", sparql_graph_pattern(group_inner));
3683            if !keys.is_empty() {
3684                out.push_str(" GROUP BY");
3685                for key in keys {
3686                    let _ = write!(out, " {key}");
3687                }
3688            }
3689        }
3690        None => {
3691            if project.is_empty() {
3692                out.push_str(" *");
3693            } else {
3694                for (variable, expr) in project {
3695                    match expr {
3696                        Some(expr) => {
3697                            let _ = write!(out, " ({} AS {variable})", sparql_expression(expr));
3698                        }
3699                        None => {
3700                            let _ = write!(out, " {variable}");
3701                        }
3702                    }
3703                }
3704            }
3705            out.push_str(&fmt_sparql_from_clauses(dataset));
3706            let _ = write!(out, " WHERE {{ {} }}", sparql_graph_pattern(body));
3707        }
3708    }
3709    if let Some(order) = order {
3710        out.push_str(" ORDER BY");
3711        for key in order {
3712            let _ = write!(out, " {}", sparql_order(key));
3713        }
3714    }
3715    if start > 0 {
3716        let _ = write!(out, " OFFSET {start}");
3717    }
3718    if let Some(length) = length {
3719        let _ = write!(out, " LIMIT {length}");
3720    }
3721    out
3722}
3723
3724/// Mirror of spargebra's `Display for GraphPattern` (term printing swapped for
3725/// the shortened forms above).
3726fn sparql_graph_pattern(pattern: &GraphPattern) -> String {
3727    match pattern {
3728        GraphPattern::Bgp { patterns } => {
3729            let mut out = String::new();
3730            for p in patterns {
3731                let _ = write!(out, "{} .", sparql_triple(p));
3732            }
3733            out
3734        }
3735        GraphPattern::Path {
3736            subject,
3737            path,
3738            object,
3739        } => format!(
3740            "{} {} {} .",
3741            sparql_term(subject),
3742            sparql_property_path(path),
3743            sparql_term(object)
3744        ),
3745        GraphPattern::Join { left, right } => match right.as_ref() {
3746            // The second block might be considered as a modification of the
3747            // first one — brace it like spargebra does.
3748            GraphPattern::LeftJoin { .. }
3749            | GraphPattern::Minus { .. }
3750            | GraphPattern::Extend { .. }
3751            | GraphPattern::Filter { .. } => format!(
3752                "{} {{ {} }}",
3753                sparql_graph_pattern(left),
3754                sparql_graph_pattern(right)
3755            ),
3756            _ => format!(
3757                "{} {}",
3758                sparql_graph_pattern(left),
3759                sparql_graph_pattern(right)
3760            ),
3761        },
3762        GraphPattern::LeftJoin {
3763            left,
3764            right,
3765            expression,
3766        } => match expression {
3767            Some(expr) => format!(
3768                "{} OPTIONAL {{ {} FILTER({}) }}",
3769                sparql_graph_pattern(left),
3770                sparql_graph_pattern(right),
3771                sparql_expression(expr)
3772            ),
3773            None => format!(
3774                "{} OPTIONAL {{ {} }}",
3775                sparql_graph_pattern(left),
3776                sparql_graph_pattern(right)
3777            ),
3778        },
3779        GraphPattern::Filter { expr, inner } => format!(
3780            "{} FILTER({})",
3781            sparql_graph_pattern(inner),
3782            sparql_expression(expr)
3783        ),
3784        GraphPattern::Union { left, right } => format!(
3785            "{{ {} }} UNION {{ {} }}",
3786            sparql_graph_pattern(left),
3787            sparql_graph_pattern(right)
3788        ),
3789        GraphPattern::Graph { name, inner } => format!(
3790            "GRAPH {} {{ {} }}",
3791            sparql_named(name),
3792            sparql_graph_pattern(inner)
3793        ),
3794        GraphPattern::Extend {
3795            inner,
3796            variable,
3797            expression,
3798        } => format!(
3799            "{} BIND({} AS {variable})",
3800            sparql_graph_pattern(inner),
3801            sparql_expression(expression)
3802        ),
3803        GraphPattern::Minus { left, right } => format!(
3804            "{} MINUS {{ {} }}",
3805            sparql_graph_pattern(left),
3806            sparql_graph_pattern(right)
3807        ),
3808        GraphPattern::Service {
3809            name,
3810            inner,
3811            silent,
3812        } => {
3813            if *silent {
3814                format!(
3815                    "SERVICE SILENT {} {{ {} }}",
3816                    sparql_named(name),
3817                    sparql_graph_pattern(inner)
3818                )
3819            } else {
3820                format!(
3821                    "SERVICE {} {{ {} }}",
3822                    sparql_named(name),
3823                    sparql_graph_pattern(inner)
3824                )
3825            }
3826        }
3827        GraphPattern::Values {
3828            variables,
3829            bindings,
3830        } => {
3831            let mut out = String::from("VALUES ( ");
3832            for var in variables {
3833                let _ = write!(out, "{var} ");
3834            }
3835            out.push_str(") { ");
3836            for row in bindings {
3837                out.push_str("( ");
3838                for value in row {
3839                    match value {
3840                        Some(value) => {
3841                            let _ = write!(out, "{} ", sparql_ground_term(value));
3842                        }
3843                        None => out.push_str("UNDEF "),
3844                    }
3845                }
3846                out.push_str(") ");
3847            }
3848            out.push_str(" }");
3849            out
3850        }
3851        GraphPattern::Group {
3852            inner,
3853            variables,
3854            aggregates,
3855        } => {
3856            // Aggregate aliases have no group-pattern surface syntax, so the
3857            // Group renders as a nested SELECT (spargebra does the same, but
3858            // with aggregates before keys — normalized here to keys first to
3859            // match the planned printer).
3860            let inner_text = sparql_graph_pattern(inner);
3861            let agg_texts = group_agg_texts(aggregates, IriStyle::Prefixed);
3862            group_subselect_sparql(variables, &agg_texts, &inner_text, &[], &[])
3863        }
3864        // Modifier / projection nodes away from the root are a nested query —
3865        // recurse through the root printer (spargebra wraps them in braces).
3866        p => format!("{{ {} }}", sparql_root_pattern(p, None)),
3867    }
3868}
3869
3870/// IRI in display form: well-known namespaces render prefixed (`owl:Class`),
3871/// everything else stays a full `<…>` IRI so the output re-parses without a
3872/// PREFIX prologue.
3873fn sparql_iri(node: &NamedNode) -> String {
3874    prefixed_iri_name(node.as_str()).unwrap_or_else(|| format!("<{}>", node.as_str()))
3875}
3876
3877fn sparql_named(pattern: &NamedNodePattern) -> String {
3878    match pattern {
3879        NamedNodePattern::NamedNode(node) => sparql_iri(node),
3880        NamedNodePattern::Variable(var) => var.to_string(),
3881    }
3882}
3883
3884/// `rdf:type` shortens to `a` where the SPARQL grammar allows the keyword:
3885/// triple predicates and simple property paths.
3886fn sparql_predicate_node(node: &NamedNode) -> String {
3887    if node.as_str() == RDF_TYPE_IRI {
3888        "a".to_string()
3889    } else {
3890        sparql_iri(node)
3891    }
3892}
3893
3894fn sparql_predicate(pattern: &NamedNodePattern) -> String {
3895    match pattern {
3896        NamedNodePattern::NamedNode(node) => sparql_predicate_node(node),
3897        NamedNodePattern::Variable(var) => var.to_string(),
3898    }
3899}
3900
3901fn sparql_term(term: &TermPattern) -> String {
3902    match term {
3903        TermPattern::NamedNode(node) => sparql_iri(node),
3904        TermPattern::BlankNode(id) => id.to_string(),
3905        TermPattern::Literal(l) => l.to_string(),
3906        TermPattern::Variable(var) => var.to_string(),
3907    }
3908}
3909
3910fn sparql_triple(triple: &TriplePattern) -> String {
3911    format!(
3912        "{} {} {}",
3913        sparql_term(&triple.subject),
3914        sparql_predicate(&triple.predicate),
3915        sparql_term(&triple.object)
3916    )
3917}
3918
3919fn sparql_ground_term(term: &GroundTerm) -> String {
3920    match term {
3921        GroundTerm::NamedNode(node) => sparql_iri(node),
3922        GroundTerm::Literal(l) => l.to_string(),
3923    }
3924}
3925
3926/// Mirror of spargebra's `Display for PropertyPathExpression`; a simple named
3927/// path is predicate position, so `rdf:type` renders `a`.
3928fn sparql_property_path(path: &PropertyPathExpression) -> String {
3929    match path {
3930        PropertyPathExpression::NamedNode(p) => sparql_predicate_node(p),
3931        PropertyPathExpression::Reverse(p) => format!("^({})", sparql_property_path(p)),
3932        PropertyPathExpression::Sequence(a, b) => format!(
3933            "({} / {})",
3934            sparql_property_path(a),
3935            sparql_property_path(b)
3936        ),
3937        PropertyPathExpression::Alternative(a, b) => format!(
3938            "({} | {})",
3939            sparql_property_path(a),
3940            sparql_property_path(b)
3941        ),
3942        PropertyPathExpression::ZeroOrMore(p) => format!("({})*", sparql_property_path(p)),
3943        PropertyPathExpression::OneOrMore(p) => format!("({})+", sparql_property_path(p)),
3944        PropertyPathExpression::ZeroOrOne(p) => format!("({})?", sparql_property_path(p)),
3945        PropertyPathExpression::NegatedPropertySet(ps) => {
3946            let inner = ps.iter().map(sparql_iri).collect::<Vec<_>>().join(" | ");
3947            format!("!({inner})")
3948        }
3949    }
3950}
3951
3952/// IRI rendering style for the shared spargebra-`Expression` renderer.
3953///
3954/// `Full` must stay byte-identical to spargebra's `Display` so the planned
3955/// printer keeps its historical output; `Prefixed` additionally shortens
3956/// well-known IRIs (the `optimised-sparql` behavior).
3957#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3958enum IriStyle {
3959    Prefixed,
3960    Full,
3961}
3962
3963/// Mirror of spargebra's `Display for Expression` (parenthesization quirks
3964/// included, so output stays byte-comparable with the old `Query::to_string()`
3965/// apart from term shortening).
3966fn sparql_expression(expr: &Expression) -> String {
3967    expression_text(expr, IriStyle::Prefixed, &[])
3968}
3969
3970/// Render `expr` in `style`, replacing every `Variable` reference that names
3971/// an internal aggregate output (a key of `agg_texts`) with its parenthesized
3972/// aggregate text. The parentheses keep precedence intact when the aggregate
3973/// lands inside a larger expression (`COUNT(?x) + 1 * 2`).
3974fn expression_text(
3975    expr: &Expression,
3976    style: IriStyle,
3977    agg_texts: &[(&Variable, String)],
3978) -> String {
3979    let sub = |expr: &Expression| expression_text(expr, style, agg_texts);
3980    match expr {
3981        Expression::NamedNode(node) => match style {
3982            IriStyle::Prefixed => sparql_iri(node),
3983            IriStyle::Full => format!("<{}>", node.as_str()),
3984        },
3985        Expression::Literal(l) => l.to_string(),
3986        Expression::Variable(var) => match agg_texts.iter().find(|(a, _)| *a == var) {
3987            Some((_, text)) => format!("({text})"),
3988            None => var.to_string(),
3989        },
3990        Expression::Or(a, b) => format!("({} || {})", sub(a), sub(b)),
3991        Expression::And(a, b) => format!("({} && {})", sub(a), sub(b)),
3992        Expression::Equal(a, b) => format!("({} = {})", sub(a), sub(b)),
3993        Expression::SameTerm(a, b) => format!("sameTerm({}, {})", sub(a), sub(b)),
3994        Expression::Greater(a, b) => format!("({} > {})", sub(a), sub(b)),
3995        Expression::GreaterOrEqual(a, b) => format!("({} >= {})", sub(a), sub(b)),
3996        Expression::Less(a, b) => format!("({} < {})", sub(a), sub(b)),
3997        Expression::LessOrEqual(a, b) => format!("({} <= {})", sub(a), sub(b)),
3998        Expression::In(a, list) => {
3999            format!(
4000                "({} IN {})",
4001                sub(a),
4002                expression_arg_list(list, style, agg_texts)
4003            )
4004        }
4005        Expression::Add(a, b) => format!("{} + {}", sub(a), sub(b)),
4006        Expression::Subtract(a, b) => format!("{} - {}", sub(a), sub(b)),
4007        Expression::Multiply(a, b) => format!("{} * {}", sub(a), sub(b)),
4008        Expression::Divide(a, b) => format!("{} / {}", sub(a), sub(b)),
4009        Expression::UnaryPlus(e) => format!("+{}", sub(e)),
4010        Expression::UnaryMinus(e) => format!("-{}", sub(e)),
4011        Expression::Not(e) => match e.as_ref() {
4012            Expression::Exists(p) => format!("NOT EXISTS {{ {} }}", sparql_graph_pattern(p)),
4013            e => format!("!{}", sub(e)),
4014        },
4015        Expression::FunctionCall(function, parameters) => format!(
4016            "{}{}",
4017            function_text(function, style),
4018            expression_arg_list(parameters, style, agg_texts)
4019        ),
4020        Expression::Bound(v) => format!("BOUND({v})"),
4021        Expression::Exists(p) => format!("EXISTS {{ {} }}", sparql_graph_pattern(p)),
4022        Expression::If(a, b, c) => format!("IF({}, {}, {})", sub(a), sub(b), sub(c)),
4023        Expression::Coalesce(parameters) => {
4024            format!(
4025                "COALESCE{}",
4026                expression_arg_list(parameters, style, agg_texts)
4027            )
4028        }
4029    }
4030}
4031
4032fn expression_arg_list(
4033    exprs: &[Expression],
4034    style: IriStyle,
4035    agg_texts: &[(&Variable, String)],
4036) -> String {
4037    let items = exprs
4038        .iter()
4039        .map(|expr| expression_text(expr, style, agg_texts))
4040        .collect::<Vec<_>>()
4041        .join(", ");
4042    format!("({items})")
4043}
4044
4045fn function_text(function: &Function, style: IriStyle) -> String {
4046    match function {
4047        Function::Custom(iri) => match style {
4048            IriStyle::Prefixed => sparql_iri(iri),
4049            IriStyle::Full => format!("<{}>", iri.as_str()),
4050        },
4051        other => other.to_string(),
4052    }
4053}
4054
4055fn sparql_aggregate(agg: &AggregateExpression) -> String {
4056    match agg {
4057        AggregateExpression::CountSolutions { distinct } => {
4058            if *distinct {
4059                "COUNT(DISTINCT *)".to_string()
4060            } else {
4061                "COUNT(*)".to_string()
4062            }
4063        }
4064        AggregateExpression::FunctionCall {
4065            name:
4066                AggregateFunction::GroupConcat {
4067                    separator: Some(separator),
4068                },
4069            expr,
4070            distinct,
4071        } => {
4072            let distinct = if *distinct { "DISTINCT " } else { "" };
4073            let separator = spargebra::term::Literal::new_simple_literal(separator);
4074            format!(
4075                "GROUP_CONCAT({distinct}{}; SEPARATOR = {separator})",
4076                sparql_expression(expr)
4077            )
4078        }
4079        AggregateExpression::FunctionCall {
4080            name,
4081            expr,
4082            distinct,
4083        } => {
4084            let distinct = if *distinct { "DISTINCT " } else { "" };
4085            format!(
4086                "{}({distinct}{})",
4087                sparql_aggregate_name(name),
4088                sparql_expression(expr)
4089            )
4090        }
4091    }
4092}
4093
4094fn sparql_aggregate_name(name: &AggregateFunction) -> String {
4095    match name {
4096        AggregateFunction::Custom(iri) => sparql_iri(iri),
4097        other => other.to_string(),
4098    }
4099}
4100
4101fn sparql_order(order: &OrderExpression) -> String {
4102    match order {
4103        OrderExpression::Asc(e) => format!("ASC({})", sparql_expression(e)),
4104        OrderExpression::Desc(e) => format!("DESC({})", sparql_expression(e)),
4105    }
4106}
4107
4108/// Whether `expr` references `variable` directly (as a `Variable` or
4109/// `BOUND()` argument). Used by the projection alias fold; `EXISTS` bodies are
4110/// ignored, matching the observation that moving the alias into the projection
4111/// keeps the same bindings visible to the expression.
4112fn expression_uses_variable(expr: &Expression, variable: &Variable) -> bool {
4113    match expr {
4114        Expression::Variable(v) | Expression::Bound(v) => v == variable,
4115        Expression::NamedNode(_) | Expression::Literal(_) | Expression::Exists(_) => false,
4116        Expression::Or(a, b)
4117        | Expression::And(a, b)
4118        | Expression::Equal(a, b)
4119        | Expression::SameTerm(a, b)
4120        | Expression::Greater(a, b)
4121        | Expression::GreaterOrEqual(a, b)
4122        | Expression::Less(a, b)
4123        | Expression::LessOrEqual(a, b)
4124        | Expression::Add(a, b)
4125        | Expression::Subtract(a, b)
4126        | Expression::Multiply(a, b)
4127        | Expression::Divide(a, b) => {
4128            expression_uses_variable(a, variable) || expression_uses_variable(b, variable)
4129        }
4130        Expression::In(a, list) => {
4131            expression_uses_variable(a, variable)
4132                || list.iter().any(|e| expression_uses_variable(e, variable))
4133        }
4134        Expression::UnaryPlus(e) | Expression::UnaryMinus(e) | Expression::Not(e) => {
4135            expression_uses_variable(e, variable)
4136        }
4137        Expression::If(a, b, c) => {
4138            expression_uses_variable(a, variable)
4139                || expression_uses_variable(b, variable)
4140                || expression_uses_variable(c, variable)
4141        }
4142        Expression::Coalesce(list) | Expression::FunctionCall(_, list) => {
4143            list.iter().any(|e| expression_uses_variable(e, variable))
4144        }
4145    }
4146}
4147
4148/// Rendered text for each of a Group's internal aggregate output variables.
4149fn group_agg_texts(
4150    aggregates: &[(Variable, AggregateExpression)],
4151    style: IriStyle,
4152) -> Vec<(&Variable, String)> {
4153    aggregates
4154        .iter()
4155        .map(|(v, agg)| {
4156            let text = match style {
4157                IriStyle::Prefixed => sparql_aggregate(agg),
4158                IriStyle::Full => agg.to_string(),
4159            };
4160            (v, text)
4161        })
4162        .collect()
4163}
4164
4165/// Whether every variable `expr` references directly (`Variable` / `BOUND`)
4166/// is in `scope`. `EXISTS` always fails: its body may reference inner
4167/// variables we cannot see, so the alias falls back to `BIND` rendering.
4168fn expression_scopes_to(expr: &Expression, scope: &[&Variable]) -> bool {
4169    match expr {
4170        Expression::Variable(v) | Expression::Bound(v) => scope.contains(&v),
4171        Expression::NamedNode(_) | Expression::Literal(_) => true,
4172        Expression::Exists(_) => false,
4173        Expression::Or(a, b)
4174        | Expression::And(a, b)
4175        | Expression::Equal(a, b)
4176        | Expression::SameTerm(a, b)
4177        | Expression::Greater(a, b)
4178        | Expression::GreaterOrEqual(a, b)
4179        | Expression::Less(a, b)
4180        | Expression::LessOrEqual(a, b)
4181        | Expression::Add(a, b)
4182        | Expression::Subtract(a, b)
4183        | Expression::Multiply(a, b)
4184        | Expression::Divide(a, b) => {
4185            expression_scopes_to(a, scope) && expression_scopes_to(b, scope)
4186        }
4187        Expression::In(a, list) => {
4188            expression_scopes_to(a, scope) && list.iter().all(|e| expression_scopes_to(e, scope))
4189        }
4190        Expression::UnaryPlus(e) | Expression::UnaryMinus(e) | Expression::Not(e) => {
4191            expression_scopes_to(e, scope)
4192        }
4193        Expression::If(a, b, c) => {
4194            expression_scopes_to(a, scope)
4195                && expression_scopes_to(b, scope)
4196                && expression_scopes_to(c, scope)
4197        }
4198        Expression::Coalesce(list) | Expression::FunctionCall(_, list) => {
4199            list.iter().all(|e| expression_scopes_to(e, scope))
4200        }
4201    }
4202}
4203
4204/// Collect the variables `expr` references directly (`Variable` / `BOUND`),
4205/// deduplicated, in first-appearance order. `EXISTS` bodies are not walked —
4206/// they never reach here because [`expression_scopes_to`] rejects them.
4207fn collect_expression_vars<'a>(expr: &'a Expression, out: &mut Vec<&'a Variable>) {
4208    match expr {
4209        Expression::Variable(v) | Expression::Bound(v) => {
4210            if !out.contains(&v) {
4211                out.push(v);
4212            }
4213        }
4214        Expression::NamedNode(_) | Expression::Literal(_) | Expression::Exists(_) => {}
4215        Expression::Or(a, b)
4216        | Expression::And(a, b)
4217        | Expression::Equal(a, b)
4218        | Expression::SameTerm(a, b)
4219        | Expression::Greater(a, b)
4220        | Expression::GreaterOrEqual(a, b)
4221        | Expression::Less(a, b)
4222        | Expression::LessOrEqual(a, b)
4223        | Expression::Add(a, b)
4224        | Expression::Subtract(a, b)
4225        | Expression::Multiply(a, b)
4226        | Expression::Divide(a, b) => {
4227            collect_expression_vars(a, out);
4228            collect_expression_vars(b, out);
4229        }
4230        Expression::In(a, list) => {
4231            collect_expression_vars(a, out);
4232            for e in list {
4233                collect_expression_vars(e, out);
4234            }
4235        }
4236        Expression::UnaryPlus(e) | Expression::UnaryMinus(e) | Expression::Not(e) => {
4237            collect_expression_vars(e, out);
4238        }
4239        Expression::If(a, b, c) => {
4240            collect_expression_vars(a, out);
4241            collect_expression_vars(b, out);
4242            collect_expression_vars(c, out);
4243        }
4244        Expression::Coalesce(list) | Expression::FunctionCall(_, list) => {
4245            for e in list {
4246                collect_expression_vars(e, out);
4247            }
4248        }
4249    }
4250}
4251
4252/// Hoisted alias entries in application order plus the aggregate variables
4253/// they consume (their bare `(agg AS ?internal)` SELECT entries are dropped).
4254type HoistedGroupAliases<'a> = (Vec<(&'a Variable, String)>, Vec<&'a Variable>);
4255
4256/// Hoist an `Extend`-over-`Group` alias chain into group SELECT entries.
4257///
4258/// `aliases` must be in application order (innermost `Extend` first, the order
4259/// spargebra binds `SELECT … (expr AS ?alias) …` expressions). Each alias's
4260/// free variables must be group keys, aggregate outputs, or aliases hoisted
4261/// before it — otherwise the projection would reference non-grouped variables,
4262/// which re-parsed SPARQL rejects. A bare aggregate reference (`?c := ?i1`)
4263/// becomes the aggregate's own SELECT entry; anything else has its internal
4264/// aggregate variables substituted with their parenthesized aggregate text.
4265///
4266/// Returns the entries in application order plus the aggregate variables the
4267/// entries consume (their bare `(agg AS ?internal)` entries must be dropped).
4268/// `None` means the chain is not hoistable and the caller falls back to
4269/// subselect + `BIND` rendering.
4270fn hoist_group_aliases<'a>(
4271    keys: &[Variable],
4272    agg_texts: &[(&Variable, String)],
4273    aliases: &[(&'a Variable, &'a Expression)],
4274    style: IriStyle,
4275) -> Option<HoistedGroupAliases<'a>> {
4276    let mut scope: Vec<&Variable> = keys.iter().collect();
4277    scope.extend(agg_texts.iter().map(|(v, _)| *v));
4278    let mut entries: Vec<(&'a Variable, String)> = Vec::new();
4279    for (alias, expr) in aliases {
4280        let direct = match expr {
4281            Expression::Variable(v) => agg_texts
4282                .iter()
4283                .find(|(a, _)| *a == v)
4284                .map(|(_, text)| text.clone()),
4285            _ => None,
4286        };
4287        match direct {
4288            Some(text) => entries.push((*alias, text)),
4289            None => {
4290                if !expression_scopes_to(expr, &scope) {
4291                    return None;
4292                }
4293                entries.push((*alias, expression_text(expr, style, agg_texts)));
4294            }
4295        }
4296        scope.push(*alias);
4297    }
4298    let mut referenced: Vec<&Variable> = Vec::new();
4299    for (_, expr) in aliases {
4300        collect_expression_vars(expr, &mut referenced);
4301    }
4302    referenced.retain(|v| agg_texts.iter().any(|(a, _)| a == v));
4303    Some((entries, referenced))
4304}
4305
4306/// The group subselect's `SELECT` list: keys, then aggregates no hoisted alias
4307/// consumed, then the hoisted aliases in application order.
4308fn group_select_list(
4309    keys: &[Variable],
4310    agg_texts: &[(&Variable, String)],
4311    hoisted: &[(&Variable, String)],
4312    referenced: &[&Variable],
4313) -> String {
4314    let mut items: Vec<String> = keys.iter().map(ToString::to_string).collect();
4315    for (v, text) in agg_texts {
4316        if !referenced.contains(v) {
4317            items.push(format!("({text} AS {v})"));
4318        }
4319    }
4320    for (var, text) in hoisted {
4321        items.push(format!("({text} AS {var})"));
4322    }
4323    items.join(" ")
4324}
4325
4326/// Render a Group as the nested `SELECT … GROUP BY …` query — the only SPARQL
4327/// surface syntax for a grouping below the query root. Hoisted aliases land
4328/// inside, so no external `BIND` over an internal aggregate variable is needed.
4329fn group_subselect_sparql(
4330    keys: &[Variable],
4331    agg_texts: &[(&Variable, String)],
4332    inner: &str,
4333    hoisted: &[(&Variable, String)],
4334    referenced: &[&Variable],
4335) -> String {
4336    let select = group_select_list(keys, agg_texts, hoisted, referenced);
4337    if keys.is_empty() {
4338        format!("{{ SELECT {select} WHERE {{ {inner} }} }}")
4339    } else {
4340        let keys_text = keys
4341            .iter()
4342            .map(ToString::to_string)
4343            .collect::<Vec<_>>()
4344            .join(" ");
4345        format!("{{ SELECT {select} WHERE {{ {inner} }} GROUP BY {keys_text} }}")
4346    }
4347}
4348
4349/// Indent compact Jena SSE for human reading.
4350pub fn pretty_sse(compact: &str) -> String {
4351    let tokens = tokenize(compact);
4352    let mut out = String::new();
4353    let mut i = 0;
4354    while i < tokens.len() {
4355        if !out.is_empty() {
4356            out.push('\n');
4357        }
4358        i = write_form(&tokens, i, 0, &mut out);
4359    }
4360    if !out.ends_with('\n') {
4361        out.push('\n');
4362    }
4363    out
4364}
4365
4366#[derive(Debug, Clone, PartialEq, Eq)]
4367enum Tok {
4368    Open,
4369    Close,
4370    Atom(String),
4371}
4372
4373fn tokenize(input: &str) -> Vec<Tok> {
4374    let mut tokens = Vec::new();
4375    let mut chars = input.chars().peekable();
4376    while let Some(&ch) = chars.peek() {
4377        match ch {
4378            ' ' | '\t' | '\n' | '\r' => {
4379                chars.next();
4380            }
4381            '(' => {
4382                chars.next();
4383                tokens.push(Tok::Open);
4384            }
4385            ')' => {
4386                chars.next();
4387                tokens.push(Tok::Close);
4388            }
4389            '<' => {
4390                let mut atom = String::from("<");
4391                chars.next();
4392                for c in chars.by_ref() {
4393                    atom.push(c);
4394                    if c == '>' {
4395                        break;
4396                    }
4397                }
4398                tokens.push(Tok::Atom(atom));
4399            }
4400            '"' => {
4401                let mut atom = String::from("\"");
4402                chars.next();
4403                for c in chars.by_ref() {
4404                    atom.push(c);
4405                    if c == '"' {
4406                        break;
4407                    }
4408                }
4409                while let Some(&c) = chars.peek() {
4410                    if c.is_whitespace() || c == '(' || c == ')' {
4411                        break;
4412                    }
4413                    atom.push(c);
4414                    chars.next();
4415                }
4416                tokens.push(Tok::Atom(atom));
4417            }
4418            _ => {
4419                let mut atom = String::new();
4420                while let Some(&c) = chars.peek() {
4421                    if c.is_whitespace() || c == '(' || c == ')' || c == '<' || c == '"' {
4422                        break;
4423                    }
4424                    atom.push(c);
4425                    chars.next();
4426                }
4427                if !atom.is_empty() {
4428                    tokens.push(Tok::Atom(atom));
4429                }
4430            }
4431        }
4432    }
4433    tokens
4434}
4435
4436fn write_form(tokens: &[Tok], start: usize, indent: usize, out: &mut String) -> usize {
4437    match tokens.get(start) {
4438        None => start,
4439        // Stray `)` (unbalanced compact SSE): skip so `pretty_sse` cannot spin.
4440        Some(Tok::Close) => start + 1,
4441        Some(Tok::Atom(a)) => {
4442            out.push_str(a);
4443            start + 1
4444        }
4445        Some(Tok::Open) => {
4446            let mut i = start + 1;
4447            let mut children: Vec<(usize, usize)> = Vec::new();
4448            while i < tokens.len() {
4449                match &tokens[i] {
4450                    Tok::Close => {
4451                        format_form(tokens, &children, indent, out);
4452                        return i + 1;
4453                    }
4454                    Tok::Open => {
4455                        let child_start = i;
4456                        i = skip_form(tokens, i);
4457                        children.push((child_start, i));
4458                    }
4459                    Tok::Atom(_) => {
4460                        let child_start = i;
4461                        i += 1;
4462                        children.push((child_start, i));
4463                    }
4464                }
4465            }
4466            format_form(tokens, &children, indent, out);
4467            tokens.len()
4468        }
4469    }
4470}
4471
4472fn skip_form(tokens: &[Tok], open_at: usize) -> usize {
4473    let mut depth = 0usize;
4474    let mut i = open_at;
4475    while i < tokens.len() {
4476        match &tokens[i] {
4477            Tok::Open => depth += 1,
4478            Tok::Close => {
4479                depth -= 1;
4480                if depth == 0 {
4481                    return i + 1;
4482                }
4483            }
4484            Tok::Atom(_) => {}
4485        }
4486        i += 1;
4487    }
4488    tokens.len()
4489}
4490
4491fn format_form(tokens: &[Tok], children: &[(usize, usize)], indent: usize, out: &mut String) {
4492    let has_list_child = children
4493        .iter()
4494        .any(|&(s, _)| matches!(tokens.get(s), Some(Tok::Open)));
4495
4496    if !has_list_child {
4497        out.push('(');
4498        for (n, &(s, _)) in children.iter().enumerate() {
4499            if n > 0 {
4500                out.push(' ');
4501            }
4502            if let Some(Tok::Atom(a)) = tokens.get(s) {
4503                out.push_str(a);
4504            }
4505        }
4506        out.push(')');
4507        return;
4508    }
4509
4510    out.push('(');
4511    let mut idx = 0;
4512    while idx < children.len() {
4513        let (s, _) = children[idx];
4514        let Some(Tok::Atom(a)) = tokens.get(s) else {
4515            break;
4516        };
4517        if idx > 0 {
4518            out.push(' ');
4519        }
4520        out.push_str(a);
4521        idx += 1;
4522    }
4523    while idx < children.len() {
4524        let (s, _) = children[idx];
4525        out.push('\n');
4526        for _ in 0..(indent + 1) {
4527            out.push_str("  ");
4528        }
4529        let mut child = String::new();
4530        let _ = write_form(tokens, s, indent + 1, &mut child);
4531        out.push_str(child.trim_end_matches('\n'));
4532        idx += 1;
4533    }
4534    out.push(')');
4535}
4536
4537// ---------------------------------------------------------------------------
4538// SPARQL-syntax pretty printer (`pretty=true` for `*-sparql` formats)
4539// ---------------------------------------------------------------------------
4540
4541/// Indent compact SPARQL-syntax explain output (`optimised-sparql` /
4542/// `planned-sparql`) for human reading: one triple pattern or group element
4543/// per line, two-space indent per `{`, `;` property lists continue on their
4544/// own indented lines, and `[...]` blank-node property lists nest.
4545///
4546/// A lexer plus bracket-depth counter, not a parser: IRIs and quoted literals
4547/// are consumed as opaque atoms, so braces, dots, and keywords inside them
4548/// never affect the layout. `;` inside parentheses (aggregate
4549/// `GROUP_CONCAT(x; SEPARATOR = ...)`) stays glued; `;` at property-list level
4550/// breaks the line and indents the continuation by one step (once per
4551/// statement, not per `;`). Input is the compact single-line text produced by
4552/// [`format_l1_sparql`] / [`fmt_plan_sparql_query`] (or the equivalent
4553/// spargebra `Display` output), but hand-written SPARQL using `;` / `[]`
4554/// abbreviations lexes the same way. The result stays valid SPARQL —
4555/// statement dots are optional before `}` and before element keywords in the
4556/// group-graph-pattern grammar, and those are exactly the places where a line
4557/// break is inserted without a dot.
4558pub fn pretty_sparql(compact: &str) -> String {
4559    let tokens = tokenize_sparql(compact);
4560    let mut out = String::new();
4561    let mut line = String::new();
4562    let mut depth = 0usize;
4563    // A `;` at property-list level indents the rest of the statement by one
4564    // step; the bump applies once per statement (a second `;` keeps the same
4565    // indent) and is undone by the statement's `.`.
4566    let mut semi_bumped = false;
4567    // One entry per open `[` blank-node property list; `;` inside one does not
4568    // bump further because the bracket already provides the indent.
4569    let mut bnode_depth = 0usize;
4570    // `(`/`)` nesting counted from atom contents; `;` / `.` inside parens are
4571    // expression syntax, not statement structure.
4572    let mut parens = 0usize;
4573    let mut i = 0;
4574    while i < tokens.len() {
4575        match &tokens[i] {
4576            SqlTok::Atom(atom) => {
4577                parens += atom.matches('(').count();
4578                parens = parens.saturating_sub(atom.matches(')').count());
4579                if is_element_keyword(atom) && !line.is_empty() {
4580                    flush_sparql_line(&mut line, depth, &mut out);
4581                }
4582                // Closing parens / commas attach tightly (`... "|")`, `})`).
4583                if !line.is_empty() && !atom.starts_with(')') && !atom.starts_with(',') {
4584                    line.push(' ');
4585                }
4586                line.push_str(atom);
4587            }
4588            SqlTok::Semi => {
4589                line.push(';');
4590                if parens == 0 {
4591                    flush_sparql_line(&mut line, depth, &mut out);
4592                    if bnode_depth == 0 && !semi_bumped {
4593                        depth += 1;
4594                        semi_bumped = true;
4595                    }
4596                }
4597            }
4598            SqlTok::Dot => {
4599                if line.is_empty() {
4600                    line.push('.');
4601                } else {
4602                    line.push_str(" .");
4603                }
4604                if parens == 0 {
4605                    flush_sparql_line(&mut line, depth, &mut out);
4606                    if semi_bumped {
4607                        depth = depth.saturating_sub(1);
4608                        semi_bumped = false;
4609                    }
4610                }
4611            }
4612            SqlTok::Open => {
4613                if semi_bumped {
4614                    depth = depth.saturating_sub(1);
4615                    semi_bumped = false;
4616                }
4617                if !line.is_empty() {
4618                    line.push(' ');
4619                }
4620                line.push('{');
4621                flush_sparql_line(&mut line, depth, &mut out);
4622                depth += 1;
4623            }
4624            SqlTok::Close => {
4625                if semi_bumped {
4626                    depth = depth.saturating_sub(1);
4627                    semi_bumped = false;
4628                }
4629                if !line.is_empty() {
4630                    flush_sparql_line(&mut line, depth, &mut out);
4631                }
4632                depth = depth.saturating_sub(1);
4633                line.push('}');
4634                if !glues_after_close(tokens.get(i + 1)) {
4635                    flush_sparql_line(&mut line, depth, &mut out);
4636                }
4637            }
4638            SqlTok::OpenBracket => {
4639                if tokens.get(i + 1) == Some(&SqlTok::CloseBracket) {
4640                    // Empty bnode `[]` (the planned-Sparql printer uses it for
4641                    // unbound slots) stays glued like an atom.
4642                    if !line.is_empty() {
4643                        line.push(' ');
4644                    }
4645                    line.push_str("[]");
4646                    i += 1;
4647                } else {
4648                    if !line.is_empty() {
4649                        line.push(' ');
4650                    }
4651                    line.push('[');
4652                    flush_sparql_line(&mut line, depth, &mut out);
4653                    depth += 1;
4654                    bnode_depth += 1;
4655                }
4656            }
4657            SqlTok::CloseBracket => {
4658                if !line.is_empty() {
4659                    flush_sparql_line(&mut line, depth, &mut out);
4660                }
4661                depth = depth.saturating_sub(1);
4662                bnode_depth = bnode_depth.saturating_sub(1);
4663                line.push(']');
4664                if !glues_after_bnode_close(tokens.get(i + 1)) {
4665                    flush_sparql_line(&mut line, depth, &mut out);
4666                }
4667            }
4668        }
4669        i += 1;
4670    }
4671    flush_sparql_line(&mut line, depth, &mut out);
4672    if !out.ends_with('\n') {
4673        out.push('\n');
4674    }
4675    out
4676}
4677
4678#[derive(Debug, Clone, PartialEq, Eq)]
4679enum SqlTok {
4680    Open,
4681    Close,
4682    OpenBracket,
4683    CloseBracket,
4684    Dot,
4685    Semi,
4686    Atom(String),
4687}
4688
4689/// Lex compact SPARQL into brackets, statement dots and semicolons, and
4690/// opaque atoms.
4691///
4692/// `.` / `;` only become statement tokens when isolated (whitespace or
4693/// bracket on the following side for `.`, always for `;` outside atoms); a
4694/// dot with a non-space neighbour is part of an atom (`1.5`, dotted local
4695/// names). `<...>` is one IRI atom when a `>` arrives before whitespace or a
4696/// bracket; otherwise the leading `<` / `<=` is a comparison-operator atom.
4697fn tokenize_sparql(input: &str) -> Vec<SqlTok> {
4698    fn is_space(c: char) -> bool {
4699        matches!(c, ' ' | '\t' | '\n' | '\r')
4700    }
4701    let mut tokens = Vec::new();
4702    let mut chars = input.chars().peekable();
4703    while let Some(&ch) = chars.peek() {
4704        match ch {
4705            c if is_space(c) => {
4706                chars.next();
4707            }
4708            '{' => {
4709                chars.next();
4710                tokens.push(SqlTok::Open);
4711            }
4712            '}' => {
4713                chars.next();
4714                tokens.push(SqlTok::Close);
4715            }
4716            '[' => {
4717                chars.next();
4718                tokens.push(SqlTok::OpenBracket);
4719            }
4720            ']' => {
4721                chars.next();
4722                tokens.push(SqlTok::CloseBracket);
4723            }
4724            ';' => {
4725                chars.next();
4726                tokens.push(SqlTok::Semi);
4727            }
4728            '.' => {
4729                chars.next();
4730                let isolated = match chars.peek() {
4731                    None => true,
4732                    Some(&c) => is_space(c) || matches!(c, '{' | '}' | '[' | ']'),
4733                };
4734                if isolated {
4735                    tokens.push(SqlTok::Dot);
4736                } else {
4737                    // Leading-dot atom (defensive: the serializers always
4738                    // emit statement dots with surrounding whitespace).
4739                    let mut atom = String::from(".");
4740                    while let Some(&c) = chars.peek() {
4741                        if is_space(c) || matches!(c, '{' | '}' | '[' | ']' | '"' | '\'' | ';') {
4742                            break;
4743                        }
4744                        atom.push(c);
4745                        chars.next();
4746                    }
4747                    tokens.push(SqlTok::Atom(atom));
4748                }
4749            }
4750            '<' => {
4751                chars.next();
4752                let mut atom = String::from("<");
4753                while let Some(&c) = chars.peek() {
4754                    if c == '>' {
4755                        atom.push(c);
4756                        chars.next();
4757                        break;
4758                    }
4759                    if is_space(c) || matches!(c, '{' | '}' | '[' | ']') {
4760                        break;
4761                    }
4762                    atom.push(c);
4763                    chars.next();
4764                }
4765                tokens.push(SqlTok::Atom(atom));
4766            }
4767            '"' | '\'' => {
4768                let atom = scan_sparql_string(&mut chars, ch);
4769                tokens.push(SqlTok::Atom(atom));
4770            }
4771            _ => {
4772                let mut atom = String::new();
4773                while let Some(&c) = chars.peek() {
4774                    if is_space(c) || matches!(c, '{' | '}' | '[' | ']' | '"' | '\'' | '<' | ';') {
4775                        break;
4776                    }
4777                    atom.push(c);
4778                    chars.next();
4779                }
4780                if !atom.is_empty() {
4781                    tokens.push(SqlTok::Atom(atom));
4782                }
4783            }
4784        }
4785    }
4786    tokens
4787}
4788
4789/// Consume one SPARQL string literal (short or triple-quoted, with `@lang` /
4790/// `^^<iri>` / `^^pfx:local` suffix) starting at the opening quote.
4791fn scan_sparql_string(chars: &mut std::iter::Peekable<std::str::Chars<'_>>, quote: char) -> String {
4792    let mut atom = String::new();
4793    atom.push(quote);
4794    chars.next();
4795    // `""` may open a triple-quoted literal.
4796    let long = chars.peek() == Some(&quote);
4797    if long {
4798        chars.next();
4799        atom.push(quote);
4800    }
4801    let long = long && chars.peek() == Some(&quote);
4802    if long {
4803        chars.next();
4804        atom.push(quote);
4805    }
4806    if long {
4807        // Raw newlines and unescaped quotes are opaque inside the literal;
4808        // only the exact triple-quote terminator ends it.
4809        let mut run = 0usize;
4810        for c in chars.by_ref() {
4811            atom.push(c);
4812            run = if c == quote { run + 1 } else { 0 };
4813            if run == 3 {
4814                break;
4815            }
4816        }
4817    } else {
4818        while let Some(c) = chars.next() {
4819            atom.push(c);
4820            if c == '\\' {
4821                if let Some(escaped) = chars.next() {
4822                    atom.push(escaped);
4823                }
4824            } else if c == quote {
4825                break;
4826            }
4827        }
4828    }
4829    match chars.peek() {
4830        Some('@') => {
4831            atom.push('@');
4832            chars.next();
4833            while let Some(&c) = chars.peek() {
4834                if c.is_ascii_alphanumeric() || c == '-' {
4835                    atom.push(c);
4836                    chars.next();
4837                } else {
4838                    break;
4839                }
4840            }
4841        }
4842        Some('^') => {
4843            atom.push('^');
4844            chars.next();
4845            if chars.peek() == Some(&'^') {
4846                atom.push('^');
4847                chars.next();
4848                if chars.peek() == Some(&'<') {
4849                    while let Some(&c) = chars.peek() {
4850                        atom.push(c);
4851                        chars.next();
4852                        if c == '>' {
4853                            break;
4854                        }
4855                    }
4856                } else {
4857                    while let Some(&c) = chars.peek() {
4858                        if is_sparql_stop(c) {
4859                            break;
4860                        }
4861                        atom.push(c);
4862                        chars.next();
4863                    }
4864                }
4865            }
4866        }
4867        _ => {}
4868    }
4869    atom
4870}
4871
4872fn is_sparql_stop(c: char) -> bool {
4873    matches!(
4874        c,
4875        ' ' | '\t' | '\n' | '\r' | '{' | '}' | '[' | ']' | '"' | '\'' | ';'
4876    )
4877}
4878
4879/// Graph-pattern element starters that begin a new line when the current line
4880/// already has content. Without this, a trailing triple without its optional
4881/// statement dot would glue to the next element (`?s <p> ?o OPTIONAL { ... }`).
4882/// Keywords are matched uppercase because both the spargebra `Display` and the
4883/// planned-SPARQL printers emit uppercase keywords.
4884fn is_element_keyword(atom: &str) -> bool {
4885    matches!(
4886        atom,
4887        "OPTIONAL" | "MINUS" | "GRAPH" | "VALUES" | "FROM" | "FILTER" | "BIND"
4888    ) || atom.starts_with("FILTER(")
4889        || atom.starts_with("BIND(")
4890}
4891
4892/// Atoms allowed to stay on their closing-brace line: `} UNION {`,
4893/// `} OFFSET 1 LIMIT 2`, `} GROUP BY ?k`, `} ORDER BY`, and the `)` that
4894/// closes `FILTER(EXISTS { ... })`. Everything else breaks after `}`.
4895fn glues_after_close(next: Option<&SqlTok>) -> bool {
4896    match next {
4897        Some(SqlTok::Open) => true,
4898        Some(SqlTok::Atom(atom)) => {
4899            matches!(
4900                atom.as_str(),
4901                "UNION" | "OFFSET" | "LIMIT" | "GROUP" | "ORDER" | "HAVING"
4902            ) || atom.starts_with(')')
4903        }
4904        Some(SqlTok::Close)
4905        | Some(SqlTok::OpenBracket)
4906        | Some(SqlTok::CloseBracket)
4907        | Some(SqlTok::Dot)
4908        | Some(SqlTok::Semi)
4909        | None => false,
4910    }
4911}
4912
4913/// A closing `]` keeps a following `.` or `;` on its line (`] .` ends the
4914/// statement, `] ;` continues the property list), as well as `,` / `)`
4915/// object-list continuations. Everything else breaks after `]`.
4916fn glues_after_bnode_close(next: Option<&SqlTok>) -> bool {
4917    match next {
4918        Some(SqlTok::Dot) | Some(SqlTok::Semi) => true,
4919        Some(SqlTok::Atom(atom)) => atom.starts_with(')') || atom.starts_with(','),
4920        _ => false,
4921    }
4922}
4923
4924fn flush_sparql_line(line: &mut String, depth: usize, out: &mut String) {
4925    if line.is_empty() {
4926        return;
4927    }
4928    for _ in 0..depth {
4929        out.push_str("  ");
4930    }
4931    out.push_str(line);
4932    out.push('\n');
4933    line.clear();
4934}
4935
4936#[cfg(test)]
4937mod tests {
4938    use super::*;
4939    use crate::plan::{CustomOp, CustomOpCost};
4940    use pretty_assertions::assert_eq;
4941    use waratah_storage::{EncodedTerm, NamedNode};
4942
4943    /// Minimal payload for rendering a CustomNode without a plugin behind
4944    /// it (`waratah_compute` tests cannot install `waratah_geo`).
4945    #[derive(Debug)]
4946    struct ExplainCostPayload;
4947    impl crate::plugin::PluginPayload for ExplainCostPayload {
4948        fn plugin_id(&self) -> &'static str {
4949            "geosparql"
4950        }
4951    }
4952
4953    fn cost_custom_op(cost: Option<CustomOpCost>) -> PlanNode {
4954        PlanNode::CustomNode(CustomOp {
4955            plugin_id: "geosparql",
4956            op_id: "geo_scan",
4957            payload: crate::plugin::PluginPayloadBox::new(ExplainCostPayload),
4958            children: Vec::new(),
4959            variables: vec![Variable::new("wkt").unwrap()],
4960            produced_row_count_estimate: 5350,
4961            cost,
4962            pinned: Vec::new(),
4963        })
4964    }
4965
4966    #[test]
4967    fn custom_op_cost_renders_under_estimates_only() {
4968        let render = |node: &PlanNode, estimates: bool| {
4969            let ctx = PrintCtx {
4970                estimates,
4971                profile: None,
4972                slice_path: false,
4973                suppress_star: false,
4974                page_rows: 1,
4975            };
4976            let mut body = String::new();
4977            fmt_plan_node(node, &ctx, &mut body).unwrap();
4978            body
4979        };
4980        let stamped = cost_custom_op(Some(CustomOpCost {
4981            drain_rows: 5350,
4982            per_key_unit: 8,
4983            inline_point_unit: 1,
4984            direct_probe: true,
4985            probe_keyed_columns: 0b1,
4986            probe_filter_unit: 8,
4987            probe_memo_entry_rows: 0,
4988        }));
4989        assert_eq!(
4990            render(&stamped, true),
4991            "(custom-op ~5350 geosparql geo_scan ?wkt cost=drain~5350,unit~8)"
4992        );
4993        // Without estimates the whole `~N` prefix disappears; the cost
4994        // annotation is estimates-gated with it.
4995        assert_eq!(
4996            render(&stamped, false),
4997            "(custom-op geosparql geo_scan ?wkt)"
4998        );
4999        // An opaque op (cost: None) renders exactly as before the cost model.
5000        assert_eq!(
5001            render(&cost_custom_op(None), true),
5002            "(custom-op ~5350 geosparql geo_scan ?wkt)"
5003        );
5004    }
5005
5006    fn encoded_iri_sse(iri: &str) -> String {
5007        format_encoded_term(&EncodedTerm::from(&NamedNode::new(iri).unwrap()), &[])
5008    }
5009
5010    #[test]
5011    fn well_known_iris_render_prefixed_without_registry() {
5012        // Table entries decode registry-free and print under their
5013        // conventional namespace prefix.
5014        assert_eq!(
5015            encoded_iri_sse("http://www.w3.org/2001/XMLSchema#integer"),
5016            "xsd:integer"
5017        );
5018        assert_eq!(
5019            encoded_iri_sse("http://www.w3.org/2000/01/rdf-schema#label"),
5020            "rdfs:label"
5021        );
5022        assert_eq!(
5023            encoded_iri_sse("http://www.w3.org/2002/07/owl#Class"),
5024            "owl:Class"
5025        );
5026        assert_eq!(
5027            encoded_iri_sse("http://www.w3.org/2004/02/skos/core#prefLabel"),
5028            "skos:prefLabel"
5029        );
5030        // rdf:type prints `rdf:type` in term position (the `a` keyword is
5031        // predicate-only in SPARQL) and `a` via the predicate formatter.
5032        assert_eq!(
5033            encoded_iri_sse("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
5034            "rdf:type"
5035        );
5036        assert_eq!(
5037            format_encoded_term_predicate(
5038                &EncodedTerm::from(
5039                    &NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap()
5040                ),
5041                &[]
5042            ),
5043            "a"
5044        );
5045        // Registry-resolved IRIs under a known namespace shorten too.
5046        let schema_author = StrHash::new("http://schema.org/author");
5047        let resolved = [(schema_author, "http://schema.org/author".to_string())];
5048        assert_eq!(
5049            format_encoded_term(
5050                &EncodedTerm::NamedNode {
5051                    iri_id: schema_author
5052                },
5053                &resolved
5054            ),
5055            "schema:author"
5056        );
5057        // Unknown IRIs still fall back to the short hash.
5058        assert!(
5059            encoded_iri_sse("http://ex/not-well-known").starts_with("<#"),
5060            "{}",
5061            encoded_iri_sse("http://ex/not-well-known")
5062        );
5063    }
5064
5065    #[test]
5066    fn pretty_keeps_flat_triple_on_one_line() {
5067        let pretty = pretty_sse(r#"(triple ?s <http://ex/p> "x")"#);
5068        assert_eq!(pretty, "(triple ?s <http://ex/p> \"x\")\n");
5069    }
5070
5071    #[test]
5072    fn pretty_indents_nested_lists() {
5073        let compact =
5074            "(project (?s) (bgp (triple ?s <http://ex/p> ?o) (triple ?s <http://ex/q> ?o)))";
5075        let pretty = pretty_sse(compact);
5076        assert_eq!(
5077            pretty,
5078            "(project\n  (?s)\n  (bgp\n    (triple ?s <http://ex/p> ?o)\n    (triple ?s <http://ex/q> ?o)))\n"
5079        );
5080    }
5081
5082    #[test]
5083    fn pretty_sse_stray_close_does_not_spin() {
5084        let out = pretty_sse("(triple ?s <http://ex/p> ?o) )");
5085        assert!(out.contains("triple"), "{out}");
5086    }
5087
5088    fn assert_sse_paren_balanced(compact: &str) {
5089        let mut depth = 0i32;
5090        for tok in tokenize(compact) {
5091            match tok {
5092                Tok::Open => depth += 1,
5093                Tok::Close => {
5094                    depth -= 1;
5095                    assert!(depth >= 0, "extra `)` in SSE: {compact}");
5096                }
5097                Tok::Atom(_) => {}
5098            }
5099        }
5100        assert_eq!(depth, 0, "unclosed `(` in SSE: {compact}");
5101    }
5102
5103    #[test]
5104    fn planned_domain_counts_sse_has_balanced_parens() {
5105        let sparql = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
5106                      SELECT ?o (COUNT(?s) AS ?c) WHERE { ?s rdfs:subClassOf ?o } GROUP BY ?o";
5107        let compact = LogicalPlan::explain(sparql, ExplainFormat::Planned, false, None).unwrap();
5108        assert!(
5109            compact.contains("(domain_counts"),
5110            "expected group elimination in plan SSE: {compact}"
5111        );
5112        assert_sse_paren_balanced(&compact);
5113        assert!(
5114            !compact.ends_with("))))"),
5115            "regression: double-close on domain_counts node: {compact}"
5116        );
5117        let _ = pretty_sse(&compact);
5118    }
5119
5120    #[test]
5121    fn planned_pattern_count_sse_has_balanced_parens() {
5122        let sparql = "SELECT (COUNT(*) AS ?c) WHERE { ?s ?p ?o }";
5123        let compact = LogicalPlan::explain(sparql, ExplainFormat::Planned, false, None).unwrap();
5124        assert!(
5125            compact.contains("(pattern_count"),
5126            "expected PatternCount group elimination in plan SSE: {compact}"
5127        );
5128        assert!(
5129            compact.contains("COUNT(*)"),
5130            "expected COUNT(*) annotation: {compact}"
5131        );
5132        assert_sse_paren_balanced(&compact);
5133        let _ = pretty_sse(&compact);
5134
5135        let partial = "SELECT (COUNT(?s) AS ?n) WHERE { ?s ?p <http://ex/Dog> }";
5136        let partial_plan =
5137            LogicalPlan::explain(partial, ExplainFormat::Planned, false, None).unwrap();
5138        assert!(
5139            partial_plan.contains("(pattern_count"),
5140            "partially-bound BGP must still eliminate: {partial_plan}"
5141        );
5142        assert!(
5143            partial_plan.contains("COUNT(?s)"),
5144            "expected COUNT(?s) annotation: {partial_plan}"
5145        );
5146        assert_sse_paren_balanced(&partial_plan);
5147    }
5148
5149    #[test]
5150    fn explain_sse_outputs_are_paren_balanced() {
5151        let queries = [
5152            "SELECT ?s WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?x }",
5153            "SELECT ?p (COUNT(*) AS ?c) WHERE { ?s ?p ?o } GROUP BY ?p",
5154            "SELECT (COUNT(*) AS ?c) WHERE { ?s ?p ?o }",
5155            r#"ASK WHERE { ?s <http://ex/p> ?o }"#,
5156            r#"SELECT ?rack ?server WHERE {
5157              ?rack a <http://ex/Rack> .
5158              OPTIONAL {
5159                ?server a <http://ex/Server> .
5160                ?server <http://ex/locatedIn> ?rack .
5161              }
5162            }"#,
5163            "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
5164             SELECT ?o (COUNT(?s) AS ?c) WHERE { ?s rdfs:subClassOf ?o } GROUP BY ?o",
5165        ];
5166        for sparql in queries {
5167            for format in [
5168                ExplainFormat::Sse,
5169                ExplainFormat::Optimised,
5170                ExplainFormat::Planned,
5171                ExplainFormat::Estimate,
5172            ] {
5173                let compact = LogicalPlan::explain(sparql, format, false, None).unwrap();
5174                assert_sse_paren_balanced(&compact);
5175                let _ = pretty_sse(&compact);
5176            }
5177        }
5178    }
5179
5180    #[test]
5181    fn pretty_sparql_splits_triples_and_indents_groups() {
5182        let pretty = pretty_sparql(
5183            "SELECT ?person ?weather WHERE { ?person <http://ex/livesIn> ?city . ?city <http://ex/hasWeather> \"Sunny\" }",
5184        );
5185        assert_eq!(
5186            pretty,
5187            "SELECT ?person ?weather WHERE {\n  ?person <http://ex/livesIn> ?city .\n  ?city <http://ex/hasWeather> \"Sunny\"\n}\n"
5188        );
5189    }
5190
5191    #[test]
5192    fn pretty_sparql_keeps_union_and_subselect_modifiers_glued() {
5193        let pretty = pretty_sparql(
5194            "SELECT * WHERE { { ?a <http://ex/p> ?b . } UNION { ?c <http://ex/p> ?d . } }",
5195        );
5196        assert_eq!(
5197            pretty,
5198            "SELECT * WHERE {\n  {\n    ?a <http://ex/p> ?b .\n  } UNION {\n    ?c <http://ex/p> ?d .\n  }\n}\n"
5199        );
5200        crate::rephrase_error::parse_query(&pretty).unwrap();
5201        // `} OFFSET n LIMIT n` of a subselect stays on the closing-brace line.
5202        let pretty = pretty_sparql(
5203            "SELECT ?y WHERE { { SELECT ?x WHERE { ?a <http://ex/p> ?b . } OFFSET 1 LIMIT 2 } }",
5204        );
5205        assert_eq!(
5206            pretty,
5207            "SELECT ?y WHERE {\n  {\n    SELECT ?x WHERE {\n      ?a <http://ex/p> ?b .\n    } OFFSET 1 LIMIT 2\n  }\n}\n"
5208        );
5209        crate::rephrase_error::parse_query(&pretty).unwrap();
5210    }
5211
5212    #[test]
5213    fn pretty_sparql_ignores_braces_and_dots_inside_literals() {
5214        // `}`, `{`, and `.` inside a quoted literal, an escaped quote, and a
5215        // decimal-looking run never affect brace depth or line breaks.
5216        let pretty = pretty_sparql(
5217            "SELECT ?s WHERE { ?s <http://ex/p> \"brace } dot . { end\" . ?s <http://ex/q> \"esc \\\" quote}1.5\" }",
5218        );
5219        assert_eq!(
5220            pretty,
5221            "SELECT ?s WHERE {\n  ?s <http://ex/p> \"brace } dot . { end\" .\n  ?s <http://ex/q> \"esc \\\" quote}1.5\"\n}\n"
5222        );
5223        crate::rephrase_error::parse_query(&pretty).unwrap();
5224    }
5225
5226    #[test]
5227    fn pretty_sparql_triple_quoted_literal_keeps_raw_newline_and_braces() {
5228        let pretty =
5229            pretty_sparql("SELECT ?s WHERE { ?s <http://ex/p> \"\"\"multi\nline } {\"\"\" }");
5230        assert_eq!(
5231            pretty,
5232            "SELECT ?s WHERE {\n  ?s <http://ex/p> \"\"\"multi\nline } {\"\"\"\n}\n"
5233        );
5234        crate::rephrase_error::parse_query(&pretty).unwrap();
5235    }
5236
5237    #[test]
5238    fn pretty_sparql_semicolon_lists_and_bnode_brackets() {
5239        // Full IRIs so the pretty form round-trips through the parser (the
5240        // explain printers emit no PREFIX block).
5241        let pretty = pretty_sparql(
5242            "SELECT * WHERE { ?s <http://ex/type> <http://ex/Car> ; <http://ex/hasSeats> 4 ; <http://ex/isColour> ?c . ?s <http://ex/hasAttribute> [ <http://ex/attrName> \"transmission\" ; <http://ex/attrValue> ?t ] . }",
5243        );
5244        assert_eq!(
5245            pretty,
5246            "SELECT * WHERE {\n  ?s <http://ex/type> <http://ex/Car>;\n    <http://ex/hasSeats> 4;\n    <http://ex/isColour> ?c .\n  ?s <http://ex/hasAttribute> [\n    <http://ex/attrName> \"transmission\";\n    <http://ex/attrValue> ?t\n  ] .\n}\n"
5247        );
5248        crate::rephrase_error::parse_query(&pretty).unwrap();
5249    }
5250
5251    #[test]
5252    fn pretty_sparql_empty_bnode_slots_stay_glued() {
5253        let pretty = pretty_sparql("SELECT ?s WHERE { [] <http://ex/p> ?o . ?s <http://ex/q> [] }");
5254        assert_eq!(
5255            pretty,
5256            "SELECT ?s WHERE {\n  [] <http://ex/p> ?o .\n  ?s <http://ex/q> []\n}\n"
5257        );
5258        crate::rephrase_error::parse_query(&pretty).unwrap();
5259    }
5260
5261    #[test]
5262    fn pretty_sparql_semicolon_inside_parens_stays_glued() {
5263        // `;` inside `GROUP_CONCAT(x; SEPARATOR = ...)` is expression syntax,
5264        // not a property-list break.
5265        let pretty = pretty_sparql(
5266            "SELECT (GROUP_CONCAT(?s; SEPARATOR = \"|\") AS ?l) WHERE { ?s <http://ex/p> ?o . }",
5267        );
5268        assert_eq!(
5269            pretty,
5270            "SELECT (GROUP_CONCAT(?s; SEPARATOR = \"|\") AS ?l) WHERE {\n  ?s <http://ex/p> ?o .\n}\n"
5271        );
5272        assert!(!pretty.contains(";\n"), "{pretty}");
5273        crate::rephrase_error::parse_query(&pretty).unwrap();
5274    }
5275
5276    #[test]
5277    fn planned_sparql_pretty_is_multiline_and_reparses() {
5278        let sparql = "SELECT ?s WHERE { ?s <http://ex/p> ?o . OPTIONAL { ?s <http://ex/q> ?x . FILTER(?x > 1) } FILTER(EXISTS { ?s <http://ex/r> ?y }) }";
5279        let compact =
5280            LogicalPlan::explain(sparql, ExplainFormat::PlannedSparql, false, None).unwrap();
5281        assert!(!compact.contains('\n'), "{compact}");
5282        let pretty =
5283            LogicalPlan::explain(sparql, ExplainFormat::PlannedSparql, true, None).unwrap();
5284        assert!(pretty.starts_with("SELECT ?s WHERE {\n"), "{pretty}");
5285        assert!(pretty.contains("\n  OPTIONAL {\n"), "{pretty}");
5286        assert!(pretty.contains("\n  FILTER(EXISTS {\n"), "{pretty}");
5287        assert!(pretty.ends_with("})\n}\n"), "{pretty}");
5288        // The planned printer falls back to relative `<#hash>` IRIs for
5289        // unresolved terms, so give the round-trip parse a BASE to resolve
5290        // them against; this still proves the pretty text is grammar-valid.
5291        crate::rephrase_error::parse_query(&format!("BASE <http://waratah.invalid/> {pretty}"))
5292            .unwrap();
5293    }
5294
5295    #[test]
5296    fn optimised_sparql_pretty_is_multiline_and_reparses() {
5297        let sparql = "DESCRIBE <http://ex/x> WHERE { <http://ex/x> <http://ex/p> ?o . ?o <http://ex/q> ?x . FILTER(?x > 1) }";
5298        let compact =
5299            LogicalPlan::explain(sparql, ExplainFormat::OptimisedSparql, false, None).unwrap();
5300        assert!(!compact.contains('\n'), "{compact}");
5301        let pretty =
5302            LogicalPlan::explain(sparql, ExplainFormat::OptimisedSparql, true, None).unwrap();
5303        assert!(
5304            pretty.starts_with("DESCRIBE <http://ex/x> WHERE {"),
5305            "{pretty}"
5306        );
5307        assert!(pretty.contains('\n'), "{pretty}");
5308        crate::rephrase_error::parse_query(&pretty).unwrap();
5309
5310        // The generic L1 SELECT path goes through the vendored
5311        // spargebra-`Display` mirror; these queries have no well-known IRIs,
5312        // so the output is unchanged and still re-parses without PREFIXes.
5313        let sparql = "SELECT ?s WHERE { ?s <http://ex/p> ?o . ?o <http://ex/q> ?x }";
5314        let pretty =
5315            LogicalPlan::explain(sparql, ExplainFormat::OptimisedSparql, true, None).unwrap();
5316        assert!(pretty.starts_with("SELECT ?s WHERE {\n"), "{pretty}");
5317        crate::rephrase_error::parse_query(&pretty).unwrap();
5318    }
5319
5320    #[test]
5321    fn l1_sparql_shortens_well_known_iris_and_type_predicate() {
5322        let sparql = r#"
5323            PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
5324            PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
5325            PREFIX owl:  <http://www.w3.org/2002/07/owl#>
5326            SELECT DISTINCT ?class ?label ?parent WHERE {
5327              { ?inst a ?class . } UNION { ?class a rdfs:Class } UNION { ?class a owl:Class }
5328              FILTER ISIRI(?class)
5329              OPTIONAL { ?class rdfs:label ?label }
5330              OPTIONAL { ?class rdfs:subClassOf ?parent. FILTER ISIRI(?parent) }
5331            } ORDER BY ?class LIMIT 10000
5332        "#;
5333        let out =
5334            LogicalPlan::explain(sparql, ExplainFormat::OptimisedSparql, false, None).unwrap();
5335        assert!(out.contains("?class a owl:Class"), "{out}");
5336        assert!(out.contains("?class a rdfs:Class"), "{out}");
5337        assert!(out.contains("?class rdfs:label ?label"), "{out}");
5338        assert!(out.contains("?class rdfs:subClassOf ?parent"), "{out}");
5339        assert!(
5340            !out.contains("22-rdf-syntax-ns#type"),
5341            "rdf:type must render as `a` in predicate position: {out}"
5342        );
5343        assert!(
5344            !out.contains("rdf-schema#"),
5345            "well-known IRIs must render prefixed: {out}"
5346        );
5347        assert!(out.ends_with("ORDER BY ASC(?class) LIMIT 10000"), "{out}");
5348    }
5349
5350    #[test]
5351    fn l1_sparql_aggregate_alias_hoists_into_select() {
5352        let sparql = "SELECT ?class (COUNT(?inst) AS ?c) WHERE { ?inst a ?class } GROUP BY ?class";
5353        let out =
5354            LogicalPlan::explain(sparql, ExplainFormat::OptimisedSparql, false, None).unwrap();
5355        // One flat SELECT — no group subselect, no internal hash-named
5356        // aggregate variable, no BIND.
5357        assert_eq!(
5358            out,
5359            "SELECT ?class (COUNT(?inst) AS ?c) WHERE { ?inst a ?class . } GROUP BY ?class"
5360        );
5361    }
5362
5363    #[test]
5364    fn l2_sparql_aggregate_alias_hoists_into_select() {
5365        let sparql = "SELECT ?class (COUNT(?inst) AS ?c) WHERE { ?inst a ?class } GROUP BY ?class";
5366        let out = LogicalPlan::explain(sparql, ExplainFormat::PlannedSparql, false, None).unwrap();
5367        assert_eq!(
5368            out,
5369            "SELECT ?class (COUNT(?inst) AS ?c) WHERE { ?inst a ?class } GROUP BY ?class"
5370        );
5371    }
5372
5373    #[test]
5374    fn l2_sparql_union_body_group_hoists_at_top_level() {
5375        let sparql = r#"
5376            SELECT ?class (COUNT(?inst) AS ?c) WHERE {
5377              { ?inst a ?class } UNION { ?class a <http://www.w3.org/2002/07/owl#Class> }
5378              FILTER ISIRI(?class)
5379              OPTIONAL { ?class <http://www.w3.org/2000/01/rdf-schema#label> ?label }
5380            } GROUP BY ?class
5381        "#;
5382        let out = LogicalPlan::explain(sparql, ExplainFormat::PlannedSparql, false, None).unwrap();
5383        assert!(
5384            out.starts_with("SELECT ?class (COUNT(?inst) AS ?c) WHERE {"),
5385            "{out}"
5386        );
5387        assert!(out.ends_with("GROUP BY ?class"), "{out}");
5388        assert!(!out.contains("BIND("), "{out}");
5389        assert!(!out.contains("SELECT ?class ?c"), "{out}");
5390    }
5391
5392    #[test]
5393    fn l2_sparql_group_under_join_hoists_alias_inside_subselect() {
5394        let sparql = r#"
5395            SELECT ?s ?c WHERE {
5396              ?s <http://ex/p> ?x .
5397              { SELECT ?class (COUNT(?m) AS ?c) WHERE { ?class <http://ex/m> ?m } GROUP BY ?class }
5398            }
5399        "#;
5400        let out = LogicalPlan::explain(sparql, ExplainFormat::PlannedSparql, false, None).unwrap();
5401        // The alias lives inside the group subselect; no external BIND over an
5402        // internal variable. Aggregator inputs are scope-renamed, so assert on
5403        // stable fragments only.
5404        assert!(out.contains("COUNT("), "{out}");
5405        assert!(out.contains("AS ?c)"), "{out}");
5406        assert!(!out.contains("BIND("), "{out}");
5407    }
5408
5409    #[test]
5410    fn l1_sparql_group_under_join_hoists_alias_inside_subselect() {
5411        let sparql = r#"
5412            SELECT ?s ?c WHERE {
5413              ?s <http://ex/p> ?x .
5414              { SELECT ?class (COUNT(?m) AS ?c) WHERE { ?class <http://ex/m> ?m } GROUP BY ?class }
5415            }
5416        "#;
5417        let out =
5418            LogicalPlan::explain(sparql, ExplainFormat::OptimisedSparql, false, None).unwrap();
5419        // Nested position: the alias hoists into the subselect's SELECT list.
5420        assert!(
5421            out.contains(
5422                "{ SELECT ?class (COUNT(?m) AS ?c) WHERE { ?class <http://ex/m> ?m . } GROUP BY ?class }"
5423            ),
5424            "{out}"
5425        );
5426        assert!(!out.contains("BIND("), "{out}");
5427    }
5428
5429    #[test]
5430    fn l1_sparql_global_aggregate_hoists_without_group_by() {
5431        let sparql = "SELECT (COUNT(*) AS ?count) WHERE { ?s a ?o }";
5432        let out =
5433            LogicalPlan::explain(sparql, ExplainFormat::OptimisedSparql, false, None).unwrap();
5434        assert_eq!(out, "SELECT (COUNT(*) AS ?count) WHERE { ?s a ?o . }");
5435    }
5436
5437    #[test]
5438    fn l0_sse_is_parse_only() {
5439        let sse = LogicalPlan::explain(
5440            r#"
5441            SELECT ?person ?city WHERE {
5442              ?person <http://ex/livesIn> ?city .
5443              ?city <http://ex/hasWeather> "Sunny" .
5444            }
5445            "#,
5446            ExplainFormat::Sse,
5447            false,
5448            None,
5449        )
5450        .unwrap();
5451        assert!(sse.contains("(project"), "{sse}");
5452        assert!(sse.contains("(bgp"), "{sse}");
5453        assert!(
5454            sse.find("livesIn").unwrap() < sse.find("Sunny").unwrap(),
5455            "L0 keeps query order: {sse}"
5456        );
5457    }
5458
5459    #[test]
5460    fn l2_collapses_scan_joins_to_bgp() {
5461        let sse = LogicalPlan::explain(
5462            "SELECT ?s WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?o }",
5463            ExplainFormat::Planned,
5464            false,
5465            None,
5466        )
5467        .unwrap();
5468        assert!(sse.contains("(bgp"), "{sse}");
5469        assert!(sse.contains("(triple"), "{sse}");
5470    }
5471
5472    #[test]
5473    fn estimate_preserves_each_scan_join() {
5474        let sse = LogicalPlan::explain(
5475            "SELECT ?s WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?x . ?s <http://ex/r> ?y }",
5476            ExplainFormat::Estimate,
5477            false,
5478            None,
5479        )
5480        .unwrap();
5481        assert_eq!(sse.matches("(join ").count(), 2, "{sse}");
5482        assert!(!sse.contains("(bgp"), "{sse}");
5483        assert_eq!(sse.matches("(scan ").count(), 3, "{sse}");
5484    }
5485
5486    #[test]
5487    fn estimate_path_shows_produced_and_unclamped_price() {
5488        // The path line carries both numbers like a scan: the planned
5489        // produced count and the unpushed pattern price — here the
5490        // both-ends-unbound nested-sequence alternation (10M per forward
5491        // branch, 1M per `r` branch), which also documents the number the
5492        // swap comparator and the fold consume before the push-aware clamp
5493        // narrows it. A *simple*-predicate alternation no longer produces a
5494        // path node at all (see `simple_alternation_lowers_to_union_of_scans`).
5495        let sse = LogicalPlan::explain(
5496            "SELECT ?f ?g WHERE { ?f (<http://ex/p>/<http://ex/q>)|<http://ex/r> ?g }",
5497            ExplainFormat::Estimate,
5498            false,
5499            None,
5500        )
5501        .unwrap();
5502        assert!(sse.contains("(path"), "{sse}");
5503        assert!(sse.contains("(price ~11000000)"), "{sse}");
5504    }
5505
5506    #[test]
5507    fn simple_alternation_lowers_to_union_of_scans() {
5508        // `:p|:q` leaves the walker entirely: UNION over two scan arms. The
5509        // scan estimator prices each free S/P scan at 2M (vs the old path
5510        // estimator's 1M per branch), so the union produced count is 4M.
5511        let sse = LogicalPlan::explain(
5512            "SELECT ?f ?g WHERE { ?f <http://ex/p>|<http://ex/q> ?g }",
5513            ExplainFormat::Estimate,
5514            false,
5515            None,
5516        )
5517        .unwrap();
5518        assert!(!sse.contains("(path"), "no path node may remain: {sse}");
5519        assert!(sse.contains("(union ~4000000"), "{sse}");
5520        assert_eq!(sse.matches("(scan ").count(), 2, "{sse}");
5521        assert_eq!(
5522            sse.matches("(price ~2000000)").count(),
5523            2,
5524            "each arm priced at the free scan price: {sse}"
5525        );
5526    }
5527
5528    #[test]
5529    fn l0_ask_has_no_injected_slice() {
5530        let sse = LogicalPlan::explain(
5531            r#"ASK WHERE { ?s <http://ex/p> ?o }"#,
5532            ExplainFormat::Sse,
5533            false,
5534            None,
5535        )
5536        .unwrap();
5537        assert!(sse.contains("(ask"), "{sse}");
5538        assert!(
5539            !sse.contains("(slice"),
5540            "L0 ASK should not inject LIMIT 1: {sse}"
5541        );
5542    }
5543
5544    #[test]
5545    fn l1_ask_injects_slice() {
5546        let sse = LogicalPlan::explain(
5547            r#"ASK WHERE { ?s <http://ex/p> ?o }"#,
5548            ExplainFormat::Optimised,
5549            false,
5550            None,
5551        )
5552        .unwrap();
5553        assert!(sse.contains("(ask"), "{sse}");
5554        assert!(sse.contains("(slice"), "L1 ASK should show LIMIT 1: {sse}");
5555    }
5556
5557    #[test]
5558    fn l1_does_not_apply_incoming_bound_optional_reorder() {
5559        let sparql = r#"
5560            SELECT ?rack ?server WHERE {
5561              ?rack a <http://ex/Rack> .
5562              OPTIONAL {
5563                ?server a <http://ex/Server> .
5564                ?server <http://ex/locatedIn> ?rack .
5565              }
5566            }
5567        "#;
5568        let l1 = LogicalPlan::explain(sparql, ExplainFormat::Optimised, false, None).unwrap();
5569        let optional = l1.split("(leftjoin").nth(1).unwrap_or(&l1);
5570        let type_at = optional.find("Server").expect("type triple");
5571        let fk_at = optional.find("locatedIn").expect("fk triple");
5572        assert!(
5573            type_at < fk_at,
5574            "L1 must not apply IncomingBound OPTIONAL reorder: {l1}"
5575        );
5576
5577        let l2 = LogicalPlan::explain(sparql, ExplainFormat::Planned, false, None).unwrap();
5578        let leftjoin = l2.split("(leftjoin").nth(1).unwrap_or(&l2);
5579        let type_at = leftjoin
5580            .find(&encoded_iri_sse("http://ex/Server"))
5581            .expect("type triple");
5582        let fk_at = leftjoin
5583            .find(&encoded_iri_sse("http://ex/locatedIn"))
5584            .expect("fk triple");
5585        assert!(
5586            fk_at < type_at,
5587            "L2 PlanNode should put incoming-bound :locatedIn first: {l2}"
5588        );
5589    }
5590
5591    #[test]
5592    fn l2_sparql_collapses_scan_joins_and_omits_physical_hints() {
5593        let sparql = LogicalPlan::explain(
5594            "SELECT ?s WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?o }",
5595            ExplainFormat::PlannedSparql,
5596            false,
5597            None,
5598        )
5599        .unwrap();
5600        assert!(sparql.contains("SELECT"), "{sparql}");
5601        assert!(sparql.contains("<#"), "{sparql}");
5602        assert!(sparql.contains("?s"), "{sparql}");
5603        assert!(sparql.contains("?o"), "{sparql}");
5604        assert!(!sparql.contains("(bgp"), "{sparql}");
5605        assert!(!sparql.contains("broadcast"), "{sparql}");
5606        assert!(!sparql.contains("~"), "{sparql}");
5607    }
5608
5609    #[test]
5610    fn l2_sparql_omits_group_by_for_global_aggregate() {
5611        let sparql = LogicalPlan::explain(
5612            "SELECT (COUNT(*) AS ?count) WHERE { ?s a ?o }",
5613            ExplainFormat::PlannedSparql,
5614            false,
5615            None,
5616        )
5617        .unwrap();
5618        assert!(!sparql.contains("GROUP BY"), "{sparql}");
5619        assert!(sparql.contains("COUNT(*)"), "{sparql}");
5620        spargebra::SparqlParser::new()
5621            .parse_query(&sparql)
5622            .unwrap_or_else(|error| panic!("planned SPARQL should parse: {error}\n{sparql}"));
5623    }
5624
5625    #[test]
5626    fn l2_sparql_preserves_describe_targets() {
5627        let sparql = LogicalPlan::explain(
5628            "DESCRIBE <http://ex/alice> WHERE { <http://ex/alice> a ?type }",
5629            ExplainFormat::PlannedSparql,
5630            false,
5631            None,
5632        )
5633        .unwrap();
5634        assert!(
5635            sparql.starts_with("DESCRIBE <http://ex/alice> WHERE"),
5636            "{sparql}"
5637        );
5638        assert!(!sparql.starts_with("DESCRIBE *"), "{sparql}");
5639    }
5640
5641    #[test]
5642    fn l2_sparql_expands_describe_star_projection() {
5643        let sparql = LogicalPlan::explain(
5644            "DESCRIBE * WHERE { ?resource a ?type }",
5645            ExplainFormat::PlannedSparql,
5646            false,
5647            None,
5648        )
5649        .unwrap();
5650        assert!(
5651            sparql.starts_with("DESCRIBE ?resource ?type WHERE"),
5652            "{sparql}"
5653        );
5654    }
5655
5656    #[test]
5657    fn l1_sparql_preserves_describe_targets() {
5658        let sparql = LogicalPlan::explain(
5659            "DESCRIBE <http://ex/alice> WHERE { <http://ex/alice> a ?type } LIMIT 2",
5660            ExplainFormat::OptimisedSparql,
5661            false,
5662            None,
5663        )
5664        .unwrap();
5665        assert!(
5666            sparql.starts_with("DESCRIBE <http://ex/alice> WHERE"),
5667            "{sparql}"
5668        );
5669        assert!(!sparql.contains(" AS ?"), "{sparql}");
5670        assert!(sparql.ends_with("LIMIT 2"), "{sparql}");
5671        spargebra::SparqlParser::new()
5672            .parse_query(&sparql)
5673            .unwrap_or_else(|error| panic!("optimised SPARQL should parse: {error}\n{sparql}"));
5674    }
5675
5676    #[test]
5677    fn l2_prints_distinct_and_select_distinct() {
5678        let sse = LogicalPlan::explain(
5679            "SELECT DISTINCT ?s WHERE { ?s <http://ex/p> ?o } LIMIT 5",
5680            ExplainFormat::Planned,
5681            false,
5682            None,
5683        )
5684        .unwrap();
5685        assert!(sse.contains("(distinct"), "{sse}");
5686        assert!(sse.contains("(slice"), "{sse}");
5687
5688        let sparql = LogicalPlan::explain(
5689            "SELECT DISTINCT ?s WHERE { ?s <http://ex/p> ?o } LIMIT 5",
5690            ExplainFormat::PlannedSparql,
5691            false,
5692            None,
5693        )
5694        .unwrap();
5695        assert!(sparql.contains("SELECT DISTINCT"), "{sparql}");
5696        assert!(sparql.contains("LIMIT 5"), "{sparql}");
5697    }
5698
5699    #[test]
5700    fn l2_sparql_shows_order_by_before_offset_limit() {
5701        let sparql = LogicalPlan::explain(
5702            "SELECT DISTINCT ?s WHERE { ?s <http://ex/p> ?o } ORDER BY DESC(?s) LIMIT 5 OFFSET 2",
5703            ExplainFormat::PlannedSparql,
5704            false,
5705            None,
5706        )
5707        .unwrap();
5708        assert!(sparql.contains("SELECT DISTINCT"), "{sparql}");
5709        let order_at = sparql
5710            .find("ORDER BY DESC(?s)")
5711            .unwrap_or_else(|| panic!("missing ORDER BY: {sparql}"));
5712        let where_at = sparql.find("} ").expect("WHERE close");
5713        assert!(order_at > where_at, "ORDER BY after WHERE: {sparql}");
5714        let offset_at = sparql.find("OFFSET 2").expect("OFFSET");
5715        let limit_at = sparql.find("LIMIT 5").expect("LIMIT");
5716        assert!(order_at < offset_at && offset_at < limit_at, "{sparql}");
5717    }
5718
5719    #[test]
5720    fn l2_sparql_shows_order_by_without_slice_or_distinct() {
5721        let sparql = LogicalPlan::explain(
5722            "SELECT ?s WHERE { ?s <http://ex/p> ?o } ORDER BY ?s",
5723            ExplainFormat::PlannedSparql,
5724            false,
5725            None,
5726        )
5727        .unwrap();
5728        assert!(
5729            sparql.ends_with("ORDER BY ASC(?s)"),
5730            "bare ORDER BY must survive the peel: {sparql}"
5731        );
5732    }
5733
5734    #[test]
5735    fn l2_sparql_subselect_shows_order_by() {
5736        let sparql = LogicalPlan::explain(
5737            "SELECT ?s WHERE { { SELECT ?s WHERE { ?s <http://ex/p> ?o } ORDER BY ?s LIMIT 2 } }",
5738            ExplainFormat::PlannedSparql,
5739            false,
5740            None,
5741        )
5742        .unwrap();
5743        assert!(
5744            sparql.contains("ORDER BY ASC(?s) OFFSET 0 LIMIT 2"),
5745            "subselect ORDER BY belongs inside its braces: {sparql}"
5746        );
5747    }
5748
5749    #[test]
5750    fn l2_sparql_type_iri_is_a_only_in_predicate_position() {
5751        // Subject position: `a` is a syntax error there, so the type IRI
5752        // renders as `rdf:type`.
5753        let subject = LogicalPlan::explain(
5754            "SELECT * WHERE { <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?p ?o }",
5755            ExplainFormat::PlannedSparql,
5756            false,
5757            None,
5758        )
5759        .unwrap();
5760        assert!(subject.contains("rdf:type ?p ?o"), "{subject}");
5761        assert!(!subject.contains(" a ?p"), "{subject}");
5762
5763        // Predicate position keeps the `a` keyword.
5764        let predicate = LogicalPlan::explain(
5765            "SELECT * WHERE { ?s a ?o }",
5766            ExplainFormat::PlannedSparql,
5767            false,
5768            None,
5769        )
5770        .unwrap();
5771        assert!(predicate.contains("?s a ?o"), "{predicate}");
5772
5773        // VALUES cell and negated property set are not predicate position.
5774        let values = LogicalPlan::explain(
5775            "SELECT ?o WHERE { VALUES ?o { <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> } }",
5776            ExplainFormat::PlannedSparql,
5777            false,
5778            None,
5779        )
5780        .unwrap();
5781        assert!(values.contains("(rdf:type)"), "{values}");
5782        assert!(!values.contains("(a)"), "{values}");
5783        let nps = LogicalPlan::explain(
5784            "SELECT ?s ?o WHERE { ?s !<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?o }",
5785            ExplainFormat::PlannedSparql,
5786            false,
5787            None,
5788        )
5789        .unwrap();
5790        assert!(nps.contains("!(rdf:type)"), "{nps}");
5791    }
5792
5793    #[test]
5794    fn l1_sse_keeps_from_named() {
5795        let sse = LogicalPlan::explain(
5796            "DESCRIBE <http://ex/alice> FROM NAMED <http://ex/g1> WHERE { ?s ?p ?o }",
5797            ExplainFormat::Optimised,
5798            false,
5799            None,
5800        )
5801        .unwrap();
5802        assert!(
5803            sse.contains("(named <http://ex/g1>)"),
5804            "Optimised SSE must keep FROM NAMED: {sse}"
5805        );
5806    }
5807
5808    #[test]
5809    fn l1_sparql_keeps_from_named_on_describe() {
5810        let sparql = LogicalPlan::explain(
5811            "DESCRIBE <http://ex/alice> FROM NAMED <http://ex/g1> WHERE { ?s ?p ?o }",
5812            ExplainFormat::OptimisedSparql,
5813            false,
5814            None,
5815        )
5816        .unwrap();
5817        assert!(sparql.contains("FROM NAMED <http://ex/g1>"), "{sparql}");
5818        spargebra::SparqlParser::new()
5819            .parse_query(&sparql)
5820            .unwrap_or_else(|error| panic!("optimised SPARQL should parse: {error}\n{sparql}"));
5821    }
5822
5823    #[test]
5824    fn planned_describe_from_named_has_no_default_graph_scan() {
5825        let sse = LogicalPlan::explain(
5826            "DESCRIBE ?s FROM NAMED <http://ex/g1> WHERE { ?s ?p ?o }",
5827            ExplainFormat::Planned,
5828            false,
5829            None,
5830        )
5831        .unwrap();
5832        assert!(
5833            !sse.contains("DEFAULT"),
5834            "empty SPARQL default must not scan RDF DefaultGraph: {sse}"
5835        );
5836        assert!(sse.contains("(table"), "empty default BGP is VALUES: {sse}");
5837    }
5838
5839    #[test]
5840    fn planned_default_union_shows_merge_default_graph() {
5841        let options = ExplainOptions {
5842            default_union: true,
5843            ..ExplainOptions::default()
5844        };
5845        let select = LogicalPlan::explain_with(
5846            "SELECT ?s WHERE { ?s ?p ?o }",
5847            ExplainFormat::Planned,
5848            false,
5849            None,
5850            &options,
5851        )
5852        .unwrap();
5853        assert!(
5854            select.contains("(merge_default_graph)"),
5855            "SELECT --default-union: {select}"
5856        );
5857        assert!(
5858            !select.contains("DEFAULT"),
5859            "AllGraphs is unbound G, not RDF DefaultGraph: {select}"
5860        );
5861
5862        let describe = LogicalPlan::explain_with(
5863            "DESCRIBE ?s WHERE { ?s ?p ?o }",
5864            ExplainFormat::Planned,
5865            false,
5866            None,
5867            &options,
5868        )
5869        .unwrap();
5870        assert!(
5871            describe.contains("(merge_default_graph)"),
5872            "DESCRIBE --default-union: {describe}"
5873        );
5874    }
5875
5876    #[test]
5877    fn planned_protocol_named_only_empties_default_despite_from() {
5878        let options = ExplainOptions {
5879            protocol_named_graphs: vec!["http://ex/g2".into()],
5880            ..ExplainOptions::default()
5881        };
5882        let sse = LogicalPlan::explain_with(
5883            "SELECT ?s FROM <http://ex/g1> WHERE { ?s ?p ?o }",
5884            ExplainFormat::Planned,
5885            false,
5886            None,
5887            &options,
5888        )
5889        .unwrap();
5890        assert!(
5891            !sse.contains("DEFAULT"),
5892            "protocol named-only overrides FROM: {sse}"
5893        );
5894        assert!(sse.contains("(table"), "empty default BGP is VALUES: {sse}");
5895    }
5896    #[test]
5897    fn estimate_shows_exact_and_pre_filter_eager_comparisons() {
5898        let exact = LogicalPlan::explain(
5899            r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y >= 1967 && ?y <= 1971) }"#,
5900            ExplainFormat::Estimate,
5901            false,
5902            None,
5903        )
5904        .unwrap();
5905        assert!(exact.contains("(eager exact"), "{exact}");
5906        assert!(exact.contains("(O >= 1967)"), "{exact}");
5907        assert!(exact.contains("(O <= 1971)"), "{exact}");
5908        assert!(!exact.contains("(filter"), "{exact}");
5909
5910        let pre = LogicalPlan::explain(
5911            r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y > "abcdef") }"#,
5912            ExplainFormat::Estimate,
5913            false,
5914            None,
5915        )
5916        .unwrap();
5917        assert!(pre.contains("(eager pre-filter (O > \"abcdef\"))"), "{pre}");
5918        assert!(pre.contains("(filter"), "{pre}");
5919
5920        let mixed = LogicalPlan::explain(
5921            r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y >= 1967 && ?y > "abcdef") }"#,
5922            ExplainFormat::Estimate,
5923            false,
5924            None,
5925        )
5926        .unwrap();
5927        assert!(mixed.contains("(eager exact (O >= 1967))"), "{mixed}");
5928        assert!(
5929            mixed.contains("(eager pre-filter (O > \"abcdef\"))"),
5930            "{mixed}"
5931        );
5932        assert!(mixed.contains("(filter"), "{mixed}");
5933    }
5934
5935    #[test]
5936    fn planned_names_a_bare_scan_that_carries_eager_comparisons() {
5937        let out = LogicalPlan::explain(
5938            r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y >= 1967) }"#,
5939            ExplainFormat::Planned,
5940            false,
5941            None,
5942        )
5943        .unwrap();
5944        assert!(out.contains("(scan (triple"), "{out}");
5945        assert!(out.contains("(eager exact (O >= 1967))"), "{out}");
5946    }
5947    #[test]
5948    fn planned_sparql_appends_exact_eager_filters_after_the_scan() {
5949        let compact = LogicalPlan::explain(
5950            r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y >= 1967 && ?y <= 1971) }"#,
5951            ExplainFormat::PlannedSparql,
5952            false,
5953            None,
5954        )
5955        .unwrap();
5956        assert!(compact.contains("FILTER(?y >= 1967)"), "{compact}");
5957        assert!(compact.contains("FILTER(?y <= 1971)"), "{compact}");
5958
5959        let pretty = LogicalPlan::explain(
5960            r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y >= 1967) }"#,
5961            ExplainFormat::PlannedSparql,
5962            true,
5963            None,
5964        )
5965        .unwrap();
5966        assert!(pretty.contains("\n  FILTER(?y >= 1967)"), "{pretty}");
5967    }
5968
5969    #[test]
5970    fn planned_sparql_does_not_repeat_a_pre_filter() {
5971        let compact = LogicalPlan::explain(
5972            r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y > "abcdef") }"#,
5973            ExplainFormat::PlannedSparql,
5974            false,
5975            None,
5976        )
5977        .unwrap();
5978        assert!(compact.contains("FILTER((?y > \"abcdef\"))"), "{compact}");
5979        assert_eq!(
5980            compact.matches("FILTER(").count(),
5981            1,
5982            "the surviving Filter owns the pre-filter once: {compact}"
5983        );
5984    }
5985
5986    #[test]
5987    fn planned_sparql_shows_exact_and_pre_filter_side_by_side() {
5988        let compact = LogicalPlan::explain(
5989            r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y >= 1967 && ?y > "abcdef") }"#,
5990            ExplainFormat::PlannedSparql,
5991            false,
5992            None,
5993        )
5994        .unwrap();
5995        assert!(compact.contains("FILTER(?y >= 1967)"), "{compact}");
5996        assert!(compact.contains("FILTER((?y > \"abcdef\"))"), "{compact}");
5997        assert_eq!(compact.matches("FILTER(").count(), 2, "{compact}");
5998    }
5999
6000    /// With the slot comparison switch off, planning stamps nothing: the scan
6001    /// carries no `(eager …)` and the planned SPARQL shows the query's own
6002    /// `FILTER` once. That is the pre-feature rendering, which is what makes
6003    /// the switch a clean A/B.
6004    #[test]
6005    fn explain_with_the_switch_off_shows_no_eager_stamp() {
6006        let off =
6007            crate::context::QueryContext::from_snapshot(waratah_storage::SnapshotId::latest())
6008                .with_eager_scan_filter(false);
6009        let query = r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y >= 1967) }"#;
6010        let options = ExplainOptions::default();
6011
6012        let planned = LogicalPlan::explain_with_context(
6013            query,
6014            ExplainFormat::Planned,
6015            false,
6016            None,
6017            &off,
6018            &options,
6019        )
6020        .unwrap();
6021        assert!(
6022            !planned.contains("eager"),
6023            "the switch must leave no eager stamp on the scan: {planned}"
6024        );
6025        assert!(
6026            planned.contains("(filter "),
6027            "the conjunct must still be in the plan: {planned}"
6028        );
6029
6030        let sparql = LogicalPlan::explain_with_context(
6031            query,
6032            ExplainFormat::PlannedSparql,
6033            false,
6034            None,
6035            &off,
6036            &options,
6037        )
6038        .unwrap();
6039        assert_eq!(
6040            sparql.matches("FILTER(").count(),
6041            1,
6042            "the plan's own Filter owns the conjunct, so the scan appends none: {sparql}"
6043        );
6044    }
6045}