Skip to main content

waratah_compute/
dataset.rs

1//! SPARQL QueryDataset: the window of graphs a query may scan.
2//!
3//! RDF `DefaultGraph` (unnamed, all-zero encoding) is not the same as the
4//! SPARQL default graph (the `FROM` / `default-graph-uri` union, or the engine
5//! fallback). Unbound G (`pattern.graph_name = None`) matches every quad.
6
7use std::sync::{Arc, OnceLock};
8
9use spargebra::algebra::QueryDataset as SparqlQueryDataset;
10use waratah_stats::GRAPH_FILTER_TERM_CAP;
11use waratah_storage::encode::encode_term_bytes;
12use waratah_storage::{
13    EncodedTerm, NamedNode, StrHash, StrHashSet, Term, new_str_hash_set, strings_entries_for_term,
14};
15
16use crate::error::ComputeError;
17
18// GRAPH_FILTER_TERM_CAP is re-exported from waratah_stats.
19
20/// Allow-list or block-list of encoded graph names for a scan RPC.
21///
22/// Members are stored as a set: named-graph IRIs in a [`StrHashSet`],
23/// [`EncodedTerm::DefaultGraph`] as a flag, and blank (or other) graphs in a
24/// small extras vec. `exclude` is the polarity of the whole filter, not a
25/// per-term flag: `false` = allow-list (keep members), `true` = block-list
26/// (keep non-members). The wire slice is built only in [`Self::terms`] /
27/// [`Self::to_wire`], sorted, and cached on this [`Arc`] so path hops of the
28/// same filter do not rebuild it.
29///
30/// Compute still builds these as SPARQL windows (`FROM NAMED` allow-lists,
31/// `GRAPH ?g` block-list of RDF DefaultGraph). The wire flag is inverted:
32/// [`Self::wire_allow`] is proto `graph_filter_allow` (`false` = block-list).
33#[derive(Clone)]
34pub struct GraphFilter {
35    inner: Arc<GraphFilterData>,
36}
37
38struct GraphFilterData {
39    iris: StrHashSet,
40    extras: Vec<EncodedTerm>,
41    has_default: bool,
42    /// `false` = keep only members; `true` = drop members.
43    exclude: bool,
44    wire: OnceLock<Arc<[EncodedTerm]>>,
45}
46
47impl GraphFilter {
48    /// Whether two filters are the SAME window allocation. Scope-dedup
49    /// consumers (the text planner's sibling-stamp tracking) need
50    /// soundness only — never-equal-when-different — and the lowering
51    /// clones one allocation per window, so pointer identity is the
52    /// practical equality: two structurally equal filters from different
53    /// allocations read as distinct, which costs duplicate candidate arms
54    /// that the union's Distinct folds, never a wrong answer.
55    pub fn same_allocation(&self, other: &Self) -> bool {
56        std::sync::Arc::ptr_eq(&self.inner, &other.inner)
57    }
58
59    /// Allow-list of `terms`. Empty means an empty graph window (no rows).
60    pub fn allow(terms: impl AsRef<[EncodedTerm]>) -> Self {
61        Self::from_terms(terms.as_ref(), false)
62    }
63
64    /// Empty allow-list: residual G matches nothing (skip the scan RPC).
65    pub fn empty_allow() -> Self {
66        Self::from_data(GraphFilterData::empty(false))
67    }
68
69    /// Block-list of `terms`. Empty means block nothing (no extra G constraint).
70    pub fn exclude(terms: impl AsRef<[EncodedTerm]>) -> Self {
71        Self::from_terms(terms.as_ref(), true)
72    }
73
74    /// Named-graph-only scans: block the RDF unnamed graph.
75    pub fn exclude_default() -> Self {
76        let mut data = GraphFilterData::empty(true);
77        data.has_default = true;
78        Self::from_data(data)
79    }
80
81    fn from_terms(terms: &[EncodedTerm], exclude: bool) -> Self {
82        let mut data = GraphFilterData::empty(exclude);
83        for term in terms {
84            data.insert(term);
85        }
86        Self::from_data(data)
87    }
88
89    fn from_data(data: GraphFilterData) -> Self {
90        Self {
91            inner: Arc::new(data),
92        }
93    }
94
95    /// `true` if this filter is a block-list.
96    pub fn is_exclude(&self) -> bool {
97        self.inner.exclude
98    }
99
100    /// Number of member graphs (IRIs + extras + DefaultGraph flag).
101    pub fn len(&self) -> usize {
102        self.inner.len()
103    }
104
105    /// Whether the member set is empty (polarity still applies).
106    pub fn is_empty(&self) -> bool {
107        self.len() == 0
108    }
109
110    /// Allow-list with no members: the empty graph window.
111    pub fn is_empty_allow(&self) -> bool {
112        !self.inner.exclude && self.inner.len() == 0
113    }
114
115    /// Wire `graph_filter_allow`: `true` for allow-lists, `false` for block-lists.
116    pub fn wire_allow(&self) -> bool {
117        !self.inner.exclude
118    }
119
120    /// Sorted members for the scan / path-hop RPC. Cached on this [`Arc`].
121    pub fn terms(&self) -> &[EncodedTerm] {
122        self.inner
123            .wire
124            .get_or_init(|| self.inner.build_wire())
125            .as_ref()
126    }
127
128    /// [`Self::terms`] as a cheap [`Arc`] clone (path `PushedKeyVals`, VALUES rows).
129    pub fn terms_arc(&self) -> Arc<[EncodedTerm]> {
130        Arc::clone(self.inner.wire.get_or_init(|| self.inner.build_wire()))
131    }
132
133    /// Whether `graph` is a member of the set (ignores polarity).
134    pub fn contains_member(&self, graph: &EncodedTerm) -> bool {
135        self.inner.contains(graph)
136    }
137
138    /// Whether `graph` survives this filter.
139    ///
140    /// Empty allow-list: no graph. Empty block-list: every graph.
141    /// Allow-list keeps members; block-list keeps non-members.
142    pub fn allows(&self, graph: &EncodedTerm) -> bool {
143        let member = self.inner.contains(graph);
144        if self.inner.exclude { !member } else { member }
145    }
146
147    /// Map a plan-side filter onto the scan RPC.
148    ///
149    /// `None` is an empty block-list (block nothing). Empty allow-lists stay
150    /// allow-lists so a missed skip-RPC cannot become a full scan.
151    pub fn to_wire(filter: Option<&Self>) -> (&[EncodedTerm], bool) {
152        match filter {
153            Some(filter) => (filter.terms(), filter.wire_allow()),
154            None => (&[], false),
155        }
156    }
157
158    /// Union `extra` into a block-list.
159    ///
160    /// `None` means wrong polarity or the merged list exceeds
161    /// [`GRAPH_FILTER_TERM_CAP`] — callers must leave the original filter
162    /// in place, not assign `None` onto `graph_filter`.
163    pub(crate) fn union_exclude(&self, extra: &[EncodedTerm]) -> Option<ComposedGraph> {
164        if !self.inner.exclude {
165            return None;
166        }
167        if extra.len() > GRAPH_FILTER_TERM_CAP as usize {
168            return None;
169        }
170        let mut data = self.inner.clone_data();
171        for term in extra {
172            data.insert(term);
173        }
174        if data.len() > GRAPH_FILTER_TERM_CAP as usize {
175            return None;
176        }
177        Some(ComposedGraph::Filter(Self::from_data(data)))
178    }
179
180    /// Subtract `drop` from an allow-list.
181    ///
182    /// `None` means wrong polarity or `drop` exceeds [`GRAPH_FILTER_TERM_CAP`]
183    /// — callers must leave the original filter in place. An empty remainder
184    /// is [`ComposedGraph::Empty`], not `Option::None`.
185    pub(crate) fn subtract_allow(&self, drop: &[EncodedTerm]) -> Option<ComposedGraph> {
186        if self.inner.exclude {
187            return None;
188        }
189        if drop.len() > GRAPH_FILTER_TERM_CAP as usize {
190            return None;
191        }
192        let mut data = self.inner.clone_data();
193        for term in drop {
194            data.remove(term);
195        }
196        Some(composed_from_allow(Self::from_data(data)))
197    }
198}
199
200impl GraphFilterData {
201    fn empty(exclude: bool) -> Self {
202        Self {
203            iris: new_str_hash_set(),
204            extras: Vec::new(),
205            has_default: false,
206            exclude,
207            wire: OnceLock::new(),
208        }
209    }
210
211    fn clone_data(&self) -> Self {
212        Self {
213            iris: self.iris.clone(),
214            extras: self.extras.clone(),
215            has_default: self.has_default,
216            exclude: self.exclude,
217            wire: OnceLock::new(),
218        }
219    }
220
221    fn len(&self) -> usize {
222        self.iris.len() + self.extras.len() + usize::from(self.has_default)
223    }
224
225    fn contains(&self, graph: &EncodedTerm) -> bool {
226        match graph {
227            EncodedTerm::DefaultGraph => self.has_default,
228            EncodedTerm::NamedNode { iri_id } => self.iris.contains(iri_id),
229            other => self.extras.contains(other),
230        }
231    }
232
233    fn insert(&mut self, term: &EncodedTerm) {
234        match term {
235            EncodedTerm::NamedNode { iri_id } => {
236                self.iris.insert(*iri_id);
237            }
238            EncodedTerm::DefaultGraph => self.has_default = true,
239            other => {
240                if !self.extras.contains(other) {
241                    self.extras.push(other.clone());
242                }
243            }
244        }
245    }
246
247    fn remove(&mut self, term: &EncodedTerm) {
248        match term {
249            EncodedTerm::NamedNode { iri_id } => {
250                self.iris.remove(iri_id);
251            }
252            EncodedTerm::DefaultGraph => self.has_default = false,
253            other => self.extras.retain(|existing| existing != other),
254        }
255    }
256
257    fn singleton_term(&self) -> Option<EncodedTerm> {
258        if self.len() != 1 {
259            return None;
260        }
261        if self.has_default {
262            return Some(EncodedTerm::DefaultGraph);
263        }
264        if let Some(iri_id) = self.iris.iter().next() {
265            return Some(EncodedTerm::NamedNode { iri_id: *iri_id });
266        }
267        self.extras.first().cloned()
268    }
269
270    fn build_wire(&self) -> Arc<[EncodedTerm]> {
271        let mut terms = Vec::with_capacity(self.len());
272        if self.has_default {
273            terms.push(EncodedTerm::DefaultGraph);
274        }
275        for iri_id in &self.iris {
276            terms.push(EncodedTerm::NamedNode { iri_id: *iri_id });
277        }
278        terms.extend(self.extras.iter().cloned());
279        terms.sort_by_cached_key(encode_term_bytes);
280        Arc::from(terms)
281    }
282}
283
284impl PartialEq for GraphFilter {
285    fn eq(&self, other: &Self) -> bool {
286        self.inner.exclude == other.inner.exclude
287            && self.inner.has_default == other.inner.has_default
288            && self.inner.iris == other.inner.iris
289            && extras_eq(&self.inner.extras, &other.inner.extras)
290    }
291}
292
293impl Eq for GraphFilter {}
294
295fn extras_eq(left: &[EncodedTerm], right: &[EncodedTerm]) -> bool {
296    left.len() == right.len() && left.iter().all(|term| right.contains(term))
297}
298
299impl std::fmt::Debug for GraphFilter {
300    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
301        f.debug_struct("GraphFilter")
302            .field("exclude", &self.inner.exclude)
303            .field("terms", &self.terms())
304            .finish()
305    }
306}
307
308/// Allow-list remainder → ground / residual filter / empty producer.
309fn composed_from_allow(filter: GraphFilter) -> ComposedGraph {
310    match filter.len() {
311        0 => ComposedGraph::Empty,
312        1 => ComposedGraph::Ground(filter.inner.singleton_term().expect("len 1")),
313        _ => ComposedGraph::Filter(filter),
314    }
315}
316
317/// Result of intersecting an existing G constraint with a pushed allow-list.
318#[derive(Debug, Clone, PartialEq)]
319pub(crate) enum ComposedGraph {
320    /// Single legal graph: bind `pattern.graph_name` and drop the residual.
321    Ground(EncodedTerm),
322    /// Residual allow- or block-list; G stays unbound.
323    Filter(GraphFilter),
324    /// No legal graph remains (empty producer).
325    Empty,
326}
327
328impl ComposedGraph {
329    /// `(graph_name, graph_filter)` to store on a scan or path.
330    pub(crate) fn into_slots(self) -> (Option<EncodedTerm>, Option<GraphFilter>) {
331        match self {
332            Self::Ground(term) => (Some(term), None),
333            Self::Filter(filter) => (None, Some(filter)),
334            Self::Empty => (None, Some(GraphFilter::empty_allow())),
335        }
336    }
337}
338
339/// Intersect `pushed` (VALUES / sameTerm / join keys) with the G constraint
340/// already on the scan or path.
341///
342/// A singleton becomes [`ComposedGraph::Ground`] only if it is still legal.
343/// Disjoint → [`ComposedGraph::Empty`], not an absent filter. Multi-value
344/// push intersects; it does not replace. `None` means the result allow-list
345/// would exceed [`GRAPH_FILTER_TERM_CAP`] (leave the original constraint).
346pub(crate) fn compose_graph_constraint(
347    graph_name: Option<&EncodedTerm>,
348    graph_filter: Option<&GraphFilter>,
349    pushed: &[EncodedTerm],
350) -> Option<ComposedGraph> {
351    let legal = |term: &EncodedTerm| -> bool {
352        if let Some(ground) = graph_name
353            && ground != term
354        {
355            return false;
356        }
357        match graph_filter {
358            Some(filter) => filter.allows(term),
359            None => true,
360        }
361    };
362    let mut kept = GraphFilterData::empty(false);
363    for term in pushed {
364        if legal(term) {
365            kept.insert(term);
366        }
367    }
368    if (kept.len() as u64) > GRAPH_FILTER_TERM_CAP {
369        return None;
370    }
371    Some(composed_from_allow(GraphFilter::from_data(kept)))
372}
373
374/// Apply [`compose_graph_constraint`] in place. `false` = over cap (unchanged).
375pub(crate) fn push_graph_terms(
376    graph_name: &mut Option<EncodedTerm>,
377    graph_filter: &mut Option<GraphFilter>,
378    pushed: &[EncodedTerm],
379) -> bool {
380    let Some(composed) =
381        compose_graph_constraint(graph_name.as_ref(), graph_filter.as_ref(), pushed)
382    else {
383        return false;
384    };
385    let (name, filter) = composed.into_slots();
386    *graph_name = name;
387    *graph_filter = filter;
388    true
389}
390
391/// How a bare BGP / path (SPARQL default graph) binds G.
392#[derive(Debug, Clone, PartialEq)]
393pub enum DefaultGraphWindow {
394    /// RDF unnamed graph only (`Some(DefaultGraph)`).
395    RdfDefault,
396    /// Every graph, named and unnamed (`graph_name = None`).
397    /// Storage unique's S/P/O (`merge_default_graph`) — RDF merge, not a bag of quads.
398    AllGraphs,
399    /// No `FROM` graphs: bare BGP matches nothing.
400    Empty,
401    /// Single `FROM` IRI: ground G.
402    Ground(EncodedTerm),
403    /// Several `FROM` IRIs: unbound G plus allow-list.
404    /// Same RDF-merge unique as [`Self::AllGraphs`].
405    Allow(GraphFilter),
406}
407
408impl DefaultGraphWindow {
409    /// Multi-source SPARQL default graph: an RDF merge of physical graphs.
410    ///
411    /// [`Self::AllGraphs`] (`default_union`) and [`Self::Allow`] (several `FROM`
412    /// IRIs) need storage-side S/P/O unique + G rewritten to DefaultGraph.
413    /// A single grounded graph does not.
414    pub fn merge_default_graph(&self) -> bool {
415        matches!(self, Self::AllGraphs | Self::Allow(_))
416    }
417}
418
419/// How `GRAPH` patterns bind G.
420#[derive(Debug, Clone, PartialEq)]
421pub enum NamedGraphWindow {
422    /// Engine default: no catalog. Unbound G, block RDF default, collect `?g`.
423    EngineAllNamed,
424    /// `FROM NAMED` absent or empty when a dataset description is present.
425    Empty,
426    /// One named graph IRI.
427    Ground(EncodedTerm),
428    /// Enumerated `FROM NAMED` / protocol named-graph list.
429    Allow(GraphFilter),
430}
431
432/// Resolved SPARQL dataset for one query (planner + executor).
433#[derive(Debug, Clone, PartialEq)]
434pub struct QueryDataset {
435    /// Window for triple patterns not inside `GRAPH { }`.
436    pub default: DefaultGraphWindow,
437    /// Window for `GRAPH <g>` / `GRAPH ?g`.
438    pub named: NamedGraphWindow,
439    /// Hash → raw IRI for hashed `FROM NAMED` / protocol named-graph URIs.
440    ///
441    /// Plan-time `GRAPH ?g` VALUES domains use this so late materialization
442    /// does not ask the registry for IRIs that were never stored.
443    pub named_strings: Vec<(StrHash, String)>,
444}
445
446impl QueryDataset {
447    /// Engine fallback: no `FROM` / protocol dataset.
448    pub fn engine_fallback(default_union: bool) -> Self {
449        Self {
450            default: if default_union {
451                DefaultGraphWindow::AllGraphs
452            } else {
453                DefaultGraphWindow::RdfDefault
454            },
455            named: NamedGraphWindow::EngineAllNamed,
456            named_strings: Vec::new(),
457        }
458    }
459
460    /// Build from SPARQL Protocol graph IRIs, else query-text `FROM` / `FROM NAMED`,
461    /// else `default_union`.
462    pub fn resolve(
463        protocol_default: &[String],
464        protocol_named: &[String],
465        query: Option<&SparqlQueryDataset>,
466        default_union: bool,
467    ) -> Result<Self, ComputeError> {
468        if !protocol_default.is_empty() || !protocol_named.is_empty() {
469            return Self::from_iri_lists(protocol_default, protocol_named);
470        }
471        if let Some(query) = query {
472            return Self::from_sparql(query);
473        }
474        Ok(Self::engine_fallback(default_union))
475    }
476
477    fn from_sparql(query: &SparqlQueryDataset) -> Result<Self, ComputeError> {
478        let default_iris: Vec<String> = query
479            .default
480            .iter()
481            .map(|n| n.as_str().to_owned())
482            .collect();
483        let named_iris: Vec<String> = query
484            .named
485            .as_ref()
486            .map(|graphs| graphs.iter().map(|n| n.as_str().to_owned()).collect())
487            .unwrap_or_default();
488        // spargebra always sets `named: Some(_)` when any FROM/FROM NAMED is present.
489        Self::from_iri_lists(&default_iris, &named_iris)
490    }
491
492    /// Explicit dataset description (`FROM` / protocol graph URIs). Empty lists
493    /// are empty SPARQL windows, not the engine fallback — that is
494    /// [`Self::engine_fallback`].
495    fn from_iri_lists(
496        default_iris: &[String],
497        named_iris: &[String],
498    ) -> Result<Self, ComputeError> {
499        // Encode first (trim / validate), then unique, then cap. Duplicate
500        // FROM / default-graph-uri is an RDF merge of one graph, not N graphs.
501        let default_terms = unique_encoded_terms(encode_graph_iris(default_iris)?.0);
502        let (named_terms, named_strings) = encode_graph_iris(named_iris)?;
503        let named_terms = unique_encoded_terms(named_terms);
504        let named_strings = unique_named_strings(named_strings);
505        if default_terms.len() > GRAPH_FILTER_TERM_CAP as usize {
506            return Err(ComputeError::UnsupportedSparql(format!(
507                "FROM / default-graph-uri list exceeds {GRAPH_FILTER_TERM_CAP} graphs"
508            )));
509        }
510        if named_terms.len() > GRAPH_FILTER_TERM_CAP as usize {
511            return Err(ComputeError::UnsupportedSparql(format!(
512                "FROM NAMED / named-graph-uri list exceeds {GRAPH_FILTER_TERM_CAP} graphs"
513            )));
514        }
515        let default = match default_terms.as_slice() {
516            [] => DefaultGraphWindow::Empty,
517            [one] => DefaultGraphWindow::Ground(one.clone()),
518            many => DefaultGraphWindow::Allow(GraphFilter::allow(many)),
519        };
520        let named = match named_terms.as_slice() {
521            [] => NamedGraphWindow::Empty,
522            [one] => NamedGraphWindow::Ground(one.clone()),
523            many => NamedGraphWindow::Allow(GraphFilter::allow(many)),
524        };
525        Ok(Self {
526            default,
527            named,
528            named_strings,
529        })
530    }
531
532    /// Whether a `GRAPH <iri>` name is in the named window.
533    pub fn named_contains(&self, graph: &EncodedTerm) -> bool {
534        match &self.named {
535            NamedGraphWindow::EngineAllNamed => !matches!(graph, EncodedTerm::DefaultGraph),
536            NamedGraphWindow::Empty => false,
537            NamedGraphWindow::Ground(term) => term == graph,
538            NamedGraphWindow::Allow(filter) => filter.contains_member(graph),
539        }
540    }
541}
542
543impl Default for QueryDataset {
544    fn default() -> Self {
545        Self::engine_fallback(false)
546    }
547}
548
549/// Encoded graph IRIs plus hash → raw pairs for hashed named nodes.
550type EncodedGraphIris = (Vec<EncodedTerm>, Vec<(StrHash, String)>);
551
552/// Encode graph IRIs and keep hash → raw pairs for hashed named nodes.
553fn encode_graph_iris(iris: &[String]) -> Result<EncodedGraphIris, ComputeError> {
554    let mut terms = Vec::with_capacity(iris.len());
555    let mut strings = Vec::new();
556    for iri in iris {
557        let iri = iri.trim();
558        if iri.is_empty() {
559            return Err(ComputeError::UnsupportedSparql(
560                "graph IRI must be a non-empty absolute URI".into(),
561            ));
562        }
563        if iri.starts_with('<') || iri.ends_with('>') {
564            return Err(ComputeError::UnsupportedSparql(
565                "graph IRI must not be wrapped in <>".into(),
566            ));
567        }
568        let node = NamedNode::new(iri).map_err(|err| {
569            ComputeError::UnsupportedSparql(format!("invalid graph IRI {iri:?}: {err}"))
570        })?;
571        let encoded = EncodedTerm::from(&node);
572        strings.extend(strings_entries_for_term(&Term::NamedNode(node), &encoded));
573        terms.push(encoded);
574    }
575    Ok((terms, strings))
576}
577
578fn unique_encoded_terms(terms: Vec<EncodedTerm>) -> Vec<EncodedTerm> {
579    let mut out = Vec::with_capacity(terms.len());
580    for term in terms {
581        if !out.contains(&term) {
582            out.push(term);
583        }
584    }
585    out
586}
587
588fn unique_named_strings(strings: Vec<(StrHash, String)>) -> Vec<(StrHash, String)> {
589    let mut out = Vec::with_capacity(strings.len());
590    for pair in strings {
591        if !out.iter().any(|(hash, _)| hash == &pair.0) {
592            out.push(pair);
593        }
594    }
595    out
596}
597
598/// Active graph window while lowering a graph pattern.
599#[derive(Debug, Clone, PartialEq)]
600pub(crate) enum GraphScope {
601    /// SPARQL default graph (`FROM` / `default_union`).
602    Default,
603    /// `GRAPH <iri>` (or sameTerm-grounded `?g`).
604    NamedIri(EncodedTerm),
605    /// `GRAPH ?g`.
606    NamedVar {
607        variable: spargebra::term::Variable,
608        window: NamedVarWindow,
609    },
610    /// Dataset named set is empty, or `GRAPH <iri>` is not in `FROM NAMED`.
611    Empty,
612}
613
614/// How `GRAPH ?g` constrains inner scans when `?g` is not yet a single IRI.
615#[derive(Debug, Clone, PartialEq)]
616pub(crate) enum NamedVarWindow {
617    /// Unbound G, block RDF default, project `?g` from results.
618    Collect,
619    /// Finite known named graphs (allow-list).
620    Allow(GraphFilter),
621    /// Single named graph.
622    Ground(EncodedTerm),
623}
624
625impl GraphScope {
626    pub(crate) fn named_iri(term: EncodedTerm, dataset: &QueryDataset) -> Self {
627        if dataset.named_contains(&term) {
628            Self::NamedIri(term)
629        } else {
630            Self::Empty
631        }
632    }
633
634    pub(crate) fn named_var(variable: spargebra::term::Variable, dataset: &QueryDataset) -> Self {
635        let window = match &dataset.named {
636            NamedGraphWindow::Empty => return Self::Empty,
637            NamedGraphWindow::EngineAllNamed => NamedVarWindow::Collect,
638            NamedGraphWindow::Ground(term) => NamedVarWindow::Ground(term.clone()),
639            NamedGraphWindow::Allow(filter) => NamedVarWindow::Allow(filter.clone()),
640        };
641        Self::NamedVar { variable, window }
642    }
643}
644
645#[cfg(test)]
646mod tests {
647    use super::*;
648
649    #[test]
650    fn engine_fallback_false_is_rdf_default() {
651        let ds = QueryDataset::engine_fallback(false);
652        assert_eq!(ds.default, DefaultGraphWindow::RdfDefault);
653        assert_eq!(ds.named, NamedGraphWindow::EngineAllNamed);
654    }
655
656    #[test]
657    fn engine_fallback_true_is_all_graphs() {
658        let ds = QueryDataset::engine_fallback(true);
659        assert_eq!(ds.default, DefaultGraphWindow::AllGraphs);
660    }
661
662    #[test]
663    fn exclude_default_blocks_unnamed_only() {
664        let filter = GraphFilter::exclude_default();
665        assert!(!filter.allows(&EncodedTerm::DefaultGraph));
666        let named = EncodedTerm::from(&NamedNode::new("http://ex/g").unwrap());
667        assert!(filter.allows(&named));
668    }
669
670    #[test]
671    fn protocol_overrides_query_when_any_uri_present() {
672        let ds =
673            QueryDataset::resolve(&["http://ex/from-protocol".into()], &[], None, true).unwrap();
674        match ds.default {
675            DefaultGraphWindow::Ground(term) => {
676                assert_eq!(
677                    term,
678                    EncodedTerm::from(&NamedNode::new("http://ex/from-protocol").unwrap())
679                );
680            }
681            other => panic!("expected Ground, got {other:?}"),
682        }
683        assert_eq!(ds.named, NamedGraphWindow::Empty);
684    }
685
686    #[test]
687    fn from_named_only_empties_default_window() {
688        let ds = QueryDataset::resolve(&[], &["http://ex/g".into()], None, true).unwrap();
689        assert_eq!(ds.default, DefaultGraphWindow::Empty);
690        match ds.named {
691            NamedGraphWindow::Ground(term) => {
692                assert_eq!(
693                    term,
694                    EncodedTerm::from(&NamedNode::new("http://ex/g").unwrap())
695                );
696            }
697            other => panic!("expected Ground named window, got {other:?}"),
698        }
699    }
700
701    #[test]
702    fn rejects_angle_brackets() {
703        let err = QueryDataset::resolve(&["<http://ex/g>".into()], &[], None, false).unwrap_err();
704        assert!(err.to_string().contains("<>"), "{err}");
705    }
706
707    #[test]
708    fn cap_rejects_too_many_from() {
709        let iris: Vec<String> = (0..=GRAPH_FILTER_TERM_CAP)
710            .map(|i| format!("http://ex/g{i}"))
711            .collect();
712        let err = QueryDataset::resolve(&iris, &[], None, false).unwrap_err();
713        assert!(err.to_string().contains("exceeds"), "{err}");
714    }
715
716    #[test]
717    fn duplicate_from_iris_are_one_ground_graph() {
718        let ds = QueryDataset::resolve(
719            &["http://ex/g".into(), "http://ex/g".into()],
720            &[],
721            None,
722            false,
723        )
724        .unwrap();
725        match &ds.default {
726            DefaultGraphWindow::Ground(term) => {
727                assert_eq!(
728                    term,
729                    &EncodedTerm::from(&NamedNode::new("http://ex/g").unwrap())
730                );
731            }
732            other => panic!("expected Ground, got {other:?}"),
733        }
734        assert!(!ds.default.merge_default_graph());
735    }
736
737    #[test]
738    fn duplicate_from_does_not_count_toward_cap() {
739        let iris: Vec<String> = (0..=GRAPH_FILTER_TERM_CAP)
740            .map(|_| "http://ex/g".to_string())
741            .collect();
742        let ds = QueryDataset::resolve(&iris, &[], None, false).unwrap();
743        assert!(
744            matches!(ds.default, DefaultGraphWindow::Ground(_)),
745            "expected Ground after unique, got {:?}",
746            ds.default
747        );
748    }
749
750    /// Test helper: encode an IRI as an EncodedTerm.
751    fn iri(iri: &str) -> EncodedTerm {
752        EncodedTerm::from(&NamedNode::new(iri).unwrap())
753    }
754
755    #[test]
756    fn empty_allow_matches_nothing_empty_block_matches_everything() {
757        let named = iri("http://ex/g");
758        assert!(!GraphFilter::empty_allow().allows(&named));
759        assert!(!GraphFilter::empty_allow().allows(&EncodedTerm::DefaultGraph));
760        let empty_block = GraphFilter::exclude(Vec::<EncodedTerm>::new());
761        assert!(empty_block.allows(&named));
762        assert!(empty_block.allows(&EncodedTerm::DefaultGraph));
763        assert_eq!(GraphFilter::to_wire(None), (&[][..], false));
764        assert_eq!(
765            GraphFilter::to_wire(Some(&GraphFilter::empty_allow())),
766            (&[][..], true)
767        );
768    }
769
770    #[test]
771    fn compose_from_named_with_disjoint_push_is_empty() {
772        let g1 = iri("http://ex/g1");
773        let g2 = iri("http://ex/g2");
774        let filter = GraphFilter::allow(Arc::from([g1.clone()]));
775        assert_eq!(
776            compose_graph_constraint(None, Some(&filter), &[g2]),
777            Some(ComposedGraph::Empty)
778        );
779    }
780
781    #[test]
782    fn compose_from_named_grounds_only_when_legal() {
783        let g1 = iri("http://ex/g1");
784        let g2 = iri("http://ex/g2");
785        let filter = GraphFilter::allow(Arc::from([g1.clone(), g2.clone()]));
786        assert_eq!(
787            compose_graph_constraint(None, Some(&filter), std::slice::from_ref(&g2)),
788            Some(ComposedGraph::Ground(g2))
789        );
790        let block = GraphFilter::exclude_default();
791        assert_eq!(
792            compose_graph_constraint(None, Some(&block), &[EncodedTerm::DefaultGraph]),
793            Some(ComposedGraph::Empty)
794        );
795        assert_eq!(
796            compose_graph_constraint(None, Some(&block), std::slice::from_ref(&g1)),
797            Some(ComposedGraph::Ground(g1))
798        );
799    }
800
801    #[test]
802    fn compose_multi_value_intersects_not_replaces() {
803        let g1 = iri("http://ex/g1");
804        let g2 = iri("http://ex/g2");
805        let g3 = iri("http://ex/g3");
806        let filter = GraphFilter::allow(Arc::from([g1.clone(), g2.clone()]));
807        match compose_graph_constraint(None, Some(&filter), &[g2.clone(), g3]) {
808            Some(ComposedGraph::Ground(term)) => assert_eq!(term, g2),
809            other => panic!("expected Ground(g2), got {other:?}"),
810        }
811    }
812
813    #[test]
814    fn subtract_allow_empty_remainder_is_composed_empty() {
815        let g1 = iri("http://ex/g1");
816        let g2 = iri("http://ex/g2");
817        let filter = GraphFilter::allow(Arc::from([g1.clone(), g2.clone()]));
818        assert_eq!(filter.subtract_allow(&[g1, g2]), Some(ComposedGraph::Empty));
819        assert!(
820            GraphFilter::exclude_default()
821                .subtract_allow(std::slice::from_ref(&iri("http://ex/g1")))
822                .is_none(),
823            "wrong polarity must not look like an empty remainder"
824        );
825    }
826
827    #[test]
828    fn subtract_allow_singleton_remainder_grounds() {
829        let g1 = iri("http://ex/g1");
830        let g2 = iri("http://ex/g2");
831        let filter = GraphFilter::allow(Arc::from([g1.clone(), g2.clone()]));
832        assert_eq!(
833            filter.subtract_allow(std::slice::from_ref(&g2)),
834            Some(ComposedGraph::Ground(g1))
835        );
836    }
837
838    #[test]
839    fn allow_list_equality_ignores_insert_order_and_wire_is_sorted() {
840        let g1 = iri("http://ex/g1");
841        let g2 = iri("http://ex/g2");
842        let a = GraphFilter::allow([g2.clone(), g1.clone()]);
843        let b = GraphFilter::allow([g1.clone(), g2.clone()]);
844        assert_eq!(a, b);
845        assert_eq!(a.terms(), b.terms());
846        let first = a.terms().as_ptr();
847        assert_eq!(
848            a.terms().as_ptr(),
849            first,
850            "wire slice must be cached on the Arc"
851        );
852        let mut encoded = a.terms().to_vec();
853        encoded.sort_by_cached_key(encode_term_bytes);
854        assert_eq!(a.terms(), encoded.as_slice());
855    }
856
857    #[test]
858    fn union_exclude_wrong_polarity_and_over_cap_leave_none() {
859        let g1 = iri("http://ex/g1");
860        let allow = GraphFilter::allow(Arc::from([g1.clone()]));
861        assert!(
862            allow
863                .union_exclude(std::slice::from_ref(&iri("http://ex/g2")))
864                .is_none()
865        );
866        let extra: Vec<EncodedTerm> = (0..=GRAPH_FILTER_TERM_CAP)
867            .map(|i| iri(&format!("http://ex/x{i}")))
868            .collect();
869        assert!(
870            GraphFilter::exclude_default()
871                .union_exclude(&extra)
872                .is_none(),
873            "over-threshold must leave the original filter, not clear it"
874        );
875        let merged = GraphFilter::exclude_default()
876            .union_exclude(std::slice::from_ref(&g1))
877            .expect("under-threshold union");
878        match merged {
879            ComposedGraph::Filter(filter) => {
880                assert!(filter.is_exclude());
881                assert!(filter.contains_member(&EncodedTerm::DefaultGraph));
882                assert!(filter.contains_member(&g1));
883            }
884            other => panic!("expected Filter, got {other:?}"),
885        }
886    }
887}