Skip to main content

waratah_storage/encode/
decode.rs

1//! Encoded term → [`Term`]: the late-materialization side of encoding.
2//!
3//! Scans and joins move [`EncodedTerm`]s only. Raw strings enter the picture at
4//! the very end, when a compute node resolves the hashes named by
5//! [`hashes_in_term`] and rebuilds `oxrdf` terms with [`decode_term`].
6
7use std::collections::HashMap;
8use std::hash::BuildHasher;
9
10use crate::vocab::xsd;
11
12use super::encoded_term::{CrsId, EncodedTerm, GeoDatatype, well_known_iri};
13pub use super::encoded_term::{GEO_WKB_LITERAL, GEO_WKT_LITERAL};
14use super::str_hash::StrHash;
15use crate::{BlankNode, GraphName, Literal, NamedNode, StorageError, Term};
16
17/// Source of raw strings for hash-referenced terms.
18///
19/// Implemented by the compute node over a `ResolveStrings` response and by the
20/// local registry in tests; the decoder never performs I/O itself.
21pub trait StrResolver {
22    /// Raw string registered under `hash`, if known.
23    fn resolve(&self, hash: StrHash) -> Option<&str>;
24}
25
26impl<S: BuildHasher> StrResolver for HashMap<StrHash, String, S> {
27    fn resolve(&self, hash: StrHash) -> Option<&str> {
28        self.get(&hash).map(String::as_str)
29    }
30}
31
32impl<T: StrResolver + ?Sized> StrResolver for &T {
33    fn resolve(&self, hash: StrHash) -> Option<&str> {
34        (**self).resolve(hash)
35    }
36}
37
38/// Hashes that must be resolved before `term` can be decoded.
39///
40/// Inline terms (small strings, numerics, blank-node ids) resolve to nothing:
41/// they carry their own value and never hit the registry. Well-known RDF/XSD
42/// datatype IRIs ([`well_known_iri`]) also skip the registry.
43pub fn hashes_in_term(term: &EncodedTerm) -> Vec<StrHash> {
44    match term {
45        EncodedTerm::NamedNode { iri_id } => need_resolve(*iri_id).into_iter().collect(),
46        EncodedTerm::BigBlankNode { id_id } => vec![*id_id],
47        EncodedTerm::BigStringLiteral { value_id }
48        | EncodedTerm::BigSmallLangStringLiteral { value_id, .. } => vec![*value_id],
49        EncodedTerm::SmallBigLangStringLiteral { language_id, .. } => vec![*language_id],
50        EncodedTerm::BigBigLangStringLiteral {
51            value_id,
52            language_id,
53        } => vec![*value_id, *language_id],
54        EncodedTerm::SmallTypedLiteral { datatype_id, .. } => {
55            need_resolve(*datatype_id).into_iter().collect()
56        }
57        EncodedTerm::BigTypedLiteral {
58            value_id,
59            datatype_id,
60        } => {
61            let mut hashes = vec![*value_id];
62            if let Some(dt) = need_resolve(*datatype_id) {
63                hashes.push(dt);
64            }
65            hashes
66        }
67        _ => Vec::new(),
68    }
69}
70
71fn need_resolve(hash: StrHash) -> Option<StrHash> {
72    if well_known_iri(hash).is_some() {
73        None
74    } else {
75        Some(hash)
76    }
77}
78
79/// Rebuild an [`Term`] from its encoded form.
80///
81/// Returns [`StorageError::RegistryMiss`] when `resolver` lacks a hash the term
82/// depends on, so a partial registry never silently produces a wrong binding.
83pub fn decode_term(term: &EncodedTerm, resolver: &impl StrResolver) -> Result<Term, StorageError> {
84    Ok(match term {
85        EncodedTerm::DefaultGraph => {
86            return Err(StorageError::Corrupt(
87                "the default graph is not an RDF term".into(),
88            ));
89        }
90        EncodedTerm::Placeholder => {
91            return Err(StorageError::Corrupt(
92                "internal Placeholder is not an RDF term".into(),
93            ));
94        }
95        EncodedTerm::NamedNode { iri_id } => named_node(resolver, *iri_id)?.into(),
96        EncodedTerm::NumericalBlankNode { id } => {
97            BlankNode::new_from_unique_id(u128::from_be_bytes(*id)).into()
98        }
99        EncodedTerm::SmallBlankNode(id) => blank_node(id.as_str())?.into(),
100        EncodedTerm::BigBlankNode { id_id } => blank_node(lookup(resolver, *id_id)?)?.into(),
101        EncodedTerm::SmallStringLiteral(value) => {
102            Literal::new_simple_literal(value.as_str()).into()
103        }
104        EncodedTerm::BigStringLiteral { value_id } => {
105            Literal::new_simple_literal(lookup(resolver, *value_id)?).into()
106        }
107        EncodedTerm::SmallSmallLangStringLiteral { value, language } => {
108            lang_literal(value.as_str(), language.as_str())?.into()
109        }
110        EncodedTerm::SmallBigLangStringLiteral { value, language_id } => {
111            lang_literal(value.as_str(), lookup(resolver, *language_id)?)?.into()
112        }
113        EncodedTerm::BigSmallLangStringLiteral { value_id, language } => {
114            lang_literal(lookup(resolver, *value_id)?, language.as_str())?.into()
115        }
116        EncodedTerm::BigBigLangStringLiteral {
117            value_id,
118            language_id,
119        } => lang_literal(
120            lookup(resolver, *value_id)?,
121            lookup(resolver, *language_id)?,
122        )?
123        .into(),
124        EncodedTerm::SmallTypedLiteral { value, datatype_id } => {
125            Literal::new_typed_literal(value.as_str(), named_node(resolver, *datatype_id)?).into()
126        }
127        EncodedTerm::BigTypedLiteral {
128            value_id,
129            datatype_id,
130        } => Literal::new_typed_literal(
131            lookup(resolver, *value_id)?,
132            named_node(resolver, *datatype_id)?,
133        )
134        .into(),
135        EncodedTerm::BooleanLiteral(value) => typed(value.to_string(), xsd::BOOLEAN),
136        EncodedTerm::FloatLiteral(value) => typed(value.to_string(), xsd::FLOAT),
137        EncodedTerm::DoubleLiteral(value) => typed(value.to_string(), xsd::DOUBLE),
138        EncodedTerm::IntegerLiteral(value) => typed(value.to_string(), xsd::INTEGER),
139        EncodedTerm::DecimalLiteral(value) => typed(value.to_string(), xsd::DECIMAL),
140        EncodedTerm::DateTimeLiteral(value) => typed(value.to_string(), xsd::DATE_TIME),
141        EncodedTerm::TimeLiteral(value) => typed(value.to_string(), xsd::TIME),
142        EncodedTerm::DateLiteral(value) => typed(value.to_string(), xsd::DATE),
143        EncodedTerm::GYearMonthLiteral(value) => typed(value.to_string(), xsd::G_YEAR_MONTH),
144        EncodedTerm::GYearLiteral(value) => typed(value.to_string(), xsd::G_YEAR),
145        EncodedTerm::GMonthDayLiteral(value) => typed(value.to_string(), xsd::G_MONTH_DAY),
146        EncodedTerm::GDayLiteral(value) => typed(value.to_string(), xsd::G_DAY),
147        EncodedTerm::GMonthLiteral(value) => typed(value.to_string(), xsd::G_MONTH),
148        EncodedTerm::DurationLiteral(value) => typed(value.to_string(), xsd::DURATION),
149        EncodedTerm::YearMonthDurationLiteral(value) => {
150            typed(value.to_string(), xsd::YEAR_MONTH_DURATION)
151        }
152        EncodedTerm::DayTimeDurationLiteral(value) => {
153            typed(value.to_string(), xsd::DAY_TIME_DURATION)
154        }
155        // Native geo points are CRS84 lon/lat inline, so a registry-free
156        // fallback decode can emit the canonical CRS84 WKT. Compute-side
157        // ground evaluation does NOT take this result when a plugin is
158        // registered: it prefers the plugin's ingest-CRS lexical (points
159        // materialize from the inline coords) and keeps this CRS84 form only
160        // as the plugin-less last resort — see waratah_compute's
161        // `decode_cached` and waratah_geo's materialize path.
162        EncodedTerm::LiteralPoint {
163            x,
164            y,
165            geo_datatype: GeoDatatype::WktLiteral,
166            ..
167        } => {
168            // The GeoSPARQL datatype IRI is a fixed const; unchecked is
169            // justified the same way as any other well-known IRI table entry.
170            let datatype = NamedNode::new_unchecked(GEO_WKT_LITERAL);
171            Literal::new_typed_literal(
172                format!("<{}> POINT({x} {y})", CrsId::Crs84.canonical_uri()),
173                datatype.as_ref(),
174            )
175            .into()
176        }
177        // A wkbLiteral point has no lexical payload inline: the blob-side
178        // plugin path is the only honest decoder. This is a capability
179        // boundary, not corruption — callers with a cached lexical or a
180        // fetched blob payload decode through the plugin registry instead.
181        EncodedTerm::LiteralPoint {
182            geo_datatype: GeoDatatype::WkbLiteral,
183            ..
184        } => {
185            return Err(StorageError::RequiresBlobStore(
186                "wkbLiteral points decode only through the plugin registry (blob store / inline materialize required)"
187                    .into(),
188            ));
189        }
190        // Blob-backed terms (non-point geometry, generic binary literals)
191        // carry no payload bytes — only the registry-side blob store has
192        // them, so a bare decode cannot rebuild the literal. This is a
193        // capability boundary, not corruption: callers with a cached lexical
194        // or a fetched blob payload decode through the plugin registry.
195        EncodedTerm::LiteralGeometry { .. } | EncodedTerm::BlobLiteral { .. } => {
196            return Err(StorageError::RequiresBlobStore(
197                "blob-backed literal decodes only through the plugin registry (blob store required)"
198                    .into(),
199            ));
200        }
201    })
202}
203
204/// Rebuild a graph name, mapping [`EncodedTerm::DefaultGraph`] to the default graph.
205pub fn decode_graph_name(
206    term: &EncodedTerm,
207    resolver: &impl StrResolver,
208) -> Result<GraphName, StorageError> {
209    if matches!(term, EncodedTerm::DefaultGraph) {
210        return Ok(GraphName::DefaultGraph);
211    }
212    match decode_term(term, resolver)? {
213        Term::NamedNode(node) => Ok(node.into()),
214        Term::BlankNode(node) => Ok(node.into()),
215        Term::Literal(_) => Err(StorageError::Corrupt(
216            "a literal cannot name a graph".into(),
217        )),
218    }
219}
220
221fn lookup<R: StrResolver>(resolver: &R, hash: StrHash) -> Result<&str, StorageError> {
222    resolver
223        .resolve(hash)
224        .ok_or_else(|| StorageError::RegistryMiss(hash.as_u128()))
225}
226
227fn named_node<R: StrResolver>(resolver: &R, hash: StrHash) -> Result<NamedNode, StorageError> {
228    let iri = match well_known_iri(hash) {
229        Some(iri) => iri,
230        None => lookup(resolver, hash)?,
231    };
232    NamedNode::new(iri).map_err(|e| StorageError::Corrupt(format!("registered IRI {iri:?}: {e}")))
233}
234
235fn blank_node(id: &str) -> Result<BlankNode, StorageError> {
236    BlankNode::new(id).map_err(|e| StorageError::Corrupt(format!("blank node id {id:?}: {e}")))
237}
238
239fn lang_literal(value: &str, language: &str) -> Result<Literal, StorageError> {
240    Literal::new_language_tagged_literal(value, language)
241        .map_err(|e| StorageError::Corrupt(format!("language tag {language:?}: {e}")))
242}
243
244fn typed(value: String, datatype: oxrdf::NamedNodeRef<'_>) -> Term {
245    Literal::new_typed_literal(value, datatype).into()
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251    use crate::encode::encode_term;
252    use pretty_assertions::assert_eq;
253
254    /// Encode a term, register whatever hashes it needs, and decode it back.
255    fn round_trip(term: Term) {
256        let encoded = encode_term(&term).unwrap();
257        let mut registry = HashMap::new();
258        for (hash, raw) in crate::encode::strings_entries_for_term(&term, &encoded) {
259            registry.insert(hash, raw);
260        }
261        // A datatype IRI is registered by the writer even when the value is inline.
262        assert_eq!(decode_term(&encoded, &registry).unwrap(), term);
263    }
264
265    #[test]
266    fn named_nodes_and_literals_round_trip() {
267        round_trip(NamedNode::new("http://ex/brisbane").unwrap().into());
268        round_trip(
269            NamedNode::new("http://example.org/a-considerably-longer-iri-than-fifteen-bytes")
270                .unwrap()
271                .into(),
272        );
273        round_trip(Literal::from("Sunny").into());
274        round_trip(Literal::from("a literal well past the inline small-string limit").into());
275        round_trip(
276            Literal::new_language_tagged_literal("bonjour", "fr")
277                .unwrap()
278                .into(),
279        );
280    }
281
282    #[test]
283    fn inline_terms_need_no_registry_entries() {
284        for term in [
285            Term::from(Literal::from("Sunny")),
286            Term::from(Literal::from(42_i32)),
287            Term::from(Literal::from(true)),
288            Term::from(BlankNode::new("b0").unwrap()),
289        ] {
290            let encoded = encode_term(&term).unwrap();
291            assert!(
292                hashes_in_term(&encoded).is_empty(),
293                "{term} should decode without the registry"
294            );
295            let empty = HashMap::new();
296            assert_eq!(decode_term(&encoded, &empty).unwrap(), term);
297        }
298    }
299
300    #[test]
301    fn hashed_terms_report_the_hashes_they_need() {
302        let iri = NamedNode::new("http://ex/hasWeather").unwrap();
303        let encoded = encode_term(&Term::from(iri)).unwrap();
304        assert_eq!(
305            hashes_in_term(&encoded),
306            vec![StrHash::new("http://ex/hasWeather")]
307        );
308    }
309
310    #[test]
311    fn missing_registry_entry_is_a_typed_miss() {
312        let iri = NamedNode::new("http://ex/never-registered").unwrap();
313        let encoded = encode_term(&Term::from(iri)).unwrap();
314        let empty = HashMap::new();
315        assert!(matches!(
316            decode_term(&encoded, &empty).unwrap_err(),
317            StorageError::RegistryMiss(_)
318        ));
319    }
320
321    #[test]
322    fn numeric_literals_keep_their_datatype() {
323        let encoded = encode_term(&Term::from(Literal::from(42_i32))).unwrap();
324        let empty = HashMap::new();
325        let Term::Literal(literal) = decode_term(&encoded, &empty).unwrap() else {
326            panic!("expected a literal");
327        };
328        assert_eq!(literal.value(), "42");
329        assert_eq!(literal.datatype(), xsd::INTEGER);
330    }
331
332    #[test]
333    fn well_known_datatype_iri_decodes_without_registry() {
334        use crate::encode::XSD_INTEGER;
335        let empty = HashMap::new();
336        assert!(hashes_in_term(&XSD_INTEGER).is_empty());
337        let Term::NamedNode(node) = decode_term(&XSD_INTEGER, &empty).unwrap() else {
338            panic!("expected a named node");
339        };
340        assert_eq!(node.as_str(), xsd::INTEGER.as_str());
341    }
342
343    #[test]
344    fn default_graph_decodes_only_as_a_graph_name() {
345        let empty = HashMap::new();
346        assert!(decode_term(&EncodedTerm::DefaultGraph, &empty).is_err());
347        assert_eq!(
348            decode_graph_name(&EncodedTerm::DefaultGraph, &empty).unwrap(),
349            GraphName::DefaultGraph
350        );
351    }
352
353    #[test]
354    fn blob_backed_geo_refusal_is_requires_blob_store_not_corrupt() {
355        // The refusal is a capability boundary (callers fetch the payload or
356        // use a cached lexical and decode through the plugin registry), so it
357        // must stay distinguishable from real corruption.
358        use super::super::encoded_term::GeomKind;
359        let encoded = EncodedTerm::LiteralGeometry {
360            geom_kind: GeomKind::Polygon,
361            crs: CrsId::Crs84,
362            geo_datatype: GeoDatatype::WkbLiteral,
363            blob_id: StrHash::from_bytes(&[7_u8; 32]),
364            requires_spike_reduction: false,
365        };
366        let empty = HashMap::new();
367        assert!(matches!(
368            decode_term(&encoded, &empty).unwrap_err(),
369            StorageError::RequiresBlobStore(_)
370        ));
371    }
372}