Skip to main content

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    use crate::build_progress::{self as progress, Stat, Ticker, Unit};
1294    use crate::build_trace::Phase;
1295    let graphs = opts.graph_layout;
1296    let n = Some(quads.len() as u64);
1297    progress::begin(Phase::Dictionary, n, Unit::Statements);
1298    let mut ticker = Ticker::new();
1299    let mut db = DictionaryBuilder::new();
1300    for (s, p, o, g) in &quads {
1301        db.observe(s, p, o);
1302        if let (GraphLayout::Quad, Some(g)) = (graphs, g) {
1303            db.observe_graph(g);
1304        }
1305        ticker.tick(1);
1306    }
1307    ticker.flush();
1308    let dict = db.build();
1309    crate::build_trace::lap(Phase::Dictionary);
1310    progress::set_stat(Stat::Terms, dict.term_count().into());
1311
1312    progress::begin(Phase::Encode, n, Unit::Statements);
1313    let mut default_triples = Vec::new();
1314    let mut named = NamedQuads::new(graphs, &dict);
1315    for (s, p, o, g) in &quads {
1316        let t = dict.encode(s, p, o).expect("observed term");
1317        match g {
1318            None => default_triples.push(t),
1319            Some(graph) => named.push(&dict, graph.clone(), t),
1320        }
1321        ticker.tick(1);
1322    }
1323    drop(ticker);
1324    crate::build_trace::lap(Phase::Encode);
1325
1326    // Derive the metadata blob (the Dataset Card) from the raw quads NOW, while
1327    // they are resident — then DROP them before the memory-heavy pyramid + index
1328    // phases. On a big build the string quads are the largest working set (every
1329    // term an owned String, heavily duplicated) and are fully redundant with the
1330    // dictionary + id-triples once encoded, so freeing them here cuts peak RAM by
1331    // their whole size. `pyramid_levels` is not known yet (0 in the callback);
1332    // it is filled into the returned `stats` by `finish_assembly`, and no metadata
1333    // callback depends on it (the card derives from the quads + term/graph counts).
1334    let stats = BuildStats {
1335        statements: quads.len(),
1336        default_triples: default_triples.len(),
1337        named_graphs: named.graph_count(),
1338        terms: dict.term_count() as usize,
1339        pyramid_levels: 0,
1340    };
1341    let pending = metadata(&stats, &quads);
1342    crate::build_trace::lap(crate::build_trace::Phase::CardDerive);
1343    drop(quads);
1344
1345    finish_assembly(dict, default_triples, named, opts, pending, stats)
1346}
1347
1348/// **Two-pass, low-RAM** assembly: build a `.rete` by **streaming** the input(s)
1349/// twice instead of holding every parsed quad in memory. `stream` is invoked
1350/// **twice** and MUST replay the exact same quads in the same order each time —
1351/// pass 1 observes every term into the dictionary; pass 2 encodes them to
1352/// id-triples. The raw string quads (every term an owned String, heavily
1353/// duplicated — by far the largest working set on a big graph) are **never
1354/// collected**, so peak RAM is bounded by the dictionary + id-triples + index
1355/// rather than the string-quad multiset. Output is **byte-identical** to
1356/// [`assemble_dataset_with_opts`] on the same quads (same dictionary, same
1357/// id-triples in file order, same downstream pipeline).
1358///
1359/// The metadata callback derives the Dataset Card from the built dictionary +
1360/// default-graph id-triples (resolving terms through the dictionary), since the
1361/// raw quads were never retained. `stream` propagates parse/IO errors.
1362pub fn assemble_dataset_streaming<S, M: IntoMetadata>(
1363    stream: S,
1364    with_pyramid: bool,
1365    with_text_index: impl crate::text_index::IntoTextIndex,
1366    type_override: Option<&str>,
1367    metadata: impl FnOnce(&BuildStats, &Dictionary, &[(u32, u32, u32)]) -> M,
1368) -> Result<(Vec<u8>, BuildStats), IngestError>
1369where
1370    S: FnMut(&mut dyn FnMut(RawQuad)) -> Result<(), IngestError>,
1371{
1372    assemble_dataset_streaming_algo(
1373        stream,
1374        with_pyramid,
1375        with_text_index,
1376        type_override,
1377        PyramidAlgo::Louvain,
1378        metadata,
1379    )
1380}
1381
1382/// Like [`assemble_dataset_streaming`], but selects the community [`PyramidAlgo`]
1383/// (the streaming, low-RAM build path for `rete build --pyramid-algo …`).
1384#[allow(clippy::too_many_arguments)]
1385pub fn assemble_dataset_streaming_algo<S, M: IntoMetadata>(
1386    stream: S,
1387    with_pyramid: bool,
1388    with_text_index: impl crate::text_index::IntoTextIndex,
1389    type_override: Option<&str>,
1390    algo: PyramidAlgo,
1391    metadata: impl FnOnce(&BuildStats, &Dictionary, &[(u32, u32, u32)]) -> M,
1392) -> Result<(Vec<u8>, BuildStats), IngestError>
1393where
1394    S: FnMut(&mut dyn FnMut(RawQuad)) -> Result<(), IngestError>,
1395{
1396    assemble_dataset_streaming_with_perms(
1397        stream,
1398        with_pyramid,
1399        with_text_index,
1400        type_override,
1401        algo,
1402        crate::index::PermSet::ALL,
1403        metadata,
1404    )
1405}
1406
1407/// Like [`assemble_dataset_streaming_algo`], but writes only the permutations in
1408/// `perms` — the two-pass low-RAM twin of [`assemble_dataset_with_perms`].
1409#[allow(clippy::too_many_arguments)]
1410pub fn assemble_dataset_streaming_with_perms<S, M: IntoMetadata>(
1411    stream: S,
1412    with_pyramid: bool,
1413    with_text_index: impl crate::text_index::IntoTextIndex,
1414    type_override: Option<&str>,
1415    algo: PyramidAlgo,
1416    perms: crate::index::PermSet,
1417    metadata: impl FnOnce(&BuildStats, &Dictionary, &[(u32, u32, u32)]) -> M,
1418) -> Result<(Vec<u8>, BuildStats), IngestError>
1419where
1420    S: FnMut(&mut dyn FnMut(RawQuad)) -> Result<(), IngestError>,
1421{
1422    assemble_dataset_streaming_with_layout(
1423        stream,
1424        with_pyramid,
1425        with_text_index,
1426        type_override,
1427        algo,
1428        perms,
1429        GraphLayout::PerGraph,
1430        metadata,
1431    )
1432}
1433
1434/// Like [`assemble_dataset_streaming_with_perms`], storing the named graphs in
1435/// `graphs` layout — the two-pass low-RAM twin of
1436/// [`assemble_dataset_with_layout`]. [`GraphLayout::Quad`] with a permutation
1437/// set other than the 3- or 6-permutation one is an error.
1438#[allow(clippy::too_many_arguments)]
1439pub fn assemble_dataset_streaming_with_layout<S, M: IntoMetadata>(
1440    stream: S,
1441    with_pyramid: bool,
1442    with_text_index: impl crate::text_index::IntoTextIndex,
1443    type_override: Option<&str>,
1444    algo: PyramidAlgo,
1445    perms: crate::index::PermSet,
1446    graphs: GraphLayout,
1447    metadata: impl FnOnce(&BuildStats, &Dictionary, &[(u32, u32, u32)]) -> M,
1448) -> Result<(Vec<u8>, BuildStats), IngestError>
1449where
1450    S: FnMut(&mut dyn FnMut(RawQuad)) -> Result<(), IngestError>,
1451{
1452    let text_index = crate::text_index::IntoTextIndex::into_text_index(with_text_index);
1453    let opts = AssembleOptions {
1454        with_pyramid,
1455        with_text_index: text_index.is_some(),
1456        text_index_scope: text_index.as_ref(),
1457        type_override,
1458        algo,
1459        perms,
1460        graph_layout: graphs,
1461        ..AssembleOptions::legacy()
1462    };
1463    assemble_dataset_streaming_opts(stream, &opts, metadata)
1464}
1465
1466/// The two-pass low-RAM twin of [`assemble_dataset_opts`]. A quad-index layout
1467/// with a permutation set other than the 3- or 6-permutation one is an error.
1468pub fn assemble_dataset_streaming_opts<S, M: IntoMetadata>(
1469    mut stream: S,
1470    opts: &AssembleOptions<'_>,
1471    metadata: impl FnOnce(&BuildStats, &Dictionary, &[(u32, u32, u32)]) -> M,
1472) -> Result<(Vec<u8>, BuildStats), IngestError>
1473where
1474    S: FnMut(&mut dyn FnMut(RawQuad)) -> Result<(), IngestError>,
1475{
1476    let graphs = opts.graph_layout;
1477    if graphs == GraphLayout::Quad && crate::quad::check_perms(opts.perms).is_err() {
1478        return Err(IngestError::Io(
1479            "the quad index needs the 3- or 6-permutation set".into(),
1480        ));
1481    }
1482    // Pass 1: observe every term (the dictionary dedups; the string quads are
1483    // freed line by line and never collected). With the quad index, graph
1484    // names are terms too. The stream sets each pass's progress total (the
1485    // input bytes it will read).
1486    use crate::build_progress::{self as progress, Stat, Unit};
1487    use crate::build_trace::Phase;
1488    progress::begin(Phase::ParseDictionary, None, Unit::None);
1489    let mut db = DictionaryBuilder::new();
1490    stream(&mut |(s, p, o, g)| {
1491        db.observe(&s, &p, &o);
1492        if let (GraphLayout::Quad, Some(g)) = (graphs, g) {
1493            db.observe_graph(&g);
1494        }
1495    })?;
1496    let dict = db.build();
1497    crate::build_trace::lap(Phase::ParseDictionary);
1498    progress::set_stat(Stat::Terms, dict.term_count().into());
1499
1500    // Pass 2: encode each quad to an id-triple, bucketing named graphs.
1501    progress::begin(Phase::ParseEncode, None, Unit::None);
1502    let mut default_triples: Vec<(u32, u32, u32)> = Vec::new();
1503    let mut named = NamedQuads::new(graphs, &dict);
1504    stream(&mut |(s, p, o, g)| {
1505        let t = dict.encode(&s, &p, &o).expect("observed term");
1506        match g {
1507            None => default_triples.push(t),
1508            Some(graph) => named.push(&dict, graph, t),
1509        }
1510    })?;
1511    crate::build_trace::lap(crate::build_trace::Phase::ParseEncode);
1512
1513    let statements = default_triples.len() + named.quad_count();
1514    let stats = BuildStats {
1515        statements,
1516        default_triples: default_triples.len(),
1517        named_graphs: named.graph_count(),
1518        terms: dict.term_count() as usize,
1519        pyramid_levels: 0,
1520    };
1521    let pending = metadata(&stats, &dict, &default_triples);
1522    crate::build_trace::lap(crate::build_trace::Phase::CardDerive);
1523    Ok(finish_assembly(
1524        dict,
1525        default_triples,
1526        named,
1527        opts,
1528        pending,
1529        stats,
1530    ))
1531}
1532
1533/// The shared tail of every build path: from a finished dictionary + encoded
1534/// id-triples (default graph + named), build the community pyramid, the optional
1535/// full-text index, the permutation indexes, and serialize the file image. Takes
1536/// the id-triples **by value** so they are freed as the permutations consume them.
1537fn finish_assembly<M: IntoMetadata>(
1538    dict: Dictionary,
1539    mut default_triples: Vec<(u32, u32, u32)>,
1540    named: NamedQuads,
1541    opts: &AssembleOptions<'_>,
1542    pending: M,
1543    mut stats: BuildStats,
1544) -> (Vec<u8>, BuildStats) {
1545    use crate::build_progress::{self as progress, Unit};
1546    use crate::build_trace::Phase;
1547    let has_named = named.graph_count() > 0;
1548    let perms = opts.perms;
1549
1550    // The pyramid and the full-text index are built FIRST, while the dictionary and
1551    // the default id-triples are both still resident — both need the two together.
1552    // The pyramid sees the triples in input order (Louvain is order-sensitive).
1553    let (meta, levels) = if opts.with_pyramid {
1554        progress::begin(Phase::Pyramid, None, Unit::None);
1555        crate::file::build_pyramid_meta_layout(
1556            &dict,
1557            &default_triples,
1558            DEFAULT_TILE_BUDGET,
1559            opts.type_override,
1560            opts.algo,
1561            opts.pyramid_layout,
1562        )
1563    } else {
1564        (Vec::new(), 0)
1565    };
1566    stats.pyramid_levels = levels;
1567    if opts.with_pyramid {
1568        crate::build_trace::lap(crate::build_trace::Phase::Pyramid);
1569    }
1570
1571    // The full-text index over the literals of the requested scope: the
1572    // default graph's (the only scope before 0.4.0), optionally every named
1573    // graph's too, optionally only some predicates'.
1574    let with_text_index = opts
1575        .with_text_index
1576        .then(|| opts.text_index_scope.cloned().unwrap_or_default());
1577    // The named graphs' triples, for an index whose scope covers them: per
1578    // graph, or (in the quad layout) the quads' `(s, p, o)`, copied only when
1579    // the scope needs them; the index does not care which graph a word came
1580    // from.
1581    let quad_spo: Vec<(u32, u32, u32)>;
1582    let named_triples: Vec<&[(u32, u32, u32)]> = match &named {
1583        NamedQuads::PerGraph(m) => m.values().map(Vec::as_slice).collect(),
1584        NamedQuads::Quad { quads, .. } => {
1585            quad_spo = if with_text_index
1586                .as_ref()
1587                .is_some_and(crate::text_index::TextIndexScope::covers_named_graphs)
1588            {
1589                quads.iter().map(|q| (q[1], q[2], q[3])).collect()
1590            } else {
1591                Vec::new()
1592            };
1593            vec![quad_spo.as_slice()]
1594        }
1595    };
1596    if with_text_index.is_some() {
1597        progress::begin(Phase::TextIndex, None, Unit::None);
1598    }
1599    let text_index = match &with_text_index {
1600        Some(scope) => crate::text_index::build_section(
1601            &dict,
1602            scope,
1603            &default_triples,
1604            named_triples.into_iter(),
1605            crate::file::writer_codec(),
1606        ),
1607        None => Vec::new(),
1608    };
1609    if with_text_index.is_some() {
1610        crate::build_trace::lap(crate::build_trace::Phase::TextIndex);
1611    }
1612    let text_index_partial = with_text_index
1613        .as_ref()
1614        .is_some_and(crate::text_index::TextIndexScope::restricts_predicates);
1615    let text_index_named = with_text_index
1616        .as_ref()
1617        .is_some_and(crate::text_index::TextIndexScope::covers_named_graphs);
1618
1619    // The LABEL_INDEX and SCHEMA sections are computed over the DEDUPLICATED
1620    // default graph in SPO order (and the schema's second pass in POS order),
1621    // the order every index build re-sorts into anyway — which is what lets
1622    // the memory-bounded build, reading its sorted permutation streams, write
1623    // the very same bytes. Both need the dictionary, so they run before it is
1624    // dropped. Without either section the triples stay in input order.
1625    let mut label_section = Vec::new();
1626    let mut schema_section = Vec::new();
1627    if opts.label_index || opts.schema {
1628        progress::begin(Phase::LabelsSchema, None, Unit::None);
1629        crate::schema_section::sort_dedup_spo(&mut default_triples);
1630        if opts.label_index {
1631            let entries = crate::label_index::entries_from_sorted_triples(&dict, &default_triples);
1632            label_section =
1633                crate::label_index::encode_section(&entries, crate::file::writer_codec());
1634        }
1635        if opts.schema {
1636            schema_section = crate::schema_section::compute_in_memory(
1637                &dict,
1638                &mut default_triples,
1639                opts.type_override,
1640            )
1641            .encode();
1642        }
1643        crate::build_trace::lap(crate::build_trace::Phase::LabelsSchema);
1644    }
1645
1646    // From here the dictionary is only needed for its own serialized bytes. Encode
1647    // it, capture the header term count, then DROP it before building the
1648    // permutation indexes — which work purely on id-triples and never touch the
1649    // dictionary. On a large graph this frees the single biggest resident structure
1650    // (the dictionary) right when the index sort needs the headroom. The output is
1651    // byte-for-byte identical to serializing the dictionary inline.
1652    let codec = crate::file::writer_codec();
1653    progress::begin(Phase::DictionarySection, None, Unit::None);
1654    let dict_container = crate::file::encode_dict_container(&dict, codec);
1655    let term_count = dict.term_count() as u64;
1656    let has_quoted_triples = dict.has_quoted_triples();
1657    drop(dict);
1658    crate::build_trace::lap(crate::build_trace::Phase::DictionarySection);
1659
1660    // Build each graph's six permutations one-at-a-time on a large graph (a single
1661    // permuted copy resident at a time, each sort still parallel) instead of all
1662    // six concurrently; below the threshold the faster all-permutations-parallel
1663    // build is used (its 6x transient copy is negligible there). `build_seq` is
1664    // byte-identical to `build`.
1665    // Every graph's triples, once per permutation (the quad index's quads
1666    // once, as it finishes).
1667    let (per_graph, quad_rows): (u64, u64) = match &named {
1668        NamedQuads::PerGraph(m) => (m.values().map(|t| t.len() as u64).sum(), 0),
1669        NamedQuads::Quad { quads, .. } => (0, quads.len() as u64),
1670    };
1671    let rows = (default_triples.len() as u64 + per_graph) * perms.len() as u64 + quad_rows;
1672    progress::begin(Phase::IndexPermutations, Some(rows), Unit::Records);
1673    let build_index = |triples: Vec<(u32, u32, u32)>| -> crate::GraphIndex {
1674        let n = triples.len();
1675        let b = GraphIndexBuilder::from_triples(triples)
1676            .with_perms(perms)
1677            .with_progress();
1678        if n > LOWMEM_TRIPLE_THRESHOLD {
1679            b.build_seq()
1680        } else {
1681            b.build()
1682        }
1683    };
1684    let def = build_index(default_triples);
1685    // The named graphs: one index per graph, or one quad index for all of them
1686    // (no per-graph index is ever built on that path).
1687    let (named_indexes, quad_index): (Vec<(String, crate::GraphIndex)>, _) = match named {
1688        NamedQuads::PerGraph(named) => (
1689            named
1690                .into_iter()
1691                .map(|(g, ts)| (g, build_index(ts)))
1692                .collect(),
1693            None,
1694        ),
1695        NamedQuads::Quad { quads, .. } => {
1696            let n = quads.len() as u64;
1697            let q = crate::quad::encode_quad_index(quads, perms, codec)
1698                .expect("the quad index needs the 3- or 6-permutation set");
1699            progress::advance(n);
1700            (Vec::new(), Some(q))
1701        }
1702    };
1703    let named_quads = match &quad_index {
1704        Some(q) => q.quad_count,
1705        None => named_indexes
1706            .iter()
1707            .map(|(_, ix)| ix.triple_count() as u64)
1708            .sum::<u64>(),
1709    };
1710    crate::build_trace::lap(crate::build_trace::Phase::IndexPermutations);
1711
1712    // Only now is the DEDUPLICATED size of the file known: every index sorts and
1713    // dedups, so an input containing duplicate statements (a harvest that pages
1714    // with overlapping windows, a merge of overlapping dumps) writes fewer quads
1715    // than it ingested. `write_dataset_from_parts` stamps exactly this sum into
1716    // the header, so a metadata payload finalized with it cannot disagree with
1717    // the header — which is what an embedded Dataset Card used to do.
1718    let counts = FinalCounts {
1719        default_triples: def.triple_count() as u64,
1720        quads: def.triple_count() as u64 + named_quads,
1721    };
1722    let blob = pending.into_metadata(counts);
1723    progress::begin(Phase::Serialize, None, Unit::None);
1724    // Report what was WRITTEN, not what was read: the returned stats drive the
1725    // CLI's "wrote …: N quads" line, which described the file, not the input.
1726    stats.statements = counts.quads as usize;
1727    stats.default_triples = counts.default_triples as usize;
1728
1729    let bytes = crate::file::write_dataset_from_parts(
1730        &dict_container,
1731        term_count,
1732        &def,
1733        match &quad_index {
1734            Some(q) => crate::file::NamedPart::Quad(q),
1735            None => crate::file::NamedPart::PerGraph(&named_indexes),
1736        },
1737        has_named,
1738        has_quoted_triples,
1739        &meta,
1740        levels,
1741        &blob,
1742        &text_index,
1743        text_index_partial,
1744        text_index_named,
1745        codec,
1746    );
1747    // Kinds 8 and 9 go after everything else: they are outside the content
1748    // hash, so appending them moves nothing and changes no hash.
1749    let bytes = if label_section.is_empty() && schema_section.is_empty() {
1750        bytes
1751    } else {
1752        crate::file::append_sections(
1753            &bytes,
1754            &[
1755                (crate::header::SectionKind::LabelIndex, &label_section),
1756                (crate::header::SectionKind::Schema, &schema_section),
1757            ],
1758        )
1759        .expect("appending to an image this function just wrote")
1760    };
1761    crate::build_trace::lap(crate::build_trace::Phase::Serialize);
1762    (bytes, stats)
1763}
1764
1765/// Above this default-graph triple count, the index is built one permutation at a
1766/// time (low peak RAM) instead of all six in parallel. Chosen so typical builds
1767/// keep the faster parallel path while multi-hundred-million-triple graphs stay
1768/// within a bounded memory budget.
1769const LOWMEM_TRIPLE_THRESHOLD: usize = 30_000_000;
1770
1771#[cfg(test)]
1772mod tests {
1773    use super::*;
1774    use crate::Rete;
1775
1776    #[test]
1777    fn parses_iris_bnodes_literals() {
1778        let input = r#"
1779            # a comment
1780            <http://ex/Alice> <http://ex/knows> <http://ex/Bob> .
1781            <http://ex/Alice> <http://ex/age> "30"^^<http://www.w3.org/2001/XMLSchema#integer> .
1782            <http://ex/Bob> <http://ex/label> "Bob"@en .
1783            _:b0 <http://ex/p> "plain" .
1784        "#;
1785        let t = parse(input).unwrap();
1786        assert_eq!(t.len(), 4);
1787        assert_eq!(t[0].0, "<http://ex/Alice>");
1788        assert_eq!(t[0].2, "<http://ex/Bob>");
1789        assert_eq!(t[1].2, "\"30\"^^<http://www.w3.org/2001/XMLSchema#integer>");
1790        assert_eq!(t[2].2, "\"Bob\"@en");
1791        assert_eq!(t[3].0, "_:b0");
1792        assert_eq!(t[3].2, "\"plain\"");
1793    }
1794
1795    #[test]
1796    fn literal_with_spaces_and_escaped_quote() {
1797        let input = r#"<http://ex/s> <http://ex/p> "a \"quoted\" phrase here" ."#;
1798        let t = parse(input).unwrap();
1799        assert_eq!(t.len(), 1);
1800        assert_eq!(t[0].2, r#""a \"quoted\" phrase here""#);
1801    }
1802
1803    /// RDF-star: a quoted triple whose object is a **language-tagged literal**
1804    /// sits directly against the closing `>>` with no separating whitespace
1805    /// (`"name"@fr>>`). The language-tag scan must stop at `>` — a regression
1806    /// guard for the greedy scan-to-whitespace that swallowed `@fr>>` as the tag.
1807    #[test]
1808    fn quoted_triple_langtagged_object() {
1809        let s = r#"<<<http://ex/sp> <http://ex/name> "Hirondelle rustique"@fr>>"#;
1810        let (tok, rest) = take_term(s).unwrap();
1811        assert_eq!(
1812            tok,
1813            r#"<<<http://ex/sp> <http://ex/name> "Hirondelle rustique"@fr>>"#
1814        );
1815        assert_eq!(rest, "");
1816        // and it round-trips through a full annotation line
1817        let line = r#"<<<http://ex/sp> <http://ex/name> "Oreneta vulgar"@ca>> <http://purl.org/dc/terms/source> "Catalogue of Life" ."#;
1818        let t = parse(line).unwrap();
1819        assert_eq!(t.len(), 1);
1820        assert_eq!(
1821            t[0].0,
1822            r#"<<<http://ex/sp> <http://ex/name> "Oreneta vulgar"@ca>>"#
1823        );
1824        assert_eq!(t[0].2, r#""Catalogue of Life""#);
1825        // a plain lang-tagged object still terminates at whitespace
1826        assert_eq!(take_term(r#""x"@pt-BR ."#).unwrap().0, r#""x"@pt-BR"#);
1827    }
1828
1829    /// RDF 1.2 triple-term surface `<<( s p o )>>` parses to the SAME canonical
1830    /// token as the RDF-star `<< s p o >>`, so the two are interoperable (a query
1831    /// written either way matches data ingested either way).
1832    #[test]
1833    fn rdf12_triple_term_same_token_as_rdf_star() {
1834        let rdf12 = r#"<http://ex/r> <http://ex/p> <<( <http://ex/s> <http://ex/q> "o" )>> ."#;
1835        let star = r#"<http://ex/r> <http://ex/p> << <http://ex/s> <http://ex/q> "o" >> ."#;
1836        let a = parse(rdf12).unwrap();
1837        let b = parse(star).unwrap();
1838        assert_eq!(a.len(), 1);
1839        assert_eq!(a[0].2, r#"<<<http://ex/s> <http://ex/q> "o">>"#);
1840        assert_eq!(
1841            a[0].2, b[0].2,
1842            "RDF 1.2 and RDF-star must dedupe to one token"
1843        );
1844        // take_term consumes exactly the triple term (nothing left dangling).
1845        let (tok, rest) =
1846            take_term(r#"<<( <http://ex/s> <http://ex/q> <http://ex/o> )>>"#).unwrap();
1847        assert_eq!(tok, "<<<http://ex/s> <http://ex/q> <http://ex/o>>>");
1848        assert_eq!(rest, "");
1849    }
1850
1851    #[test]
1852    fn rejects_missing_dot() {
1853        assert!(parse("<a> <b> <c>").is_err());
1854    }
1855
1856    #[test]
1857    fn parses_quads_with_and_without_graph() {
1858        let input = "<http://ex/a> <http://ex/p> <http://ex/b> .\n\
1859                     <http://ex/a> <http://ex/p> <http://ex/c> <http://ex/g> .";
1860        let q = parse_quads(input).unwrap();
1861        assert_eq!(q.len(), 2);
1862        assert_eq!(q[0].3, None); // default graph
1863        assert_eq!(q[1].3, Some("<http://ex/g>".to_string()));
1864    }
1865
1866    #[test]
1867    fn parse_reader_matches_text_parse() {
1868        // The streaming reader must produce exactly the same quads as parsing the
1869        // whole text — including blank/comment skipping, a named graph, and CRLF.
1870        let nt = "<http://ex/a> <http://ex/p> <http://ex/b> .\r\n\
1871                  # comment\n\
1872                  \n\
1873                  _:b0 <http://ex/q> \"lit\"@en .\n";
1874        let via_text = parse_statements(nt, "nt").unwrap();
1875        let via_reader = parse_reader(std::io::Cursor::new(nt), "nt", 0).unwrap();
1876        assert_eq!(via_text, via_reader);
1877
1878        let nq = "<http://ex/a> <http://ex/p> <http://ex/b> .\n\
1879                  <http://ex/a> <http://ex/p> <http://ex/c> <http://ex/g> .\n";
1880        assert_eq!(
1881            parse_quads(nq).unwrap(),
1882            parse_reader(std::io::Cursor::new(nq), "nq", 0).unwrap()
1883        );
1884        // Turtle and TriG stream too — that is what lets the external build take a
1885        // multi-gigabyte `.ttl.gz` without expanding it to N-Triples first. Reading
1886        // a structured syntax from a reader must agree with parsing its whole text.
1887        let ttl = "@prefix ex: <http://ex/> .\nex:A ex:knows ex:B , ex:C .\n";
1888        assert_eq!(
1889            parse_statements(ttl, "ttl").unwrap(),
1890            parse_reader(std::io::Cursor::new(ttl), "ttl", 0).unwrap()
1891        );
1892        let trig = "@prefix ex: <http://ex/> .\nex:g { ex:A ex:knows ex:B . }\n";
1893        let streamed = parse_reader(std::io::Cursor::new(trig), "trig", 0).unwrap();
1894        assert_eq!(parse_statements(trig, "trig").unwrap(), streamed);
1895        assert_eq!(streamed[0].3.as_deref(), Some("<http://ex/g>"));
1896        // An unknown format is still a hard error, not a silent guess.
1897        assert!(parse_reader(std::io::Cursor::new(nt), "jsonld", 0).is_err());
1898    }
1899
1900    #[test]
1901    fn parse_statements_dispatches_by_format() {
1902        let nt = "<http://ex/a> <http://ex/p> <http://ex/b> .";
1903        assert_eq!(parse_statements(nt, "nt").unwrap().len(), 1);
1904        let ttl = "@prefix ex: <http://ex/> .\nex:A ex:knows ex:B , ex:C .";
1905        assert_eq!(parse_statements(ttl, "ttl").unwrap().len(), 2);
1906        // N-Triples is a subset of both Turtle and TriG, so the same text parses
1907        // under all three — and lands in the default graph under each.
1908        assert_eq!(parse_statements(nt, "trig").unwrap().len(), 1);
1909        assert!(parse_statements(nt, "trig").unwrap()[0].3.is_none());
1910        assert!(parse_statements(nt, "jsonld").is_err());
1911    }
1912
1913    /// A TriG graph block carries its graph name through as the same canonical
1914    /// token N-Quads would produce — so the two syntaxes agree on dictionary keys
1915    /// and a `.trig` shard federates with a `.nq` one.
1916    #[test]
1917    fn trig_graph_names_match_nquads() {
1918        let trig = "@prefix ex: <http://ex/> .\nex:g { ex:a ex:p ex:b . }\nex:a ex:p ex:c .\n";
1919        let nq = "<http://ex/a> <http://ex/p> <http://ex/b> <http://ex/g> .\n\
1920                  <http://ex/a> <http://ex/p> <http://ex/c> .\n";
1921        let mut from_trig = parse_statements(trig, "trig").unwrap();
1922        let mut from_nq = parse_statements(nq, "nq").unwrap();
1923        from_trig.sort();
1924        from_nq.sort();
1925        assert_eq!(from_trig, from_nq);
1926    }
1927
1928    /// RDF/XML (how most OWL ontologies ship) parses to the same canonical tokens,
1929    /// including the abbreviated typed-node syntax and `rdf:resource` references.
1930    #[test]
1931    fn parses_rdfxml_owl() {
1932        let xml = r#"<?xml version="1.0"?>
1933            <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
1934                     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
1935                     xmlns:owl="http://www.w3.org/2002/07/owl#">
1936              <owl:Class rdf:about="http://ex/Dog">
1937                <rdfs:subClassOf rdf:resource="http://ex/Animal"/>
1938                <rdfs:label>Dog</rdfs:label>
1939              </owl:Class>
1940            </rdf:RDF>"#;
1941        let triples = parse_rdfxml(xml).unwrap();
1942        // rdf:type owl:Class, rdfs:subClassOf, rdfs:label = 3 triples.
1943        assert_eq!(triples.len(), 3);
1944        assert!(triples.iter().any(|(s, p, o)| s == "<http://ex/Dog>"
1945            && p == "<http://www.w3.org/2000/01/rdf-schema#subClassOf>"
1946            && o == "<http://ex/Animal>"));
1947        // Same data through the format dispatcher (triples → default graph).
1948        assert_eq!(parse_statements(xml, "rdfxml").unwrap().len(), 3);
1949        // Malformed XML is a clear RdfXml error, not a silent empty parse.
1950        assert!(matches!(
1951            parse_statements("<rdf:RDF><not closed", "rdfxml"),
1952            Err(IngestError::RdfXml(_))
1953        ));
1954    }
1955
1956    /// Regression coverage for RUSTSEC-2026-0195: namespace declarations from
1957    /// an untrusted RDF/XML document must not make parsing panic or exhaust the
1958    /// bounded test process.
1959    #[test]
1960    fn rdfxml_namespace_fanout_is_bounded() {
1961        let declarations = (0..2_000)
1962            .map(|i| format!(r#" xmlns:p{i}="http://example.test/{i}/""#))
1963            .collect::<String>();
1964        let xml = format!(
1965            r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"{declarations}/>"#
1966        );
1967        let result = parse_statements(&xml, "rdfxml");
1968        assert!(result.is_ok() || result.unwrap_err().to_string().contains("namespace"));
1969    }
1970
1971    /// Regression coverage for RUSTSEC-2026-0194: duplicate-name checking must
1972    /// complete for a large valid start tag without panicking or exhausting the
1973    /// bounded test process.
1974    #[test]
1975    fn rdfxml_attribute_fanout_completes() {
1976        let attributes = (0..2_000)
1977            .map(|i| format!(r#" p:a{i}="{i}""#))
1978            .collect::<String>();
1979        let xml = format!(
1980            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>"#
1981        );
1982        assert!(parse_statements(&xml, "rdfxml").is_ok());
1983    }
1984
1985    /// Text in, queryable file image out — the whole in-memory build path the
1986    /// wasm `build()` binding uses, including a named graph.
1987    #[test]
1988    fn assemble_dataset_round_trips() {
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                    <http://ex/a> <http://ex/age> \"30\"^^<http://www.w3.org/2001/XMLSchema#integer> .\n\
1992                    <http://ex/a> <http://ex/p> <http://ex/d> <http://ex/g1> .";
1993        let quads = parse_statements(text, "nq").unwrap();
1994        let (bytes, stats) = assemble_dataset(quads, &[]);
1995        assert_eq!(stats.statements, 4);
1996        assert_eq!(stats.default_triples, 3);
1997        assert_eq!(stats.named_graphs, 1);
1998        assert!(stats.terms >= 7);
1999
2000        let rete = Rete::open(&bytes).unwrap();
2001        assert_eq!(
2002            rete.query(None, Some("<http://ex/knows>"), None).len(),
2003            2,
2004            "default-graph pattern query"
2005        );
2006        assert_eq!(rete.graph_names(), vec!["<http://ex/g1>"]);
2007        let out = crate::eval_query(
2008            &rete,
2009            "SELECT ?x WHERE { ?x <http://ex/knows> ?y . ?y <http://ex/knows> ?z }",
2010        )
2011        .unwrap();
2012        match out {
2013            crate::QueryOutput::Select(_, rows) => assert_eq!(rows.len(), 1),
2014            other => panic!("expected select result, got {other:?}"),
2015        }
2016    }
2017
2018    /// The exact minimal input the playground Build tab uses: two triples, no
2019    /// literals, no rdf:type, no named graph — the smallest graph that still
2020    /// builds a community pyramid. (The wasm `build()` panic this guards was a
2021    /// `std::time::Instant::now()` in the pyramid timing path; native has a clock
2022    /// so this passes here, while the playground harness exercises the wasm path.)
2023    #[test]
2024    fn assemble_minimal_typeless_graph() {
2025        let text = "<http://ex/A> <http://ex/knows> <http://ex/B> .\n\
2026                    <http://ex/B> <http://ex/knows> <http://ex/C> .\n";
2027        let quads = parse_statements(text, "nt").unwrap();
2028        let (bytes, stats) = assemble_dataset(quads, &[]);
2029        assert_eq!(stats.default_triples, 2);
2030        let rete = Rete::open(&bytes).unwrap();
2031        assert_eq!(rete.query(None, Some("<http://ex/knows>"), None).len(), 2);
2032    }
2033}