Skip to main content

waratah_compute/
schema_summary.rs

1//! Per-repository schema summary for the AI context endpoint (contract S2,
2//! `GET /waratah/repositories/{id}/ai-context`).
3//!
4//! Computed as a fixed set of internal SPARQL SELECTs through the node's
5//! own query engine — which is the hexastore-axes computation, not a
6//! generic self-query: the planner lowers the `?s a ?cls` head/count shapes
7//! onto the TSG skip-scan RPCs (`AxisHeadScan` / `AxisHeadScanCounts`,
8//! ARCHITECTURE.md §2) and batches the ground `VALUES` IRIs of every facet
9//! lookup into broadcast seek-unions, so no full-relation scan ever runs.
10//! Rewriting this against the storage traits directly would duplicate the
11//! graph-window / MVCC semantics the query engine already owns.
12//!
13//! Every query runs at `SnapshotId::latest()` with union-over-graphs
14//! semantics (`with_default_union(true)`, plan D10): the summary describes
15//! the whole repository, so schema triples in named graphs are not
16//! invisible on default-configured engines. The count scans already
17//! implement `merge_default_graph` for exactly this shape.
18
19use std::collections::{HashMap, HashSet};
20
21use waratah_storage::EncodedTriplePattern;
22use waratah_storage::IndexPermutation;
23use waratah_storage::PartitionAxis;
24use waratah_storage::SnapshotId;
25use waratah_storage::Term;
26use waratah_storage::vocab::rdfs;
27
28use crate::clients::{
29    BlobStoreClient, HexastoreCatalog, HexastoreGeo, HexastoreScan, StringResolve,
30};
31use crate::error::ComputeError;
32use crate::node::ComputeNode;
33use crate::solutions::QueryResults;
34
35/// Server maximum for returned classes (contract: `"caps".classes`).
36pub const MAX_CLASSES: usize = 200;
37/// Server maximum for returned properties (contract: `"caps".properties`).
38pub const MAX_PROPERTIES: usize = 400;
39/// `instanceCounts=auto` computes counts only up to this triple count.
40pub const AUTO_INSTANCE_COUNT_MAX_TRIPLES: u64 = 2_000_000;
41
42/// Resolved limits the API layer reports and clamps against.
43pub struct SchemaSummaryLimits {
44    /// Maximum classes returned (server maximum).
45    pub max_classes: usize,
46    /// Maximum properties returned (server maximum).
47    pub max_properties: usize,
48}
49
50/// The two server maxima, for the route layer (`caps` wire field + limit
51/// clamping).
52pub fn schema_summary_limits() -> SchemaSummaryLimits {
53    SchemaSummaryLimits {
54        max_classes: MAX_CLASSES,
55        max_properties: MAX_PROPERTIES,
56    }
57}
58
59/// Whether instance counts are computed.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum InstanceCounts {
62    /// Compute only when `triple_count <= AUTO_INSTANCE_COUNT_MAX_TRIPLES`.
63    Auto,
64    /// Always compute (may be slow — caller accepted that).
65    Always,
66    /// Never compute (`instanceCount` keys are omitted).
67    Never,
68}
69
70/// Caller request for a summary; limits must already be clamped to the
71/// server maxima by the route layer.
72#[derive(Debug, Clone)]
73pub struct SchemaSummaryParams {
74    /// Maximum classes to return.
75    pub class_limit: usize,
76    /// Maximum properties to return.
77    pub property_limit: usize,
78    /// Whether instance counts are computed.
79    pub instance_counts: InstanceCounts,
80    /// Externally supplied union quad count (the route's ETag pre-count).
81    /// When present it replaces the internal `union_quad_count` RPC, so
82    /// the ETag validator and the body's `tripleCount` are the same
83    /// number — a mutation landing between two separate counts could
84    /// otherwise make them disagree. `None` (tests, direct callers):
85    /// counted internally.
86    pub triple_count: Option<u64>,
87}
88
89/// One class in the summary.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct ClassSummary {
92    /// Class IRI.
93    pub iri: String,
94    /// First `rdfs:label` literal, if any.
95    pub label: Option<String>,
96    /// First `rdfs:comment` literal, if any.
97    pub comment: Option<String>,
98    /// Direct + transitive `rdfs:subClassOf` closure (may name IRIs that
99    /// have no instances and thus never appear in the classes list).
100    /// Blank-node targets are NOT followed: SPARQL query text cannot name
101    /// a stored blank node (`_:x` in a query is query-scoped), so
102    /// `A subClassOf _:r` contributes no ancestor and OWL restriction
103    /// axioms are invisible to the closure.
104    pub super_classes: Vec<String>,
105    /// Distinct subject count; `None` when counts were not computed.
106    pub instance_count: Option<u64>,
107}
108
109/// One property in the summary.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct PropertySummary {
112    /// Property IRI.
113    pub iri: String,
114    /// First `rdfs:label` literal, if any.
115    pub label: Option<String>,
116    /// `owl:ObjectProperty` → object, `owl:DatatypeProperty` → data, plain
117    /// `rdf:Property` or undeclared → other.
118    pub kind: PropertyKind,
119    /// First `rdfs:domain` IRI, if any.
120    pub domain: Option<String>,
121    /// First `rdfs:range` IRI, if any.
122    pub range: Option<String>,
123    /// Direct `rdfs:subPropertyOf` targets (no transitive closure).
124    pub sub_property_of: Vec<String>,
125}
126
127/// Property kind derived from its `rdf:type` declarations.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum PropertyKind {
130    /// Declared `owl:ObjectProperty`.
131    Object,
132    /// Declared `owl:DatatypeProperty`.
133    Data,
134    /// Plain `rdf:Property` or undeclared.
135    Other,
136}
137
138/// The computed summary.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct SchemaSummary {
141    /// Exact visible quad count at the summary's snapshot.
142    pub triple_count: u64,
143    /// Classes, ordered by descending instance count then IRI when counts
144    /// were computed, else by IRI; at most `class_limit` entries.
145    pub classes: Vec<ClassSummary>,
146    /// Whether more classes existed than were returned.
147    pub classes_clipped: bool,
148    /// Properties, ordered by IRI; at most `property_limit` entries.
149    pub properties: Vec<PropertySummary>,
150    /// Whether more properties existed than were returned.
151    pub properties_clipped: bool,
152    /// Whether `instance_count` values were computed (drives the
153    /// `truncated.instanceCounts` wire flag).
154    pub instance_counts_computed: bool,
155}
156
157/// The two owl IRIs `kind` needs (oxrdf's vocab has no `owl` module).
158const OWL_OBJECT_PROPERTY: &str = "http://www.w3.org/2002/07/owl#ObjectProperty";
159const OWL_DATATYPE_PROPERTY: &str = "http://www.w3.org/2002/07/owl#DatatypeProperty";
160const RDF_PROPERTY: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#Property";
161
162impl<H: HexastoreScan + HexastoreCatalog + HexastoreGeo, R: StringResolve + BlobStoreClient>
163    ComputeNode<H, R>
164{
165    /// Build the schema summary (contract S2). See the module doc for why
166    /// this issues internal SPARQL instead of reading the axes directly.
167    pub async fn schema_summary(
168        &self,
169        params: &SchemaSummaryParams,
170    ) -> Result<SchemaSummary, ComputeError> {
171        let snapshot = SnapshotId::latest();
172        // Union count, NOT `quad_count`: that helper pins the default graph
173        // (RDF4J `/size` semantics) while this summary spans every graph —
174        // `tripleCount` and the ETag validator must both see named-graph
175        // writes. The route passes its ETag pre-count in
176        // `params.triple_count` so both derive from ONE count RPC.
177        let triple_count = match params.triple_count {
178            Some(count) => count,
179            None => self.union_quad_count(snapshot).await?,
180        };
181        let count_instances = match params.instance_counts {
182            InstanceCounts::Never => false,
183            InstanceCounts::Always => true,
184            InstanceCounts::Auto => triple_count <= AUTO_INSTANCE_COUNT_MAX_TRIPLES,
185        };
186
187        // One context for every query: latest snapshot, union over graphs.
188        let ctx = self.context(snapshot).with_default_union(true);
189
190        // Classes: the TSG head-count shape when counts are wanted, the
191        // TSG head scan otherwise. The selection read is LIMIT-bounded
192        // (`limit + 1` rows — one extra proves clipping) so a
193        // distinct-class-per-entity repository cannot make one request
194        // materialize the whole head set. Deliberately NO `ORDER BY` in
195        // the query: the head scans emit in encoded-key order, so the
196        // engine would have to materialize everything before sorting —
197        // exactly the unbounded read this bounds. Storage-emission order
198        // selects which rows survive (deterministic per snapshot); the
199        // RETURNED list is then ordered on compute over the bounded page.
200        let (class_rows, instance_counts) = if count_instances {
201            let sparql = format!(
202                "SELECT ?cls (COUNT(DISTINCT ?s) AS ?n) WHERE {{ ?s a ?cls }} \
203                 GROUP BY ?cls LIMIT {}",
204                params.class_limit.saturating_add(1)
205            );
206            let rows = self.select_rows(&ctx, &sparql).await?;
207            let counts: HashMap<String, u64> = rows
208                .iter()
209                .filter_map(|row| row.iri(0).zip(row.integer(1)))
210                .collect();
211            (rows, counts)
212        } else {
213            let sparql = format!(
214                "SELECT DISTINCT ?cls WHERE {{ ?s a ?cls }} LIMIT {}",
215                params.class_limit.saturating_add(1)
216            );
217            (self.select_rows(&ctx, &sparql).await?, HashMap::new())
218        };
219        let classes_clipped = class_rows.len() > params.class_limit;
220        let mut class_iris: Vec<String> = class_rows
221            .into_iter()
222            .take(params.class_limit)
223            .filter_map(|row| row.iri(0))
224            .collect();
225        if count_instances {
226            // Most populated classes first (ties by IRI) over the selected
227            // page, so the returned list leads with the classes an agent
228            // is most likely to ask about.
229            class_iris.sort_by(|a, b| {
230                instance_counts
231                    .get(b)
232                    .cmp(&instance_counts.get(a))
233                    .then_with(|| a.cmp(b))
234            });
235        } else {
236            class_iris.sort_unstable();
237        }
238        class_iris.dedup();
239
240        let property_sparql = format!(
241            "SELECT DISTINCT ?p WHERE {{ ?s ?p ?o }} LIMIT {}",
242            params.property_limit.saturating_add(1)
243        );
244        let properties_clipped_rows = self.select_rows(&ctx, &property_sparql).await?;
245        let properties_clipped = properties_clipped_rows.len() > params.property_limit;
246        let mut property_iris: Vec<String> = properties_clipped_rows
247            .into_iter()
248            .take(params.property_limit)
249            .filter_map(|row| row.iri(0))
250            .collect();
251        property_iris.sort_unstable();
252        property_iris.dedup();
253
254        // Facets over the selected IRIs only: one batched VALUES query per
255        // predicate (broadcast seek-union per term at the partition).
256        // Literal-valued facets (label, comment) and IRI-valued facets
257        // (domain, range, subClassOf, subPropertyOf) share one row shape.
258        let mut all_iris = class_iris.clone();
259        all_iris.extend(property_iris.iter().cloned());
260        let labels = self
261            .facet_literals(&ctx, rdfs::LABEL.as_str(), &all_iris)
262            .await?;
263        let comments = self
264            .facet_literals(&ctx, rdfs::COMMENT.as_str(), &class_iris)
265            .await?;
266        let domains = self
267            .facet_iris(&ctx, rdfs::DOMAIN.as_str(), &property_iris)
268            .await?;
269        let ranges = self
270            .facet_iris(&ctx, rdfs::RANGE.as_str(), &property_iris)
271            .await?;
272        let sub_property_of = self
273            .facet_iri_lists(&ctx, rdfs::SUB_PROPERTY_OF.as_str(), &property_iris)
274            .await?;
275        let kinds = self.property_kinds(&ctx, &property_iris).await?;
276
277        // Transitive super-class closure: expand the frontier until no new
278        // ancestor appears (the known-set makes cycles terminate).
279        let super_edges = self.super_class_edges(&ctx, &class_iris).await?;
280
281        let classes = class_iris
282            .iter()
283            .map(|iri| ClassSummary {
284                iri: iri.clone(),
285                label: labels.get(iri).cloned(),
286                comment: comments.get(iri).cloned(),
287                super_classes: closure_of(iri, &super_edges),
288                instance_count: if count_instances {
289                    instance_counts.get(iri).copied()
290                } else {
291                    None
292                },
293            })
294            .collect();
295        let properties = property_iris
296            .iter()
297            .map(|iri| PropertySummary {
298                iri: iri.clone(),
299                label: labels.get(iri).cloned(),
300                kind: kinds.get(iri).copied().unwrap_or(PropertyKind::Other),
301                domain: domains.get(iri).cloned(),
302                range: ranges.get(iri).cloned(),
303                sub_property_of: sub_property_of.get(iri).cloned().unwrap_or_default(),
304            })
305            .collect();
306        Ok(SchemaSummary {
307            triple_count,
308            classes,
309            classes_clipped,
310            properties,
311            properties_clipped,
312            instance_counts_computed: count_instances,
313        })
314    }
315
316    /// Total visible quads across the default graph **and** every named
317    /// graph (unbound-S SPOG prefix count, no graph filter). This is what
318    /// the summary's `tripleCount` reports.
319    pub async fn union_quad_count(&self, snapshot: SnapshotId) -> Result<u64, ComputeError> {
320        let pattern = EncodedTriplePattern {
321            subject: None,
322            predicate: None,
323            object: None,
324            graph_name: None,
325        };
326        self.queries()
327            .count_encoded_pattern(
328                &pattern,
329                snapshot,
330                PartitionAxis::S,
331                Some(IndexPermutation::Spog),
332            )
333            .await
334    }
335
336    /// Run a SELECT and return its solution rows (empty for non-SELECT
337    /// results, which these fixed queries never produce).
338    async fn select_rows(
339        &self,
340        ctx: &crate::context::QueryContext,
341        sparql: &str,
342    ) -> Result<Vec<Row>, ComputeError> {
343        let solutions = match self.query_with(sparql, ctx).await? {
344            QueryResults::Solutions { solutions, .. } => solutions,
345            _ => Vec::new(),
346        };
347        Ok(solutions.into_iter().map(Row).collect())
348    }
349
350    /// `?x <predicate> ?v` over a batch of ground IRIs → first **literal**
351    /// value per IRI (labels, comments). Deterministic: rows are sorted
352    /// before the first wins; the engine imposes no preference among
353    /// multiple labels (plan Q6).
354    async fn facet_literals(
355        &self,
356        ctx: &crate::context::QueryContext,
357        predicate: &str,
358        iris: &[String],
359    ) -> Result<HashMap<String, String>, ComputeError> {
360        let mut map = HashMap::new();
361        for row in self.facet_rows(ctx, predicate, iris).await? {
362            if let (Some(key), Some(value)) = (row.iri(0), row.string(1)) {
363                map.entry(key).or_insert(value);
364            }
365        }
366        Ok(map)
367    }
368
369    /// Same shape → first **IRI** value per IRI (domain, range).
370    async fn facet_iris(
371        &self,
372        ctx: &crate::context::QueryContext,
373        predicate: &str,
374        iris: &[String],
375    ) -> Result<HashMap<String, String>, ComputeError> {
376        let mut map = HashMap::new();
377        for row in self.facet_rows(ctx, predicate, iris).await? {
378            if let (Some(key), Some(value)) = (row.iri(0), row.iri(1)) {
379                map.entry(key).or_insert(value);
380            }
381        }
382        Ok(map)
383    }
384
385    /// Same shape → every **IRI** value per IRI, sorted (subPropertyOf).
386    async fn facet_iri_lists(
387        &self,
388        ctx: &crate::context::QueryContext,
389        predicate: &str,
390        iris: &[String],
391    ) -> Result<HashMap<String, Vec<String>>, ComputeError> {
392        let mut map: HashMap<String, Vec<String>> = HashMap::new();
393        for row in self.facet_rows(ctx, predicate, iris).await? {
394            if let (Some(key), Some(value)) = (row.iri(0), row.iri(1)) {
395                map.entry(key).or_default().push(value);
396            }
397        }
398        for values in map.values_mut() {
399            values.sort_unstable();
400            values.dedup();
401        }
402        Ok(map)
403    }
404
405    /// Shared row fetch for the facet helpers: `VALUES ?x { … } ?x
406    /// <predicate> ?v`, sorted by (key, value) for deterministic
407    /// first-wins semantics.
408    async fn facet_rows(
409        &self,
410        ctx: &crate::context::QueryContext,
411        predicate: &str,
412        iris: &[String],
413    ) -> Result<Vec<Row>, ComputeError> {
414        if iris.is_empty() {
415            return Ok(Vec::new());
416        }
417        let mut sparql = String::from("SELECT ?x ?v WHERE { VALUES ?x { ");
418        for iri in iris {
419            sparql.push_str(&sparql_iri(iri));
420            sparql.push(' ');
421        }
422        sparql.push_str("} ?x ");
423        sparql.push_str(&sparql_iri(predicate));
424        sparql.push_str(" ?v }");
425        let mut rows = self.select_rows(ctx, &sparql).await?;
426        rows.sort_by(|a, b| {
427            a.render(0)
428                .cmp(&b.render(0))
429                .then_with(|| a.render(1).cmp(&b.render(1)))
430        });
431        Ok(rows)
432    }
433
434    /// Property kinds from the three `rdf:type` declarations that matter.
435    /// A property declared several ways reports the strongest declaration,
436    /// `Object > Data > Other` — the query has no ORDER BY, so row arrival
437    /// order is arbitrary and the stored kind must be replaced whenever a
438    /// stronger declaration shows up.
439    async fn property_kinds(
440        &self,
441        ctx: &crate::context::QueryContext,
442        iris: &[String],
443    ) -> Result<HashMap<String, PropertyKind>, ComputeError> {
444        if iris.is_empty() {
445            return Ok(HashMap::new());
446        }
447        let mut sparql = String::from("SELECT ?x ?t WHERE { VALUES ?x { ");
448        for iri in iris {
449            sparql.push_str(&sparql_iri(iri));
450            sparql.push(' ');
451        }
452        sparql.push_str(
453            "} ?x a ?t FILTER(?t IN (\
454             <http://www.w3.org/2002/07/owl#ObjectProperty>, \
455             <http://www.w3.org/2002/07/owl#DatatypeProperty>, \
456             <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>)) }",
457        );
458        let rows = self.select_rows(ctx, &sparql).await?;
459        let mut kinds: HashMap<String, PropertyKind> = HashMap::new();
460        for row in rows {
461            let (property, declared) = match (row.iri(0), row.iri(1)) {
462                (Some(property), Some(declared)) => (property, declared),
463                _ => continue,
464            };
465            let kind = match declared.as_str() {
466                OWL_OBJECT_PROPERTY => PropertyKind::Object,
467                OWL_DATATYPE_PROPERTY => PropertyKind::Data,
468                // Plain rdf:Property still reports "other" per contract.
469                RDF_PROPERTY => PropertyKind::Other,
470                _ => continue,
471            };
472            // An `or_insert` alone keeps whichever row arrived first: a
473            // property declared `rdf:Property` before
474            // `owl:DatatypeProperty` would report "other". Replace on rank.
475            let entry = kinds.entry(property).or_insert(kind);
476            if kind_rank(kind) > kind_rank(*entry) {
477                *entry = kind;
478            }
479        }
480        Ok(kinds)
481    }
482
483    /// Direct `rdfs:subClassOf` edges for `seeds` plus every ancestor
484    /// discovered on the way (frontier expansion to a fixpoint; the
485    /// known-set both bounds the work and makes cyclic hierarchies
486    /// terminate). Rows whose child or parent is not an IRI (blank-node
487    /// restriction axioms, literals) are skipped — see
488    /// `ClassSummary::super_classes` for why blank nodes cannot be walked.
489    async fn super_class_edges(
490        &self,
491        ctx: &crate::context::QueryContext,
492        seeds: &[String],
493    ) -> Result<HashMap<String, Vec<String>>, ComputeError> {
494        let mut edges: HashMap<String, Vec<String>> = HashMap::new();
495        let mut known: HashSet<String> = seeds.iter().cloned().collect();
496        let mut frontier: Vec<String> = seeds.to_vec();
497        while !frontier.is_empty() {
498            let mut rows = self
499                .facet_rows(ctx, rdfs::SUB_CLASS_OF.as_str(), &frontier)
500                .await?;
501            rows.dedup_by(|a, b| a.iri(0) == b.iri(0) && a.iri(1) == b.iri(1));
502            let mut next = Vec::new();
503            for row in rows {
504                let (child, parent) = match (row.iri(0), row.iri(1)) {
505                    (Some(child), Some(parent)) => (child, parent),
506                    _ => continue,
507                };
508                edges.entry(child).or_default().push(parent.clone());
509                if known.insert(parent.clone()) {
510                    next.push(parent);
511                }
512            }
513            frontier = next;
514        }
515        for parents in edges.values_mut() {
516            parents.sort_unstable();
517            parents.dedup();
518        }
519        Ok(edges)
520    }
521}
522
523/// One solution row with typed accessors; every accessor returns `None`
524/// for unbound or wrong-typed terms so a malformed store degrades to
525/// "facet absent" instead of failing the whole summary.
526#[derive(Debug, Clone)]
527struct Row(Vec<Option<Term>>);
528
529impl Row {
530    /// IRI at `index` (literals and blank nodes are not IRIs).
531    fn iri(&self, index: usize) -> Option<String> {
532        match self.0.get(index)? {
533            Some(Term::NamedNode(node)) => Some(node.as_str().to_owned()),
534            _ => None,
535        }
536    }
537
538    /// Lexical form at `index` when the term is a literal.
539    fn string(&self, index: usize) -> Option<String> {
540        match self.0.get(index)? {
541            Some(Term::Literal(literal)) => Some(literal.value().to_owned()),
542            _ => None,
543        }
544    }
545
546    /// Integer at `index` (counts arrive as typed literals).
547    fn integer(&self, index: usize) -> Option<u64> {
548        match self.0.get(index)? {
549            Some(Term::Literal(literal)) => literal.value().parse().ok(),
550            _ => None,
551        }
552    }
553
554    /// Display form at `index` ("" for unbound) — sort keys only.
555    fn render(&self, index: usize) -> String {
556        match self.0.get(index) {
557            Some(Some(term)) => term.to_string(),
558            _ => String::new(),
559        }
560    }
561}
562
563/// Declaration strength for the kind precedence rule (`property_kinds`):
564/// a property declared several ways reports the strongest declaration.
565fn kind_rank(kind: PropertyKind) -> u8 {
566    match kind {
567        PropertyKind::Object => 2,
568        PropertyKind::Data => 1,
569        PropertyKind::Other => 0,
570    }
571}
572
573/// Transitive closure over the direct-edge map, from `start`.
574fn closure_of(start: &str, edges: &HashMap<String, Vec<String>>) -> Vec<String> {
575    let mut visited: HashSet<String> = HashSet::new();
576    let mut stack: Vec<String> = edges
577        .get(start)
578        .map(|parents| parents.iter().rev().cloned().collect())
579        .unwrap_or_default();
580    while let Some(current) = stack.pop() {
581        if !visited.insert(current.clone()) {
582            continue;
583        }
584        if let Some(parents) = edges.get(&current) {
585            for parent in parents {
586                stack.push(parent.clone());
587            }
588        }
589    }
590    let mut closure: Vec<String> = visited.into_iter().collect();
591    closure.sort_unstable();
592    closure
593}
594
595/// SPARQL IRIREF with the characters the grammar forbids (`\`, `<`, `>`,
596/// `"`, `{`, `}`, `|`, `^`, backtick, and anything ≤ U+0020) escaped as
597/// `\uXXXX`. The engine's own parser then sees a plain ground term.
598fn sparql_iri(iri: &str) -> String {
599    let mut out = String::with_capacity(iri.len() + 2);
600    out.push('<');
601    for character in iri.chars() {
602        let forbidden = matches!(
603            character,
604            '\\' | '<' | '>' | '"' | '{' | '}' | '|' | '^' | '`'
605        ) || character <= '\u{20}';
606        if forbidden {
607            out.push_str(&format!("\\u{:04X}", character as u32));
608        } else {
609            out.push(character);
610        }
611    }
612    out.push('>');
613    out
614}
615
616#[cfg(test)]
617mod tests {
618    use super::*;
619
620    #[test]
621    fn iris_are_escaped_only_where_the_grammar_requires() {
622        assert_eq!(sparql_iri("http://ex/a"), "<http://ex/a>");
623        assert_eq!(
624            sparql_iri("http://ex/a b<c>"),
625            "<http://ex/a\\u0020b\\u003Cc\\u003E>"
626        );
627        // Backslash escapes as its \u form (\u005C) — as legal as `\\`.
628        assert_eq!(sparql_iri("http://ex/a\\b"), "<http://ex/a\\u005Cb>");
629    }
630
631    #[test]
632    fn closure_is_transitive_and_cycle_safe() {
633        let mut edges = HashMap::new();
634        edges.insert(
635            "http://ex/Person".to_owned(),
636            vec!["http://ex/Agent".to_owned()],
637        );
638        edges.insert(
639            "http://ex/Agent".to_owned(),
640            vec!["http://ex/Thing".to_owned()],
641        );
642        // Cycle: Thing is declared a sub-class of Person.
643        edges.insert(
644            "http://ex/Thing".to_owned(),
645            vec!["http://ex/Person".to_owned()],
646        );
647        assert_eq!(
648            closure_of("http://ex/Person", &edges),
649            vec![
650                "http://ex/Agent".to_owned(),
651                "http://ex/Person".to_owned(),
652                "http://ex/Thing".to_owned()
653            ]
654        );
655        assert!(closure_of("http://ex/Leaf", &edges).is_empty());
656    }
657}