Skip to main content

waratah_compute/
describe.rs

1//! SPARQL `DESCRIBE` execution: star / CBD / SCBD over hexastore scans.
2//!
3//! Resource selection is the WHERE/`Project` plan (same as SELECT). This
4//! module pulls descriptions with prefix scans, not a synthesized CONSTRUCT.
5
6use std::fmt;
7
8use waratah_storage::{EncodedTerm, EncodedTriplePattern, Variable};
9
10use crate::clients::{
11    BlobStoreClient, HexastoreCatalog, HexastoreGeo, HexastoreScan, StringResolve,
12};
13use crate::construct::{EncodedTriple, encoded_is_blank, encoded_is_literal, valid_rdf_triple};
14use crate::context::QueryContext;
15use crate::dataset::{DefaultGraphWindow, GraphFilter};
16use crate::error::ComputeError;
17use crate::plan::ScanOp;
18use crate::query::QueryEngine;
19use crate::solutions::EncodedSolutions;
20
21/// How [`QueryEngine`] builds a DESCRIBE result graph.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub enum DescribeMode {
24    /// Outgoing triples plus incoming triples whose subject is not a blank node.
25    /// No blank-node closure.
26    #[default]
27    Star,
28    /// Outgoing triples, recursively describing blank-node objects. No incoming.
29    Cbd,
30    /// [`Self::Cbd`] plus all incoming triples, plus CBD of blank incoming subjects.
31    Scbd,
32}
33
34impl fmt::Display for DescribeMode {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        f.write_str(match self {
37            Self::Star => "star",
38            Self::Cbd => "cbd",
39            Self::Scbd => "scbd",
40        })
41    }
42}
43
44impl<H: HexastoreScan + HexastoreCatalog + HexastoreGeo, R: StringResolve + BlobStoreClient>
45    QueryEngine<H, R>
46{
47    /// Describe each distinct projected term under this engine's [`DescribeMode`].
48    pub(crate) async fn describe_resources(
49        &self,
50        projection: &[Variable],
51        solutions: &EncodedSolutions,
52        ctx: &QueryContext,
53    ) -> Result<Vec<EncodedTriple>, ComputeError> {
54        // Empty SPARQL default graph: SELECT BGP is emptied in `lower_leaf`
55        // before `plan_scan_op` (which would still ground RDF DefaultGraph).
56        // DESCRIBE expansion builds its own scans, so it must not treat Empty
57        // as the unnamed graph. Constant IRI targets stay identified; there
58        // is nothing in the default graph to copy.
59        if matches!(ctx.dataset().default, DefaultGraphWindow::Empty) {
60            return Ok(Vec::new());
61        }
62        let targets = distinct_targets(projection, solutions)?;
63        let mut out = Vec::new();
64        let mut visited = Vec::new();
65        for target in targets {
66            match self.describe_mode() {
67                DescribeMode::Star => self.describe_star(&target, ctx, &mut out).await?,
68                DescribeMode::Cbd => {
69                    self.describe_cbd(&target, ctx, &mut visited, &mut out)
70                        .await?;
71                }
72                DescribeMode::Scbd => {
73                    self.describe_scbd(&target, ctx, &mut visited, &mut out)
74                        .await?;
75                }
76            }
77        }
78        Ok(out)
79    }
80
81    /// DESCRIBE materialization consumes whole relations as RAW QUADS:
82    /// the describe scan ops are deliberately variable-free (no `?p`/`?o`
83    /// slots — `make_outgoing_scan_op` binds the resource and leaves the
84    /// ScanOp's variable fields empty), so the fetch service's solutions
85    /// representation cannot serve them. Documented exception (plan §6,
86    /// stage-2 audit): `scan_batched_all` batches at `scan_batch()` ≤ the
87    /// unary ceiling (no oversized-window hazard), and the §6 "memo reuse"
88    /// premise was refuted — star mode's two scans have distinct keys and
89    /// CBD's `visited` set already guards re-description.
90    async fn describe_star(
91        &self,
92        resource: &EncodedTerm,
93        ctx: &QueryContext,
94        out: &mut Vec<EncodedTriple>,
95    ) -> Result<(), ComputeError> {
96        if !encoded_is_literal(resource) && !matches!(resource, EncodedTerm::DefaultGraph) {
97            for quad in self
98                .scan_batched_all(&make_outgoing_scan_op(resource.clone(), ctx), ctx)
99                .await?
100            {
101                push_quad(out, quad.subject, quad.predicate, quad.object);
102            }
103        }
104        for quad in self
105            .scan_batched_all(&make_incoming_scan_op(resource.clone(), ctx), ctx)
106            .await?
107        {
108            if encoded_is_blank(&quad.subject) {
109                continue;
110            }
111            push_quad(out, quad.subject, quad.predicate, quad.object);
112        }
113        Ok(())
114    }
115
116    fn describe_cbd<'a>(
117        &'a self,
118        resource: &'a EncodedTerm,
119        ctx: &'a QueryContext,
120        visited: &'a mut Vec<EncodedTerm>,
121        out: &'a mut Vec<EncodedTriple>,
122    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), ComputeError>> + Send + 'a>>
123    {
124        Box::pin(async move {
125            if encoded_is_literal(resource) || matches!(resource, EncodedTerm::DefaultGraph) {
126                return Ok(());
127            }
128            if visited.iter().any(|seen| seen == resource) {
129                return Ok(());
130            }
131            visited.push(resource.clone());
132            for quad in self
133                .scan_batched_all(&make_outgoing_scan_op(resource.clone(), ctx), ctx)
134                .await?
135            {
136                let object = quad.object.clone();
137                let is_blank_object = encoded_is_blank(&object);
138                push_quad(out, quad.subject, quad.predicate, quad.object);
139                if is_blank_object {
140                    for b_quad in self
141                        .scan_batched_all(&make_outgoing_scan_op(object, ctx), ctx)
142                        .await?
143                    {
144                        push_quad(out, b_quad.subject, b_quad.predicate, b_quad.object);
145                    }
146                }
147            }
148            Ok(())
149        })
150    }
151
152    async fn describe_scbd(
153        &self,
154        resource: &EncodedTerm,
155        ctx: &QueryContext,
156        visited: &mut Vec<EncodedTerm>,
157        out: &mut Vec<EncodedTriple>,
158    ) -> Result<(), ComputeError> {
159        self.describe_cbd(resource, ctx, visited, out).await?;
160        let incoming = self
161            .scan_batched_all(&make_incoming_scan_op(resource.clone(), ctx), ctx)
162            .await?;
163        let mut blank_subjects = Vec::new();
164        for quad in incoming {
165            if encoded_is_blank(&quad.subject) && !blank_subjects.contains(&quad.subject) {
166                blank_subjects.push(quad.subject.clone());
167            }
168            push_quad(out, quad.subject, quad.predicate, quad.object);
169        }
170        for blank in &blank_subjects {
171            self.describe_cbd(blank, ctx, visited, out).await?;
172        }
173        Ok(())
174    }
175}
176
177fn distinct_targets(
178    projection: &[Variable],
179    solutions: &EncodedSolutions,
180) -> Result<Vec<EncodedTerm>, ComputeError> {
181    let mut out = Vec::new();
182    for variable in projection {
183        let Some(column) = solutions.column(variable)? else {
184            continue;
185        };
186        for term in column.terms(&solutions.dict()).into_iter().flatten() {
187            if matches!(term, EncodedTerm::DefaultGraph) {
188                continue;
189            }
190            if !out.contains(&term) {
191                out.push(term);
192            }
193        }
194    }
195    Ok(out)
196}
197
198fn describe_graph_window(ctx: &QueryContext) -> (Option<EncodedTerm>, Option<GraphFilter>, bool) {
199    let window = &ctx.dataset().default;
200    let (graph_name, graph_filter) = match window {
201        DefaultGraphWindow::RdfDefault => (Some(EncodedTerm::DefaultGraph), None),
202        // SELECT empties BGP via `lower_leaf`. DESCRIBE must not ground RDF
203        // DefaultGraph. Empty allow-list skip-RPCs in scan-fetch if a helper
204        // is called without the `describe_resources` early return.
205        DefaultGraphWindow::Empty => (None, Some(GraphFilter::empty_allow())),
206        DefaultGraphWindow::AllGraphs => (None, None),
207        DefaultGraphWindow::Ground(term) => (Some(term.clone()), None),
208        DefaultGraphWindow::Allow(filter) => (None, Some(filter.clone())),
209    };
210    (graph_name, graph_filter, window.merge_default_graph())
211}
212
213fn make_outgoing_scan_op(subject: EncodedTerm, ctx: &QueryContext) -> ScanOp {
214    let (graph_name, graph_filter, merge_default_graph) = describe_graph_window(ctx);
215    ScanOp {
216        ancestor_push_return_bound: None,
217        fetch_once: None,
218        pattern: EncodedTriplePattern {
219            subject: Some(subject),
220            predicate: None,
221            object: None,
222            graph_name,
223        },
224        subject: None,
225        predicate: None,
226        object: None,
227        graph: None,
228        produced_row_count_estimate: 1,
229        broadcasted: None,
230        graph_filter,
231        grounded: Vec::new(),
232        merge_default_graph,
233        marks: Vec::new(),
234        domain_scan: None,
235        head_scan: None,
236        head_scan_counts: None,
237        domain_counts: None,
238        iri_only: Vec::new(),
239        eager: Vec::new(),
240        join_domains: crate::plan::JoinDomainStamps::default(),
241    }
242}
243
244fn make_incoming_scan_op(object: EncodedTerm, ctx: &QueryContext) -> ScanOp {
245    let (graph_name, graph_filter, merge_default_graph) = describe_graph_window(ctx);
246    ScanOp {
247        ancestor_push_return_bound: None,
248        fetch_once: None,
249        pattern: EncodedTriplePattern {
250            subject: None,
251            predicate: None,
252            object: Some(object),
253            graph_name,
254        },
255        subject: None,
256        predicate: None,
257        object: None,
258        graph: None,
259        produced_row_count_estimate: 1,
260        broadcasted: None,
261        graph_filter,
262        grounded: Vec::new(),
263        merge_default_graph,
264        marks: Vec::new(),
265        domain_scan: None,
266        head_scan: None,
267        head_scan_counts: None,
268        domain_counts: None,
269        iri_only: Vec::new(),
270        eager: Vec::new(),
271        join_domains: crate::plan::JoinDomainStamps::default(),
272    }
273}
274
275fn push_quad(
276    out: &mut Vec<EncodedTriple>,
277    subject: EncodedTerm,
278    predicate: EncodedTerm,
279    object: EncodedTerm,
280) {
281    if !valid_rdf_triple(&subject, &predicate, &object) {
282        return;
283    }
284    let triple = EncodedTriple {
285        subject,
286        predicate,
287        object,
288    };
289    if !out.contains(&triple) {
290        out.push(triple);
291    }
292}