Skip to main content

rete_core/
dictionary.rs

1//! Dictionary assembly: classify RDF terms by role and assign the HDT-style
2//! global IDs that triple blocks reference (SPEC.md §5, §5.1).
3//!
4//! Four sections are built from the §5.1 front-coded primitive:
5//! `shared` (used as both subject and object), `subjects` (subject-only),
6//! `objects` (object-only), and `predicates`. Subject IDs run `1..=S` (shared)
7//! then `S+1..` (subject-only); object IDs reuse `1..=S` for the same shared
8//! terms then `S+1..` for object-only. Predicates have their own space.
9
10use std::collections::HashSet;
11
12use crate::chunk_cache::ChunkCache;
13use crate::dict::{ChunkedSection, DictSectionBuilder};
14use crate::terms::{NodeId, ObjectId, PredicateId, SubjectId};
15
16/// Sort a term slice ascending — in parallel when the `parallel` feature is on.
17/// The front-coded dictionary sections need ascending order; doing it once here
18/// (rather than per-insert in a `BTreeSet`) is the fast path for large graphs.
19#[cfg(feature = "parallel")]
20fn sort_terms(v: &mut [String]) {
21    use rayon::slice::ParallelSliceMut;
22    v.par_sort_unstable();
23}
24#[cfg(not(feature = "parallel"))]
25fn sort_terms(v: &mut [String]) {
26    v.sort_unstable();
27}
28
29/// Builds a [`Dictionary`] from observed `(subject, predicate, object)` terms.
30///
31/// Terms are deduped with `HashSet` during ingest (O(1) average insert, no tree
32/// rebalancing) and sorted **once** in [`Self::build`]. This replaces a trio of
33/// `BTreeSet<String>` whose per-insert `O(log n)` cost + a `String` allocation
34/// for *every* observed term (most of them duplicates) dominated the build on
35/// large graphs.
36#[derive(Default)]
37pub struct DictionaryBuilder {
38    subjects: HashSet<String>,
39    objects: HashSet<String>,
40    predicates: HashSet<String>,
41}
42
43impl DictionaryBuilder {
44    pub fn new() -> Self {
45        Self::default()
46    }
47
48    /// Record one triple's terms (IDs are assigned later, in [`Self::build`]).
49    /// We probe with the borrowed `&str` first and only allocate a `String` for
50    /// a genuinely new term — so a graph of N triples does far fewer than 3N
51    /// allocations (each subject/predicate recurs across many triples).
52    pub fn observe(&mut self, subject: &str, predicate: &str, object: &str) {
53        if !self.subjects.contains(subject) {
54            self.subjects.insert(subject.to_string());
55        }
56        if !self.objects.contains(object) {
57            self.objects.insert(object.to_string());
58        }
59        if !self.predicates.contains(predicate) {
60            self.predicates.insert(predicate.to_string());
61        }
62    }
63
64    pub fn build(self) -> Dictionary {
65        // Sort each role's terms once (ascending) — identical output order to
66        // the old BTreeSet iteration, but without the per-insert tree cost.
67        let mut subjects: Vec<String> = self.subjects.into_iter().collect();
68        let mut predicates: Vec<String> = self.predicates.into_iter().collect();
69        let object_set = self.objects; // kept for the shared (subject ∩ object) test
70        sort_terms(&mut subjects);
71        sort_terms(&mut predicates);
72
73        // A term is "shared" when it appears as both a subject and an object.
74        let subject_set: HashSet<&str> = subjects.iter().map(String::as_str).collect();
75
76        let mut shared_b = DictSectionBuilder::new();
77        let mut subj_b = DictSectionBuilder::new();
78        let mut obj_b = DictSectionBuilder::new();
79        let mut pred_b = DictSectionBuilder::new();
80
81        // Subjects ascending: shared (also an object) vs subject-only.
82        for s in &subjects {
83            if object_set.contains(s) {
84                shared_b.push(s.clone());
85            } else {
86                subj_b.push(s.clone());
87            }
88        }
89        // Objects ascending: object-only (shared terms were emitted above).
90        let mut objects: Vec<String> = object_set.into_iter().collect();
91        sort_terms(&mut objects);
92        for o in &objects {
93            if !subject_set.contains(o.as_str()) {
94                obj_b.push(o.clone());
95            }
96        }
97        for p in &predicates {
98            pred_b.push(p.clone());
99        }
100
101        // RDF-star: a quoted triple only ever appears in subject/object position,
102        // so a single prefix scan of those term sets detects the whole file.
103        let has_quoted_triples = subjects.iter().any(|s| s.starts_with("<<"))
104            || objects.iter().any(|o| o.starts_with("<<"));
105
106        let shared = shared_b.build();
107        let mut dict =
108            Dictionary::from_sections([shared, subj_b.build(), obj_b.build(), pred_b.build()]);
109        dict.has_quoted_triples = has_quoted_triples;
110        dict
111    }
112}
113
114/// Reusable per-window scratch for [`Dictionary::resolve_window`]: one job list
115/// per section (`(local_id, out_slot)` pairs) and the resolved-term output.
116/// Held across windows by the export loop so a window allocates only when a
117/// buffer must grow.
118#[derive(Default)]
119pub struct WindowResolver {
120    /// Jobs per dictionary section (shared, subject-only, object-only,
121    /// predicates): each `(section-local id, output slot)`.
122    jobs: [Vec<(u32, usize)>; 4],
123    /// Resolved terms, indexed by output slot `row * 3 + {0:s, 1:p, 2:o}`.
124    out: Vec<Option<String>>,
125}
126
127/// A read-only dictionary mapping terms ↔ role-specific IDs.
128///
129/// Holds the four sections as [`ChunkedSection`]s — local files keep each
130/// section as one resident chunk; a lazily-opened remote file faults
131/// individual chunks in on first touch. Lookups never re-parse a header.
132pub struct Dictionary {
133    /// shared, subjects, objects, predicates.
134    sections: [ChunkedSection; 4],
135    shared_len: u32,
136    /// Whether any term is an RDF-star quoted triple (`<< … >>`). Set at build
137    /// time (from the observed terms); `false` on the read path, where the
138    /// header's `FLAG_HAS_QUOTED_TRIPLES` is the source of truth instead.
139    has_quoted_triples: bool,
140}
141
142impl Dictionary {
143    /// Rebuild from four serialized sections (shared, subjects, objects,
144    /// predicates), e.g. when reading a `.rete` file. The four sections share one
145    /// [`ChunkCache`] (unlimited cap here, so every section body stays resident
146    /// exactly as before).
147    pub fn from_sections(sections: [Vec<u8>; 4]) -> Self {
148        let cache = ChunkCache::unlimited_arc();
149        let mut section_index = 0u8;
150        let chunked = sections.map(|bytes| {
151            let s = ChunkedSection::local(bytes, cache.clone(), section_index);
152            section_index += 1;
153            s
154        });
155        Self::from_chunked_sections(chunked)
156    }
157
158    /// Rebuild from four already-chunked sections (the remote lazy-open path).
159    pub fn from_chunked_sections(sections: [ChunkedSection; 4]) -> Self {
160        let shared_len = sections[0].term_count();
161        Dictionary {
162            sections,
163            shared_len,
164            has_quoted_triples: false,
165        }
166    }
167
168    /// Total number of distinct terms across all four sections.
169    pub fn term_count(&self) -> u32 {
170        self.sections.iter().map(|s| s.term_count()).sum()
171    }
172
173    /// Set the byte cap of the shared chunk cache (bounded-export phase 2).
174    /// `u64::MAX` (the default from every open) means unlimited — no eviction,
175    /// residency identical to the pre-budget design. A finite cap evicts
176    /// least-recently-used chunk bodies down to it on every fault, so a full
177    /// dump's peak dictionary residency is bounded rather than the whole
178    /// decompressed dictionary. All four sections share one cache; setting it on
179    /// each is idempotent (they are the same `Arc`).
180    pub fn set_cache_cap(&self, cap: u64) {
181        for s in &self.sections {
182            s.cache().set_cap(cap);
183        }
184    }
185
186    /// The current chunk-cache byte cap (`u64::MAX` = unlimited).
187    pub fn cache_cap(&self) -> u64 {
188        self.sections[0].cache().cap()
189    }
190
191    /// A snapshot of the shared chunk cache's observability counters — for
192    /// `RETE_OPEN_DEBUG` accounting and the eviction tests.
193    pub fn cache_stats(&self) -> crate::chunk_cache::CacheStats {
194        self.sections[0].cache().stats()
195    }
196
197    /// Does this dataset contain RDF-star quoted triples? Meaningful only for a
198    /// freshly built dictionary (a read-back one carries the truth in the file
199    /// header's `FLAG_HAS_QUOTED_TRIPLES`, not here).
200    pub fn has_quoted_triples(&self) -> bool {
201        self.has_quoted_triples
202    }
203
204    /// Did any lazy chunk fetch fail since this dictionary was opened — or
205    /// since the last [`reset_load_failure`](Self::reset_load_failure)?
206    pub fn load_incomplete(&self) -> bool {
207        self.sections.iter().any(|s| s.load_incomplete())
208    }
209
210    /// Forget recorded fetch failures across every section (see
211    /// `GraphIndex::reset_load_failure` — the per-query reset for resident
212    /// sessions). Failed chunks were never cached, so they simply retry.
213    pub fn reset_load_failure(&self) {
214        self.sections.iter().for_each(|s| s.reset_load_failure());
215    }
216
217    /// Batch-fault every unloaded chunk of every section (no-op for local
218    /// dictionaries). Callers about to resolve *every* term — export, dump —
219    /// call this once so the sweep coalesces into a few range reads instead
220    /// of one fetch per chunk.
221    pub fn prefetch_all(&self) {
222        for s in &self.sections {
223            s.prefetch_all();
224        }
225    }
226
227    /// Batch-fault just the chunks needed to resolve a bounded result set:
228    /// `node_ids` are unified-node ids (the `Val::Id(id)` with `id >= 0`),
229    /// `predicate_ids` are predicate-space ids. Groups them by `(section,
230    /// chunk)` and coalesces each section's faults into a few range reads —
231    /// turning "one request per distinct output term" into "a handful per
232    /// query". No-op for a local dictionary (every chunk is already resident).
233    pub fn prefetch_terms(&self, node_ids: &[u32], predicate_ids: &[u32]) {
234        let mut want: [std::collections::BTreeSet<usize>; 4] = Default::default();
235        for &n in node_ids {
236            if let Some((si, ci)) = self.node_chunk(n) {
237                want[si].insert(ci);
238            }
239        }
240        for &p in predicate_ids {
241            if let Some(ci) = self.sections[3].chunk_of_id(p) {
242                want[3].insert(ci);
243            }
244        }
245        for (si, set) in want.iter().enumerate() {
246            if set.len() >= 2 {
247                let cis: Vec<usize> = set.iter().copied().collect();
248                self.sections[si].prefetch_chunks(&cis);
249            }
250        }
251    }
252
253    /// The `(section, chunk)` holding a unified node id — mirrors the section
254    /// routing in [`node_term`](Self::node_term).
255    fn node_chunk(&self, node: u32) -> Option<(usize, usize)> {
256        let su = self.subject_only_count();
257        let (si, local) = if node < self.shared_len + su {
258            let id = node + 1; // subject_term(id)
259            if id <= self.shared_len {
260                (0, id)
261            } else {
262                (1, id - self.shared_len)
263            }
264        } else {
265            let id = node + 1 - su; // object_term(id)
266            if id <= self.shared_len {
267                (0, id)
268            } else {
269                (2, id - self.shared_len)
270            }
271        };
272        Some((si, self.sections[si].chunk_of_id(local)?))
273    }
274
275    /// Number of shared terms `S`.
276    pub fn shared_count(&self) -> u32 {
277        self.shared_len
278    }
279
280    /// Number of subject-only terms `Su`.
281    pub fn subject_only_count(&self) -> u32 {
282        self.sections[1].term_count()
283    }
284
285    /// Number of object-only terms `Oo`.
286    pub fn object_only_count(&self) -> u32 {
287        self.sections[2].term_count()
288    }
289
290    // --- unified node space (for graph algorithms / the pyramid) ----------
291    //
292    // Subjects and objects use *separate* ID spaces that overlap on shared
293    // terms; the pyramid needs one node per distinct term. We lay them out as:
294    //   [0 .. S)            shared
295    //   [S .. S+Su)         subject-only
296    //   [S+Su .. S+Su+Oo)   object-only
297
298    /// Total distinct graph nodes `N = S + Su + Oo`.
299    pub fn node_count(&self) -> u32 {
300        self.shared_len + self.subject_only_count() + self.object_only_count()
301    }
302
303    /// Unified node ID for a subject-role ID. Shared and subject-only IDs are
304    /// already contiguous (`1..=S+Su`), so this is just `sid - 1`.
305    pub fn subject_node(&self, sid: SubjectId) -> NodeId {
306        // saturating_sub: a corrupt block may carry id 0; valid ids are ≥1 so this
307        // is identical for well-formed files but never underflow-panics.
308        sid.saturating_sub(1)
309    }
310
311    /// Unified node ID for an object-role ID: shared stay at `oid-1`, object-only
312    /// IDs are shifted past the subject-only block.
313    pub fn object_node(&self, oid: ObjectId) -> NodeId {
314        if oid <= self.shared_len {
315            oid.saturating_sub(1)
316        } else {
317            oid.saturating_sub(1) + self.subject_only_count()
318        }
319    }
320
321    /// Resolve a unified node ID back to its term.
322    pub fn node_term(&self, node: NodeId) -> Option<String> {
323        let su = self.subject_only_count();
324        if node < self.shared_len + su {
325            self.subject_term(node + 1)
326        } else {
327            self.object_term(node + 1 - su)
328        }
329    }
330
331    /// Batch-fault the dictionary chunks that decoding these subject-role ids
332    /// will touch — one coalesced read per section instead of a blocking round
333    /// trip per id. Purely a cache warmer (resident sections no-op).
334    pub fn prefetch_subject_terms(&self, ids: &[SubjectId]) {
335        let mut per_section: [Vec<usize>; 2] = Default::default();
336        for &id in ids {
337            let (si, local) = if id <= self.shared_len {
338                (0usize, id)
339            } else {
340                (1, id - self.shared_len)
341            };
342            if let Some(ci) = self.sections[si].chunk_of_term(local) {
343                per_section[si].push(ci);
344            }
345        }
346        for (si, cis) in per_section.iter_mut().enumerate() {
347            cis.sort_unstable();
348            cis.dedup();
349            self.sections[si].prefetch_chunks(cis);
350        }
351    }
352
353    /// [`prefetch_subject_terms`](Self::prefetch_subject_terms) for unified
354    /// node ids — the id space solution rows carry. Warms every chunk a batch
355    /// of row decodes (a FILTER's string ops, the projection) is about to
356    /// fault, using [`node_term`](Self::node_term)'s exact routing.
357    pub fn prefetch_node_terms(&self, nodes: &[NodeId]) {
358        let su = self.subject_only_count();
359        let mut per_section: [Vec<usize>; 3] = Default::default();
360        for &node in nodes {
361            let (si, local) = if node < self.shared_len + su {
362                let sid = node + 1;
363                if sid <= self.shared_len {
364                    (0usize, sid)
365                } else {
366                    (1, sid - self.shared_len)
367                }
368            } else {
369                let oid = node + 1 - su;
370                if oid <= self.shared_len {
371                    (0, oid)
372                } else {
373                    (2, oid - self.shared_len)
374                }
375            };
376            if let Some(ci) = self.sections[si].chunk_of_term(local) {
377                per_section[si].push(ci);
378            }
379        }
380        for (si, cis) in per_section.iter_mut().enumerate() {
381            cis.sort_unstable();
382            cis.dedup();
383            self.sections[si].prefetch_chunks(cis);
384        }
385    }
386
387    /// Unified node ID for a term, resolving via subject role then object role.
388    pub fn node_of_term(&self, term: &str) -> Option<NodeId> {
389        if let Some(sid) = self.subject_id(term) {
390            return Some(self.subject_node(sid));
391        }
392        self.object_id(term).map(|oid| self.object_node(oid))
393    }
394
395    /// Subject-role ID of a node, or `None` if the node never appears as a
396    /// subject (an object-only term).
397    pub fn node_as_subject_id(&self, node: NodeId) -> Option<SubjectId> {
398        if node < self.shared_len + self.subject_only_count() {
399            Some(node + 1)
400        } else {
401            None
402        }
403    }
404
405    /// Object-role ID of a node, or `None` if the node never appears as an
406    /// object (a subject-only term).
407    pub fn node_as_object_id(&self, node: NodeId) -> Option<ObjectId> {
408        let (s, su) = (self.shared_len, self.subject_only_count());
409        if node < s {
410            Some(node + 1) // shared
411        } else if node >= s + su {
412            Some(node + 1 - su) // object-only
413        } else {
414            None // subject-only
415        }
416    }
417
418    // --- term -> id -------------------------------------------------------
419
420    /// Subject-role ID for `term`: shared `1..=S`, else subject-only `S+1..`.
421    pub fn subject_id(&self, term: &str) -> Option<SubjectId> {
422        if let Some(id) = self.sections[0].id(term) {
423            return Some(id);
424        }
425        self.sections[1].id(term).map(|id| self.shared_len + id)
426    }
427
428    /// Object-role ID for `term`: shared `1..=S`, else object-only `S+1..`.
429    pub fn object_id(&self, term: &str) -> Option<ObjectId> {
430        if let Some(id) = self.sections[0].id(term) {
431            return Some(id);
432        }
433        self.sections[2].id(term).map(|id| self.shared_len + id)
434    }
435
436    /// Predicate ID for `term` (independent space).
437    pub fn predicate_id(&self, term: &str) -> Option<PredicateId> {
438        self.sections[3].id(term)
439    }
440
441    // --- id -> term -------------------------------------------------------
442
443    pub fn subject_term(&self, id: SubjectId) -> Option<String> {
444        if id <= self.shared_len {
445            self.sections[0].term(id)
446        } else {
447            self.sections[1].term(id - self.shared_len)
448        }
449    }
450
451    pub fn object_term(&self, id: ObjectId) -> Option<String> {
452        if id <= self.shared_len {
453            self.sections[0].term(id)
454        } else {
455            self.sections[2].term(id - self.shared_len)
456        }
457    }
458
459    pub fn predicate_term(&self, id: PredicateId) -> Option<String> {
460        self.sections[3].term(id)
461    }
462
463    /// Encode a `(s, p, o)` term triple to its `(subject_id, predicate_id,
464    /// object_id)`. `None` if any term is unknown.
465    pub fn encode(&self, s: &str, p: &str, o: &str) -> Option<(SubjectId, PredicateId, ObjectId)> {
466        Some((
467            self.subject_id(s)?,
468            self.predicate_id(p)?,
469            self.object_id(o)?,
470        ))
471    }
472
473    /// Resolve a window of `(subject_id, predicate_id, object_id)` triples in
474    /// **chunk order** and emit each fully-resolved row through `emit` in the
475    /// window's **original order**.
476    ///
477    /// This is the batch twin of resolving each row with
478    /// [`subject_term`](Self::subject_term) /
479    /// [`predicate_term`](Self::predicate_term) /
480    /// [`object_term`](Self::object_term) and emitting on `(Some, Some, Some)`
481    /// — the exact thing it replaces inside `Rete::dump_filtered_each`. A row is
482    /// emitted only when all three of its terms resolve, and the bytes of each
483    /// term are identical to the per-row path, so the dump stays
484    /// byte-for-byte the same.
485    ///
486    /// What changes is *how* the terms are decoded. Each row contributes three
487    /// jobs to the section that owns its id (shared/subject-only for the
488    /// subject, predicates for the predicate, shared/object-only for the
489    /// object); each section then resolves its jobs in one chunk-ordered,
490    /// single-pass walk ([`ChunkedSection::resolve_into`]). A window whose
491    /// object ids scatter across the object-only section therefore touches each
492    /// chunk once — one faulted body, one forward walk — instead of the
493    /// scattered re-faults and per-row re-walks the row-order path performed.
494    ///
495    /// `w` carries the per-window scratch buffers so back-to-back windows cost
496    /// no allocation beyond growth.
497    ///
498    /// [`ChunkedSection::resolve_into`]: crate::dict::ChunkedSection::resolve_into
499    pub fn resolve_window(
500        &self,
501        ids: &[(SubjectId, PredicateId, ObjectId)],
502        w: &mut WindowResolver,
503        mut emit: impl FnMut(&str, &str, &str),
504    ) {
505        for j in &mut w.jobs {
506            j.clear();
507        }
508        w.out.clear();
509        w.out.resize(ids.len() * 3, None);
510        for (i, &(s, p, o)) in ids.iter().enumerate() {
511            // Subject role: shared (section 0) if `id <= S`, else subject-only
512            // (section 1) with the shared block subtracted — the exact routing
513            // of `subject_term`.
514            if s <= self.shared_len {
515                w.jobs[0].push((s, i * 3));
516            } else {
517                w.jobs[1].push((s - self.shared_len, i * 3));
518            }
519            // Predicate role: its own section (3).
520            w.jobs[3].push((p, i * 3 + 1));
521            // Object role: shared (section 0) if `id <= S`, else object-only
522            // (section 2) — the exact routing of `object_term`.
523            if o <= self.shared_len {
524                w.jobs[0].push((o, i * 3 + 2));
525            } else {
526                w.jobs[2].push((o - self.shared_len, i * 3 + 2));
527            }
528        }
529        for si in 0..4 {
530            self.sections[si].resolve_into(&mut w.jobs[si], &mut w.out);
531        }
532        for i in 0..ids.len() {
533            if let (Some(s), Some(p), Some(o)) =
534                (&w.out[i * 3], &w.out[i * 3 + 1], &w.out[i * 3 + 2])
535            {
536                emit(s, p, o);
537            }
538        }
539    }
540
541    /// The four serialized sections (header + body each), for the file writer.
542    pub fn sections(&self) -> [Vec<u8>; 4] {
543        [
544            self.sections[0].raw_section_bytes(),
545            self.sections[1].raw_section_bytes(),
546            self.sections[2].raw_section_bytes(),
547            self.sections[3].raw_section_bytes(),
548        ]
549    }
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555
556    fn dict() -> Dictionary {
557        let mut b = DictionaryBuilder::new();
558        // Alice knows Bob; Bob knows Carol. So Bob is both subject and object
559        // (shared); Alice is subject-only; Carol is object-only.
560        b.observe("Alice", "knows", "Bob");
561        b.observe("Bob", "knows", "Carol");
562        b.build()
563    }
564
565    #[test]
566    fn shared_term_has_same_id_in_both_roles() {
567        let d = dict();
568        assert_eq!(d.shared_count(), 1); // just "Bob"
569        let sid = d.subject_id("Bob").unwrap();
570        let oid = d.object_id("Bob").unwrap();
571        assert_eq!(sid, oid, "shared term must share its ID across roles");
572        assert_eq!(sid, 1, "shared terms get the lowest IDs");
573    }
574
575    #[test]
576    fn role_specific_terms_round_trip() {
577        let d = dict();
578        // subject-only Alice
579        let a = d.subject_id("Alice").unwrap();
580        assert!(a > d.shared_count());
581        assert_eq!(d.subject_term(a).as_deref(), Some("Alice"));
582        // object-only Carol
583        let c = d.object_id("Carol").unwrap();
584        assert!(c > d.shared_count());
585        assert_eq!(d.object_term(c).as_deref(), Some("Carol"));
586        // predicate
587        let k = d.predicate_id("knows").unwrap();
588        assert_eq!(d.predicate_term(k).as_deref(), Some("knows"));
589        // Alice never appears as object, Carol never as subject.
590        assert_eq!(d.object_id("Alice"), None);
591        assert_eq!(d.subject_id("Carol"), None);
592    }
593
594    #[test]
595    fn encode_full_triples() {
596        let d = dict();
597        let t1 = d.encode("Alice", "knows", "Bob").unwrap();
598        let t2 = d.encode("Bob", "knows", "Carol").unwrap();
599        // Bob is object in t1 and subject in t2 — same ID both times.
600        assert_eq!(t1.2, t2.0);
601        assert!(d.encode("Nobody", "knows", "Bob").is_none());
602    }
603}