Skip to main content

waratah_compute/
solutions.rs

1//! Intermediate and final result sets.
2//!
3//! [`EncodedSolutions`] is what flows between scans and joins: variable columns
4//! of query-local [`waratah_exec::TermId`]s, never raw strings. Internally it
5//! is a columnar [`waratah_exec::TermBatch`]; production joins use
6//! [`waratah_exec::hash_join_columnar`] /
7//! [`waratah_exec::left_hash_join_columnar`] /
8//! [`waratah_exec::shuffle_hash_join`]. [`QueryResults`] is the materialized
9//! end of the pipeline.
10
11use std::fmt::Write as _;
12use std::path::PathBuf;
13use std::sync::{Arc, OnceLock};
14
15use rustc_hash::FxHashSet;
16use waratah_exec::{
17    DEFAULT_SHUFFLE_PARTITIONS, DistinctState, ExecError, JoinBuild, JoinCursor,
18    LeftJoinProbeDecision, LeftJoinProbeMark, SemiJoinSet, TermBatch, TermColumn, TermDict, TermId,
19    counted_presence_encoded_term, gather_left_join_indices_columnar, hash_join_build,
20    hash_join_columnar, hash_join_columnar_capped, left_hash_join_columnar,
21    left_hash_join_columnar_indices, shuffle_hash_join,
22};
23use waratah_proto::PatternSlot;
24use waratah_storage::{
25    DomainScanCountHit, DomainScanHit, ENCODED_TERM_TRUE, EncodedQuad, EncodedTerm,
26    IndexPermutation, StrBlobMap, StrHashMap, Term, Variable,
27};
28
29use crate::context::{LogLevel, QueryContext};
30use crate::error::ComputeError;
31use crate::expr::ExprEvalEnv;
32use crate::filter::{FilterRow, pair_filter_row};
33use crate::plan::{DomainScanKind, HeadScanKind, ScanOp, scan_slot_variable};
34
35/// Variable-keyed columnar solutions of interned TermIds.
36///
37/// Rows may live in `batch` and/or in TermId page files ([`Self::is_parked`]).
38/// Random-access methods hydrate files into RAM once; join chunking streams
39/// pages without loading the full table.
40#[derive(Debug)]
41pub struct EncodedSolutions {
42    dict: Arc<TermDict>,
43    variables: Vec<Variable>,
44    batch: TermBatch,
45    spill: Option<Arc<SpillIndex>>,
46    loaded: Arc<OnceLock<TermBatch>>,
47}
48
49/// Column-major TermId pages on disk, same schema / dict as the tail batch.
50#[derive(Debug, Clone)]
51struct SpillIndex {
52    files: Vec<PathBuf>,
53    n_rows: usize,
54}
55
56fn assembled(dict: Arc<TermDict>, variables: Vec<Variable>, batch: TermBatch) -> EncodedSolutions {
57    EncodedSolutions {
58        dict,
59        variables,
60        batch,
61        spill: None,
62        loaded: Arc::new(OnceLock::new()),
63    }
64}
65
66impl Clone for EncodedSolutions {
67    fn clone(&self) -> Self {
68        Self {
69            dict: Arc::clone(&self.dict),
70            variables: self.variables.clone(),
71            batch: self.batch.clone(),
72            spill: self.spill.clone(),
73            loaded: Arc::clone(&self.loaded),
74        }
75    }
76}
77
78impl PartialEq for EncodedSolutions {
79    fn eq(&self, other: &Self) -> bool {
80        if self.variables != other.variables || self.len() != other.len() {
81            return false;
82        }
83        if Arc::ptr_eq(&self.dict, &other.dict) {
84            let (Ok(left), Ok(right)) = (self.hydrated_batch(), other.hydrated_batch()) else {
85                return false;
86            };
87            return left == right;
88        }
89        (0..self.len()).all(|row| {
90            self.variables.iter().all(|variable| {
91                matches!(
92                    (self.get(row, variable), other.get(row, variable)),
93                    (Ok(left), Ok(right)) if left == right
94                )
95            })
96        })
97    }
98}
99
100/// Index lists from an OPTIONAL probe, before early/deferred ground Diff-once / gather.
101#[derive(Debug, Clone)]
102pub struct LeftJoinIndices {
103    /// Output variable order (left then right-carry).
104    pub variables: Vec<Variable>,
105    /// Right columns appended to the output.
106    pub right_carry: Vec<usize>,
107    /// Soft reconcile column pairs.
108    pub soft_pairs: Vec<(usize, usize)>,
109    /// Left row indexes for output candidates.
110    pub left_indices: Vec<u32>,
111    /// Right row index (`None` = unbound miss).
112    pub right_indices: Vec<Option<u32>>,
113    /// Encoded early-probe outcome per index entry (aligned with left/right).
114    pub early_marks: Vec<LeftJoinProbeMark>,
115}
116
117/// Early OPTIONAL probe shared by [`EncodedSolutions::left_join`] and
118/// [`EncodedSolutions::left_join_indices`]: `pair_filter_row` → exec decision.
119fn left_join_probe_decision(
120    left: &EncodedSolutions,
121    left_row: usize,
122    right: &EncodedSolutions,
123    right_row: usize,
124    expression: &spargebra::algebra::Expression,
125    env: &ExprEvalEnv,
126) -> Result<LeftJoinProbeDecision, ExecError> {
127    let row = pair_filter_row(left, left_row, right, right_row, expression, env).map_err(
128        |err| match err {
129            ComputeError::UnsupportedSparql(msg) => ExecError::ProbeFilter(msg),
130            other => ExecError::ProbeFilter(other.to_string()),
131        },
132    )?;
133    Ok(match row {
134        FilterRow::Keep => LeftJoinProbeDecision::AcceptKeep,
135        FilterRow::NeedsResolve => LeftJoinProbeDecision::AcceptNeedsResolve,
136        FilterRow::Drop => LeftJoinProbeDecision::Reject,
137    })
138}
139
140impl EncodedSolutions {
141    /// Shared intern table for this solution table.
142    pub fn dict(&self) -> Arc<TermDict> {
143        Arc::clone(&self.dict)
144    }
145
146    /// Project onto a subselect boundary schema: keep `variables` columns in
147    /// order; a projected name the inner plan does not produce becomes an
148    /// all-unbound column. Dropping inner-only columns is what makes the
149    /// [`crate::plan::PlanNode::SubSelect`] boundary opaque to the outer query.
150    pub(crate) fn project_to(&self, variables: &[Variable]) -> Result<Self, ComputeError> {
151        let len = self.len();
152        if variables.is_empty() {
153            // Fully-pruned boundary: the subselect only contributes row
154            // multiplicity to an outer cross product, so the zero-width
155            // batch must keep the inner row count.
156            return Ok(assembled(
157                Arc::clone(&self.dict),
158                Vec::new(),
159                TermBatch::from_id_rows(0, vec![Vec::new(); len])?,
160            ));
161        }
162        let mut columns = Vec::with_capacity(variables.len());
163        for variable in variables {
164            columns.push(
165                self.column(variable)?
166                    .cloned()
167                    .unwrap_or_else(|| TermColumn::unbound(len)),
168            );
169        }
170        Ok(assembled(
171            Arc::clone(&self.dict),
172            variables.to_vec(),
173            TermBatch::try_new(columns)?,
174        ))
175    }
176
177    /// Project scan rows onto **live** and **counted** variables that the scan binds.
178    ///
179    /// Slot `Option`s stay set even when a name is dead. Repeated names
180    /// (`?x :p ?x`) still build equality pairs on the **quad** and drop rows
181    /// whose slots disagree. Live names and counted names (`COUNT(?v)` /
182    /// plain `COUNT(*)` multiplicity) are included in the TermId schema;
183    /// other dead names are omitted.
184    ///
185    /// Merge-default scans (`ScanOp::merge_default_graph`) already unique S/P/O on
186    /// storage and rewrite G to [`EncodedTerm::DefaultGraph`]. This projection
187    /// still ignores G when `scan.graph` is unset — users never see that slot.
188    pub fn from_scan(
189        dict: Arc<TermDict>,
190        scan: &ScanOp,
191        rows: Vec<EncodedQuad>,
192    ) -> Result<Self, ComputeError> {
193        // Schema, column mapping, and repeat pairs all come from the scan's
194        // single output-slot derivation (`ScanOp::output_slots`), so this
195        // projection cannot drift from the page schema the memo key carries.
196        let out = scan.output_slots();
197        let variables: Vec<Variable> = out
198            .materialized
199            .iter()
200            .map(|(_, variable)| variable.clone())
201            .collect();
202        let columns: Vec<usize> = out
203            .materialized
204            .iter()
205            .map(|(slot, _)| *slot as usize)
206            .collect();
207        let repeats: Vec<(usize, usize)> = out
208            .repeats
209            .iter()
210            .map(|(a, b)| (*a as usize, *b as usize))
211            .collect();
212
213        // Same-name slots (`?x :p ?x`) are a row filter on the quad, then
214        // only the live/counted slots are interned. Dead slots are dropped
215        // without entering the dict.
216        let kept_rows: Vec<EncodedQuad> = if repeats.is_empty() {
217            rows
218        } else {
219            rows.into_iter()
220                .filter(|quad| {
221                    let slots = [
222                        &quad.subject,
223                        &quad.predicate,
224                        &quad.object,
225                        &quad.graph_name,
226                    ];
227                    repeats.iter().all(|(a, b)| slots[*a] == slots[*b])
228                })
229                .collect()
230        };
231
232        let batch = if columns.is_empty() {
233            TermBatch::zero_width(kept_rows.len())
234        } else {
235            let n = kept_rows.len();
236            let mut cols: Vec<Vec<EncodedTerm>> =
237                (0..columns.len()).map(|_| Vec::with_capacity(n)).collect();
238            for quad in kept_rows {
239                let EncodedQuad {
240                    subject,
241                    predicate,
242                    object,
243                    graph_name,
244                } = quad;
245                let mut slots = [
246                    Some(subject),
247                    Some(predicate),
248                    Some(object),
249                    Some(graph_name),
250                ];
251                for (out, &slot) in columns.iter().enumerate() {
252                    cols[out].push(
253                        slots[slot]
254                            .take()
255                            .expect("each projected quad slot is taken once"),
256                    );
257                }
258            }
259            let mut term_columns = Vec::with_capacity(columns.len());
260            for col in cols {
261                term_columns.push(TermColumn::from_terms(&dict, col)?);
262            }
263            TermBatch::try_new(term_columns)?
264        };
265        Ok(assembled(dict, variables, batch))
266    }
267
268    /// Build from `(constraint, head)` domain-scan hits.
269    ///
270    /// Columns follow S/P/O/G order: the constraint slot sorts before the
271    /// head slot except on `ObjectPreds` (head `?p`, constraint `?o`), and a
272    /// live grounded `?g` projects last as the bound graph constant. Const
273    /// constraints produce no constraint column; grounded-kept constraints
274    /// repeat the constant on every row.
275    pub fn from_domain_scan_hits(
276        dict: Arc<TermDict>,
277        scan: &ScanOp,
278        kind: DomainScanKind,
279        hits: &[DomainScanHit],
280    ) -> Result<Self, ComputeError> {
281        let columns = domain_rpc_page_columns(scan, kind);
282        let variables = domain_rpc_page_variables_from_columns(&columns, scan, kind);
283        debug_assert_eq!(variables.len(), columns.len());
284        let batch = if columns.is_empty() {
285            TermBatch::zero_width(hits.len())
286        } else {
287            let mut term_columns = Vec::with_capacity(columns.len());
288            for (_, source) in &columns {
289                let col = match source {
290                    DomainRpcColSource::Constant(_, constant) => {
291                        let id = dict.intern(constant.clone())?.as_u32();
292                        TermColumn::from_ids(vec![id; hits.len()])
293                    }
294                    DomainRpcColSource::Constraint | DomainRpcColSource::Head => {
295                        TermColumn::from_terms(
296                            &dict,
297                            hits.iter()
298                                .map(|hit| source.domain_value(hit).clone())
299                                .collect(),
300                        )?
301                    }
302                };
303                term_columns.push(col);
304            }
305            TermBatch::try_new(term_columns)?
306        };
307        Ok(assembled(dict, variables, batch))
308    }
309
310    /// Build from domain count hits by run-length expansion: `count` copies
311    /// of each pair's row, in key order. Page columns are
312    /// [`domain_rpc_count_page_columns`] — counted dead slots get a bound
313    /// placeholder so `Group` `COUNT(?v)` matches multiplicity without
314    /// broadcasting subject terms on the wire.
315    pub fn from_domain_count_hits(
316        dict: Arc<TermDict>,
317        scan: &ScanOp,
318        kind: DomainScanKind,
319        hits: &[DomainScanCountHit],
320    ) -> Result<Self, ComputeError> {
321        let columns = domain_rpc_count_page_columns(scan, kind);
322        let variables = domain_rpc_page_variables_from_columns(&columns, scan, kind);
323        debug_assert_eq!(variables.len(), columns.len());
324        let mut n_rows = 0usize;
325        let mut active_hits = 0usize;
326        for hit in hits {
327            n_rows += hit.count as usize;
328            if hit.count > 0 {
329                active_hits += 1;
330            }
331        }
332        // ask the TermDict impl which term is interned at TermId::COUNTED_PRESENCE
333        let presence_encoded_term = counted_presence_encoded_term();
334        // get the TermId for the presence encoded term, to use in the dummy cols
335        let presence_id = TermId::COUNTED_PRESENCE.as_u32();
336        let mut term_columns = Vec::with_capacity(columns.len());
337        for (_, source) in &columns {
338            if matches!(
339                source,
340                DomainRpcColSource::Constant(_, constant) if *constant == presence_encoded_term
341            ) {
342                term_columns.push(TermColumn::from_ids(vec![presence_id; n_rows]));
343                continue;
344            }
345            term_columns.push(Self::domain_count_column(
346                &dict,
347                source,
348                hits,
349                n_rows,
350                active_hits,
351            )?);
352        }
353        let batch = TermBatch::try_new(term_columns)?;
354        Ok(assembled(dict, variables, batch))
355    }
356
357    /// Build one expanded count-scan column without interning repeated rows.
358    fn domain_count_column(
359        dict: &TermDict,
360        source: &DomainRpcColSource,
361        hits: &[DomainScanCountHit],
362        n_rows: usize,
363        active_hits: usize,
364    ) -> Result<TermColumn, ExecError> {
365        if let DomainRpcColSource::Constant(_, constant) = source {
366            if n_rows == 0 {
367                return Ok(TermColumn::empty());
368            }
369            let id = dict.intern(constant.clone())?.as_u32();
370            return Ok(TermColumn::from_ids(vec![id; n_rows]));
371        }
372
373        let encoded = |hit: &DomainScanCountHit| match source {
374            DomainRpcColSource::Constraint => hit.constraint.clone(),
375            DomainRpcColSource::Head => hit.term.clone(),
376            DomainRpcColSource::Constant(_, _) => unreachable!("constant handled above"),
377        };
378
379        if n_rows == active_hits {
380            // Every active run has length one. Keep the generic constructor's
381            // allocation shape so this case does not pay for a second expansion.
382            let mut cells = Vec::with_capacity(n_rows);
383            for hit in hits {
384                if hit.count > 0 {
385                    cells.push(Some(encoded(hit)));
386                }
387            }
388            return TermColumn::from_optional_terms(dict, cells);
389        }
390
391        // Intern one term per nonzero hit, then repeat only the resulting ids.
392        // Zero-length runs contribute no cells and must not intern their terms.
393        let mut hit_cells = Vec::with_capacity(active_hits);
394        for hit in hits {
395            if hit.count > 0 {
396                hit_cells.push(Some(encoded(hit)));
397            }
398        }
399        let hit_ids = dict.intern_column(hit_cells.into_iter())?;
400        let mut ids = Vec::with_capacity(n_rows);
401        for (hit, id) in hits.iter().filter(|hit| hit.count > 0).zip(hit_ids) {
402            ids.extend(std::iter::repeat_n(id, hit.count as usize));
403        }
404        Ok(TermColumn::from_ids(ids))
405    }
406
407    /// Build from bare axis-head terms. Live columns: the head, plus — on the
408    /// TSG classes scan — the implicit `rdf:type` predicate when a
409    /// grounded-kept `?p` is projected, and a grounded `?g` as the bound
410    /// graph constant. The bare gates keep every other slot dead.
411    pub fn from_head_terms(
412        dict: Arc<TermDict>,
413        scan: &ScanOp,
414        kind: HeadScanKind,
415        terms: &[EncodedTerm],
416    ) -> Result<Self, ComputeError> {
417        let head_var = scan_slot_variable(scan, kind.head_slot());
418        let use_head = head_var.is_some_and(|v| scan.is_live(v));
419
420        // (slot rank, term source) in output order.
421        let mut columns: Vec<(u8, DomainRpcColSource)> = Vec::new();
422        // TSG stores only rdf:type quads, so a live predicate name (kept by
423        // the identity fold for projection) projects as that constant on
424        // every row — the index's implicit P slot.
425        if kind.permutation() == IndexPermutation::Tsg
426            && let Some(variable) = scan_slot_variable(scan, PatternSlot::Predicate)
427            && scan.is_live(variable)
428        {
429            let term = scan
430                .pattern
431                .predicate
432                .clone()
433                .expect("TSG head scan binds rdf:type");
434            columns.push((
435                slot_rank(PatternSlot::Predicate),
436                DomainRpcColSource::Constant(variable.clone(), term),
437            ));
438        }
439        if use_head {
440            columns.push((slot_rank(kind.head_slot()), DomainRpcColSource::Head));
441        }
442        if let Some(constant) = grounded_graph_column(scan) {
443            columns.push((GRAPH_RANK, constant));
444        }
445        columns.sort_by_key(|(rank, _)| *rank);
446
447        let variables = columns
448            .iter()
449            .map(|(_, term)| match term {
450                DomainRpcColSource::Constant(variable, _) => variable.clone(),
451                DomainRpcColSource::Head => head_var.expect("live head variable").clone(),
452                DomainRpcColSource::Constraint => {
453                    unreachable!("bare head scans carry no constraint")
454                }
455            })
456            .collect::<Vec<Variable>>();
457        let batch = if columns.is_empty() {
458            TermBatch::zero_width(terms.len())
459        } else {
460            let mut term_columns = Vec::with_capacity(columns.len());
461            for (_, source) in &columns {
462                let col = match source {
463                    DomainRpcColSource::Constant(_, constant) => {
464                        let id = dict.intern(constant.clone())?.as_u32();
465                        TermColumn::from_ids(vec![id; terms.len()])
466                    }
467                    DomainRpcColSource::Head => TermColumn::from_terms(
468                        &dict,
469                        terms
470                            .iter()
471                            .map(|head| source.head_value(head).clone())
472                            .collect(),
473                    )?,
474                    DomainRpcColSource::Constraint => {
475                        unreachable!("bare head scans carry no constraint")
476                    }
477                };
478                term_columns.push(col);
479            }
480            TermBatch::try_new(term_columns)?
481        };
482        Ok(assembled(dict, variables, batch))
483    }
484
485    /// Build from fully bound rows.
486    pub fn from_bound_rows(
487        dict: Arc<TermDict>,
488        variables: Vec<Variable>,
489        rows: Vec<Vec<EncodedTerm>>,
490    ) -> Result<Self, ComputeError> {
491        let width = variables.len();
492        let batch = TermBatch::from_rows(&dict, width, rows)?;
493        Ok(assembled(dict, variables, batch))
494    }
495
496    /// Empty solution set over `variables`.
497    pub fn empty(dict: Arc<TermDict>, variables: Vec<Variable>) -> Self {
498        let width = variables.len();
499        assembled(dict, variables, TermBatch::empty(width))
500    }
501
502    /// Variables bound by these solutions, in column order.
503    pub fn variables(&self) -> &[Variable] {
504        &self.variables
505    }
506
507    /// Rows with unbound cells as `None` (for OPTIONAL / FILTER).
508    pub fn optional_rows(&self) -> Result<Vec<Vec<Option<EncodedTerm>>>, ComputeError> {
509        Ok(self.hydrated_batch()?.to_optional_rows(&self.dict))
510    }
511
512    /// Fill `out` with encoded terms for `row` (one dict lock). `out.len()` is width.
513    pub fn fill_optional_row(
514        &self,
515        row: usize,
516        out: &mut [Option<EncodedTerm>],
517    ) -> Result<(), ComputeError> {
518        self.hydrated_batch()?
519            .fill_optional_row(&self.dict, row, out);
520        Ok(())
521    }
522
523    /// Build from optional row cells (`None` = unbound).
524    pub fn from_optional_rows(
525        dict: Arc<TermDict>,
526        variables: Vec<Variable>,
527        rows: Vec<Vec<Option<EncodedTerm>>>,
528    ) -> Result<Self, ComputeError> {
529        let width = variables.len();
530        let batch = TermBatch::from_optional_rows(&dict, width, rows)?;
531        Ok(assembled(dict, variables, batch))
532    }
533
534    /// Wrap an existing TermId batch (same dict / schema).
535    pub(crate) fn from_batch(
536        dict: Arc<TermDict>,
537        variables: Vec<Variable>,
538        batch: TermBatch,
539    ) -> Self {
540        assembled(dict, variables, batch)
541    }
542
543    fn hydrated_batch(&self) -> Result<&TermBatch, ComputeError> {
544        if self.spill.is_none() {
545            return Ok(&self.batch);
546        }
547        if let Some(loaded) = self.loaded.get() {
548            return Ok(loaded);
549        }
550        let hydrated = crate::spill::hydrate_parked(self)?;
551        Ok(self.loaded.get_or_init(|| hydrated))
552    }
553
554    /// In-RAM tail (unflushed rows after parked files). Join paging uses this
555    /// plus [`Self::spill_files`] without hydrating.
556    pub(crate) fn tail_batch(&self) -> &TermBatch {
557        &self.batch
558    }
559
560    /// Consume an in-RAM table into its TermId batch. In-RAM only: a
561    /// parked table's rows live in its files, and this would return just
562    /// the un-flushed tail — the parallel merge's classification
563    /// (`spill_files().is_empty()`) guarantees it is never called on one.
564    pub(crate) fn into_tail_batch(self) -> TermBatch {
565        debug_assert!(
566            self.spill.is_none(),
567            "into_tail_batch on a parked table returns only the un-flushed tail"
568        );
569        self.batch
570    }
571
572    /// Parked page files, if this table was flushed under the memory budget.
573    pub(crate) fn spill_files(&self) -> &[PathBuf] {
574        self.spill
575            .as_ref()
576            .map(|s| s.files.as_slice())
577            .unwrap_or(&[])
578    }
579
580    /// Rows stored in parked files (not counting the RAM tail).
581    pub(crate) fn spill_rows(&self) -> usize {
582        self.spill.as_ref().map(|s| s.n_rows).unwrap_or(0)
583    }
584
585    /// True when pages sit on disk and have not been loaded for random access.
586    pub(crate) fn is_parked(&self) -> bool {
587        self.spill.is_some() && self.loaded.get().is_none()
588    }
589
590    /// Whether this table carries a spill index: rows were written to page
591    /// files, whether or not the table has since been hydrated.
592    ///
593    /// [`Self::is_parked`] is false for a hydrated parked table, but a caller
594    /// that changes the table's width must still treat that table as spilled —
595    /// every page file records the width it was written with.
596    pub(crate) fn is_spilled(&self) -> bool {
597        self.spill.is_some()
598    }
599
600    /// Rebuild from parked files plus an optional RAM tail.
601    pub(crate) fn from_parked(
602        dict: Arc<TermDict>,
603        variables: Vec<Variable>,
604        files: Vec<PathBuf>,
605        spill_rows: usize,
606        tail: TermBatch,
607    ) -> Self {
608        Self {
609            dict,
610            variables,
611            batch: tail,
612            spill: Some(Arc::new(SpillIndex {
613                files,
614                n_rows: spill_rows,
615            })),
616            loaded: Arc::new(OnceLock::new()),
617        }
618    }
619
620    /// Borrow the TermId batch (hydrates parked files on first random access).
621    pub(crate) fn batch(&self) -> Result<&TermBatch, ComputeError> {
622        self.hydrated_batch()
623    }
624
625    /// TermId payload bytes (`n_rows * width * 4`). Used to decide spill vs RAM.
626    pub(crate) fn nbytes(&self) -> u64 {
627        (self.len() as u64)
628            .saturating_mul(self.variables.len().max(1) as u64)
629            .saturating_mul(4)
630    }
631
632    /// Number of solutions.
633    pub fn len(&self) -> usize {
634        if let Some(full) = self.loaded.get() {
635            return full.len();
636        }
637        self.spill_rows().saturating_add(self.batch.len())
638    }
639
640    /// Whether there are no solutions.
641    pub fn is_empty(&self) -> bool {
642        self.len() == 0
643    }
644
645    /// Value of `variable` in `row`, if this set binds it.
646    ///
647    /// `Ok(None)` is unbound or a name this table does not carry. `Err` is a
648    /// hydrate failure on a parked table — not an unbound cell.
649    pub fn get(
650        &self,
651        row: usize,
652        variable: &Variable,
653    ) -> Result<Option<EncodedTerm>, ComputeError> {
654        Ok(self
655            .column(variable)?
656            .and_then(|col| col.term_at(&self.dict, row)))
657    }
658
659    /// Hydrated TermId table (loads parked pages once).
660    pub(crate) fn live_term_batch(&self) -> Result<&TermBatch, ComputeError> {
661        self.hydrated_batch()
662    }
663
664    /// Whether `variable` is bound in `row`.
665    pub fn is_bound(&self, row: usize, variable: &Variable) -> Result<bool, ComputeError> {
666        Ok(self.column(variable)?.is_some_and(|col| col.is_bound(row)))
667    }
668
669    /// Column for `variable`, if this set binds it.
670    ///
671    /// Missing schema names return `Ok(None)` without hydrating. Parked-file
672    /// I/O errors return `Err`.
673    pub fn column(&self, variable: &Variable) -> Result<Option<&TermColumn>, ComputeError> {
674        let Some(index) = self.variables.iter().position(|known| known == variable) else {
675            return Ok(None);
676        };
677        Ok(self.hydrated_batch()?.column(index).ok())
678    }
679
680    /// Left outer join for SPARQL `OPTIONAL` (Phase 9c).
681    ///
682    /// `early_filter` is folded into the Diff-once probe. Immediate gather fails
683    /// closed on NeedsResolve (see [`left_hash_join_columnar`]); callers that
684    /// need ground Diff-once for NeedsResolve must use [`Self::left_join_indices`].
685    pub fn left_join(
686        &self,
687        right: &Self,
688        hash_keys: &[Variable],
689        early_filter: Option<&spargebra::algebra::Expression>,
690        env: &ExprEvalEnv,
691    ) -> Result<Self, ComputeError> {
692        let (variables, right_carry, soft_pairs, left_keys, right_keys) =
693            self.left_join_layout(right, hash_keys);
694
695        let batch = if let Some(expression) = early_filter {
696            left_hash_join_columnar(
697                self.hydrated_batch()?,
698                right.hydrated_batch()?,
699                &left_keys,
700                &right_keys,
701                &right_carry,
702                &soft_pairs,
703                Some(&|left_row, right_row| {
704                    left_join_probe_decision(self, left_row, right, right_row, expression, env)
705                }),
706            )
707        } else {
708            left_hash_join_columnar(
709                self.hydrated_batch()?,
710                right.hydrated_batch()?,
711                &left_keys,
712                &right_keys,
713                &right_carry,
714                &soft_pairs,
715                None,
716            )
717        }
718        .map_err(ComputeError::from)?;
719
720        Ok(assembled(Arc::clone(&self.dict), variables, batch))
721    }
722
723    /// Diff-once index lists for OPTIONAL (before gather), with early probe marks.
724    pub fn left_join_indices(
725        &self,
726        right: &Self,
727        hash_keys: &[Variable],
728        early_filter: Option<&spargebra::algebra::Expression>,
729        env: &ExprEvalEnv,
730    ) -> Result<LeftJoinIndices, ComputeError> {
731        let (variables, right_carry, soft_pairs, left_keys, right_keys) =
732            self.left_join_layout(right, hash_keys);
733
734        let (left_indices, right_indices, early_marks) = if let Some(expression) = early_filter {
735            left_hash_join_columnar_indices(
736                self.hydrated_batch()?,
737                right.hydrated_batch()?,
738                &left_keys,
739                &right_keys,
740                &soft_pairs,
741                Some(&|left_row, right_row| {
742                    left_join_probe_decision(self, left_row, right, right_row, expression, env)
743                }),
744            )
745        } else {
746            left_hash_join_columnar_indices(
747                self.hydrated_batch()?,
748                right.hydrated_batch()?,
749                &left_keys,
750                &right_keys,
751                &soft_pairs,
752                None,
753            )
754        }
755        .map_err(ComputeError::from)?;
756
757        Ok(LeftJoinIndices {
758            variables,
759            right_carry,
760            soft_pairs,
761            left_indices,
762            right_indices,
763            early_marks,
764        })
765    }
766
767    /// Gather LeftJoin output from (possibly residual-filtered) index lists.
768    pub fn gather_left_join(
769        &self,
770        right: &Self,
771        indices: &LeftJoinIndices,
772    ) -> Result<Self, ComputeError> {
773        let batch = gather_left_join_indices_columnar(
774            self.hydrated_batch()?,
775            right.hydrated_batch()?,
776            &indices.left_indices,
777            &indices.right_indices,
778            &indices.right_carry,
779            &indices.soft_pairs,
780        )
781        .map_err(|err| {
782            ComputeError::UnsupportedSparql(format!("left join gather failed: {err}"))
783        })?;
784        Ok(assembled(
785            Arc::clone(&self.dict),
786            indices.variables.clone(),
787            batch,
788        ))
789    }
790
791    #[allow(clippy::type_complexity)]
792    fn left_join_layout(
793        &self,
794        right: &Self,
795        hash_keys: &[Variable],
796    ) -> (
797        Vec<Variable>,
798        Vec<usize>,
799        Vec<(usize, usize)>,
800        Vec<usize>,
801        Vec<usize>,
802    ) {
803        let mut variables = self.variables.clone();
804        let mut right_carry = Vec::new();
805        let mut soft_pairs = Vec::new();
806        for (column, variable) in right.variables.iter().enumerate() {
807            if let Some(left_col) = self.variables.iter().position(|known| known == variable) {
808                if !hash_keys.iter().any(|k| k == variable) {
809                    soft_pairs.push((left_col, column));
810                }
811            } else {
812                variables.push(variable.clone());
813                right_carry.push(column);
814            }
815        }
816        let left_keys = key_columns(&self.variables, hash_keys);
817        let right_keys = key_columns(&right.variables, hash_keys);
818        (variables, right_carry, soft_pairs, left_keys, right_keys)
819    }
820
821    /// Inner hash join with `right` on always-bound `hash_keys` (columnar kernel).
822    ///
823    /// An empty `hash_keys` list is a cartesian product (then soft reconcile for
824    /// shared maybe-unbound columns). The smaller side is the build side.
825    pub fn hash_join(&self, right: &Self, hash_keys: &[Variable]) -> Result<Self, ComputeError> {
826        self.join_with(right, hash_keys, JoinMode::Hash)
827    }
828
829    /// Probe `self` (left) against `right` for at most `max_out` output rows,
830    /// resuming at `cursor`. Builds the right HT into `build` when that slot is
831    /// empty; later pulls reuse it. `None` next-cursor means this left×right
832    /// pair is done.
833    pub fn hash_join_capped(
834        &self,
835        right: &Self,
836        hash_keys: &[Variable],
837        max_out: usize,
838        cursor: JoinCursor,
839        build: &mut Option<JoinBuild>,
840    ) -> Result<(Self, Option<JoinCursor>), ComputeError> {
841        let (variables, right_carry, soft_pairs, left_keys, right_keys) =
842            self.join_layout(right, hash_keys);
843        if build.is_none() {
844            *build = Some(
845                hash_join_build(right.hydrated_batch()?, &right_keys)
846                    .map_err(ComputeError::from)?,
847            );
848        }
849        let (batch, next) = hash_join_columnar_capped(
850            self.hydrated_batch()?,
851            right.hydrated_batch()?,
852            &left_keys,
853            &right_keys,
854            &right_carry,
855            &soft_pairs,
856            max_out,
857            cursor,
858            build.as_ref().expect("join build filled"),
859        )
860        .map_err(ComputeError::from)?;
861        Ok((assembled(Arc::clone(&self.dict), variables, batch), next))
862    }
863
864    /// Shuffle join: hash-partition both sides then join per bucket (Phase 9b).
865    pub fn shuffle_join(&self, right: &Self, hash_keys: &[Variable]) -> Result<Self, ComputeError> {
866        self.join_with(right, hash_keys, JoinMode::Shuffle)
867    }
868
869    /// SPARQL `UNION`: multiset concat after aligning to the name-union schema.
870    ///
871    /// Variables present on only one side are unbound (`None`) on rows from the
872    /// other side. Column order is left-first, then right-only names.
873    ///
874    /// A parked operand keeps its page files when the two schemas already
875    /// match; when they do not, both sides hydrate and the result is an in-RAM
876    /// table. Row order across a parked pair is unspecified — the row multiset
877    /// is exactly `left ++ right`, but a non-empty left-hand RAM tail is
878    /// emitted after the right-hand page files, because the tail is
879    /// structurally the table's last segment.
880    pub fn union(self, right: Self) -> Result<Self, ComputeError> {
881        let mut variables = self.variables.clone();
882        for variable in &right.variables {
883            if !variables.contains(variable) {
884                variables.push(variable.clone());
885            }
886        }
887        debug_assert!(
888            Arc::ptr_eq(&self.dict, &right.dict),
889            "UNION arms must share a TermDict"
890        );
891        if self.spill.is_some() || right.spill.is_some() {
892            return union_parked(self, right, variables);
893        }
894        let mut batch = TermBatch::with_capacity_rows(variables.len(), self.len() + right.len());
895        batch
896            .extend_aligned(self.hydrated_batch()?, &schema_map(&self, &variables))
897            .map_err(ComputeError::from)?;
898        batch
899            .extend_aligned(right.hydrated_batch()?, &schema_map(&right, &variables))
900            .map_err(ComputeError::from)?;
901        Ok(assembled(self.dict, variables, batch))
902    }
903
904    /// Append `rows` in place, widening the schema the way [`Self::union`] does.
905    ///
906    /// New names append at the END — [`Self::union`]'s schema rule — so the
907    /// rows already held are never re-laid-out: each new name gains an
908    /// all-unbound column at the current height, then the input is appended
909    /// with [`TermBatch::extend_aligned`]. An accumulator that consumes many
910    /// pages this way stays linear in the rows it has read, where calling
911    /// [`Self::union`] once per page rebuilds and re-copies the whole
912    /// accumulator every time.
913    ///
914    /// A spilled accumulator keeps its page files: its own RAM tail is flushed
915    /// first (so every accumulated row is a file before the input's rows
916    /// arrive), the input is brought to the accumulator's width and parked with
917    /// [`crate::spill::park_fully`], and the resulting file list is spliced
918    /// onto the accumulator's. The accumulator's own pages are never read
919    /// back, which is what keeps a wide union's peak at the budget plus one arm
920    /// instead of twice the accumulated table.
921    ///
922    /// Two cases still take the hydrating [`Self::union`]:
923    ///
924    /// * the input carries a name the accumulator does not — its page files
925    ///   were written at the old width, so taking the column means rewriting
926    ///   them;
927    /// * the accumulator has been hydrated by a reader — `park_fully` re-parks
928    ///   the RAM tail only, and a loaded table's tail is not its whole row set.
929    ///
930    /// Prefer [`Self::union`] over a whole pair at once when both inputs are
931    /// already in hand: it allocates the merged table at its final size, which
932    /// is fewer copies than growing here. This is for the accumulator that
933    /// cannot know its total, such as a slice's page loop.
934    pub(crate) fn absorb(&mut self, rows: Self, ctx: &QueryContext) -> Result<(), ComputeError> {
935        debug_assert!(
936            Arc::ptr_eq(&self.dict, &rows.dict),
937            "UNION arms must share a TermDict"
938        );
939        // Names the input adds, gathered without mutating `self.variables`:
940        // the widening fallback below must hand `union` the ORIGINAL width, or
941        // hydrating a spilled accumulator would read its pages at the wrong
942        // width.
943        let mut added: Vec<Variable> = Vec::new();
944        for variable in &rows.variables {
945            if !self.variables.contains(variable) && !added.contains(variable) {
946                added.push(variable.clone());
947            }
948        }
949
950        if !self.is_spilled() {
951            let added_count = added.len();
952            self.variables.extend(added);
953            if added_count > 0 {
954                self.batch.push_unbound_columns(added_count);
955            }
956            let map = schema_map(&rows, &self.variables);
957            self.batch
958                .extend_aligned(rows.hydrated_batch()?, &map)
959                .map_err(ComputeError::from)?;
960            return Ok(());
961        }
962
963        if !added.is_empty() || self.loaded.get().is_some() {
964            let dict = self.dict();
965            let left = std::mem::replace(self, Self::empty(dict, Vec::new()));
966            *self = left.union(rows)?;
967            return Ok(());
968        }
969
970        // Splice. The accumulator's own tail, if any, is flushed first: page
971        // files must stay ahead of every row that arrives later.
972        if !self.batch.is_empty() {
973            *self = crate::spill::park_fully(self, ctx)?;
974        }
975        // Bring the input to the accumulator's width, then park it. A
976        // same-order input keeps its own files; a reordered or narrower one is
977        // read once and rewritten at the wider width. Either way the
978        // accumulator is not read.
979        let parked_rows = if rows.variables == self.variables {
980            crate::spill::park_fully(&rows, ctx)?
981        } else {
982            let mut aligned = TermBatch::with_capacity_rows(self.variables.len(), rows.len());
983            aligned
984                .extend_aligned(rows.hydrated_batch()?, &schema_map(&rows, &self.variables))
985                .map_err(ComputeError::from)?;
986            let arm = Self::from_batch(Arc::clone(&self.dict), self.variables.clone(), aligned);
987            crate::spill::park_fully(&arm, ctx)?
988        };
989        let index = Arc::make_mut(self.spill.as_mut().expect("spilled accumulator"));
990        index
991            .files
992            .extend(parked_rows.spill_files().iter().cloned());
993        index.n_rows = index.n_rows.saturating_add(parked_rows.spill_rows());
994        let file_count = index.files.len();
995        if ctx.log_sink().enabled_at(LogLevel::Debug) {
996            ctx.log(
997                LogLevel::Debug,
998                &format!(
999                    "absorb-splice: rows={} width={} files={file_count}",
1000                    parked_rows.spill_rows(),
1001                    self.variables.len()
1002                ),
1003            );
1004        }
1005        Ok(())
1006    }
1007
1008    /// Append one already-interned column on the right edge, extending the
1009    /// schema by `variable`.
1010    ///
1011    /// Unlike the row-oriented `append_column` route in `query/join_kernels.rs`,
1012    /// the columns already held are untouched: no decode and no re-intern. That
1013    /// is safe only for an in-RAM table — a parked table's page files were
1014    /// written at the old width, so a column pushed onto the RAM tail would
1015    /// desynchronise them — and a parked table is refused rather than silently
1016    /// corrupted.
1017    pub(crate) fn push_term_column(
1018        mut self,
1019        variable: Variable,
1020        column: TermColumn,
1021    ) -> Result<Self, ComputeError> {
1022        if self.is_spilled() {
1023            return Err(ComputeError::Internal(
1024                "push_term_column on a spilled table".into(),
1025            ));
1026        }
1027        // A hydrated non-spilled table is not representable today (hydration
1028        // only happens for a spilled one, and hydration leaves `spill` set), but
1029        // the push appends to `batch` — the tail — while readers would take the
1030        // cached `loaded` batch, so a future hydration path must fail here
1031        // rather than silently hide the new column.
1032        debug_assert!(
1033            self.loaded.get().is_none(),
1034            "push_term_column on a hydrated table"
1035        );
1036        self.batch.push_column(column).map_err(ComputeError::from)?;
1037        self.variables.push(variable);
1038        Ok(self)
1039    }
1040
1041    /// Concatenate two solution sets that share a schema (batch refill).
1042    ///
1043    /// The schemas must match exactly — the same variables in the same column
1044    /// order. A caller whose arms may differ wants [`Self::union`], which
1045    /// widens the schema and pads missing columns as unbound; reaching this
1046    /// with mismatched schemas is a caller bug, so it is reported rather than
1047    /// repaired.
1048    ///
1049    /// "Share a schema" is about the column layout, not residency: either side
1050    /// may be parked, and a same-schema parked pair merges through the parked
1051    /// road (which may hydrate a side). Row order across a parked pair is
1052    /// unspecified — see [`Self::union`].
1053    pub fn concat(self, other: Self) -> Result<Self, ComputeError> {
1054        if self.variables != other.variables {
1055            return Err(ComputeError::Internal(format!(
1056                "concat requires identical schemas: left {:?}, right {:?}",
1057                self.variables, other.variables
1058            )));
1059        }
1060        self.union(other)
1061    }
1062
1063    /// SPARQL `Slice`: drop `start` rows, then keep `length` (`None` = the rest).
1064    ///
1065    /// Exact-range random access: returns **exactly**
1066    /// `min(length, len - start)` rows — never fewer while the range is
1067    /// non-empty. On a parked table this **hydrates**: the first call reads
1068    /// every spill page into RAM (cached on the table), so later calls are
1069    /// free but the memory is already spent.
1070    ///
1071    /// Misuse hazard: do not call this per-pull to page through a parked
1072    /// table (an OpenNode-style cursor). One call materializes the whole
1073    /// input just to serve one page — the full-hydration bug class the spill
1074    /// layer exists to prevent. Bounded paging belongs to
1075    /// [`crate::spill::take_slice`], which returns *at most* `length` rows
1076    /// without hydrating; that function has the opposite contract, so read
1077    /// its doc before swapping the two.
1078    pub fn slice_rows(&self, start: usize, length: Option<usize>) -> Result<Self, ComputeError> {
1079        let start = start.min(self.len());
1080        let end = match length {
1081            Some(n) => start.saturating_add(n).min(self.len()),
1082            None => self.len(),
1083        };
1084        self.gather(&(start..end).collect::<Vec<_>>())
1085    }
1086
1087    /// SPARQL `DISTINCT`: keep first-seen rows on `keys` (SELECT projection).
1088    ///
1089    /// Missing `keys` are treated as unbound in every row. Extra non-key columns
1090    /// are carried from the kept input rows.
1091    pub fn apply_distinct(
1092        &self,
1093        state: &mut DistinctState,
1094        keys: &[Variable],
1095    ) -> Result<Self, ComputeError> {
1096        let n = self.len();
1097        let mut dummies: Vec<TermColumn> = Vec::new();
1098        for variable in keys {
1099            if self.column(variable)?.is_none() {
1100                dummies.push(TermColumn::unbound(n));
1101            }
1102        }
1103        let mut dummy_i = 0;
1104        let mut refs: Vec<&TermColumn> = Vec::with_capacity(keys.len());
1105        for variable in keys {
1106            if let Some(col) = self.column(variable)? {
1107                refs.push(col);
1108            } else {
1109                refs.push(&dummies[dummy_i]);
1110                dummy_i += 1;
1111            }
1112        }
1113        let batch = state
1114            .filter_batch(self.hydrated_batch()?, &refs)
1115            .map_err(|err| ComputeError::UnsupportedSparql(format!("distinct failed: {err}")))?;
1116        Ok(assembled(
1117            Arc::clone(&self.dict),
1118            self.variables.clone(),
1119            batch,
1120        ))
1121    }
1122
1123    /// Gather rows by index (used by FILTER).
1124    pub fn gather(&self, indices: &[usize]) -> Result<Self, ComputeError> {
1125        if self.variables.is_empty() {
1126            return Ok(assembled(
1127                Arc::clone(&self.dict),
1128                Vec::new(),
1129                TermBatch::from_id_rows(0, vec![Vec::new(); indices.len()])
1130                    .expect("zero-width gather"),
1131            ));
1132        }
1133        let cols = self
1134            .hydrated_batch()?
1135            .columns()
1136            .iter()
1137            .map(|col| col.gather(indices))
1138            .collect();
1139        Ok(assembled(
1140            Arc::clone(&self.dict),
1141            self.variables.clone(),
1142            TermBatch::try_new(cols).expect("gather preserves width"),
1143        ))
1144    }
1145
1146    /// Keep only the rows whose `keys` tuple is bound in `set` — the semi-join
1147    /// probe side. The returned schema is this table's own, so a join whose
1148    /// right side carries nothing but keys keeps the `Join` node's declared
1149    /// output schema exactly.
1150    ///
1151    /// A missing key column is an internal error: the join invariant says every
1152    /// key is always bound on both sides, and the alternative — treating the
1153    /// whole row as a miss — would silently drop every row.
1154    pub(crate) fn semi_join_keep(
1155        &self,
1156        set: &SemiJoinSet,
1157        keys: &[Variable],
1158    ) -> Result<Self, ComputeError> {
1159        let mut cols = Vec::with_capacity(keys.len());
1160        for key in keys {
1161            match self.column(key)? {
1162                Some(col) => cols.push(col),
1163                None => {
1164                    return Err(ComputeError::Internal(format!(
1165                        "semi-join key {key} missing from the probe schema"
1166                    )));
1167                }
1168            }
1169        }
1170        let keep = set
1171            .probe_keep(self.hydrated_batch()?, &cols, false)
1172            .map_err(ComputeError::from)?;
1173        self.gather(&keep)
1174    }
1175
1176    /// Whether any row binds `variable` (`false` when this table does
1177    /// not carry it). One short-circuiting id scan — the join filter
1178    /// emptiness gates ask exactly this, without
1179    /// [`Self::distinct_values`]'s dedupe + promotion pipeline.
1180    ///
1181    /// Bound is the id-level definition: a cell is bound iff its id is
1182    /// non-zero, and every column id was interned in this table's own
1183    /// dict by construction, so `id != 0` is exactly the boundness
1184    /// `distinct_values` reported — no dict lookup is needed to
1185    /// confirm it.
1186    pub fn any_bound(&self, variable: &Variable) -> Result<bool, ComputeError> {
1187        let Some(index) = self.variables.iter().position(|known| known == variable) else {
1188            return Ok(false);
1189        };
1190        Ok(self.hydrated_batch()?.any_bound(index))
1191    }
1192
1193    /// Distinct bound values of `variable` across all rows.
1194    pub fn distinct_values(&self, variable: &Variable) -> Result<Vec<EncodedTerm>, ComputeError> {
1195        let unique_ids = self.distinct_bound_ids(variable)?;
1196        let mut terms = vec![None; unique_ids.len()];
1197        self.dict.get_many(&unique_ids, &mut terms);
1198        Ok(terms.into_iter().flatten().collect())
1199    }
1200
1201    /// New-in-`seen` distinct values of `variable`: the ids NOT already
1202    /// in `seen` are resolved and returned, and inserted into `seen`.
1203    /// Cross-table dedup at the TermId level — `EncodedTerm` carries no
1204    /// `Hash`/`Eq`, but one query's tables share one `TermDict`, so ids
1205    /// are comparable across pages. The parallel probe road uses this to
1206    /// dedupe an arm's broadcast-key terms across a batch's driver pages
1207    /// (a key spanning pages is sought once, not once per page). One
1208    /// FxHash pass over the column: the caller's set is the only dedup
1209    /// structure — no per-page set, no intermediate id vector (the
1210    /// cross-page set already subsumes the within-page one).
1211    pub(crate) fn distinct_values_update(
1212        &self,
1213        variable: &Variable,
1214        seen: &mut FxHashSet<u32>,
1215    ) -> Result<Vec<EncodedTerm>, ComputeError> {
1216        let Some(column) = self.variables.iter().position(|known| known == variable) else {
1217            return Ok(Vec::new());
1218        };
1219        let col = self
1220            .hydrated_batch()?
1221            .column(column)
1222            .expect("column exists");
1223        let mut new_ids = Vec::new();
1224        for row in 0..self.len() {
1225            let id = col.id_at(row);
1226            if id != 0 && seen.insert(id) {
1227                new_ids.push(id);
1228            }
1229        }
1230        let mut terms = vec![None; new_ids.len()];
1231        self.dict.get_many(&new_ids, &mut terms);
1232        Ok(terms.into_iter().flatten().collect())
1233    }
1234
1235    /// Number of distinct bound values of `variable` (unbound cells skipped).
1236    ///
1237    /// Same id-scan as [`Self::distinct_values`] without resolving terms.
1238    pub fn distinct_count(&self, variable: &Variable) -> Result<usize, ComputeError> {
1239        Ok(self.distinct_bound_ids(variable)?.len())
1240    }
1241
1242    fn distinct_bound_ids(&self, variable: &Variable) -> Result<Vec<u32>, ComputeError> {
1243        let Some(column) = self.variables.iter().position(|known| known == variable) else {
1244            return Ok(Vec::new());
1245        };
1246        let mut unique_ids = Vec::new();
1247        // Distinct ids can never exceed the row count, so one reserve up
1248        // front keeps hashbrown's doubling growth — a full re-insert of
1249        // every entry seen so far at each boundary — out of every call.
1250        let mut seen = FxHashSet::with_capacity_and_hasher(self.len(), Default::default());
1251        let col = self
1252            .hydrated_batch()?
1253            .column(column)
1254            .expect("column exists");
1255        for row in 0..self.len() {
1256            let id = col.id_at(row);
1257            if id == 0 {
1258                continue;
1259            }
1260            if seen.insert(id) {
1261                unique_ids.push(id);
1262            }
1263        }
1264        Ok(unique_ids)
1265    }
1266
1267    fn join_with(
1268        &self,
1269        right: &Self,
1270        hash_keys: &[Variable],
1271        mode: JoinMode,
1272    ) -> Result<Self, ComputeError> {
1273        let (variables, right_carry, soft_pairs, left_keys, right_keys) =
1274            self.join_layout(right, hash_keys);
1275
1276        let batch = match mode {
1277            JoinMode::Hash => hash_join_columnar(
1278                self.hydrated_batch()?,
1279                right.hydrated_batch()?,
1280                &left_keys,
1281                &right_keys,
1282                &right_carry,
1283                &soft_pairs,
1284            ),
1285            JoinMode::Shuffle => shuffle_hash_join(
1286                self.hydrated_batch()?,
1287                right.hydrated_batch()?,
1288                &left_keys,
1289                &right_keys,
1290                &right_carry,
1291                &soft_pairs,
1292                DEFAULT_SHUFFLE_PARTITIONS,
1293            ),
1294        }
1295        .map_err(ComputeError::from)?;
1296
1297        Ok(assembled(Arc::clone(&self.dict), variables, batch))
1298    }
1299
1300    #[allow(clippy::type_complexity)]
1301    fn join_layout(
1302        &self,
1303        right: &Self,
1304        hash_keys: &[Variable],
1305    ) -> (
1306        Vec<Variable>,
1307        Vec<usize>,
1308        Vec<(usize, usize)>,
1309        Vec<usize>,
1310        Vec<usize>,
1311    ) {
1312        let mut variables = self.variables.clone();
1313        let mut right_carry = Vec::new();
1314        let mut soft_pairs = Vec::new();
1315        for (column, variable) in right.variables.iter().enumerate() {
1316            if let Some(left_col) = self.variables.iter().position(|known| known == variable) {
1317                if !hash_keys.iter().any(|k| k == variable) {
1318                    soft_pairs.push((left_col, column));
1319                }
1320            } else {
1321                variables.push(variable.clone());
1322                right_carry.push(column);
1323            }
1324        }
1325        let left_keys = key_columns(&self.variables, hash_keys);
1326        let right_keys = key_columns(&right.variables, hash_keys);
1327        (variables, right_carry, soft_pairs, left_keys, right_keys)
1328    }
1329}
1330
1331/// S/P/O column order rank for hit-column ordering.
1332fn slot_rank(slot: PatternSlot) -> u8 {
1333    match slot {
1334        PatternSlot::Subject => 0,
1335        PatternSlot::Predicate => 1,
1336        PatternSlot::Object => 2,
1337    }
1338}
1339
1340/// Slot rank of the graph column (last, after S/P/O).
1341const GRAPH_RANK: u8 = 3;
1342
1343/// Term source for one column of a domain / head scan row.
1344#[derive(Clone)]
1345pub(crate) enum DomainRpcColSource {
1346    /// The hit's slot-0 constraint term (domain scans only).
1347    Constraint,
1348    /// The hit's slot-1 head term.
1349    Head,
1350    /// A bound slot constant: TSG's implicit `rdf:type` predicate, or a
1351    /// grounded graph name.
1352    Constant(Variable, EncodedTerm),
1353}
1354
1355impl DomainRpcColSource {
1356    fn variable(&self, constraint: Option<&Variable>, head: Option<&Variable>) -> Variable {
1357        match self {
1358            Self::Constraint => constraint.expect("live constraint variable").clone(),
1359            Self::Head => head.expect("live head variable").clone(),
1360            Self::Constant(variable, _) => variable.clone(),
1361        }
1362    }
1363
1364    fn domain_value<'a>(&'a self, hit: &'a DomainScanHit) -> &'a EncodedTerm {
1365        match self {
1366            Self::Constraint => &hit.constraint,
1367            Self::Head => &hit.term,
1368            Self::Constant(_, term) => term,
1369        }
1370    }
1371
1372    fn head_value<'a>(&'a self, head: &'a EncodedTerm) -> &'a EncodedTerm {
1373        match self {
1374            Self::Constraint => unreachable!("bare head scans carry no constraint column"),
1375            Self::Head => head,
1376            Self::Constant(_, term) => term,
1377        }
1378    }
1379}
1380
1381/// Variable names for one page of a **DomainScan** or **DomainScanCounts**
1382/// materialized scan (planner reroute to the domain RPC — not plain quads).
1383///
1384/// Schema depends only on [`ScanOp`] liveness marks and `kind`; hits do not
1385/// change the column set. Counted dead slots are omitted on plain domain
1386/// scans; on DomainScanCounts they appear with a fold placeholder (see
1387/// [`domain_rpc_count_page_columns`]). Multiplicity on the counts RPC is
1388/// run-length expansion in [`EncodedSolutions::from_domain_count_hits`].
1389/// Use this for [`ParkAcc`](crate::spill::ParkAcc) on domain paths — not
1390/// [`ScanOp::materialized_variables`] (plain [`EncodedSolutions::from_scan`] layout).
1391pub(crate) fn domain_rpc_page_variables_from_columns(
1392    columns: &[(u8, DomainRpcColSource)],
1393    scan: &ScanOp,
1394    kind: DomainScanKind,
1395) -> Vec<Variable> {
1396    let constraint_var = scan_slot_variable(scan, kind.constraint_slot());
1397    let head_var = scan_slot_variable(scan, kind.head_slot());
1398    columns
1399        .iter()
1400        .map(|(_, term)| term.variable(constraint_var, head_var))
1401        .collect()
1402}
1403
1404pub(crate) fn domain_rpc_page_columns(
1405    scan: &ScanOp,
1406    kind: DomainScanKind,
1407) -> Vec<(u8, DomainRpcColSource)> {
1408    let constraint_var = scan_slot_variable(scan, kind.constraint_slot());
1409    let head_var = scan_slot_variable(scan, kind.head_slot());
1410    let use_constraint = constraint_var.is_some_and(|v| scan.is_live(v) || scan.is_counted(v));
1411    let use_head = head_var.is_some_and(|v| scan.is_live(v) || scan.is_counted(v));
1412    let mut columns: Vec<(u8, DomainRpcColSource)> = Vec::new();
1413    if use_constraint {
1414        columns.push((
1415            slot_rank(kind.constraint_slot()),
1416            DomainRpcColSource::Constraint,
1417        ));
1418    }
1419    if use_head {
1420        columns.push((slot_rank(kind.head_slot()), DomainRpcColSource::Head));
1421    }
1422    if let Some(constant) = grounded_graph_column(scan) {
1423        columns.push((GRAPH_RANK, constant));
1424    }
1425    columns.sort_by_key(|(rank, _)| *rank);
1426    columns
1427}
1428
1429/// DomainScanCounts page layout: [`domain_rpc_page_columns`] plus a bound
1430/// placeholder column for each counted dead slot so grouped `COUNT(?v)` sees
1431/// one binding per run-length-expanded row.
1432///
1433/// The placeholder uses [`ENCODED_TERM_TRUE`] /
1434/// [`waratah_exec::TermId::COUNTED_PRESENCE`] (XSD `true`, not real slot
1435/// values). Follow-on options: a virtual counted column (no per-row TermIds)
1436/// or Group-time row-equivalent `COUNT(?v)` without materializing the dead
1437/// slot — see domain-count discussion in `ARCH.md`.
1438pub(crate) fn domain_rpc_count_page_columns(
1439    scan: &ScanOp,
1440    kind: DomainScanKind,
1441) -> Vec<(u8, DomainRpcColSource)> {
1442    let mut columns = domain_rpc_page_columns(scan, kind);
1443    if let Some(dead) = scan_slot_variable(scan, kind.dead_slot())
1444        && scan.is_counted(dead)
1445    {
1446        columns.push((
1447            slot_rank(kind.dead_slot()),
1448            DomainRpcColSource::Constant(dead.clone(), ENCODED_TERM_TRUE),
1449        ));
1450        columns.sort_by_key(|(rank, _)| *rank);
1451    }
1452    columns
1453}
1454
1455/// `(variable, term)` for a live `?g` a rewrite can project: only when the
1456/// identity fold GROUND the graph (`pattern.graph_name` bound to one term).
1457/// `graph_ok` refuses an unbound live `?g`, so the gate and this stay in
1458/// sync; a runtime push onto the ground can only re-yield the same term or
1459/// empty the scan, so the plan-time name is every emitted row's graph.
1460fn grounded_graph_column(scan: &ScanOp) -> Option<DomainRpcColSource> {
1461    let variable = scan.graph.as_ref()?;
1462    if !scan.is_live(variable) {
1463        return None;
1464    }
1465    scan.pattern
1466        .graph_name
1467        .clone()
1468        .map(|term| DomainRpcColSource::Constant(variable.clone(), term))
1469}
1470
1471enum JoinMode {
1472    Hash,
1473    Shuffle,
1474}
1475
1476fn key_columns(variables: &[Variable], hash_keys: &[Variable]) -> Vec<usize> {
1477    hash_keys
1478        .iter()
1479        .filter_map(|key| variables.iter().position(|known| known == key))
1480        .collect()
1481}
1482
1483/// SPARQL UNION / concat when at least one side is parked: keep files on disk
1484/// when both arms share a schema; otherwise hydrate and merge in RAM.
1485fn union_parked(
1486    left: EncodedSolutions,
1487    right: EncodedSolutions,
1488    variables: Vec<Variable>,
1489) -> Result<EncodedSolutions, ComputeError> {
1490    if left.variables != variables || right.variables != variables {
1491        // At least one arm lacks a name the merged schema carries. Both sides
1492        // hydrate here anyway — this is the road that gives up on keeping the
1493        // pages parked — so the merge is one pre-sized pass instead of two
1494        // aligned copies plus a stack.
1495        let mut batch = TermBatch::with_capacity_rows(variables.len(), left.len() + right.len());
1496        batch
1497            .extend_aligned(left.hydrated_batch()?, &schema_map(&left, &variables))
1498            .map_err(ComputeError::from)?;
1499        batch
1500            .extend_aligned(right.hydrated_batch()?, &schema_map(&right, &variables))
1501            .map_err(ComputeError::from)?;
1502        return Ok(assembled(left.dict, variables, batch));
1503    }
1504    let mut files = left
1505        .spill
1506        .as_ref()
1507        .map(|s| s.files.clone())
1508        .unwrap_or_default();
1509    let mut n_rows = left.spill_rows();
1510    if let Some(spill) = &right.spill {
1511        files.extend(spill.files.iter().cloned());
1512        n_rows += spill.n_rows;
1513    }
1514    let tail = TermBatch::concat(variables.len(), [left.batch, right.batch])
1515        .expect("union tails aligned to the same width");
1516    if files.is_empty() {
1517        Ok(assembled(left.dict, variables, tail))
1518    } else {
1519        Ok(EncodedSolutions::from_parked(
1520            left.dict, variables, files, n_rows, tail,
1521        ))
1522    }
1523}
1524
1525/// Output column → source column for `target`, `None` where the solutions do
1526/// not carry the variable.
1527fn schema_map(solutions: &EncodedSolutions, target: &[Variable]) -> Vec<Option<usize>> {
1528    target
1529        .iter()
1530        .map(|variable| {
1531            solutions
1532                .variables
1533                .iter()
1534                .position(|known| known == variable)
1535        })
1536        .collect()
1537}
1538
1539/// Single-pass concatenation of same-schema pages into one table.
1540///
1541/// [`EncodedSolutions::concat`] is pairwise and copies the accumulated table
1542/// on every call. The fused group pager combines several stored pages into one
1543/// fold page, so it copies each page once into a batch allocated at the target
1544/// capacity and drops the page immediately. Every page must share the schema;
1545/// a mismatch is an internal error.
1546pub(crate) struct PageConcat {
1547    dict: Arc<TermDict>,
1548    variables: Vec<Variable>,
1549    batch: TermBatch,
1550}
1551
1552impl PageConcat {
1553    pub(crate) fn new(dict: Arc<TermDict>, variables: Vec<Variable>, capacity: usize) -> Self {
1554        let batch = TermBatch::with_capacity_rows(variables.len(), capacity);
1555        Self {
1556            dict,
1557            variables,
1558            batch,
1559        }
1560    }
1561
1562    pub(crate) fn push(&mut self, page: &EncodedSolutions) -> Result<(), ComputeError> {
1563        if page.variables != self.variables {
1564            return Err(ComputeError::Internal(format!(
1565                "page concatenation requires identical schemas: left {:?}, right {:?}",
1566                self.variables, page.variables
1567            )));
1568        }
1569        self.batch
1570            .extend_aligned(page.hydrated_batch()?, &schema_map(page, &self.variables))
1571            .map_err(ComputeError::from)
1572    }
1573
1574    pub(crate) fn finish(self) -> EncodedSolutions {
1575        assembled(self.dict, self.variables, self.batch)
1576    }
1577}
1578
1579/// SELECT rows still encoded, plus interned strings from a registry resolve.
1580///
1581/// Joins never see this type. HTTP serializes by borrowing [`Self::strings`]
1582/// (and in-place bytes on each [`EncodedTerm`]); CLI / compliance decode into
1583/// owned [`Term`]s via [`QueryEngine::query`](crate::QueryEngine::query).
1584#[derive(Debug, Clone)]
1585pub struct ProjectedSolutions {
1586    /// Projected variables, in `SELECT` order.
1587    pub variables: Vec<Variable>,
1588    /// Encoded projected columns (unprojected join keys already dropped).
1589    pub solutions: EncodedSolutions,
1590    /// Hash → raw string for hashed IRIs/lexicals in those columns.
1591    pub strings: StrHashMap,
1592    /// Blob id → payload bytes for blob-backed terms in those columns,
1593    /// uniformly content-addressed. Populated only by the materialization
1594    /// window's store fetches (query-const payloads are not copied here —
1595    /// nothing decodes this map; serialization reads `strings`, and the
1596    /// query-local map remains the consts' only copy).
1597    pub blobs: StrBlobMap,
1598}
1599
1600impl ProjectedSolutions {
1601    /// Number of solution rows.
1602    pub fn len(&self) -> usize {
1603        self.solutions.len()
1604    }
1605
1606    /// Whether there are no solutions.
1607    pub fn is_empty(&self) -> bool {
1608        self.solutions.is_empty()
1609    }
1610}
1611
1612/// Query result after execute (and, for SELECT, registry resolve).
1613///
1614/// HTTP SELECT uses [`Self::Select`] so it never builds an owned `oxrdf` [`Term`]
1615/// table. ASK / CONSTRUCT / DESCRIBE stay [`Self::Ready`].
1616#[derive(Debug, Clone)]
1617pub enum QueryOutput {
1618    /// Encoded SELECT rows plus the interned resolve map.
1619    Select(ProjectedSolutions),
1620    /// ASK boolean or CONSTRUCT / DESCRIBE graph.
1621    Ready(QueryResults),
1622}
1623
1624impl QueryOutput {
1625    /// Number of solutions, result triples, or `1`/`0` for ASK.
1626    pub fn len(&self) -> usize {
1627        match self {
1628            Self::Select(projected) => projected.len(),
1629            Self::Ready(results) => results.len(),
1630        }
1631    }
1632
1633    /// Whether the query returned no solutions / no triples / ASK `false`.
1634    pub fn is_empty(&self) -> bool {
1635        self.len() == 0
1636    }
1637}
1638
1639/// Materialized query results: SELECT bindings, an ASK boolean, or a graph.
1640#[derive(Debug, Clone, PartialEq)]
1641pub enum QueryResults {
1642    /// SPARQL `SELECT` solutions.
1643    Solutions {
1644        /// Projected variables, in `SELECT` order.
1645        variables: Vec<Variable>,
1646        /// One entry per solution; `None` marks an unbound variable.
1647        solutions: Vec<Vec<Option<Term>>>,
1648    },
1649    /// SPARQL `CONSTRUCT` / `DESCRIBE` triples (default graph).
1650    Graph {
1651        /// Distinct result triples.
1652        triples: Vec<waratah_storage::Triple>,
1653    },
1654    /// SPARQL `ASK` — `true` iff the WHERE pattern has a solution.
1655    Boolean(bool),
1656}
1657
1658impl QueryResults {
1659    /// Number of solutions or result triples (`1`/`0` for ASK true/false).
1660    pub fn len(&self) -> usize {
1661        match self {
1662            Self::Solutions { solutions, .. } => solutions.len(),
1663            Self::Graph { triples } => triples.len(),
1664            Self::Boolean(true) => 1,
1665            Self::Boolean(false) => 0,
1666        }
1667    }
1668
1669    /// Whether the query returned no solutions / no triples / ASK `false`.
1670    pub fn is_empty(&self) -> bool {
1671        self.len() == 0
1672    }
1673
1674    /// SELECT projection variables (`[]` for graph and ASK results).
1675    pub fn variables(&self) -> &[Variable] {
1676        match self {
1677            Self::Solutions { variables, .. } => variables,
1678            Self::Graph { .. } | Self::Boolean(_) => &[],
1679        }
1680    }
1681
1682    /// SELECT solution rows (`[]` for graph and ASK results).
1683    pub fn solutions(&self) -> &[Vec<Option<Term>>] {
1684        match self {
1685            Self::Solutions { solutions, .. } => solutions,
1686            Self::Graph { .. } | Self::Boolean(_) => &[],
1687        }
1688    }
1689
1690    /// CONSTRUCT/DESCRIBE triples (`[]` for SELECT and ASK results).
1691    pub fn triples(&self) -> &[waratah_storage::Triple] {
1692        match self {
1693            Self::Graph { triples } => triples,
1694            Self::Solutions { .. } | Self::Boolean(_) => &[],
1695        }
1696    }
1697
1698    /// SPARQL `ASK` boolean (`None` for SELECT / graph results).
1699    pub fn as_boolean(&self) -> Option<bool> {
1700        match self {
1701            Self::Boolean(value) => Some(*value),
1702            Self::Solutions { .. } | Self::Graph { .. } => None,
1703        }
1704    }
1705
1706    /// Value of `variable` in `row` (SELECT only).
1707    pub fn get(&self, row: usize, variable: &str) -> Option<&Term> {
1708        let Self::Solutions {
1709            variables,
1710            solutions,
1711        } = self
1712        else {
1713            return None;
1714        };
1715        let column = variables
1716            .iter()
1717            .position(|known| known.as_str() == variable)?;
1718        solutions.get(row)?[column].as_ref()
1719    }
1720
1721    /// SPARQL Query Results TSV for SELECT; N-Triples for a graph; `true`/`false` for ASK.
1722    pub fn to_tsv(&self) -> String {
1723        match self {
1724            Self::Boolean(value) => format!("{value}\n"),
1725            Self::Solutions {
1726                variables,
1727                solutions,
1728            } => {
1729                let mut out = String::new();
1730                let header = variables
1731                    .iter()
1732                    .map(|variable| format!("?{}", variable.as_str()))
1733                    .collect::<Vec<_>>()
1734                    .join("\t");
1735                let _ = writeln!(out, "{header}");
1736                for solution in solutions {
1737                    let row = solution
1738                        .iter()
1739                        .map(|term| term.as_ref().map(Term::to_string).unwrap_or_default())
1740                        .collect::<Vec<_>>()
1741                        .join("\t");
1742                    let _ = writeln!(out, "{row}");
1743                }
1744                out
1745            }
1746            Self::Graph { triples } => {
1747                let mut out = String::new();
1748                for triple in triples {
1749                    let _ = writeln!(out, "{triple} .");
1750                }
1751                out
1752            }
1753        }
1754    }
1755}
1756
1757#[cfg(test)]
1758mod tests {
1759    use super::*;
1760    use crate::plan::{LogicalPlan, PlanNode};
1761    use pretty_assertions::assert_eq;
1762    use waratah_storage::{Literal, NamedNode};
1763
1764    fn var(name: &str) -> Variable {
1765        Variable::new(name).unwrap()
1766    }
1767
1768    fn dict() -> Arc<TermDict> {
1769        TermDict::new_shared()
1770    }
1771
1772    fn iri(local: &str) -> EncodedTerm {
1773        EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap())
1774    }
1775
1776    fn quad(subject: &str, predicate: &str, object: EncodedTerm) -> EncodedQuad {
1777        EncodedQuad::new(
1778            iri(subject),
1779            iri(predicate),
1780            object,
1781            EncodedTerm::DefaultGraph,
1782        )
1783    }
1784
1785    fn demo_plan() -> LogicalPlan {
1786        LogicalPlan::parse(
1787            r#"
1788            SELECT ?person ?weather WHERE {
1789              ?person <http://ex/livesIn> ?city .
1790              ?city <http://ex/hasWeather> ?weather .
1791            }
1792        "#,
1793        )
1794        .unwrap()
1795    }
1796
1797    fn count_hit(constraint: EncodedTerm, term: EncodedTerm, count: u64) -> DomainScanCountHit {
1798        DomainScanCountHit {
1799            constraint,
1800            term,
1801            count,
1802        }
1803    }
1804
1805    fn expanded_count_column(
1806        dict: &TermDict,
1807        source: &DomainRpcColSource,
1808        hits: &[DomainScanCountHit],
1809    ) -> TermColumn {
1810        let n_rows: usize = hits.iter().map(|hit| hit.count as usize).sum();
1811        let mut cells = Vec::with_capacity(n_rows);
1812        for hit in hits {
1813            let encoded = match source {
1814                DomainRpcColSource::Constraint => hit.constraint.clone(),
1815                DomainRpcColSource::Head => hit.term.clone(),
1816                DomainRpcColSource::Constant(_, constant) => constant.clone(),
1817            };
1818            for _ in 0..hit.count {
1819                cells.push(Some(encoded.clone()));
1820            }
1821        }
1822        TermColumn::from_optional_terms(dict, cells).unwrap()
1823    }
1824
1825    #[test]
1826    fn domain_count_runs_match_expanded_term_ids() {
1827        let cases = [
1828            vec![
1829                count_hit(iri("c1"), iri("t1"), 0),
1830                count_hit(iri("c1"), iri("t2"), 1),
1831                count_hit(iri("c2"), iri("t1"), 3),
1832                count_hit(iri("c1"), iri("t2"), 2),
1833            ],
1834            vec![
1835                count_hit(iri("c1"), iri("t1"), 1),
1836                count_hit(iri("c2"), iri("t2"), 0),
1837                count_hit(iri("c2"), iri("t2"), 1),
1838            ],
1839        ];
1840
1841        for hits in cases {
1842            let n_rows: usize = hits.iter().map(|hit| hit.count as usize).sum();
1843            let active_hits = hits.iter().filter(|hit| hit.count > 0).count();
1844            for source in [DomainRpcColSource::Constraint, DomainRpcColSource::Head] {
1845                let dict = dict();
1846                let expected = expanded_count_column(&dict, &source, &hits);
1847                let actual = EncodedSolutions::domain_count_column(
1848                    &dict,
1849                    &source,
1850                    &hits,
1851                    n_rows,
1852                    active_hits,
1853                )
1854                .unwrap();
1855                assert_eq!(actual.ids(), expected.ids());
1856            }
1857        }
1858    }
1859
1860    #[test]
1861    fn domain_count_zero_run_does_not_intern_its_term() {
1862        let zero_term = iri("zero");
1863        let hits = [count_hit(iri("c"), zero_term.clone(), 0)];
1864        let dict = dict();
1865
1866        let column =
1867            EncodedSolutions::domain_count_column(&dict, &DomainRpcColSource::Head, &hits, 0, 0)
1868                .unwrap();
1869
1870        assert!(column.is_empty());
1871        assert!(dict.peek(&zero_term).is_none());
1872    }
1873
1874    #[test]
1875    fn domain_count_constant_is_interned_once_and_empty_page_stays_empty() {
1876        let constant = iri("graph");
1877        let source = DomainRpcColSource::Constant(var("g"), constant.clone());
1878        let hits = [
1879            count_hit(iri("c1"), iri("t1"), 3),
1880            count_hit(iri("c2"), iri("t2"), 2),
1881        ];
1882        let dict = dict();
1883
1884        let column = EncodedSolutions::domain_count_column(&dict, &source, &hits, 5, 2).unwrap();
1885        let id = dict.intern(constant.clone()).unwrap().as_u32();
1886        assert_eq!(column.ids(), &[id; 5]);
1887
1888        let empty_dict = TermDict::new_shared();
1889        let empty = EncodedSolutions::domain_count_column(&empty_dict, &source, &[], 0, 0).unwrap();
1890        assert!(empty.is_empty());
1891        assert!(empty_dict.peek(&constant).is_none());
1892    }
1893
1894    #[test]
1895    fn domain_count_zero_run_skips_placeholder_but_positive_run_rejects_it() {
1896        let source = DomainRpcColSource::Head;
1897        let dict = dict();
1898        let zero = [count_hit(iri("c"), EncodedTerm::Placeholder, 0)];
1899        assert!(
1900            EncodedSolutions::domain_count_column(&dict, &source, &zero, 0, 0)
1901                .unwrap()
1902                .is_empty()
1903        );
1904
1905        let positive = [count_hit(iri("c"), EncodedTerm::Placeholder, 1)];
1906        assert!(matches!(
1907            EncodedSolutions::domain_count_column(&dict, &source, &positive, 1, 1),
1908            Err(ExecError::LengthMismatch(_))
1909        ));
1910    }
1911
1912    #[test]
1913    fn scan_rows_project_onto_pattern_variables() {
1914        let plan = demo_plan();
1915        let scans = plan.scans().unwrap();
1916        let lives_in = scans
1917            .iter()
1918            .find(|scan| scan.object == Some(var("city")))
1919            .unwrap();
1920
1921        let dict = dict();
1922        let solutions = EncodedSolutions::from_scan(
1923            Arc::clone(&dict),
1924            lives_in,
1925            vec![
1926                quad("alice", "livesIn", iri("brisbane")),
1927                quad("bob", "livesIn", iri("hobart")),
1928            ],
1929        )
1930        .unwrap();
1931        assert_eq!(solutions.variables(), [var("person"), var("city")]);
1932        assert_eq!(solutions.len(), 2);
1933        assert_eq!(
1934            solutions.get(0, &var("person")).unwrap(),
1935            Some(iri("alice"))
1936        );
1937        assert_eq!(
1938            solutions.get(0, &var("city")).unwrap(),
1939            Some(iri("brisbane"))
1940        );
1941    }
1942
1943    #[test]
1944    fn hash_join_on_shared_variable() {
1945        let dict = dict();
1946        let plan = demo_plan();
1947        let scans = plan.scans().unwrap();
1948        let lives_in = scans
1949            .iter()
1950            .find(|scan| scan.object == Some(var("city")))
1951            .unwrap();
1952        let weather = scans
1953            .iter()
1954            .find(|scan| scan.object == Some(var("weather")))
1955            .unwrap();
1956
1957        let left = EncodedSolutions::from_scan(
1958            Arc::clone(&dict),
1959            lives_in,
1960            vec![
1961                quad("alice", "livesIn", iri("brisbane")),
1962                quad("bob", "livesIn", iri("hobart")),
1963            ],
1964        )
1965        .unwrap();
1966        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
1967        let right = EncodedSolutions::from_scan(
1968            Arc::clone(&dict),
1969            weather,
1970            vec![quad("brisbane", "hasWeather", sunny.clone())],
1971        )
1972        .unwrap();
1973
1974        let joined = left.hash_join(&right, &[var("city")]).unwrap();
1975        assert_eq!(
1976            joined.variables(),
1977            [var("person"), var("city"), var("weather")]
1978        );
1979        assert_eq!(joined.len(), 1, "only brisbane is sunny");
1980        assert_eq!(joined.get(0, &var("person")).unwrap(), Some(iri("alice")));
1981        assert_eq!(joined.get(0, &var("weather")).unwrap(), Some(sunny));
1982    }
1983
1984    #[test]
1985    fn hash_join_result_is_independent_of_build_side() {
1986        let plan = demo_plan();
1987        let scans = plan.scans().unwrap();
1988        let lives_in = scans
1989            .iter()
1990            .find(|scan| scan.object == Some(var("city")))
1991            .unwrap();
1992        let weather = scans
1993            .iter()
1994            .find(|scan| scan.object == Some(var("weather")))
1995            .unwrap();
1996
1997        let dict = dict();
1998        let left = EncodedSolutions::from_scan(
1999            Arc::clone(&dict),
2000            lives_in,
2001            vec![
2002                quad("alice", "livesIn", iri("brisbane")),
2003                quad("bob", "livesIn", iri("hobart")),
2004                quad("carol", "livesIn", iri("brisbane")),
2005            ],
2006        )
2007        .unwrap();
2008        let right = EncodedSolutions::from_scan(
2009            Arc::clone(&dict),
2010            weather,
2011            vec![quad(
2012                "brisbane",
2013                "hasWeather",
2014                EncodedTerm::from(&Literal::from("Sunny")),
2015            )],
2016        )
2017        .unwrap();
2018
2019        let joined = left.hash_join(&right, &[var("city")]).unwrap();
2020        assert_eq!(joined.len(), 2);
2021        let people: Vec<_> = (0..joined.len())
2022            .map(|row| joined.get(row, &var("person")).unwrap().unwrap())
2023            .collect();
2024        assert!(people.contains(&iri("alice")) && people.contains(&iri("carol")));
2025    }
2026
2027    #[test]
2028    fn join_without_shared_variables_is_a_cartesian_product() {
2029        let plan = LogicalPlan::parse(
2030            "SELECT ?a ?b WHERE { ?a <http://ex/livesIn> ?x . ?b <http://ex/hasWeather> ?y }",
2031        )
2032        .unwrap();
2033        assert!(plan.join_ops().unwrap()[0].hash_keys.is_empty());
2034        let scans = plan.scans().unwrap();
2035
2036        let dict = dict();
2037        let left = EncodedSolutions::from_scan(
2038            Arc::clone(&dict),
2039            scans[0],
2040            vec![quad("alice", "livesIn", iri("brisbane"))],
2041        )
2042        .unwrap();
2043        let right = EncodedSolutions::from_scan(
2044            Arc::clone(&dict),
2045            scans[1],
2046            vec![
2047                quad(
2048                    "brisbane",
2049                    "hasWeather",
2050                    EncodedTerm::from(&Literal::from("Sunny")),
2051                ),
2052                quad(
2053                    "hobart",
2054                    "hasWeather",
2055                    EncodedTerm::from(&Literal::from("Cold")),
2056                ),
2057            ],
2058        )
2059        .unwrap();
2060        assert_eq!(left.hash_join(&right, &[]).unwrap().len(), 2);
2061    }
2062
2063    #[test]
2064    fn repeated_variable_in_one_pattern_keeps_matching_rows_only() {
2065        let plan = LogicalPlan::parse("SELECT ?x WHERE { ?x <http://ex/knows> ?x }").unwrap();
2066        let scans = plan.scans().unwrap();
2067        let solutions = EncodedSolutions::from_scan(
2068            dict(),
2069            scans[0],
2070            vec![
2071                quad("alice", "knows", iri("alice")),
2072                quad("alice", "knows", iri("bob")),
2073            ],
2074        )
2075        .unwrap();
2076        assert_eq!(solutions.variables(), [var("x")]);
2077        assert_eq!(solutions.len(), 1);
2078    }
2079
2080    #[test]
2081    fn scan_interns_duplicate_terms_to_one_id() {
2082        let plan = demo_plan();
2083        let scans = plan.scans().unwrap();
2084        let lives_in = scans
2085            .iter()
2086            .find(|scan| scan.object == Some(var("city")))
2087            .unwrap();
2088        let solutions = EncodedSolutions::from_scan(
2089            dict(),
2090            lives_in,
2091            vec![
2092                quad("alice", "livesIn", iri("brisbane")),
2093                quad("bob", "livesIn", iri("brisbane")),
2094            ],
2095        )
2096        .unwrap();
2097        let city = solutions.column(&var("city")).unwrap().unwrap();
2098        assert_ne!(city.id_at(0), 0);
2099        assert_eq!(city.id_at(0), city.id_at(1));
2100    }
2101
2102    #[test]
2103    fn grounded_scan_keeps_row_count_with_no_columns() {
2104        let plan = LogicalPlan::parse(
2105            "SELECT * WHERE { <http://ex/alice> <http://ex/knows> <http://ex/bob> }",
2106        )
2107        .unwrap();
2108        let scans = plan.scans().unwrap();
2109        let scan = scans[0];
2110        assert!(scan.subject.is_none() && scan.predicate.is_none() && scan.object.is_none());
2111        let solutions = EncodedSolutions::from_scan(
2112            dict(),
2113            scan,
2114            vec![
2115                quad("alice", "knows", iri("bob")),
2116                quad("alice", "knows", iri("bob")),
2117            ],
2118        )
2119        .unwrap();
2120        assert!(solutions.variables().is_empty());
2121        assert_eq!(solutions.len(), 2);
2122
2123        let empty = EncodedSolutions::from_scan(dict(), scan, Vec::new()).unwrap();
2124        assert!(empty.variables().is_empty());
2125        assert_eq!(empty.len(), 0);
2126    }
2127
2128    #[test]
2129    fn scan_drops_a_graph_that_the_pattern_does_not_project() {
2130        let plan = LogicalPlan::parse("SELECT ?s ?o WHERE { ?s <http://ex/p> ?o }").unwrap();
2131        let scans = plan.scans().unwrap();
2132        let graph = iri("secret-graph");
2133        let solutions = EncodedSolutions::from_scan(
2134            dict(),
2135            scans[0],
2136            vec![EncodedQuad::new(
2137                iri("alice"),
2138                iri("p"),
2139                iri("bob"),
2140                graph.clone(),
2141            )],
2142        )
2143        .unwrap();
2144        assert_eq!(solutions.variables(), [var("s"), var("o")]);
2145        let rows = solutions.optional_rows().unwrap();
2146        assert!(
2147            rows.iter()
2148                .flatten()
2149                .all(|cell| cell.as_ref() != Some(&graph))
2150        );
2151    }
2152
2153    #[test]
2154    fn domain_hits_intern_live_constraint_and_head() {
2155        let plan = LogicalPlan::parse(
2156            "SELECT DISTINCT ?s ?o WHERE { ?s ?p ?o . FILTER(sameTerm(?s, <http://ex/alice>)) }",
2157        )
2158        .unwrap();
2159        let scans = plan.scans().unwrap();
2160        let scan = scans[0];
2161        assert_eq!(scan.domain_scan, Some(DomainScanKind::SubjectDomain));
2162        let alice = iri("alice");
2163        let hits = [
2164            DomainScanHit {
2165                constraint: alice.clone(),
2166                term: iri("brisbane"),
2167            },
2168            DomainScanHit {
2169                constraint: alice.clone(),
2170                term: iri("hobart"),
2171            },
2172        ];
2173        let solutions = EncodedSolutions::from_domain_scan_hits(
2174            dict(),
2175            scan,
2176            DomainScanKind::SubjectDomain,
2177            &hits,
2178        )
2179        .unwrap();
2180        assert_eq!(solutions.variables(), [var("s"), var("o")]);
2181        assert_eq!(solutions.get(0, &var("s")).unwrap(), Some(alice));
2182        assert_eq!(solutions.get(1, &var("o")).unwrap(), Some(iri("hobart")));
2183        let subject = solutions.column(&var("s")).unwrap().unwrap();
2184        assert_ne!(subject.id_at(0), 0);
2185        assert_eq!(subject.id_at(0), subject.id_at(1));
2186
2187        let empty = EncodedSolutions::from_domain_scan_hits(
2188            dict(),
2189            scan,
2190            DomainScanKind::SubjectDomain,
2191            &[],
2192        )
2193        .unwrap();
2194        assert_eq!(empty.variables(), [var("s"), var("o")]);
2195        assert_eq!(empty.len(), 0);
2196    }
2197
2198    #[test]
2199    fn object_preds_projects_predicate_before_object() {
2200        let plan = LogicalPlan::parse(
2201            "SELECT DISTINCT ?o ?p WHERE { ?s ?p ?o . FILTER(sameTerm(?o, <http://ex/o1>)) }",
2202        )
2203        .unwrap();
2204        let scans = plan.scans().unwrap();
2205        let scan = scans[0];
2206        assert_eq!(scan.domain_scan, Some(DomainScanKind::ObjectPreds));
2207        let hits = [DomainScanHit {
2208            constraint: iri("o1"),
2209            term: iri("knows"),
2210        }];
2211        let solutions = EncodedSolutions::from_domain_scan_hits(
2212            dict(),
2213            scan,
2214            DomainScanKind::ObjectPreds,
2215            &hits,
2216        )
2217        .unwrap();
2218        assert_eq!(solutions.variables(), [var("p"), var("o")]);
2219        assert_eq!(solutions.get(0, &var("p")).unwrap(), Some(iri("knows")));
2220        assert_eq!(solutions.get(0, &var("o")).unwrap(), Some(iri("o1")));
2221    }
2222
2223    #[test]
2224    fn head_terms_intern_the_live_head() {
2225        let plan = LogicalPlan::parse("SELECT DISTINCT ?s WHERE { ?s ?p ?o }").unwrap();
2226        let scans = plan.scans().unwrap();
2227        let scan = scans[0];
2228        assert_eq!(scan.head_scan, Some(HeadScanKind::Subjects));
2229        let solutions = EncodedSolutions::from_head_terms(
2230            dict(),
2231            scan,
2232            HeadScanKind::Subjects,
2233            &[iri("alice"), iri("alice"), iri("bob")],
2234        )
2235        .unwrap();
2236        assert_eq!(solutions.variables(), [var("s")]);
2237        assert_eq!(solutions.len(), 3);
2238        let subject = solutions.column(&var("s")).unwrap().unwrap();
2239        assert_eq!(subject.id_at(0), subject.id_at(1));
2240        assert_ne!(subject.id_at(0), subject.id_at(2));
2241
2242        let empty =
2243            EncodedSolutions::from_head_terms(dict(), scan, HeadScanKind::Subjects, &[]).unwrap();
2244        assert_eq!(empty.variables(), [var("s")]);
2245        assert_eq!(empty.len(), 0);
2246    }
2247
2248    #[test]
2249    fn classes_head_projects_rdf_type_once() {
2250        let plan = LogicalPlan::parse(
2251            "SELECT DISTINCT ?p ?c WHERE { ?s ?p ?c . FILTER(sameTerm(?p, <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>)) }",
2252        )
2253        .unwrap();
2254        let scans = plan.scans().unwrap();
2255        let scan = scans[0];
2256        assert_eq!(scan.head_scan, Some(HeadScanKind::Classes));
2257        let solutions = EncodedSolutions::from_head_terms(
2258            dict(),
2259            scan,
2260            HeadScanKind::Classes,
2261            &[iri("Person"), iri("Place")],
2262        )
2263        .unwrap();
2264        assert_eq!(solutions.variables(), [var("p"), var("c")]);
2265        let predicate = solutions.column(&var("p")).unwrap().unwrap();
2266        assert_eq!(predicate.id_at(0), TermId::RDF_TYPE.as_u32());
2267        assert_eq!(predicate.id_at(1), TermId::RDF_TYPE.as_u32());
2268        assert_eq!(solutions.get(1, &var("c")).unwrap(), Some(iri("Place")));
2269    }
2270
2271    #[test]
2272    fn head_terms_repeat_a_grounded_graph_id() {
2273        let plan = LogicalPlan::parse(
2274            "SELECT DISTINCT ?g ?c WHERE { GRAPH ?g { ?s a ?c } FILTER(sameTerm(?g, <http://ex/g1>)) }",
2275        )
2276        .unwrap();
2277        let scans = plan.scans().unwrap();
2278        let scan = scans[0];
2279        assert_eq!(scan.head_scan, Some(HeadScanKind::Classes));
2280        let solutions = EncodedSolutions::from_head_terms(
2281            dict(),
2282            scan,
2283            HeadScanKind::Classes,
2284            &[iri("Person"), iri("Place")],
2285        )
2286        .unwrap();
2287        assert_eq!(solutions.variables(), [var("c"), var("g")]);
2288        let graph = solutions.column(&var("g")).unwrap().unwrap();
2289        assert_ne!(graph.id_at(0), 0);
2290        assert_eq!(graph.id_at(0), graph.id_at(1));
2291        assert_eq!(solutions.get(0, &var("g")).unwrap(), Some(iri("g1")));
2292    }
2293
2294    #[test]
2295    fn union_aligns_asymmetric_variables_and_stacks_rows() {
2296        let left_plan = LogicalPlan::parse("SELECT ?s ?x WHERE { ?s <http://ex/p> ?x }").unwrap();
2297        let right_plan = LogicalPlan::parse("SELECT ?s ?r WHERE { ?s <http://ex/q> ?r }").unwrap();
2298        let dict = dict();
2299        let left = EncodedSolutions::from_scan(
2300            Arc::clone(&dict),
2301            left_plan.scans().unwrap()[0],
2302            vec![quad("alice", "p", iri("x1"))],
2303        )
2304        .unwrap();
2305        let right = EncodedSolutions::from_scan(
2306            Arc::clone(&dict),
2307            right_plan.scans().unwrap()[0],
2308            vec![quad("bob", "q", iri("r1"))],
2309        )
2310        .unwrap();
2311
2312        let united = left.union(right).unwrap();
2313        assert_eq!(united.variables(), [var("s"), var("x"), var("r")]);
2314        assert_eq!(united.len(), 2);
2315        assert_eq!(united.get(0, &var("s")).unwrap(), Some(iri("alice")));
2316        assert_eq!(united.get(0, &var("x")).unwrap(), Some(iri("x1")));
2317        assert_eq!(united.get(0, &var("r")).unwrap(), None);
2318        assert_eq!(united.get(1, &var("s")).unwrap(), Some(iri("bob")));
2319        assert_eq!(united.get(1, &var("x")).unwrap(), None);
2320        assert_eq!(united.get(1, &var("r")).unwrap(), Some(iri("r1")));
2321    }
2322
2323    #[test]
2324    fn absorb_widens_in_place_as_new_names_arrive() {
2325        let dict = dict();
2326        let page = |variables: Vec<Variable>, rows: Vec<Vec<Option<EncodedTerm>>>| {
2327            EncodedSolutions::from_optional_rows(Arc::clone(&dict), variables, rows).unwrap()
2328        };
2329        let ctx = QueryContext::from_snapshot(waratah_storage::SnapshotId::latest());
2330        let mut acc = page(vec![var("s")], vec![vec![Some(iri("a"))]]);
2331        // A page that binds a name the accumulator does not have yet: the
2332        // new column is unbound for the row already held.
2333        acc.absorb(
2334            page(
2335                vec![var("s"), var("x")],
2336                vec![vec![Some(iri("b")), Some(iri("x1"))]],
2337            ),
2338            &ctx,
2339        )
2340        .unwrap();
2341        assert_eq!(acc.variables(), [var("s"), var("x")]);
2342        assert_eq!(acc.len(), 2);
2343        assert_eq!(acc.get(0, &var("s")).unwrap(), Some(iri("a")));
2344        assert_eq!(acc.get(0, &var("x")).unwrap(), None);
2345        assert_eq!(acc.get(1, &var("s")).unwrap(), Some(iri("b")));
2346        assert_eq!(acc.get(1, &var("x")).unwrap(), Some(iri("x1")));
2347        // A later page with another new name appends it at the end.
2348        acc.absorb(page(vec![var("r")], vec![vec![Some(iri("r1"))]]), &ctx)
2349            .unwrap();
2350        assert_eq!(acc.variables(), [var("s"), var("x"), var("r")]);
2351        assert_eq!(acc.len(), 3);
2352        assert_eq!(acc.get(0, &var("r")).unwrap(), None);
2353        assert_eq!(acc.get(2, &var("s")).unwrap(), None);
2354        assert_eq!(acc.get(2, &var("r")).unwrap(), Some(iri("r1")));
2355    }
2356
2357    /// A spilled accumulator takes an asymmetric arm by splicing parked files,
2358    /// not by reading its own pages back. The old road returned a hydrated,
2359    /// in-RAM table (and paid O(accumulator) I/O per arm); `is_spilled()`
2360    /// staying true is what distinguishes the two.
2361    #[test]
2362    fn absorb_splices_an_asymmetric_arm_into_a_spilled_accumulator() {
2363        let dict = dict();
2364        let ctx = QueryContext::from_snapshot(waratah_storage::SnapshotId::latest());
2365        let page = |variables: Vec<Variable>, rows: Vec<Vec<Option<EncodedTerm>>>| {
2366            EncodedSolutions::from_optional_rows(Arc::clone(&dict), variables, rows).unwrap()
2367        };
2368        let parked = crate::spill::park_fully(
2369            &page(
2370                vec![var("s"), var("x")],
2371                vec![
2372                    vec![Some(iri("a")), Some(iri("x1"))],
2373                    vec![Some(iri("b")), None],
2374                ],
2375            ),
2376            &ctx,
2377        )
2378        .unwrap();
2379        assert!(parked.is_spilled());
2380        let files_before = parked.spill_files().len();
2381
2382        let mut acc = parked;
2383        // Narrower than the accumulator: a splice, not a widen.
2384        acc.absorb(page(vec![var("s")], vec![vec![Some(iri("c"))]]), &ctx)
2385            .unwrap();
2386        assert!(acc.is_spilled(), "the accumulator must stay on disk");
2387        assert!(acc.is_parked(), "nothing may hydrate the accumulator");
2388        assert_eq!(acc.len(), 3);
2389        assert!(
2390            acc.spill_files().len() > files_before,
2391            "the arm's rows must arrive as new page files"
2392        );
2393        assert_eq!(acc.get(0, &var("s")).unwrap(), Some(iri("a")));
2394        assert_eq!(acc.get(0, &var("x")).unwrap(), Some(iri("x1")));
2395        assert_eq!(acc.get(1, &var("x")).unwrap(), None);
2396        assert_eq!(acc.get(2, &var("s")).unwrap(), Some(iri("c")));
2397        assert_eq!(acc.get(2, &var("x")).unwrap(), None);
2398    }
2399
2400    /// A hydrated accumulator cannot be re-parked from its tail, so the
2401    /// hydrating merge is the correct road. It must still produce the right
2402    /// rows and schema.
2403    #[test]
2404    fn absorb_after_hydration_still_merges_correctly() {
2405        let dict = dict();
2406        let ctx = QueryContext::from_snapshot(waratah_storage::SnapshotId::latest());
2407        let page = |variables: Vec<Variable>, rows: Vec<Vec<Option<EncodedTerm>>>| {
2408            EncodedSolutions::from_optional_rows(Arc::clone(&dict), variables, rows).unwrap()
2409        };
2410        let mut acc = crate::spill::park_fully(
2411            &page(
2412                vec![var("s"), var("x")],
2413                vec![vec![Some(iri("a")), Some(iri("x1"))]],
2414            ),
2415            &ctx,
2416        )
2417        .unwrap();
2418        // Force the hydration the guard detects.
2419        assert_eq!(acc.get(0, &var("s")).unwrap(), Some(iri("a")));
2420        assert!(!acc.is_parked(), "a read hydrates the table");
2421        acc.absorb(page(vec![var("s")], vec![vec![Some(iri("b"))]]), &ctx)
2422            .unwrap();
2423        assert_eq!(acc.variables(), [var("s"), var("x")]);
2424        assert_eq!(acc.len(), 2);
2425        assert_eq!(acc.get(0, &var("x")).unwrap(), Some(iri("x1")));
2426        assert_eq!(acc.get(1, &var("s")).unwrap(), Some(iri("b")));
2427        assert_eq!(acc.get(1, &var("x")).unwrap(), None);
2428    }
2429
2430    #[test]
2431    fn push_term_column_extends_the_schema_without_touching_the_table() {
2432        let dict = dict();
2433        let solutions = EncodedSolutions::from_optional_rows(
2434            Arc::clone(&dict),
2435            vec![var("s")],
2436            vec![vec![Some(iri("a"))], vec![Some(iri("b"))]],
2437        )
2438        .unwrap();
2439        let id = dict.intern_ref(&iri("City")).unwrap().as_u32();
2440        let extended = solutions
2441            .push_term_column(var("kind"), TermColumn::from_ids(vec![id, id]))
2442            .unwrap();
2443        assert_eq!(extended.variables(), [var("s"), var("kind")]);
2444        assert_eq!(extended.len(), 2);
2445        assert_eq!(extended.get(0, &var("s")).unwrap(), Some(iri("a")));
2446        assert_eq!(extended.get(1, &var("s")).unwrap(), Some(iri("b")));
2447        assert_eq!(extended.get(0, &var("kind")).unwrap(), Some(iri("City")));
2448        assert_eq!(extended.get(1, &var("kind")).unwrap(), Some(iri("City")));
2449    }
2450
2451    #[test]
2452    fn union_of_empty_arms_is_empty() {
2453        let plan = LogicalPlan::parse(
2454            "SELECT ?s WHERE { { ?s <http://ex/p> ?o } UNION { ?s <http://ex/q> ?o } }",
2455        )
2456        .unwrap();
2457        let PlanNode::Union { left, right } = &plan.root else {
2458            panic!("expected Union, got {:?}", plan.root);
2459        };
2460        let dict = dict();
2461        let left = EncodedSolutions::empty(Arc::clone(&dict), left.variables());
2462        let right = EncodedSolutions::empty(dict, right.variables());
2463        let united = left.union(right).unwrap();
2464        assert!(united.is_empty());
2465        // `SELECT ?s` marks ?o dead in both arms, so each arm's schema is
2466        // [s] and the union drops ?o from the wire entirely.
2467        assert_eq!(united.variables(), [var("s")]);
2468    }
2469
2470    #[test]
2471    fn concat_preserves_a_zero_column_unit_row() {
2472        let dict = dict();
2473        let unit =
2474            EncodedSolutions::from_optional_rows(Arc::clone(&dict), Vec::new(), vec![Vec::new()])
2475                .unwrap();
2476        assert_eq!(unit.len(), 1);
2477        let stacked = EncodedSolutions::empty(dict, Vec::new())
2478            .concat(unit)
2479            .unwrap();
2480        assert_eq!(stacked.len(), 1);
2481        assert!(stacked.variables().is_empty());
2482    }
2483
2484    #[test]
2485    fn distinct_count_matches_distinct_values_len() {
2486        let dict = dict();
2487        let city = var("city");
2488        let solutions = EncodedSolutions::from_optional_rows(
2489            Arc::clone(&dict),
2490            vec![city.clone()],
2491            vec![
2492                vec![Some(iri("brisbane"))],
2493                vec![None],
2494                vec![Some(iri("brisbane"))],
2495                vec![Some(iri("hobart"))],
2496            ],
2497        )
2498        .unwrap();
2499        assert_eq!(solutions.distinct_count(&city).unwrap(), 2);
2500        assert_eq!(
2501            solutions.distinct_count(&city).unwrap(),
2502            solutions.distinct_values(&city).unwrap().len()
2503        );
2504        assert_eq!(solutions.distinct_count(&var("missing")).unwrap(), 0);
2505        assert!(
2506            solutions
2507                .distinct_values(&var("missing"))
2508                .unwrap()
2509                .is_empty()
2510        );
2511    }
2512
2513    #[test]
2514    fn any_bound_matches_distinct_values_emptiness() {
2515        // The join filter emptiness gates swapped
2516        // `distinct_values(key).is_empty()` for `any_bound(key)`; this
2517        // pins the equivalence, including the missing-variable and
2518        // all-unbound edges where the gate fires.
2519        let dict = dict();
2520        let city = var("city");
2521        let solutions = EncodedSolutions::from_optional_rows(
2522            Arc::clone(&dict),
2523            vec![city.clone(), var("never")],
2524            vec![vec![None, None], vec![None, None]],
2525        )
2526        .unwrap();
2527        // All-unbound column: gate fires, no promotion was needed to learn it.
2528        assert!(!solutions.any_bound(&city).unwrap());
2529        assert!(solutions.distinct_values(&city).unwrap().is_empty());
2530
2531        let solutions = EncodedSolutions::from_optional_rows(
2532            Arc::clone(&dict),
2533            vec![city.clone()],
2534            vec![vec![None], vec![Some(iri("hobart"))]],
2535        )
2536        .unwrap();
2537        assert!(solutions.any_bound(&city).unwrap());
2538        assert!(!solutions.distinct_values(&city).unwrap().is_empty());
2539
2540        // Missing variable: `false`, same as the old empty distinct set.
2541        assert!(!solutions.any_bound(&var("missing")).unwrap());
2542    }
2543
2544    #[test]
2545    fn tsv_renders_a_header_and_one_row_per_solution() {
2546        let results = QueryResults::Solutions {
2547            variables: vec![var("person"), var("weather")],
2548            solutions: vec![vec![
2549                Some(NamedNode::new("http://ex/alice").unwrap().into()),
2550                Some(Literal::from("Sunny").into()),
2551            ]],
2552        };
2553        assert_eq!(
2554            results.to_tsv(),
2555            "?person\t?weather\n<http://ex/alice>\t\"Sunny\"\n"
2556        );
2557        assert_eq!(
2558            results.get(0, "person").map(ToString::to_string),
2559            Some("<http://ex/alice>".to_owned())
2560        );
2561    }
2562
2563    #[test]
2564    fn tsv_renders_ask_as_true_or_false() {
2565        assert_eq!(QueryResults::Boolean(true).to_tsv(), "true\n");
2566        assert_eq!(QueryResults::Boolean(false).to_tsv(), "false\n");
2567        assert_eq!(QueryResults::Boolean(true).as_boolean(), Some(true));
2568        assert!(QueryResults::Boolean(false).is_empty());
2569        assert_eq!(QueryResults::Boolean(true).len(), 1);
2570    }
2571}