rete_core/ingest.rs
1//! Ingestion: parse RDF text (N-Triples / N-Quads / Turtle) and assemble a
2//! complete `.rete` file image. Shared by the CLI's `build`/`validate` commands
3//! and the wasm bindings (the playground's in-browser builder).
4//!
5//! The N-Triples/N-Quads reader is line-based and keeps terms as their exact
6//! canonical token strings (`<iri>`, `_:bnode`, `"lit"`, `"lit"^^<dt>`,
7//! `"lit"@lang`) so they double as dictionary keys and so a `query` can match
8//! by the same string. This is not a full RDF 1.1 parser — it covers the
9//! canonical N-Triples surface (and is deliberately tolerant of IRIs a strict
10//! parser would reject), enough for v0 ingestion. Turtle goes through `oxttl`.
11//!
12//! That tolerance is *measured*, not silent: pass an [`IriAudit`] to any of the
13//! `*_audited` entry points and the parse counts every IRI outside the
14//! N-Triples `IRIREF` grammar / RFC 3987 (see [`crate::iri`]) — or, with
15//! `strict`, refuses the input on the first one. `rete build` always audits.
16//!
17//! Assembly degrades with the build features: without the `compression`
18//! feature (e.g. on wasm) sections are written with the `NONE` codec — larger
19//! files, byte-compatible readers.
20
21use crate::{Dictionary, DictionaryBuilder, GraphIndexBuilder, PyramidAlgo, DEFAULT_TILE_BUDGET};
22
23/// A parsed triple as three canonical term tokens.
24pub type RawTriple = (String, String, String);
25
26/// A parsed quad: the triple plus an optional graph term (`None` = default graph).
27pub type RawQuad = (String, String, String, Option<String>);
28
29/// Which **surface** a `<< … >>` in Turtle/TriG input is read as — the input
30/// half of `rete export --quoted-triple-syntax`, same vocabulary, same two
31/// values.
32///
33/// The flag exists because the two standards give one piece of syntax two
34/// meanings, and no amount of looking at the bytes can tell them apart:
35///
36/// | written | under [`RdfStar`](Self::RdfStar) | under [`Rdf12`](Self::Rdf12) |
37/// |--------------------|----------------------------------|---------------------------------------|
38/// | `<< s p o >>` | a **quoted triple**, one term | a **reifier**: `_:r rdf:reifies <<( s p o )>>`, plus a blank node standing where it was |
39/// | `<<( s p o )>>` | a syntax error | a **triple term**, object position only |
40/// | `{\| … \|}` | a syntax error | an annotation on the statement before it |
41///
42/// One file, two readings, two different graphs — see the round-trip matrix in
43/// `crates/rete-cli/tests/quoted_triple_surfaces.rs`, which asserts both.
44///
45/// `<<( s p o )>>` is unambiguous: it is RDF 1.2's and nothing else's. That
46/// asymmetry is why [`RdfStar`](Self::RdfStar) is the **default**. Reading an
47/// RDF-star file as RDF 1.2 silently yields a different graph; reading an
48/// RDF 1.2 file as RDF-star is a hard parse error that names the flag. Only one
49/// of the two mistakes is survivable, so the default is the one that makes the
50/// other mistake loud.
51///
52/// **N-Triples and N-Quads ignore this entirely.** Their reader is rete's own
53/// (`take_term`), it has accepted both `<< s p o >>` and `<<( s p o )>>` since
54/// #262, and RDF 1.2 N-Triples has no reifier syntax for `<< … >>` to be — so
55/// there is no ambiguity to resolve and nothing to choose. The same goes for
56/// RDF/XML.
57///
58/// Whichever surface reads the file, what gets **stored** is the same canonical
59/// token `<<s p o>>`. rete's term model is a superset of both: a triple term is
60/// a term, and RDF 1.2 reification is ordinary RDF — a blank node, a predicate
61/// and a term — which rete already stored before this flag existed.
62#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Hash)]
63pub enum QuotedTripleSurface {
64 /// `<< s p o >>` is a **quoted triple** (RDF-star), in subject or object
65 /// position — rete's own storage token. The default, and byte-for-byte the
66 /// behaviour every rete release before this flag had.
67 #[default]
68 RdfStar,
69 /// `<<( s p o )>>` is a **triple term** and `<< s p o >>` is a **reifier**
70 /// (RDF 1.2), with `{| … |}` annotations read too.
71 Rdf12,
72}
73
74impl QuotedTripleSurface {
75 /// Parse the `--quoted-triple-syntax` value, `None` for anything else.
76 /// Shared by `rete build`, `rete validate` and `rete export` so the flag
77 /// cannot come to mean two things in two directions.
78 pub fn parse(s: &str) -> Option<Self> {
79 match s {
80 crate::card_derive::QUOTED_TRIPLE_SURFACE_RDF12 => Some(Self::Rdf12),
81 crate::card_derive::QUOTED_TRIPLE_SURFACE_RDF_STAR => Some(Self::RdfStar),
82 _ => None,
83 }
84 }
85
86 /// The flag spelling of this surface — the inverse of [`Self::parse`].
87 pub const fn as_str(self) -> &'static str {
88 match self {
89 Self::Rdf12 => crate::card_derive::QUOTED_TRIPLE_SURFACE_RDF12,
90 Self::RdfStar => crate::card_derive::QUOTED_TRIPLE_SURFACE_RDF_STAR,
91 }
92 }
93}
94
95/// The one-line hint appended to a Turtle/TriG parse error when the input looks
96/// like RDF 1.2 and was read as RDF-star — i.e. the exact mistake
97/// [`QuotedTripleSurface`]'s default makes, made loud.
98const RDF12_SURFACE_HINT: &str = "\nhint: this input contains `<<(`, the RDF 1.2 triple-term \
99 syntax — which is what `rete export` writes by default. Reading it takes \
100 `--quoted-triple-syntax rdf12`; the default, `rdf-star`, reads `<< s p o >>` as a quoted \
101 triple instead.";
102
103/// Does `text` look like it carries RDF 1.2 triple terms? A deliberately dumb
104/// substring test: `<<(` cannot begin anything else in Turtle, and this is only
105/// ever consulted to *explain a parse that already failed*, never to decide how
106/// to read a file. A `<<(` inside a string literal would make it a false
107/// positive on some other error's hint, which costs one confusing sentence and
108/// nothing else.
109fn looks_like_rdf12(text: &str) -> bool {
110 text.contains("<<(")
111}
112
113/// Why an ingest failed. Parser errors from `oxttl`/`oxrdfxml` and I/O errors
114/// are flattened to their `Display` string rather than wrapped: the variants
115/// then carry no foreign types, which keeps the error usable from the wasm
116/// bindings and stable across upstream parser upgrades.
117#[derive(Debug, thiserror::Error)]
118#[non_exhaustive]
119pub enum IngestError {
120 /// A malformed N-Triples/N-Quads line: its 1-based line number and a short
121 /// reason (`"bad subject"`, `"missing trailing '.'"`, …).
122 #[error("line {0}: {1}")]
123 Line(usize, &'static str),
124 /// The Turtle parser rejected the input.
125 #[error("turtle: {0}")]
126 Turtle(String),
127 /// The TriG parser rejected the input.
128 #[error("trig: {0}")]
129 TriG(String),
130 /// The RDF/XML parser rejected the input.
131 #[error("rdf/xml: {0}")]
132 RdfXml(String),
133 /// The requested format is not one this crate can parse.
134 #[error("unknown input format: {0} (expected nt, nq, ttl, trig, or rdf/xml)")]
135 UnknownFormat(String),
136 /// [`QuotedTripleSurface::Rdf12`] was asked for on a Turtle/TriG input, but
137 /// this build of `rete-core` has the `rdf12-turtle` feature off, so the
138 /// RDF 1.2 reader was not compiled in. Refused by name rather than read as
139 /// RDF-star, which would be the wrong graph told in silence.
140 #[error(
141 "this build cannot read the RDF 1.2 Turtle/TriG surface: rete-core was compiled without \
142 the `rdf12-turtle` feature (N-Triples/N-Quads still accept `<<( s p o )>>`)"
143 )]
144 Rdf12TurtleUnavailable,
145 /// The input could not be read (streaming builds surface the path here).
146 #[error("io: {0}")]
147 Io(String),
148 /// An IRI outside the N-Triples/N-Quads `IRIREF` grammar / RFC 3987, refused
149 /// because the caller asked for a strict [`IriAudit`] (`rete build
150 /// --strict`). Without `strict` the same finding is only counted.
151 /// `location` is `line N` for the line-based syntaxes, the format name for
152 /// the others (oxttl reports its own positions).
153 #[error("{location}: invalid IRI {token} — {reason}")]
154 InvalidIri {
155 /// Where it was seen: `line 42`, or the format name.
156 location: String,
157 /// The offending term token, verbatim.
158 token: String,
159 /// Which rule it breaks ([`crate::iri::IriDefect::reason`]).
160 reason: &'static str,
161 },
162}
163
164/// Policy **and** tally for the invalid-IRI check that runs during ingest.
165///
166/// rete's reader is deliberately tolerant of IRIs a strict parser rejects (see
167/// [`crate::iri`]), which is what lets it hold every published dataset — and
168/// also what let three of the `scholar/` exports produce N-Quads Oxigraph
169/// refuses to load. Passing an audit makes the tolerance *visible*: the build
170/// still succeeds and stores exactly what it was given, but it can now say how
171/// much of what it stored is not valid RDF. `strict` turns the same finding into
172/// a refusal, on the first offending statement.
173#[derive(Debug, Default)]
174pub struct IriAudit {
175 /// Fail the parse on the first invalid IRI instead of counting it.
176 pub strict: bool,
177 /// What the parse saw. Constant memory — see [`crate::iri::IriReport`].
178 pub report: crate::iri::IriReport,
179}
180
181impl IriAudit {
182 /// Count invalid IRIs; never fail (`rete build`'s default).
183 pub fn counting() -> Self {
184 Self::default()
185 }
186
187 /// Refuse the input at the first invalid IRI (`rete build --strict`).
188 pub fn refusing() -> Self {
189 Self {
190 strict: true,
191 report: crate::iri::IriReport::default(),
192 }
193 }
194}
195
196/// Run one statement past the audit: record any invalid IRI, and in `strict`
197/// mode turn it into an error naming the offending token. `location` is only
198/// called on the error path, so the common case allocates nothing.
199fn audit_quad<F: FnOnce() -> String>(
200 audit: Option<&mut IriAudit>,
201 s: &str,
202 p: &str,
203 o: &str,
204 g: Option<&str>,
205 location: F,
206) -> Result<(), IngestError> {
207 let Some(a) = audit else { return Ok(()) };
208 let Some(defect) = a.report.observe_quad(s, p, o, g) else {
209 return Ok(());
210 };
211 if !a.strict {
212 return Ok(());
213 }
214 let token = [Some(s), Some(p), Some(o), g]
215 .into_iter()
216 .flatten()
217 .find(|t| crate::iri::term_defect(t).is_some())
218 .unwrap_or("<?>")
219 .to_string();
220 Err(IngestError::InvalidIri {
221 location: location(),
222 token,
223 reason: defect.reason(),
224 })
225}
226
227/// Estimate the statement count of an N-Triples/N-Quads text from its newline
228/// count, so the output `Vec` can be pre-sized — a big build otherwise pays
229/// repeated `Vec` doublings, each briefly holding ~2× the (large) spine. An
230/// over-estimate by a few blank/comment lines is harmless (it's a capacity hint).
231fn estimate_statements(input: &str) -> usize {
232 bytecount_newlines(input).max(1)
233}
234
235/// Count `\n` bytes — one linear pass, far cheaper than the parse it sizes.
236fn bytecount_newlines(input: &str) -> usize {
237 input.as_bytes().iter().filter(|&&b| b == b'\n').count()
238}
239
240/// Parse one N-Quads line into a quad, or `None` for a blank/comment line.
241/// Shared by the whole-text [`parse_quads`] and the streaming [`parse_reader`].
242fn parse_nq_line(
243 raw: &str,
244 lineno: usize,
245 audit: Option<&mut IriAudit>,
246) -> Result<Option<RawQuad>, IngestError> {
247 let line = raw.trim();
248 if line.is_empty() || line.starts_with('#') {
249 return Ok(None);
250 }
251 let stripped = line
252 .strip_suffix('.')
253 .ok_or(IngestError::Line(lineno, "missing trailing '.'"))?
254 .trim_end();
255 let (s, rest) = take_term(stripped).ok_or(IngestError::Line(lineno, "bad subject"))?;
256 let (p, rest) =
257 take_term(rest.trim_start()).ok_or(IngestError::Line(lineno, "bad predicate"))?;
258 let (o, rest) = take_term(rest.trim_start()).ok_or(IngestError::Line(lineno, "bad object"))?;
259 let rest = rest.trim();
260 let graph = if rest.is_empty() {
261 None
262 } else {
263 let (g, tail) = take_term(rest).ok_or(IngestError::Line(lineno, "bad graph"))?;
264 if !tail.trim().is_empty() {
265 return Err(IngestError::Line(lineno, "trailing content after graph"));
266 }
267 Some(g)
268 };
269 audit_quad(audit, &s, &p, &o, graph.as_deref(), || {
270 format!("line {lineno}")
271 })?;
272 Ok(Some((s, p, o, graph)))
273}
274
275/// Parse one N-Triples line into a triple, or `None` for a blank/comment line.
276fn parse_nt_line(
277 raw: &str,
278 lineno: usize,
279 audit: Option<&mut IriAudit>,
280) -> Result<Option<RawTriple>, IngestError> {
281 let line = raw.trim();
282 if line.is_empty() || line.starts_with('#') {
283 return Ok(None);
284 }
285 let stripped = line
286 .strip_suffix('.')
287 .ok_or(IngestError::Line(lineno, "missing trailing '.'"))?
288 .trim_end();
289 let (s, rest) = take_term(stripped).ok_or(IngestError::Line(lineno, "bad subject"))?;
290 let (p, rest) =
291 take_term(rest.trim_start()).ok_or(IngestError::Line(lineno, "bad predicate"))?;
292 let (o, rest) = take_term(rest.trim_start()).ok_or(IngestError::Line(lineno, "bad object"))?;
293 if !rest.trim().is_empty() {
294 return Err(IngestError::Line(lineno, "trailing content after object"));
295 }
296 audit_quad(audit, &s, &p, &o, None, || format!("line {lineno}"))?;
297 Ok(Some((s, p, o)))
298}
299
300/// Parse N-Quads text: `subject predicate object [graph] .` per line.
301pub fn parse_quads(input: &str) -> Result<Vec<RawQuad>, IngestError> {
302 parse_quads_audited(input, None)
303}
304
305/// [`parse_quads`] with an optional [`IriAudit`].
306pub fn parse_quads_audited(
307 input: &str,
308 mut audit: Option<&mut IriAudit>,
309) -> Result<Vec<RawQuad>, IngestError> {
310 let mut out = Vec::with_capacity(estimate_statements(input));
311 for (i, raw) in input.lines().enumerate() {
312 if let Some(q) = parse_nq_line(raw, i + 1, audit.as_deref_mut())? {
313 out.push(q);
314 }
315 }
316 Ok(out)
317}
318
319/// Parse N-Triples text into raw term-token triples, skipping blank/comment lines.
320pub fn parse(input: &str) -> Result<Vec<RawTriple>, IngestError> {
321 parse_audited(input, None)
322}
323
324/// [`parse`] with an optional [`IriAudit`].
325pub fn parse_audited(
326 input: &str,
327 mut audit: Option<&mut IriAudit>,
328) -> Result<Vec<RawTriple>, IngestError> {
329 let mut out = Vec::with_capacity(estimate_statements(input));
330 for (i, raw) in input.lines().enumerate() {
331 if let Some(t) = parse_nt_line(raw, i + 1, audit.as_deref_mut())? {
332 out.push(t);
333 }
334 }
335 Ok(out)
336}
337
338/// **Stream-parse** N-Triples (`"nt"`) or N-Quads (`"nq"`) from a reader, one
339/// line at a time, so the whole input text is **never resident** — the big-build
340/// memory win over reading the file into a `String` first (each line String is
341/// transient, freed every iteration). `cap` pre-sizes the output `Vec` (e.g.
342/// `file_len / 64`) to avoid reallocation doublings of the large spine. Turtle is
343/// not streamable here (oxttl needs the whole input); callers use the text path
344/// for `"ttl"`.
345pub fn parse_reader<R: std::io::BufRead>(
346 reader: R,
347 format: &str,
348 cap: usize,
349) -> Result<Vec<RawQuad>, IngestError> {
350 parse_reader_audited(reader, format, cap, None)
351}
352
353/// [`parse_reader`] with an optional [`IriAudit`].
354pub fn parse_reader_audited<R: std::io::BufRead>(
355 reader: R,
356 format: &str,
357 cap: usize,
358 audit: Option<&mut IriAudit>,
359) -> Result<Vec<RawQuad>, IngestError> {
360 parse_reader_audited_surface(reader, format, cap, audit, QuotedTripleSurface::default())
361}
362
363/// [`parse_reader_audited`] reading `<< … >>` in the given
364/// [`QuotedTripleSurface`] (Turtle/TriG only — see the enum).
365pub fn parse_reader_audited_surface<R: std::io::BufRead>(
366 reader: R,
367 format: &str,
368 cap: usize,
369 audit: Option<&mut IriAudit>,
370 surface: QuotedTripleSurface,
371) -> Result<Vec<RawQuad>, IngestError> {
372 let mut out = Vec::with_capacity(cap);
373 stream_reader_audited_surface(reader, format, audit, surface, &mut |q| out.push(q))?;
374 Ok(out)
375}
376
377/// **Stream** N-Triples (`"nt"`) / N-Quads (`"nq"`) from a reader, invoking `f`
378/// once per parsed quad — like [`parse_reader`] but **without collecting** into a
379/// `Vec`. Each quad's term Strings are owned by `f` (and dropped when it returns
380/// if it doesn't retain them), so a caller that only needs to *observe* every
381/// term — e.g. the two-pass [`assemble_dataset_streaming`] building its
382/// dictionary — never materializes the whole quad multiset. The big-graph,
383/// low-RAM ingest primitive. Blank/comment lines are skipped; a parse error stops
384/// the stream and is returned.
385///
386/// Every format streams: the line-based ones a line at a time, Turtle / TriG /
387/// RDF-XML through their `oxttl`/`oxrdfxml` reader parsers, which pull from the
388/// reader incrementally. Nothing here holds the input text — so a 60 GB Turtle
389/// file is as ingestible as a 60 GB `.nt` one, which is what lets the external
390/// (memory-bounded) build accept them.
391pub fn stream_reader<R: std::io::BufRead>(
392 reader: R,
393 format: &str,
394 f: &mut dyn FnMut(RawQuad),
395) -> Result<(), IngestError> {
396 stream_reader_audited(reader, format, None, f)
397}
398
399/// [`stream_reader`] with an optional [`IriAudit`].
400///
401/// Every syntax is audited, not only the line-based ones. `oxttl`/`oxrdfxml`
402/// validate IRIs themselves and reject an invalid one before it reaches us, so
403/// in practice the Turtle/TriG/RDF-XML tallies stay at zero — but auditing them
404/// too means the count is a property of the *file*, not of which reader happened
405/// to produce it, and a future parser change cannot silently reopen the hole.
406pub fn stream_reader_audited<R: std::io::BufRead>(
407 reader: R,
408 format: &str,
409 audit: Option<&mut IriAudit>,
410 f: &mut dyn FnMut(RawQuad),
411) -> Result<(), IngestError> {
412 stream_reader_audited_surface(reader, format, audit, QuotedTripleSurface::default(), f)
413}
414
415/// [`stream_reader_audited`] reading `<< … >>` in the given
416/// [`QuotedTripleSurface`].
417///
418/// The surface reaches only the `"ttl"` and `"trig"` arms: the line-based
419/// readers are rete's own and take both spellings unconditionally, and RDF/XML
420/// has no syntax for either. Under [`QuotedTripleSurface::Rdf12`] Turtle/TriG go
421/// through `oxttl` 0.2 instead of 0.1, and the RDF 1.2 triple terms it hands
422/// back (`<<( s p o )>>`) are folded to rete's stored token on the way out, so
423/// the dictionary a file lands in does not depend on which reader read it.
424///
425/// **This entry point does not carry the RDF 1.2 hint** that the text path adds
426/// to a failed RDF-star parse: it is handed a reader, not a string, and sniffing
427/// the input would mean buffering the 60 GB file this function exists to avoid
428/// buffering. `rete build --memory-budget-mb file.ttl` therefore reports the raw
429/// parser error; every other route reports the hint.
430pub fn stream_reader_audited_surface<R: std::io::BufRead>(
431 reader: R,
432 format: &str,
433 mut audit: Option<&mut IriAudit>,
434 surface: QuotedTripleSurface,
435 f: &mut dyn FnMut(RawQuad),
436) -> Result<(), IngestError> {
437 if surface == QuotedTripleSurface::Rdf12 && matches!(format, "ttl" | "trig") {
438 return rdf12::stream(reader, format, audit, f);
439 }
440 match format {
441 "nt" | "nq" => {
442 for (i, line) in reader.lines().enumerate() {
443 let line = line.map_err(|e| IngestError::Io(e.to_string()))?;
444 if format == "nq" {
445 if let Some(q) = parse_nq_line(&line, i + 1, audit.as_deref_mut())? {
446 f(q);
447 }
448 } else if let Some((s, p, o)) = parse_nt_line(&line, i + 1, audit.as_deref_mut())? {
449 f((s, p, o, None));
450 }
451 }
452 Ok(())
453 }
454 "ttl" => turtle_star(reader, audit, f),
455 "trig" => trig_star(reader, audit, f),
456 "rdfxml" => {
457 for r in oxrdfxml::RdfXmlParser::new().for_reader(reader) {
458 let t = r.map_err(|e| IngestError::RdfXml(e.to_string()))?;
459 let q = (
460 t.subject.to_string(),
461 t.predicate.to_string(),
462 t.object.to_string(),
463 None,
464 );
465 audit_quad(audit.as_deref_mut(), &q.0, &q.1, &q.2, None, || {
466 "rdf/xml".into()
467 })?;
468 f(q);
469 }
470 Ok(())
471 }
472 other => Err(IngestError::UnknownFormat(other.to_string())),
473 }
474}
475
476/// Stream **RDF-star** Turtle: `with_quoted_triples` accepts `<< s p o >>` in
477/// subject/object position, and oxrdf 0.2's `Term::Triple` Displays as the
478/// canonical `<<…>>` token rete's own N-Triples-star tokenizer emits — so no
479/// translation is needed on the way out.
480///
481/// Its own function, and called directly from both the reader path and the text
482/// path, so that the wasm engine — which reaches only the text path and has no
483/// RDF 1.2 reader compiled in — links this and nothing else.
484fn turtle_star<R: std::io::BufRead>(
485 reader: R,
486 mut audit: Option<&mut IriAudit>,
487 f: &mut dyn FnMut(RawQuad),
488) -> Result<(), IngestError> {
489 for r in oxttl::TurtleParser::new()
490 .with_quoted_triples()
491 .for_reader(reader)
492 {
493 let t = r.map_err(|e| IngestError::Turtle(e.to_string()))?;
494 let q = (
495 t.subject.to_string(),
496 t.predicate.to_string(),
497 t.object.to_string(),
498 None,
499 );
500 audit_quad(audit.as_deref_mut(), &q.0, &q.1, &q.2, None, || {
501 "turtle".into()
502 })?;
503 f(q);
504 }
505 Ok(())
506}
507
508/// [`turtle_star`] for TriG — Turtle plus named-graph blocks (`<g> { … }`), the
509/// shape most large RDF dumps ship in.
510fn trig_star<R: std::io::BufRead>(
511 reader: R,
512 mut audit: Option<&mut IriAudit>,
513 f: &mut dyn FnMut(RawQuad),
514) -> Result<(), IngestError> {
515 for r in oxttl::TriGParser::new()
516 .with_quoted_triples()
517 .for_reader(reader)
518 {
519 let q = r.map_err(|e| IngestError::TriG(e.to_string()))?;
520 let q = (
521 q.subject.to_string(),
522 q.predicate.to_string(),
523 q.object.to_string(),
524 graph_token(&q.graph_name),
525 );
526 audit_quad(
527 audit.as_deref_mut(),
528 &q.0,
529 &q.1,
530 &q.2,
531 q.3.as_deref(),
532 || "trig".into(),
533 )?;
534 f(q);
535 }
536 Ok(())
537}
538
539/// The canonical graph token for a parsed quad — `None` for the default graph,
540/// otherwise the same `<iri>` / `_:b` spelling the N-Quads reader produces, so
541/// TriG and N-Quads inputs land identical dictionary keys. `GraphName`'s own
542/// `Display` renders the default graph as `DEFAULT`, which must never become a
543/// term, hence the explicit match.
544fn graph_token(g: &oxrdf::GraphName) -> Option<String> {
545 match g {
546 oxrdf::GraphName::DefaultGraph => None,
547 other => Some(other.to_string()),
548 }
549}
550
551/// The **RDF 1.2** Turtle/TriG reader — `oxttl` 0.2 with its `rdf-12` feature,
552/// living beside the `oxttl` 0.1 reader above rather than replacing it.
553///
554/// Everything RDF 1.2 adds over RDF 1.1 arrives through this one module:
555/// `<<( s p o )>>` triple terms, `<< s p o >>` reifiers (which expand to
556/// `_:r rdf:reifies <<( s p o )>>` plus the statement that mentioned them),
557/// `{| … |}` annotations, and `"…"@lang--dir` directional literals. None of it
558/// needs a storage change, which is the point: a reifier is a blank node, an
559/// IRI and a term, and rete has stored those since v0.
560///
561/// The one translation is at the term boundary. `oxrdf` 0.3 renders a triple
562/// term as `<<( s p o )>>`; rete's dictionary key is `<<s p o>>`. [`take_term`]
563/// already reads both — that is what made RDF 1.2 N-Quads ingestible in #262 —
564/// so the fold is a re-scan of a token oxttl has already validated.
565#[cfg(feature = "rdf12-turtle")]
566mod rdf12 {
567 use super::{audit_quad, take_term, IngestError, IriAudit, RawQuad};
568
569 /// Fold `oxrdf` 0.3's `<<( s p o )>>` rendering of a triple term into rete's
570 /// stored `<<s p o>>`, recursively (a nested triple term folds with it).
571 /// Every other token — the overwhelming majority, and all of them in a file
572 /// with no triple terms — is returned untouched, not even copied.
573 pub(super) fn fold_triple_term(t: String) -> String {
574 if !t.starts_with("<<(") {
575 return t;
576 }
577 match take_term(&t) {
578 Some((token, rest)) if rest.trim().is_empty() => token,
579 // oxttl only ever hands back a well-formed term, so this is
580 // unreachable; returning the original beats mangling it silently.
581 _ => t,
582 }
583 }
584
585 /// `super::graph_token` for `oxrdf` 0.3's `GraphName` — the same rule, a
586 /// different crate version, which is exactly why it cannot be shared.
587 fn graph_token(g: &oxrdf12::GraphName) -> Option<String> {
588 match g {
589 oxrdf12::GraphName::DefaultGraph => None,
590 other => Some(other.to_string()),
591 }
592 }
593
594 /// Stream one RDF 1.2 Turtle (`"ttl"`) or TriG (`"trig"`) input, auditing
595 /// every quad the way the RDF-star reader does.
596 pub(super) fn stream<R: std::io::BufRead>(
597 reader: R,
598 format: &str,
599 mut audit: Option<&mut IriAudit>,
600 f: &mut dyn FnMut(RawQuad),
601 ) -> Result<(), IngestError> {
602 if format == "ttl" {
603 for r in oxttl12::TurtleParser::new().for_reader(reader) {
604 let t = r.map_err(|e| IngestError::Turtle(e.to_string()))?;
605 let q = (
606 t.subject.to_string(),
607 t.predicate.to_string(),
608 fold_triple_term(t.object.to_string()),
609 None,
610 );
611 audit_quad(audit.as_deref_mut(), &q.0, &q.1, &q.2, None, || {
612 "turtle".into()
613 })?;
614 f(q);
615 }
616 } else {
617 for r in oxttl12::TriGParser::new().for_reader(reader) {
618 let q = r.map_err(|e| IngestError::TriG(e.to_string()))?;
619 let q = (
620 q.subject.to_string(),
621 q.predicate.to_string(),
622 fold_triple_term(q.object.to_string()),
623 graph_token(&q.graph_name),
624 );
625 audit_quad(
626 audit.as_deref_mut(),
627 &q.0,
628 &q.1,
629 &q.2,
630 q.3.as_deref(),
631 || "trig".into(),
632 )?;
633 f(q);
634 }
635 }
636 Ok(())
637 }
638}
639
640/// The stand-in for [`rdf12`] in a build with `rdf12-turtle` off: it refuses by
641/// name. Reading the file as RDF-star instead would answer a question nobody
642/// asked, with a different graph.
643#[cfg(not(feature = "rdf12-turtle"))]
644mod rdf12 {
645 use super::{IngestError, IriAudit, RawQuad};
646
647 pub(super) fn stream<R: std::io::BufRead>(
648 _reader: R,
649 _format: &str,
650 _audit: Option<&mut IriAudit>,
651 _f: &mut dyn FnMut(RawQuad),
652 ) -> Result<(), IngestError> {
653 Err(IngestError::Rdf12TurtleUnavailable)
654 }
655}
656
657/// Parse Turtle into canonical N-Triples-token triples via oxttl, reading
658/// `<< s p o >>` as an RDF-star quoted triple. [`parse_turtle_surface`] chooses.
659pub fn parse_turtle(text: &str) -> Result<Vec<RawTriple>, IngestError> {
660 parse_turtle_surface(text, QuotedTripleSurface::default())
661}
662
663/// [`parse_turtle`] in the given [`QuotedTripleSurface`].
664pub fn parse_turtle_surface(
665 text: &str,
666 surface: QuotedTripleSurface,
667) -> Result<Vec<RawTriple>, IngestError> {
668 Ok(parse_text_surface(text, "ttl", surface)?
669 .into_iter()
670 .map(|(s, p, o, _)| (s, p, o))
671 .collect())
672}
673
674/// Parse TriG into canonical quads via oxttl — Turtle plus named-graph blocks
675/// (`<g> { … }`), the shape most large RDF dumps ship in. Reads `<< s p o >>` as
676/// an RDF-star quoted triple; [`parse_trig_surface`] chooses.
677pub fn parse_trig(text: &str) -> Result<Vec<RawQuad>, IngestError> {
678 parse_trig_surface(text, QuotedTripleSurface::default())
679}
680
681/// [`parse_trig`] in the given [`QuotedTripleSurface`].
682pub fn parse_trig_surface(
683 text: &str,
684 surface: QuotedTripleSurface,
685) -> Result<Vec<RawQuad>, IngestError> {
686 parse_text_surface(text, "trig", surface)
687}
688
689/// The shared Turtle/TriG text path: stream the string through whichever reader
690/// `surface` selects, and — this is the part only the text path can do, because
691/// only it holds the input — say so when an RDF-star parse fails on what is
692/// plainly RDF 1.2.
693///
694/// It does not audit: the Turtle/TriG text callers audit over the finished quads
695/// (see [`parse_statements_audited_surface`]), and auditing here too would count
696/// every IRI twice.
697///
698/// The RDF-star arm calls `oxttl` 0.1 **directly** rather than routing through
699/// [`stream_reader_audited_surface`]. That is not style: this is the only ingest
700/// path the wasm engine reaches, and going through the generic reader would
701/// monomorphize it over `&[u8]` and pull the whole `match format` — every
702/// syntax's reader — into a module that previously linked one Turtle parser.
703/// Measured at +17 KB of wasm for code no browser can run, since the RDF 1.2
704/// reader is not compiled there at all. Keeping the arm direct keeps the
705/// browser artifacts what they were.
706fn parse_text_surface(
707 text: &str,
708 format: &str,
709 surface: QuotedTripleSurface,
710) -> Result<Vec<RawQuad>, IngestError> {
711 let mut out = Vec::new();
712 let r = if surface == QuotedTripleSurface::Rdf12 {
713 rdf12::stream(text.as_bytes(), format, None, &mut |q| out.push(q))
714 } else if format == "ttl" {
715 turtle_star(text.as_bytes(), None, &mut |q| out.push(q))
716 } else {
717 trig_star(text.as_bytes(), None, &mut |q| out.push(q))
718 };
719 match r {
720 Ok(()) => Ok(out),
721 // The default surface met `<<(`: that is an RDF 1.2 file being read as
722 // RDF-star, the one mistake this flag exists to prevent, and the parse
723 // error alone ("unexpected character") would send the reader hunting for
724 // a typo that is not there.
725 Err(IngestError::Turtle(m))
726 if surface == QuotedTripleSurface::RdfStar && looks_like_rdf12(text) =>
727 {
728 Err(IngestError::Turtle(format!("{m}{RDF12_SURFACE_HINT}")))
729 }
730 Err(IngestError::TriG(m))
731 if surface == QuotedTripleSurface::RdfStar && looks_like_rdf12(text) =>
732 {
733 Err(IngestError::TriG(format!("{m}{RDF12_SURFACE_HINT}")))
734 }
735 Err(e) => Err(e),
736 }
737}
738
739/// Parse RDF/XML into canonical N-Triples-token triples via oxrdfxml. This is how
740/// most OWL ontologies ship (`.rdf`/`.owl`/`.xml` with an `rdf:RDF` root) — so rete
741/// ingests them directly, no external conversion. (OWL/XML — the non-RDF functional
742/// XML serialization — is a different language; convert it with owlready2 first.)
743pub fn parse_rdfxml(text: &str) -> Result<Vec<RawTriple>, IngestError> {
744 let mut out = Vec::new();
745 for r in oxrdfxml::RdfXmlParser::new().for_reader(text.as_bytes()) {
746 let t = r.map_err(|e| IngestError::RdfXml(e.to_string()))?;
747 out.push((
748 t.subject.to_string(),
749 t.predicate.to_string(),
750 t.object.to_string(),
751 ));
752 }
753 Ok(out)
754}
755
756/// Parse one text input by format name (`"nt"`, `"nq"`, `"ttl"`, `"trig"`, or
757/// `"rdfxml"`) into quads (triples land in the default graph).
758pub fn parse_statements(text: &str, format: &str) -> Result<Vec<RawQuad>, IngestError> {
759 parse_statements_audited(text, format, None)
760}
761
762/// [`parse_statements`] with an optional [`IriAudit`]. The line-based syntaxes
763/// audit as they parse (so `strict` fails on the offending line); the others are
764/// audited over the parsed quads, which is where `oxttl` has already had its say.
765pub fn parse_statements_audited(
766 text: &str,
767 format: &str,
768 audit: Option<&mut IriAudit>,
769) -> Result<Vec<RawQuad>, IngestError> {
770 parse_statements_audited_surface(text, format, audit, QuotedTripleSurface::default())
771}
772
773/// [`parse_statements_audited`] reading `<< … >>` in the given
774/// [`QuotedTripleSurface`]. This is the entry point `rete build` and
775/// `rete validate` use for everything but a streamed line-based input, and the
776/// one that turns "RDF 1.2 file, RDF-star reader" into an error that names the
777/// flag instead of a bare syntax complaint.
778pub fn parse_statements_audited_surface(
779 text: &str,
780 format: &str,
781 mut audit: Option<&mut IriAudit>,
782 surface: QuotedTripleSurface,
783) -> Result<Vec<RawQuad>, IngestError> {
784 let quads = match format {
785 "nq" => return parse_quads_audited(text, audit),
786 "nt" => {
787 return Ok(parse_audited(text, audit)?
788 .into_iter()
789 .map(|(s, p, o)| (s, p, o, None))
790 .collect())
791 }
792 // Straight to the quad path for both: going via `parse_turtle_surface`
793 // would build a `Vec<RawQuad>`, rebuild it as a `Vec<RawTriple>` to
794 // satisfy that function's signature, and rebuild it as quads again —
795 // three copies of every term String on the biggest input rete takes.
796 "ttl" | "trig" => parse_text_surface(text, format, surface)?,
797 "rdfxml" => parse_rdfxml(text)?
798 .into_iter()
799 .map(|(s, p, o)| (s, p, o, None))
800 .collect(),
801 other => return Err(IngestError::UnknownFormat(other.to_string())),
802 };
803 for (s, p, o, g) in &quads {
804 audit_quad(audit.as_deref_mut(), s, p, o, g.as_deref(), || {
805 format.to_string()
806 })?;
807 }
808 Ok(quads)
809}
810
811/// Take one term from the front of `s`, returning `(term, remainder)`.
812pub(crate) fn take_term(s: &str) -> Option<(String, &str)> {
813 let bytes = s.as_bytes();
814 let first = *bytes.first()?;
815 match first {
816 // A quoted triple / triple term, in EITHER surface — the inner terms are
817 // themselves terms (so this recurses; nesting works). `<<` starts with `<`
818 // and an IRI scan would stop at the first inner `>`, so it must be handled
819 // before the plain-IRI case.
820 // * RDF-star: `<< subject predicate object >>`
821 // * RDF 1.2: `<<( subject predicate object )>>` (triple term)
822 // Both re-emit the SAME canonical token `<<s p o>>`, so a file written in
823 // either surface — and a query written either way — dedupe and match. This
824 // makes RDF 1.2 N-Triples interoperable with the RDF-star we already store,
825 // with no format change and no dependency swap.
826 b'<' if bytes.get(1) == Some(&b'<') => {
827 // Distinguish `<<(` (RDF 1.2) from `<<` (RDF-star) by the char after `<<`.
828 let (inner, rdf12) = match s[2..].strip_prefix('(') {
829 Some(after) => (after.trim_start(), true),
830 None => (s[2..].trim_start(), false),
831 };
832 let (subj, r) = take_term(inner)?;
833 let (pred, r) = take_term(r.trim_start())?;
834 let (obj, r) = take_term(r.trim_start())?;
835 let r = r.trim_start();
836 let rest = if rdf12 {
837 r.strip_prefix(")>>")?
838 } else {
839 r.strip_prefix(">>")?
840 };
841 // Canonical surface = oxrdf's `Triple` Display: `<<s p o>>` (tight
842 // brackets, single spaces between components) — the same token for both
843 // input surfaces, so N-Triples-star, Turtle-star, and RDF 1.2 triple
844 // terms all resolve to one dictionary entry.
845 Some((format!("<<{subj} {pred} {obj}>>"), rest))
846 }
847 b'<' => {
848 // IRI ref: up to the closing '>'.
849 let end = s.find('>')?;
850 Some((s[..=end].to_string(), &s[end + 1..]))
851 }
852 b'_' => {
853 // Blank node: up to whitespace.
854 let end = s.find(char::is_whitespace).unwrap_or(s.len());
855 Some((s[..end].to_string(), &s[end..]))
856 }
857 b'"' => {
858 // Literal: closing unescaped quote, then optional ^^<dt> or @lang.
859 let mut i = 1;
860 let b = s.as_bytes();
861 while i < b.len() {
862 match b[i] {
863 b'\\' => i += 2, // skip escaped char
864 b'"' => break,
865 _ => i += 1,
866 }
867 }
868 if i >= b.len() {
869 return None; // unterminated
870 }
871 let mut end = i + 1; // past closing quote
872 if s[end..].starts_with("^^<") {
873 let close = s[end..].find('>')? + end;
874 // RDF 1.1: `"x"^^xsd:string` IS `"x"`; keep the one canonical
875 // spelling, so the two never become two dictionary terms and
876 // a plain query constant matches either input.
877 if &s[end + 3..close] == "http://www.w3.org/2001/XMLSchema#string" {
878 return Some((s[..end].to_string(), &s[close + 1..]));
879 }
880 end = close + 1;
881 } else if s[end..].starts_with('@') {
882 // Language tag: '@' then BCP-47 subtags `[a-zA-Z0-9-]+`. Stop at
883 // the first char that can't be part of a tag — normally the
884 // whitespace before the predicate, but ALSO the `>>` that closes
885 // a quoted triple when this literal is its object (`"x"@en>>`),
886 // where there is no separating whitespace.
887 let mut j = end + 1; // past '@'
888 while j < b.len() && (b[j].is_ascii_alphanumeric() || b[j] == b'-') {
889 j += 1;
890 }
891 end = j;
892 }
893 Some((s[..end].to_string(), &s[end..]))
894 }
895 _ => None,
896 }
897}
898
899/// Split a canonical quoted-triple token `<<s p o>>` (RDF-star) into its three
900/// component term tokens, or `None` if `t` is not a quoted triple. Reuses
901/// [`take_term`] for term-boundary scanning, so nested quoting parses correctly.
902/// The inverse of the `<<…>>` construction; used by the SUBJECT/PREDICATE/OBJECT
903/// SPARQL-star builtins.
904pub(crate) fn quoted_triple_parts(t: &str) -> Option<(String, String, String)> {
905 let inner = t.strip_prefix("<<")?.strip_suffix(">>")?.trim();
906 let (s, r) = take_term(inner)?;
907 let (p, r) = take_term(r.trim_start())?;
908 let (o, r) = take_term(r.trim_start())?;
909 if !r.trim().is_empty() {
910 return None;
911 }
912 Some((s, p, o))
913}
914
915/// Counts describing an assembled file, for status lines and UIs.
916///
917/// In the [`BuildStats`] a metadata callback receives, `statements` and
918/// `default_triples` are the counts **ingested** — the input multiset, before
919/// the index deduplicates it. In the `BuildStats` an assemble function
920/// *returns*, they are the counts actually **written** (see
921/// [`FinalCounts`]), so a status line reports what the file holds. Use
922/// [`FinalCounts`] rather than these when a payload must agree with the header.
923#[derive(Debug, Clone, Copy)]
924pub struct BuildStats {
925 /// Total statements, across the default graph and every named one.
926 pub statements: usize,
927 /// Statements that landed in the default graph.
928 pub default_triples: usize,
929 /// How many named graphs the input mentioned; one index is written per graph.
930 pub named_graphs: usize,
931 /// Distinct terms in the shared dictionary.
932 pub terms: usize,
933 /// Levels in the community pyramid, or `0` when the build skipped it.
934 pub pyramid_levels: u16,
935}
936
937/// How a build stores the **named graphs** (the default graph is unaffected).
938#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
939pub enum GraphLayout {
940 /// One permutation index per graph, in the NAMED_GRAPHS section (kind 5):
941 /// the graph IRI as text, then a full container per graph. What every rete
942 /// before 0.4 writes and reads.
943 #[default]
944 PerGraph,
945 /// The **quad index** (kind 10, SPEC.md §6.5): every named-graph quad
946 /// stored once, the graph as a fourth column of graph-leading permutations
947 /// in shared tiles, behind a sorted graph directory; graph names become
948 /// dictionary terms. Far smaller and randomly addressable when graphs are
949 /// many and small. Readers before 0.4.0 refuse these files (loudly — see
950 /// `docs/compatibility.md`). Needs the 3- or 6-permutation set.
951 Quad,
952}
953
954/// One pass's named-graph quads, in the layout being built.
955enum NamedQuads {
956 PerGraph(std::collections::BTreeMap<String, Vec<(u32, u32, u32)>>),
957 Quad {
958 /// `(graph subject id, s, p, o)`.
959 quads: Vec<[u32; 4]>,
960 /// Distinct graphs seen (a bitset over subject ids).
961 seen: Vec<u64>,
962 graphs: usize,
963 /// The last graph name and its id: N-Quads dumps keep a graph's
964 /// statements together, so most quads skip the dictionary lookup.
965 last: Option<(String, u32)>,
966 },
967}
968
969impl NamedQuads {
970 fn new(layout: GraphLayout, dict: &Dictionary) -> Self {
971 match layout {
972 GraphLayout::PerGraph => NamedQuads::PerGraph(Default::default()),
973 GraphLayout::Quad => NamedQuads::Quad {
974 quads: Vec::new(),
975 seen: vec![
976 0u64;
977 (dict.shared_count() as usize + dict.subject_only_count() as usize) / 64
978 + 2
979 ],
980 graphs: 0,
981 last: None,
982 },
983 }
984 }
985
986 fn push(&mut self, dict: &Dictionary, graph: String, t: (u32, u32, u32)) {
987 match self {
988 NamedQuads::PerGraph(m) => m.entry(graph).or_default().push(t),
989 NamedQuads::Quad {
990 quads,
991 seen,
992 graphs,
993 last,
994 } => {
995 let g = match last {
996 Some((name, id)) if *name == graph => *id,
997 _ => {
998 let id = dict.subject_id(&graph).expect("observed graph name");
999 *last = Some((graph, id));
1000 id
1001 }
1002 };
1003 let (w, b) = (g as usize / 64, g % 64);
1004 if let Some(word) = seen.get_mut(w) {
1005 if *word & (1 << b) == 0 {
1006 *word |= 1 << b;
1007 *graphs += 1;
1008 }
1009 }
1010 quads.push([g, t.0, t.1, t.2]);
1011 }
1012 }
1013 }
1014
1015 fn graph_count(&self) -> usize {
1016 match self {
1017 NamedQuads::PerGraph(m) => m.len(),
1018 NamedQuads::Quad { graphs, .. } => *graphs,
1019 }
1020 }
1021
1022 fn quad_count(&self) -> usize {
1023 match self {
1024 NamedQuads::PerGraph(m) => m.values().map(Vec::len).sum(),
1025 NamedQuads::Quad { quads, .. } => quads.len(),
1026 }
1027 }
1028}
1029
1030/// The **deduplicated** counts of the file being written — what the header
1031/// records, and therefore what any embedded metadata has to report.
1032///
1033/// The input multiset is not the file: every permutation index sorts and
1034/// deduplicates, so a harvest that pages with overlapping windows writes fewer
1035/// quads than it ingested. These counts are known only once the indexes exist,
1036/// which is why a payload that carries them is derived in two stages (see
1037/// [`IntoMetadata`]).
1038#[derive(Debug, Clone, Copy)]
1039pub struct FinalCounts {
1040 /// Unique triples in the default graph.
1041 pub default_triples: u64,
1042 /// Unique quads across the default graph and every named graph — exactly
1043 /// the header's `quad_count`.
1044 pub quads: u64,
1045}
1046
1047/// What a build's metadata callback may return.
1048///
1049/// A `Vec<u8>` is the payload verbatim — the common case (no metadata, or a
1050/// payload that carries no counts). [`DeferredMetadata`] is a payload that
1051/// *does* carry counts: the callback derives everything it needs while the
1052/// source quads are still resident, and returns a finalizer that the writer
1053/// calls with the [`FinalCounts`], which only exist once the indexes have
1054/// deduplicated the input. Without that second stage a card can only report the
1055/// ingested count, which over-reports any input containing duplicates.
1056pub trait IntoMetadata {
1057 /// Produce the metadata section payload for a file with these counts.
1058 fn into_metadata(self, counts: FinalCounts) -> Vec<u8>;
1059}
1060
1061impl IntoMetadata for Vec<u8> {
1062 fn into_metadata(self, _counts: FinalCounts) -> Vec<u8> {
1063 self
1064 }
1065}
1066
1067/// A metadata payload whose final form needs the written (deduplicated) counts.
1068/// See [`IntoMetadata`].
1069pub struct DeferredMetadata(Box<dyn FnOnce(FinalCounts) -> Vec<u8>>);
1070
1071impl DeferredMetadata {
1072 /// Defer `f` until the indexes are built and the true counts are known.
1073 pub fn new(f: impl FnOnce(FinalCounts) -> Vec<u8> + 'static) -> Self {
1074 DeferredMetadata(Box::new(f))
1075 }
1076
1077 /// No metadata section — byte-identical to a metadata-free build. Lets one
1078 /// `match` arm opt out while the other defers, without a type mismatch.
1079 pub fn none() -> Self {
1080 DeferredMetadata::new(|_| Vec::new())
1081 }
1082}
1083
1084impl IntoMetadata for DeferredMetadata {
1085 fn into_metadata(self, counts: FinalCounts) -> Vec<u8> {
1086 (self.0)(counts)
1087 }
1088}
1089
1090/// Assemble a complete `.rete` file image from parsed quads: one shared
1091/// dictionary, the default-graph index, one index per named graph, and the
1092/// community pyramid. `metadata` is the opaque metadata-section payload (the
1093/// CLI puts a JSON Dataset Card there); pass `&[]` for none — that is
1094/// byte-identical to a metadata-free build.
1095pub fn assemble_dataset(quads: Vec<RawQuad>, metadata: &[u8]) -> (Vec<u8>, BuildStats) {
1096 let blob = metadata.to_vec();
1097 assemble_dataset_with(quads, move |_, _| blob)
1098}
1099
1100/// Like [`assemble_dataset`], but the metadata payload is derived from the
1101/// [`BuildStats`] and the source quads while they are still resident — for
1102/// metadata that describes the graph (the Dataset Card). Returning an empty
1103/// `Vec` is byte-identical to a metadata-free build; return a
1104/// [`DeferredMetadata`] for a payload that must also carry the file's
1105/// deduplicated counts, which exist only once the indexes are built.
1106pub fn assemble_dataset_with<M: IntoMetadata>(
1107 quads: Vec<RawQuad>,
1108 metadata: impl FnOnce(&BuildStats, &[RawQuad]) -> M,
1109) -> (Vec<u8>, BuildStats) {
1110 assemble_dataset_with_opts(quads, true, false, None, metadata)
1111}
1112
1113/// Like [`assemble_dataset_with`], but `with_pyramid = false` skips the Louvain
1114/// community pyramid entirely — no pyramid section is written (header length 0).
1115/// SPARQL / SHACL / triple / reachability queries don't use the pyramid, so a
1116/// pyramid-less file is fully queryable and markedly smaller (the pyramid is the
1117/// largest section on highly-connected graphs). Only the community / summary /
1118/// progressive paths need it.
1119pub fn assemble_dataset_with_opts<M: IntoMetadata>(
1120 quads: Vec<RawQuad>,
1121 with_pyramid: bool,
1122 with_text_index: impl crate::text_index::IntoTextIndex,
1123 type_override: Option<&str>,
1124 metadata: impl FnOnce(&BuildStats, &[RawQuad]) -> M,
1125) -> (Vec<u8>, BuildStats) {
1126 assemble_dataset_with_opts_algo(
1127 quads,
1128 with_pyramid,
1129 with_text_index,
1130 type_override,
1131 PyramidAlgo::Louvain,
1132 metadata,
1133 )
1134}
1135
1136/// Like [`assemble_dataset_with_opts`], but selects the community [`PyramidAlgo`]
1137/// (the in-memory build path for `rete build --pyramid-algo …`).
1138#[allow(clippy::too_many_arguments)]
1139pub fn assemble_dataset_with_opts_algo<M: IntoMetadata>(
1140 quads: Vec<RawQuad>,
1141 with_pyramid: bool,
1142 with_text_index: impl crate::text_index::IntoTextIndex,
1143 type_override: Option<&str>,
1144 algo: PyramidAlgo,
1145 metadata: impl FnOnce(&BuildStats, &[RawQuad]) -> M,
1146) -> (Vec<u8>, BuildStats) {
1147 assemble_dataset_with_perms(
1148 quads,
1149 with_pyramid,
1150 with_text_index,
1151 type_override,
1152 algo,
1153 crate::index::PermSet::ALL,
1154 metadata,
1155 )
1156}
1157
1158/// Like [`assemble_dataset_with_opts_algo`], but writes only the permutations in
1159/// `perms` (`rete build --permutations 3`). Every other byte of the file is
1160/// unchanged; [`crate::index::PermSet::ALL`] reproduces the default build
1161/// exactly, down to the header byte.
1162#[allow(clippy::too_many_arguments)]
1163pub fn assemble_dataset_with_perms<M: IntoMetadata>(
1164 quads: Vec<RawQuad>,
1165 with_pyramid: bool,
1166 with_text_index: impl crate::text_index::IntoTextIndex,
1167 type_override: Option<&str>,
1168 algo: PyramidAlgo,
1169 perms: crate::index::PermSet,
1170 metadata: impl FnOnce(&BuildStats, &[RawQuad]) -> M,
1171) -> (Vec<u8>, BuildStats) {
1172 assemble_dataset_with_layout(
1173 quads,
1174 with_pyramid,
1175 with_text_index,
1176 type_override,
1177 algo,
1178 perms,
1179 GraphLayout::PerGraph,
1180 metadata,
1181 )
1182}
1183
1184/// Like [`assemble_dataset_with_perms`], storing the named graphs in `graphs`
1185/// layout. [`GraphLayout::PerGraph`] reproduces it exactly.
1186///
1187/// # Panics
1188///
1189/// With [`GraphLayout::Quad`] and a permutation set other than
1190/// [`PermSet::CORE`](crate::index::PermSet::CORE) or
1191/// [`PermSet::ALL`](crate::index::PermSet::ALL), when the input has named graphs.
1192#[allow(clippy::too_many_arguments)]
1193pub fn assemble_dataset_with_layout<M: IntoMetadata>(
1194 quads: Vec<RawQuad>,
1195 with_pyramid: bool,
1196 with_text_index: impl crate::text_index::IntoTextIndex,
1197 type_override: Option<&str>,
1198 algo: PyramidAlgo,
1199 perms: crate::index::PermSet,
1200 graphs: GraphLayout,
1201 metadata: impl FnOnce(&BuildStats, &[RawQuad]) -> M,
1202) -> (Vec<u8>, BuildStats) {
1203 let text_index = crate::text_index::IntoTextIndex::into_text_index(with_text_index);
1204 let opts = AssembleOptions {
1205 with_pyramid,
1206 with_text_index: text_index.is_some(),
1207 text_index_scope: text_index.as_ref(),
1208 type_override,
1209 algo,
1210 perms,
1211 graph_layout: graphs,
1212 ..AssembleOptions::legacy()
1213 };
1214 assemble_dataset_opts(quads, &opts, metadata)
1215}
1216
1217/// Everything an in-memory build decides besides its input. The fields the
1218/// older `assemble_*` entry points take positionally, plus the sections added
1219/// after the generation-1 freeze.
1220#[derive(Debug, Clone, Copy)]
1221pub struct AssembleOptions<'a> {
1222 /// Build the community pyramid (kind 4).
1223 pub with_pyramid: bool,
1224 /// Build the full-text index (kind 6, or kind 11 when its scope leaves
1225 /// out some predicates).
1226 pub with_text_index: bool,
1227 /// The scope of that index (`--text-index-graphs`, `--text-index-include`,
1228 /// `--text-index-exclude`); `None` is the default scope, the only one
1229 /// before 0.4.0: the default graph, every predicate.
1230 pub text_index_scope: Option<&'a crate::text_index::TextIndexScope>,
1231 /// The type predicate for the schema (e.g. `wdt:P31`); `rdf:type` if `None`.
1232 pub type_override: Option<&'a str>,
1233 /// The community algorithm of the pyramid.
1234 pub algo: PyramidAlgo,
1235 /// Which index permutations to write.
1236 pub perms: crate::index::PermSet,
1237 /// How the named graphs are stored: one index per graph (kind 5) or the
1238 /// quad index (kind 10, `rete build --named-graphs quad`).
1239 pub graph_layout: GraphLayout,
1240 /// What the pyramid-meta carries besides the summary.
1241 pub pyramid_layout: crate::file::PyramidLayout,
1242 /// Write the LABEL_INDEX section (kind 8, `rete build --label-index`).
1243 pub label_index: bool,
1244 /// Write the SCHEMA section (kind 9; `rete build` writes it unless
1245 /// `--no-schema`).
1246 pub schema: bool,
1247}
1248
1249impl AssembleOptions<'_> {
1250 /// What every `assemble_*` entry point wrote before kinds 8 and 9 existed:
1251 /// a Louvain pyramid with the combined pyramid-meta, no text index, all six
1252 /// permutations, one index per named graph, no LABEL_INDEX or SCHEMA
1253 /// section.
1254 pub fn legacy() -> Self {
1255 AssembleOptions {
1256 with_pyramid: true,
1257 with_text_index: false,
1258 text_index_scope: None,
1259 type_override: None,
1260 algo: PyramidAlgo::Louvain,
1261 perms: crate::index::PermSet::ALL,
1262 graph_layout: GraphLayout::PerGraph,
1263 pyramid_layout: crate::file::PyramidLayout::Combined,
1264 label_index: false,
1265 schema: false,
1266 }
1267 }
1268
1269 /// What `rete build` writes: the pyramid-meta carries only the community
1270 /// material, the schema has its own section, and the label index is
1271 /// opt-in.
1272 pub fn sectioned() -> Self {
1273 AssembleOptions {
1274 pyramid_layout: crate::file::PyramidLayout::CommunityOnly,
1275 schema: true,
1276 ..Self::legacy()
1277 }
1278 }
1279}
1280
1281/// Assemble a file image from parsed quads under explicit [`AssembleOptions`].
1282///
1283/// # Panics
1284///
1285/// With [`GraphLayout::Quad`] and a permutation set other than
1286/// [`PermSet::CORE`](crate::index::PermSet::CORE) or
1287/// [`PermSet::ALL`](crate::index::PermSet::ALL), when the input has named graphs.
1288pub fn assemble_dataset_opts<M: IntoMetadata>(
1289 quads: Vec<RawQuad>,
1290 opts: &AssembleOptions<'_>,
1291 metadata: impl FnOnce(&BuildStats, &[RawQuad]) -> M,
1292) -> (Vec<u8>, BuildStats) {
1293 let graphs = opts.graph_layout;
1294 let mut db = DictionaryBuilder::new();
1295 for (s, p, o, g) in &quads {
1296 db.observe(s, p, o);
1297 if let (GraphLayout::Quad, Some(g)) = (graphs, g) {
1298 db.observe_graph(g);
1299 }
1300 }
1301 let dict = db.build();
1302 crate::build_trace::lap(crate::build_trace::Phase::Dictionary);
1303
1304 let mut default_triples = Vec::new();
1305 let mut named = NamedQuads::new(graphs, &dict);
1306 for (s, p, o, g) in &quads {
1307 let t = dict.encode(s, p, o).expect("observed term");
1308 match g {
1309 None => default_triples.push(t),
1310 Some(graph) => named.push(&dict, graph.clone(), t),
1311 }
1312 }
1313 crate::build_trace::lap(crate::build_trace::Phase::Encode);
1314
1315 // Derive the metadata blob (the Dataset Card) from the raw quads NOW, while
1316 // they are resident — then DROP them before the memory-heavy pyramid + index
1317 // phases. On a big build the string quads are the largest working set (every
1318 // term an owned String, heavily duplicated) and are fully redundant with the
1319 // dictionary + id-triples once encoded, so freeing them here cuts peak RAM by
1320 // their whole size. `pyramid_levels` is not known yet (0 in the callback);
1321 // it is filled into the returned `stats` by `finish_assembly`, and no metadata
1322 // callback depends on it (the card derives from the quads + term/graph counts).
1323 let stats = BuildStats {
1324 statements: quads.len(),
1325 default_triples: default_triples.len(),
1326 named_graphs: named.graph_count(),
1327 terms: dict.term_count() as usize,
1328 pyramid_levels: 0,
1329 };
1330 let pending = metadata(&stats, &quads);
1331 crate::build_trace::lap(crate::build_trace::Phase::CardDerive);
1332 drop(quads);
1333
1334 finish_assembly(dict, default_triples, named, opts, pending, stats)
1335}
1336
1337/// **Two-pass, low-RAM** assembly: build a `.rete` by **streaming** the input(s)
1338/// twice instead of holding every parsed quad in memory. `stream` is invoked
1339/// **twice** and MUST replay the exact same quads in the same order each time —
1340/// pass 1 observes every term into the dictionary; pass 2 encodes them to
1341/// id-triples. The raw string quads (every term an owned String, heavily
1342/// duplicated — by far the largest working set on a big graph) are **never
1343/// collected**, so peak RAM is bounded by the dictionary + id-triples + index
1344/// rather than the string-quad multiset. Output is **byte-identical** to
1345/// [`assemble_dataset_with_opts`] on the same quads (same dictionary, same
1346/// id-triples in file order, same downstream pipeline).
1347///
1348/// The metadata callback derives the Dataset Card from the built dictionary +
1349/// default-graph id-triples (resolving terms through the dictionary), since the
1350/// raw quads were never retained. `stream` propagates parse/IO errors.
1351pub fn assemble_dataset_streaming<S, M: IntoMetadata>(
1352 stream: S,
1353 with_pyramid: bool,
1354 with_text_index: impl crate::text_index::IntoTextIndex,
1355 type_override: Option<&str>,
1356 metadata: impl FnOnce(&BuildStats, &Dictionary, &[(u32, u32, u32)]) -> M,
1357) -> Result<(Vec<u8>, BuildStats), IngestError>
1358where
1359 S: FnMut(&mut dyn FnMut(RawQuad)) -> Result<(), IngestError>,
1360{
1361 assemble_dataset_streaming_algo(
1362 stream,
1363 with_pyramid,
1364 with_text_index,
1365 type_override,
1366 PyramidAlgo::Louvain,
1367 metadata,
1368 )
1369}
1370
1371/// Like [`assemble_dataset_streaming`], but selects the community [`PyramidAlgo`]
1372/// (the streaming, low-RAM build path for `rete build --pyramid-algo …`).
1373#[allow(clippy::too_many_arguments)]
1374pub fn assemble_dataset_streaming_algo<S, M: IntoMetadata>(
1375 stream: S,
1376 with_pyramid: bool,
1377 with_text_index: impl crate::text_index::IntoTextIndex,
1378 type_override: Option<&str>,
1379 algo: PyramidAlgo,
1380 metadata: impl FnOnce(&BuildStats, &Dictionary, &[(u32, u32, u32)]) -> M,
1381) -> Result<(Vec<u8>, BuildStats), IngestError>
1382where
1383 S: FnMut(&mut dyn FnMut(RawQuad)) -> Result<(), IngestError>,
1384{
1385 assemble_dataset_streaming_with_perms(
1386 stream,
1387 with_pyramid,
1388 with_text_index,
1389 type_override,
1390 algo,
1391 crate::index::PermSet::ALL,
1392 metadata,
1393 )
1394}
1395
1396/// Like [`assemble_dataset_streaming_algo`], but writes only the permutations in
1397/// `perms` — the two-pass low-RAM twin of [`assemble_dataset_with_perms`].
1398#[allow(clippy::too_many_arguments)]
1399pub fn assemble_dataset_streaming_with_perms<S, M: IntoMetadata>(
1400 stream: S,
1401 with_pyramid: bool,
1402 with_text_index: impl crate::text_index::IntoTextIndex,
1403 type_override: Option<&str>,
1404 algo: PyramidAlgo,
1405 perms: crate::index::PermSet,
1406 metadata: impl FnOnce(&BuildStats, &Dictionary, &[(u32, u32, u32)]) -> M,
1407) -> Result<(Vec<u8>, BuildStats), IngestError>
1408where
1409 S: FnMut(&mut dyn FnMut(RawQuad)) -> Result<(), IngestError>,
1410{
1411 assemble_dataset_streaming_with_layout(
1412 stream,
1413 with_pyramid,
1414 with_text_index,
1415 type_override,
1416 algo,
1417 perms,
1418 GraphLayout::PerGraph,
1419 metadata,
1420 )
1421}
1422
1423/// Like [`assemble_dataset_streaming_with_perms`], storing the named graphs in
1424/// `graphs` layout — the two-pass low-RAM twin of
1425/// [`assemble_dataset_with_layout`]. [`GraphLayout::Quad`] with a permutation
1426/// set other than the 3- or 6-permutation one is an error.
1427#[allow(clippy::too_many_arguments)]
1428pub fn assemble_dataset_streaming_with_layout<S, M: IntoMetadata>(
1429 stream: S,
1430 with_pyramid: bool,
1431 with_text_index: impl crate::text_index::IntoTextIndex,
1432 type_override: Option<&str>,
1433 algo: PyramidAlgo,
1434 perms: crate::index::PermSet,
1435 graphs: GraphLayout,
1436 metadata: impl FnOnce(&BuildStats, &Dictionary, &[(u32, u32, u32)]) -> M,
1437) -> Result<(Vec<u8>, BuildStats), IngestError>
1438where
1439 S: FnMut(&mut dyn FnMut(RawQuad)) -> Result<(), IngestError>,
1440{
1441 let text_index = crate::text_index::IntoTextIndex::into_text_index(with_text_index);
1442 let opts = AssembleOptions {
1443 with_pyramid,
1444 with_text_index: text_index.is_some(),
1445 text_index_scope: text_index.as_ref(),
1446 type_override,
1447 algo,
1448 perms,
1449 graph_layout: graphs,
1450 ..AssembleOptions::legacy()
1451 };
1452 assemble_dataset_streaming_opts(stream, &opts, metadata)
1453}
1454
1455/// The two-pass low-RAM twin of [`assemble_dataset_opts`]. A quad-index layout
1456/// with a permutation set other than the 3- or 6-permutation one is an error.
1457pub fn assemble_dataset_streaming_opts<S, M: IntoMetadata>(
1458 mut stream: S,
1459 opts: &AssembleOptions<'_>,
1460 metadata: impl FnOnce(&BuildStats, &Dictionary, &[(u32, u32, u32)]) -> M,
1461) -> Result<(Vec<u8>, BuildStats), IngestError>
1462where
1463 S: FnMut(&mut dyn FnMut(RawQuad)) -> Result<(), IngestError>,
1464{
1465 let graphs = opts.graph_layout;
1466 if graphs == GraphLayout::Quad && crate::quad::check_perms(opts.perms).is_err() {
1467 return Err(IngestError::Io(
1468 "the quad index needs the 3- or 6-permutation set".into(),
1469 ));
1470 }
1471 // Pass 1: observe every term (the dictionary dedups; the string quads are
1472 // freed line by line and never collected). With the quad index, graph
1473 // names are terms too.
1474 let mut db = DictionaryBuilder::new();
1475 stream(&mut |(s, p, o, g)| {
1476 db.observe(&s, &p, &o);
1477 if let (GraphLayout::Quad, Some(g)) = (graphs, g) {
1478 db.observe_graph(&g);
1479 }
1480 })?;
1481 let dict = db.build();
1482 crate::build_trace::lap(crate::build_trace::Phase::ParseDictionary);
1483
1484 // Pass 2: encode each quad to an id-triple, bucketing named graphs.
1485 let mut default_triples: Vec<(u32, u32, u32)> = Vec::new();
1486 let mut named = NamedQuads::new(graphs, &dict);
1487 stream(&mut |(s, p, o, g)| {
1488 let t = dict.encode(&s, &p, &o).expect("observed term");
1489 match g {
1490 None => default_triples.push(t),
1491 Some(graph) => named.push(&dict, graph, t),
1492 }
1493 })?;
1494 crate::build_trace::lap(crate::build_trace::Phase::ParseEncode);
1495
1496 let statements = default_triples.len() + named.quad_count();
1497 let stats = BuildStats {
1498 statements,
1499 default_triples: default_triples.len(),
1500 named_graphs: named.graph_count(),
1501 terms: dict.term_count() as usize,
1502 pyramid_levels: 0,
1503 };
1504 let pending = metadata(&stats, &dict, &default_triples);
1505 crate::build_trace::lap(crate::build_trace::Phase::CardDerive);
1506 Ok(finish_assembly(
1507 dict,
1508 default_triples,
1509 named,
1510 opts,
1511 pending,
1512 stats,
1513 ))
1514}
1515
1516/// The shared tail of every build path: from a finished dictionary + encoded
1517/// id-triples (default graph + named), build the community pyramid, the optional
1518/// full-text index, the permutation indexes, and serialize the file image. Takes
1519/// the id-triples **by value** so they are freed as the permutations consume them.
1520fn finish_assembly<M: IntoMetadata>(
1521 dict: Dictionary,
1522 mut default_triples: Vec<(u32, u32, u32)>,
1523 named: NamedQuads,
1524 opts: &AssembleOptions<'_>,
1525 pending: M,
1526 mut stats: BuildStats,
1527) -> (Vec<u8>, BuildStats) {
1528 let has_named = named.graph_count() > 0;
1529 let perms = opts.perms;
1530
1531 // The pyramid and the full-text index are built FIRST, while the dictionary and
1532 // the default id-triples are both still resident — both need the two together.
1533 // The pyramid sees the triples in input order (Louvain is order-sensitive).
1534 let (meta, levels) = if opts.with_pyramid {
1535 crate::file::build_pyramid_meta_layout(
1536 &dict,
1537 &default_triples,
1538 DEFAULT_TILE_BUDGET,
1539 opts.type_override,
1540 opts.algo,
1541 opts.pyramid_layout,
1542 )
1543 } else {
1544 (Vec::new(), 0)
1545 };
1546 stats.pyramid_levels = levels;
1547 if opts.with_pyramid {
1548 crate::build_trace::lap(crate::build_trace::Phase::Pyramid);
1549 }
1550
1551 // The full-text index over the literals of the requested scope: the
1552 // default graph's (the only scope before 0.4.0), optionally every named
1553 // graph's too, optionally only some predicates'.
1554 let with_text_index = opts
1555 .with_text_index
1556 .then(|| opts.text_index_scope.cloned().unwrap_or_default());
1557 // The named graphs' triples, for an index whose scope covers them: per
1558 // graph, or (in the quad layout) the quads' `(s, p, o)`, copied only when
1559 // the scope needs them; the index does not care which graph a word came
1560 // from.
1561 let quad_spo: Vec<(u32, u32, u32)>;
1562 let named_triples: Vec<&[(u32, u32, u32)]> = match &named {
1563 NamedQuads::PerGraph(m) => m.values().map(Vec::as_slice).collect(),
1564 NamedQuads::Quad { quads, .. } => {
1565 quad_spo = if with_text_index
1566 .as_ref()
1567 .is_some_and(crate::text_index::TextIndexScope::covers_named_graphs)
1568 {
1569 quads.iter().map(|q| (q[1], q[2], q[3])).collect()
1570 } else {
1571 Vec::new()
1572 };
1573 vec![quad_spo.as_slice()]
1574 }
1575 };
1576 let text_index = match &with_text_index {
1577 Some(scope) => crate::text_index::build_section(
1578 &dict,
1579 scope,
1580 &default_triples,
1581 named_triples.into_iter(),
1582 crate::file::writer_codec(),
1583 ),
1584 None => Vec::new(),
1585 };
1586 if with_text_index.is_some() {
1587 crate::build_trace::lap(crate::build_trace::Phase::TextIndex);
1588 }
1589 let text_index_partial = with_text_index
1590 .as_ref()
1591 .is_some_and(crate::text_index::TextIndexScope::restricts_predicates);
1592 let text_index_named = with_text_index
1593 .as_ref()
1594 .is_some_and(crate::text_index::TextIndexScope::covers_named_graphs);
1595
1596 // The LABEL_INDEX and SCHEMA sections are computed over the DEDUPLICATED
1597 // default graph in SPO order (and the schema's second pass in POS order),
1598 // the order every index build re-sorts into anyway — which is what lets
1599 // the memory-bounded build, reading its sorted permutation streams, write
1600 // the very same bytes. Both need the dictionary, so they run before it is
1601 // dropped. Without either section the triples stay in input order.
1602 let mut label_section = Vec::new();
1603 let mut schema_section = Vec::new();
1604 if opts.label_index || opts.schema {
1605 crate::schema_section::sort_dedup_spo(&mut default_triples);
1606 if opts.label_index {
1607 let entries = crate::label_index::entries_from_sorted_triples(&dict, &default_triples);
1608 label_section =
1609 crate::label_index::encode_section(&entries, crate::file::writer_codec());
1610 }
1611 if opts.schema {
1612 schema_section = crate::schema_section::compute_in_memory(
1613 &dict,
1614 &mut default_triples,
1615 opts.type_override,
1616 )
1617 .encode();
1618 }
1619 crate::build_trace::lap(crate::build_trace::Phase::LabelsSchema);
1620 }
1621
1622 // From here the dictionary is only needed for its own serialized bytes. Encode
1623 // it, capture the header term count, then DROP it before building the
1624 // permutation indexes — which work purely on id-triples and never touch the
1625 // dictionary. On a large graph this frees the single biggest resident structure
1626 // (the dictionary) right when the index sort needs the headroom. The output is
1627 // byte-for-byte identical to serializing the dictionary inline.
1628 let codec = crate::file::writer_codec();
1629 let dict_container = crate::file::encode_dict_container(&dict, codec);
1630 let term_count = dict.term_count() as u64;
1631 let has_quoted_triples = dict.has_quoted_triples();
1632 drop(dict);
1633 crate::build_trace::lap(crate::build_trace::Phase::DictionarySection);
1634
1635 // Build each graph's six permutations one-at-a-time on a large graph (a single
1636 // permuted copy resident at a time, each sort still parallel) instead of all
1637 // six concurrently; below the threshold the faster all-permutations-parallel
1638 // build is used (its 6x transient copy is negligible there). `build_seq` is
1639 // byte-identical to `build`.
1640 let build_index = |triples: Vec<(u32, u32, u32)>| -> crate::GraphIndex {
1641 let n = triples.len();
1642 let b = GraphIndexBuilder::from_triples(triples).with_perms(perms);
1643 if n > LOWMEM_TRIPLE_THRESHOLD {
1644 b.build_seq()
1645 } else {
1646 b.build()
1647 }
1648 };
1649 let def = build_index(default_triples);
1650 // The named graphs: one index per graph, or one quad index for all of them
1651 // (no per-graph index is ever built on that path).
1652 let (named_indexes, quad_index): (Vec<(String, crate::GraphIndex)>, _) = match named {
1653 NamedQuads::PerGraph(named) => (
1654 named
1655 .into_iter()
1656 .map(|(g, ts)| (g, build_index(ts)))
1657 .collect(),
1658 None,
1659 ),
1660 NamedQuads::Quad { quads, .. } => (
1661 Vec::new(),
1662 Some(
1663 crate::quad::encode_quad_index(quads, perms, codec)
1664 .expect("the quad index needs the 3- or 6-permutation set"),
1665 ),
1666 ),
1667 };
1668 let named_quads = match &quad_index {
1669 Some(q) => q.quad_count,
1670 None => named_indexes
1671 .iter()
1672 .map(|(_, ix)| ix.triple_count() as u64)
1673 .sum::<u64>(),
1674 };
1675 crate::build_trace::lap(crate::build_trace::Phase::IndexPermutations);
1676
1677 // Only now is the DEDUPLICATED size of the file known: every index sorts and
1678 // dedups, so an input containing duplicate statements (a harvest that pages
1679 // with overlapping windows, a merge of overlapping dumps) writes fewer quads
1680 // than it ingested. `write_dataset_from_parts` stamps exactly this sum into
1681 // the header, so a metadata payload finalized with it cannot disagree with
1682 // the header — which is what an embedded Dataset Card used to do.
1683 let counts = FinalCounts {
1684 default_triples: def.triple_count() as u64,
1685 quads: def.triple_count() as u64 + named_quads,
1686 };
1687 let blob = pending.into_metadata(counts);
1688 // Report what was WRITTEN, not what was read: the returned stats drive the
1689 // CLI's "wrote …: N quads" line, which described the file, not the input.
1690 stats.statements = counts.quads as usize;
1691 stats.default_triples = counts.default_triples as usize;
1692
1693 let bytes = crate::file::write_dataset_from_parts(
1694 &dict_container,
1695 term_count,
1696 &def,
1697 match &quad_index {
1698 Some(q) => crate::file::NamedPart::Quad(q),
1699 None => crate::file::NamedPart::PerGraph(&named_indexes),
1700 },
1701 has_named,
1702 has_quoted_triples,
1703 &meta,
1704 levels,
1705 &blob,
1706 &text_index,
1707 text_index_partial,
1708 text_index_named,
1709 codec,
1710 );
1711 // Kinds 8 and 9 go after everything else: they are outside the content
1712 // hash, so appending them moves nothing and changes no hash.
1713 let bytes = if label_section.is_empty() && schema_section.is_empty() {
1714 bytes
1715 } else {
1716 crate::file::append_sections(
1717 &bytes,
1718 &[
1719 (crate::header::SectionKind::LabelIndex, &label_section),
1720 (crate::header::SectionKind::Schema, &schema_section),
1721 ],
1722 )
1723 .expect("appending to an image this function just wrote")
1724 };
1725 crate::build_trace::lap(crate::build_trace::Phase::Serialize);
1726 (bytes, stats)
1727}
1728
1729/// Above this default-graph triple count, the index is built one permutation at a
1730/// time (low peak RAM) instead of all six in parallel. Chosen so typical builds
1731/// keep the faster parallel path while multi-hundred-million-triple graphs stay
1732/// within a bounded memory budget.
1733const LOWMEM_TRIPLE_THRESHOLD: usize = 30_000_000;
1734
1735#[cfg(test)]
1736mod tests {
1737 use super::*;
1738 use crate::Rete;
1739
1740 #[test]
1741 fn parses_iris_bnodes_literals() {
1742 let input = r#"
1743 # a comment
1744 <http://ex/Alice> <http://ex/knows> <http://ex/Bob> .
1745 <http://ex/Alice> <http://ex/age> "30"^^<http://www.w3.org/2001/XMLSchema#integer> .
1746 <http://ex/Bob> <http://ex/label> "Bob"@en .
1747 _:b0 <http://ex/p> "plain" .
1748 "#;
1749 let t = parse(input).unwrap();
1750 assert_eq!(t.len(), 4);
1751 assert_eq!(t[0].0, "<http://ex/Alice>");
1752 assert_eq!(t[0].2, "<http://ex/Bob>");
1753 assert_eq!(t[1].2, "\"30\"^^<http://www.w3.org/2001/XMLSchema#integer>");
1754 assert_eq!(t[2].2, "\"Bob\"@en");
1755 assert_eq!(t[3].0, "_:b0");
1756 assert_eq!(t[3].2, "\"plain\"");
1757 }
1758
1759 #[test]
1760 fn literal_with_spaces_and_escaped_quote() {
1761 let input = r#"<http://ex/s> <http://ex/p> "a \"quoted\" phrase here" ."#;
1762 let t = parse(input).unwrap();
1763 assert_eq!(t.len(), 1);
1764 assert_eq!(t[0].2, r#""a \"quoted\" phrase here""#);
1765 }
1766
1767 /// RDF-star: a quoted triple whose object is a **language-tagged literal**
1768 /// sits directly against the closing `>>` with no separating whitespace
1769 /// (`"name"@fr>>`). The language-tag scan must stop at `>` — a regression
1770 /// guard for the greedy scan-to-whitespace that swallowed `@fr>>` as the tag.
1771 #[test]
1772 fn quoted_triple_langtagged_object() {
1773 let s = r#"<<<http://ex/sp> <http://ex/name> "Hirondelle rustique"@fr>>"#;
1774 let (tok, rest) = take_term(s).unwrap();
1775 assert_eq!(
1776 tok,
1777 r#"<<<http://ex/sp> <http://ex/name> "Hirondelle rustique"@fr>>"#
1778 );
1779 assert_eq!(rest, "");
1780 // and it round-trips through a full annotation line
1781 let line = r#"<<<http://ex/sp> <http://ex/name> "Oreneta vulgar"@ca>> <http://purl.org/dc/terms/source> "Catalogue of Life" ."#;
1782 let t = parse(line).unwrap();
1783 assert_eq!(t.len(), 1);
1784 assert_eq!(
1785 t[0].0,
1786 r#"<<<http://ex/sp> <http://ex/name> "Oreneta vulgar"@ca>>"#
1787 );
1788 assert_eq!(t[0].2, r#""Catalogue of Life""#);
1789 // a plain lang-tagged object still terminates at whitespace
1790 assert_eq!(take_term(r#""x"@pt-BR ."#).unwrap().0, r#""x"@pt-BR"#);
1791 }
1792
1793 /// RDF 1.2 triple-term surface `<<( s p o )>>` parses to the SAME canonical
1794 /// token as the RDF-star `<< s p o >>`, so the two are interoperable (a query
1795 /// written either way matches data ingested either way).
1796 #[test]
1797 fn rdf12_triple_term_same_token_as_rdf_star() {
1798 let rdf12 = r#"<http://ex/r> <http://ex/p> <<( <http://ex/s> <http://ex/q> "o" )>> ."#;
1799 let star = r#"<http://ex/r> <http://ex/p> << <http://ex/s> <http://ex/q> "o" >> ."#;
1800 let a = parse(rdf12).unwrap();
1801 let b = parse(star).unwrap();
1802 assert_eq!(a.len(), 1);
1803 assert_eq!(a[0].2, r#"<<<http://ex/s> <http://ex/q> "o">>"#);
1804 assert_eq!(
1805 a[0].2, b[0].2,
1806 "RDF 1.2 and RDF-star must dedupe to one token"
1807 );
1808 // take_term consumes exactly the triple term (nothing left dangling).
1809 let (tok, rest) =
1810 take_term(r#"<<( <http://ex/s> <http://ex/q> <http://ex/o> )>>"#).unwrap();
1811 assert_eq!(tok, "<<<http://ex/s> <http://ex/q> <http://ex/o>>>");
1812 assert_eq!(rest, "");
1813 }
1814
1815 #[test]
1816 fn rejects_missing_dot() {
1817 assert!(parse("<a> <b> <c>").is_err());
1818 }
1819
1820 #[test]
1821 fn parses_quads_with_and_without_graph() {
1822 let input = "<http://ex/a> <http://ex/p> <http://ex/b> .\n\
1823 <http://ex/a> <http://ex/p> <http://ex/c> <http://ex/g> .";
1824 let q = parse_quads(input).unwrap();
1825 assert_eq!(q.len(), 2);
1826 assert_eq!(q[0].3, None); // default graph
1827 assert_eq!(q[1].3, Some("<http://ex/g>".to_string()));
1828 }
1829
1830 #[test]
1831 fn parse_reader_matches_text_parse() {
1832 // The streaming reader must produce exactly the same quads as parsing the
1833 // whole text — including blank/comment skipping, a named graph, and CRLF.
1834 let nt = "<http://ex/a> <http://ex/p> <http://ex/b> .\r\n\
1835 # comment\n\
1836 \n\
1837 _:b0 <http://ex/q> \"lit\"@en .\n";
1838 let via_text = parse_statements(nt, "nt").unwrap();
1839 let via_reader = parse_reader(std::io::Cursor::new(nt), "nt", 0).unwrap();
1840 assert_eq!(via_text, via_reader);
1841
1842 let nq = "<http://ex/a> <http://ex/p> <http://ex/b> .\n\
1843 <http://ex/a> <http://ex/p> <http://ex/c> <http://ex/g> .\n";
1844 assert_eq!(
1845 parse_quads(nq).unwrap(),
1846 parse_reader(std::io::Cursor::new(nq), "nq", 0).unwrap()
1847 );
1848 // Turtle and TriG stream too — that is what lets the external build take a
1849 // multi-gigabyte `.ttl.gz` without expanding it to N-Triples first. Reading
1850 // a structured syntax from a reader must agree with parsing its whole text.
1851 let ttl = "@prefix ex: <http://ex/> .\nex:A ex:knows ex:B , ex:C .\n";
1852 assert_eq!(
1853 parse_statements(ttl, "ttl").unwrap(),
1854 parse_reader(std::io::Cursor::new(ttl), "ttl", 0).unwrap()
1855 );
1856 let trig = "@prefix ex: <http://ex/> .\nex:g { ex:A ex:knows ex:B . }\n";
1857 let streamed = parse_reader(std::io::Cursor::new(trig), "trig", 0).unwrap();
1858 assert_eq!(parse_statements(trig, "trig").unwrap(), streamed);
1859 assert_eq!(streamed[0].3.as_deref(), Some("<http://ex/g>"));
1860 // An unknown format is still a hard error, not a silent guess.
1861 assert!(parse_reader(std::io::Cursor::new(nt), "jsonld", 0).is_err());
1862 }
1863
1864 #[test]
1865 fn parse_statements_dispatches_by_format() {
1866 let nt = "<http://ex/a> <http://ex/p> <http://ex/b> .";
1867 assert_eq!(parse_statements(nt, "nt").unwrap().len(), 1);
1868 let ttl = "@prefix ex: <http://ex/> .\nex:A ex:knows ex:B , ex:C .";
1869 assert_eq!(parse_statements(ttl, "ttl").unwrap().len(), 2);
1870 // N-Triples is a subset of both Turtle and TriG, so the same text parses
1871 // under all three — and lands in the default graph under each.
1872 assert_eq!(parse_statements(nt, "trig").unwrap().len(), 1);
1873 assert!(parse_statements(nt, "trig").unwrap()[0].3.is_none());
1874 assert!(parse_statements(nt, "jsonld").is_err());
1875 }
1876
1877 /// A TriG graph block carries its graph name through as the same canonical
1878 /// token N-Quads would produce — so the two syntaxes agree on dictionary keys
1879 /// and a `.trig` shard federates with a `.nq` one.
1880 #[test]
1881 fn trig_graph_names_match_nquads() {
1882 let trig = "@prefix ex: <http://ex/> .\nex:g { ex:a ex:p ex:b . }\nex:a ex:p ex:c .\n";
1883 let nq = "<http://ex/a> <http://ex/p> <http://ex/b> <http://ex/g> .\n\
1884 <http://ex/a> <http://ex/p> <http://ex/c> .\n";
1885 let mut from_trig = parse_statements(trig, "trig").unwrap();
1886 let mut from_nq = parse_statements(nq, "nq").unwrap();
1887 from_trig.sort();
1888 from_nq.sort();
1889 assert_eq!(from_trig, from_nq);
1890 }
1891
1892 /// RDF/XML (how most OWL ontologies ship) parses to the same canonical tokens,
1893 /// including the abbreviated typed-node syntax and `rdf:resource` references.
1894 #[test]
1895 fn parses_rdfxml_owl() {
1896 let xml = r#"<?xml version="1.0"?>
1897 <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
1898 xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
1899 xmlns:owl="http://www.w3.org/2002/07/owl#">
1900 <owl:Class rdf:about="http://ex/Dog">
1901 <rdfs:subClassOf rdf:resource="http://ex/Animal"/>
1902 <rdfs:label>Dog</rdfs:label>
1903 </owl:Class>
1904 </rdf:RDF>"#;
1905 let triples = parse_rdfxml(xml).unwrap();
1906 // rdf:type owl:Class, rdfs:subClassOf, rdfs:label = 3 triples.
1907 assert_eq!(triples.len(), 3);
1908 assert!(triples.iter().any(|(s, p, o)| s == "<http://ex/Dog>"
1909 && p == "<http://www.w3.org/2000/01/rdf-schema#subClassOf>"
1910 && o == "<http://ex/Animal>"));
1911 // Same data through the format dispatcher (triples → default graph).
1912 assert_eq!(parse_statements(xml, "rdfxml").unwrap().len(), 3);
1913 // Malformed XML is a clear RdfXml error, not a silent empty parse.
1914 assert!(matches!(
1915 parse_statements("<rdf:RDF><not closed", "rdfxml"),
1916 Err(IngestError::RdfXml(_))
1917 ));
1918 }
1919
1920 /// Regression coverage for RUSTSEC-2026-0195: namespace declarations from
1921 /// an untrusted RDF/XML document must not make parsing panic or exhaust the
1922 /// bounded test process.
1923 #[test]
1924 fn rdfxml_namespace_fanout_is_bounded() {
1925 let declarations = (0..2_000)
1926 .map(|i| format!(r#" xmlns:p{i}="http://example.test/{i}/""#))
1927 .collect::<String>();
1928 let xml = format!(
1929 r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"{declarations}/>"#
1930 );
1931 let result = parse_statements(&xml, "rdfxml");
1932 assert!(result.is_ok() || result.unwrap_err().to_string().contains("namespace"));
1933 }
1934
1935 /// Regression coverage for RUSTSEC-2026-0194: duplicate-name checking must
1936 /// complete for a large valid start tag without panicking or exhausting the
1937 /// bounded test process.
1938 #[test]
1939 fn rdfxml_attribute_fanout_completes() {
1940 let attributes = (0..2_000)
1941 .map(|i| format!(r#" p:a{i}="{i}""#))
1942 .collect::<String>();
1943 let xml = format!(
1944 r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:p="http://example.test/"><rdf:Description rdf:about="http://example.test/s"{attributes}/></rdf:RDF>"#
1945 );
1946 assert!(parse_statements(&xml, "rdfxml").is_ok());
1947 }
1948
1949 /// Text in, queryable file image out — the whole in-memory build path the
1950 /// wasm `build()` binding uses, including a named graph.
1951 #[test]
1952 fn assemble_dataset_round_trips() {
1953 let text = "<http://ex/a> <http://ex/knows> <http://ex/b> .\n\
1954 <http://ex/b> <http://ex/knows> <http://ex/c> .\n\
1955 <http://ex/a> <http://ex/age> \"30\"^^<http://www.w3.org/2001/XMLSchema#integer> .\n\
1956 <http://ex/a> <http://ex/p> <http://ex/d> <http://ex/g1> .";
1957 let quads = parse_statements(text, "nq").unwrap();
1958 let (bytes, stats) = assemble_dataset(quads, &[]);
1959 assert_eq!(stats.statements, 4);
1960 assert_eq!(stats.default_triples, 3);
1961 assert_eq!(stats.named_graphs, 1);
1962 assert!(stats.terms >= 7);
1963
1964 let rete = Rete::open(&bytes).unwrap();
1965 assert_eq!(
1966 rete.query(None, Some("<http://ex/knows>"), None).len(),
1967 2,
1968 "default-graph pattern query"
1969 );
1970 assert_eq!(rete.graph_names(), vec!["<http://ex/g1>"]);
1971 let out = crate::eval_query(
1972 &rete,
1973 "SELECT ?x WHERE { ?x <http://ex/knows> ?y . ?y <http://ex/knows> ?z }",
1974 )
1975 .unwrap();
1976 match out {
1977 crate::QueryOutput::Select(_, rows) => assert_eq!(rows.len(), 1),
1978 other => panic!("expected select result, got {other:?}"),
1979 }
1980 }
1981
1982 /// The exact minimal input the playground Build tab uses: two triples, no
1983 /// literals, no rdf:type, no named graph — the smallest graph that still
1984 /// builds a community pyramid. (The wasm `build()` panic this guards was a
1985 /// `std::time::Instant::now()` in the pyramid timing path; native has a clock
1986 /// so this passes here, while the playground harness exercises the wasm path.)
1987 #[test]
1988 fn assemble_minimal_typeless_graph() {
1989 let text = "<http://ex/A> <http://ex/knows> <http://ex/B> .\n\
1990 <http://ex/B> <http://ex/knows> <http://ex/C> .\n";
1991 let quads = parse_statements(text, "nt").unwrap();
1992 let (bytes, stats) = assemble_dataset(quads, &[]);
1993 assert_eq!(stats.default_triples, 2);
1994 let rete = Rete::open(&bytes).unwrap();
1995 assert_eq!(rete.query(None, Some("<http://ex/knows>"), None).len(), 2);
1996 }
1997}