Skip to main content

waratah_compute/
subject_window.rs

1//! Compact storage for one resolved text-subject window.
2//!
3//! The O partition streams `TextSubjectRow`s as encoded terms. Interning the
4//! subjects and graphs into the query's [`TermDict`] — the per-query
5//! dictionary every plan column already uses — turns a window that costs tens
6//! of bytes per row into four bytes per stored id, and lets every later probe
7//! page share one `Arc` instead of cloning the rows. That is what makes a
8//! multi-million-row subject window memoizable: the `Vec<TextSubjectRow>`
9//! form cost ~200 MB at 2M rows, the interned form ~8–16 MB plus the dict
10//! entries any materialized column would need anyway.
11//!
12//! Rows are sorted by `(subject, graph)`. A probe page then answers each
13//! pushed subject with a binary search over the window instead of scanning
14//! the whole window; the keyless (driver) execution still materializes every
15//! row, in bounded chunks.
16
17use std::sync::Arc;
18
19use waratah_exec::{TermDict, TermId};
20use waratah_storage::{EncodedTerm, TextSubjectRow};
21
22use crate::error::ComputeError;
23
24/// Rows decoded per `TermDict::get_many` call when materializing a window.
25/// Matches the scan frame size: one mutex hold per 8,192 rows.
26const DECODE_CHUNK: usize = 8_192;
27
28/// One resolved `(subject, graph)` window, interned into the query dict.
29#[derive(Debug)]
30pub struct TextSubjectWindow {
31    dict: Arc<TermDict>,
32    /// The request asked for the graph column; `graphs` is then parallel to
33    /// `subjects` (otherwise empty).
34    with_graph: bool,
35    /// Subject ids ascending.
36    subjects: Vec<TermId>,
37    /// Graph ids parallel to `subjects` when `with_graph`.
38    graphs: Vec<TermId>,
39}
40
41impl TextSubjectWindow {
42    /// Distinct rows in the window.
43    pub fn len(&self) -> usize {
44        self.subjects.len()
45    }
46
47    /// Whether the window has no rows.
48    pub fn is_empty(&self) -> bool {
49        self.subjects.is_empty()
50    }
51
52    /// Whether the window carries the graph column.
53    pub fn has_graph(&self) -> bool {
54        self.with_graph
55    }
56
57    /// Ids the memo budget charges: one per subject, plus one per graph.
58    pub fn stored_ids(&self) -> usize {
59        self.subjects.len() + self.graphs.len()
60    }
61
62    /// Whether the window holds `subject`.
63    ///
64    /// The probe road's membership test: a pushed subject is looked up in the
65    /// dict, then binary-searched in the sorted subject ids. A term the dict
66    /// has never interned cannot be in the window.
67    pub fn contains_subject(&self, subject: &EncodedTerm) -> bool {
68        self.dict
69            .peek(subject)
70            .is_some_and(|id| self.subjects.binary_search(&id).is_ok())
71    }
72
73    /// Graph terms for `subject`, in window order; empty when the request did
74    /// not ask for the graph column or the subject is absent. An id that does
75    /// not resolve is an ERROR: the subject form has no residual, so a lost
76    /// graph must not silently drop the row.
77    pub fn graphs_for(&self, subject: &EncodedTerm) -> Result<Vec<EncodedTerm>, ComputeError> {
78        if !self.with_graph {
79            return Ok(Vec::new());
80        }
81        let Some(id) = self.dict.peek(subject) else {
82            return Ok(Vec::new());
83        };
84        let start = self.subjects.partition_point(|candidate| *candidate < id);
85        let mut raw = Vec::new();
86        for index in start..self.subjects.len() {
87            if self.subjects[index] != id {
88                break;
89            }
90            raw.push(self.graphs[index].0);
91        }
92        let mut decoded = vec![None; raw.len()];
93        self.dict.get_many(&raw, &mut decoded);
94        let mut graphs = Vec::with_capacity(decoded.len());
95        for graph in decoded {
96            let Some(graph) = graph else {
97                return Err(ComputeError::Internal(
98                    "text subject window holds a graph id that does not resolve in the \
99                     query dictionary"
100                        .into(),
101                ));
102            };
103            graphs.push(graph);
104        }
105        Ok(graphs)
106    }
107
108    /// Every row, decoded in bounded chunks (the keyless / driver execution).
109    ///
110    /// Yields an error if a stored id does not resolve in the window's
111    /// dictionary. That cannot happen while the window holds the `Arc` (the
112    /// dictionary never evicts), so the error exists to make a corrupt window
113    /// fail the query instead of silently dropping a row — the subject form
114    /// has no residual to recover it.
115    pub fn rows(&self) -> TextSubjectRows<'_> {
116        TextSubjectRows {
117            window: self,
118            offset: 0,
119            buffer: Vec::new().into_iter(),
120        }
121    }
122}
123
124/// Chunked row materialization for [`TextSubjectWindow::rows`].
125pub struct TextSubjectRows<'a> {
126    window: &'a TextSubjectWindow,
127    offset: usize,
128    buffer: std::vec::IntoIter<Result<TextSubjectRow, ComputeError>>,
129}
130
131impl Iterator for TextSubjectRows<'_> {
132    type Item = Result<TextSubjectRow, ComputeError>;
133
134    fn next(&mut self) -> Option<Self::Item> {
135        loop {
136            if let Some(row) = self.buffer.next() {
137                return Some(row);
138            }
139            if self.offset >= self.window.len() {
140                return None;
141            }
142            let end = (self.offset + DECODE_CHUNK).min(self.window.len());
143            let ids: Vec<u32> = self.window.subjects[self.offset..end]
144                .iter()
145                .map(|id| id.0)
146                .collect();
147            let mut subjects = vec![None; ids.len()];
148            self.window.dict.get_many(&ids, &mut subjects);
149            let graphs = if self.window.with_graph {
150                let ids: Vec<u32> = self.window.graphs[self.offset..end]
151                    .iter()
152                    .map(|id| id.0)
153                    .collect();
154                let mut graphs = vec![None; ids.len()];
155                self.window.dict.get_many(&ids, &mut graphs);
156                graphs
157            } else {
158                Vec::new()
159            };
160            let mut chunk = Vec::with_capacity(subjects.len());
161            for (index, subject) in subjects.into_iter().enumerate() {
162                let Some(subject) = subject else {
163                    // The window's own ids always resolve while it holds the
164                    // dictionary; a lost slot is a dict invariant violation,
165                    // and the subject form has no residual, so report it
166                    // rather than dropping the row.
167                    chunk.push(Err(ComputeError::Internal(
168                        "text subject window holds a subject id that does not resolve in the \
169                         query dictionary"
170                            .into(),
171                    )));
172                    continue;
173                };
174                let graph = if self.window.with_graph {
175                    let Some(graph) = graphs.get(index).and_then(|graph| graph.clone()) else {
176                        chunk.push(Err(ComputeError::Internal(
177                            "text subject window holds a graph id that does not resolve in the \
178                             query dictionary"
179                                .into(),
180                        )));
181                        continue;
182                    };
183                    Some(graph)
184                } else {
185                    None
186                };
187                chunk.push(Ok(TextSubjectRow { subject, graph }));
188            }
189            self.offset = end;
190            self.buffer = chunk.into_iter();
191        }
192    }
193}
194
195/// Intern one window's rows as the partition pages arrive.
196///
197/// `push` interns each term; `finish` sorts the ids and splits the parallel
198/// columns. The intermediate `(TermId, TermId)` buffer is eight bytes per
199/// logged row (`TermId::UNBOUND` stands in for "no graph id"). Growth can
200/// leave the buffer with up to twice its length in capacity (~16 B/row
201/// transiently), and `finish` keeps the buffer alive while it writes the two
202/// columns, so its peak is the buffer plus the columns (~16 B/row, ~24 B/row
203/// with growth slack). The memo admits only the final columns: 4 B/row
204/// subject-only, 8 B/row with the graph id.
205#[derive(Debug)]
206pub struct TextSubjectWindowBuilder {
207    dict: Arc<TermDict>,
208    with_graph: bool,
209    rows: Vec<(TermId, TermId)>,
210}
211
212impl TextSubjectWindowBuilder {
213    /// One builder over `dict`; `with_graph` follows the request's row shape.
214    pub fn new(dict: Arc<TermDict>, with_graph: bool) -> Self {
215        Self {
216            dict,
217            with_graph,
218            rows: Vec::new(),
219        }
220    }
221
222    /// Rows pushed so far (admission diagnostics / perf).
223    pub fn len(&self) -> usize {
224        self.rows.len()
225    }
226
227    /// Whether no row has been pushed yet.
228    pub fn is_empty(&self) -> bool {
229        self.rows.is_empty()
230    }
231
232    /// Intern one streamed row.
233    pub fn push(&mut self, row: TextSubjectRow) -> Result<(), ComputeError> {
234        let subject = self.dict.intern(row.subject)?;
235        // Only a graph-column request stores a graph id; a stray graph on a
236        // subject-only request is dropped rather than interned into a slot
237        // the budget does not count.
238        let graph = if self.with_graph {
239            let Some(graph) = row.graph else {
240                return Err(ComputeError::Internal(
241                    "text subject resolve returned a row without its requested graph column".into(),
242                ));
243            };
244            self.dict.intern(graph)?
245        } else {
246            TermId::UNBOUND
247        };
248        self.rows.push((subject, graph));
249        Ok(())
250    }
251
252    /// Sort and compact the window.
253    pub fn finish(mut self) -> TextSubjectWindow {
254        self.rows
255            .sort_unstable_by_key(|(subject, graph)| (*subject, *graph));
256        let mut subjects = Vec::with_capacity(self.rows.len());
257        let mut graphs = if self.with_graph {
258            Vec::with_capacity(self.rows.len())
259        } else {
260            Vec::new()
261        };
262        for (subject, graph) in self.rows {
263            subjects.push(subject);
264            if self.with_graph {
265                graphs.push(graph);
266            }
267        }
268        TextSubjectWindow {
269            dict: self.dict,
270            with_graph: self.with_graph,
271            subjects,
272            graphs,
273        }
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280    use waratah_storage::NamedNode;
281
282    fn subject(n: usize) -> EncodedTerm {
283        EncodedTerm::from(&NamedNode::new(format!("http://ex/s{n}")).unwrap())
284    }
285
286    fn graph(n: usize) -> EncodedTerm {
287        EncodedTerm::from(&NamedNode::new(format!("http://ex/g{n}")).unwrap())
288    }
289
290    fn row(s: usize, g: Option<usize>) -> TextSubjectRow {
291        TextSubjectRow {
292            subject: subject(s),
293            graph: g.map(graph),
294        }
295    }
296
297    fn build(with_graph: bool, rows: Vec<TextSubjectRow>) -> TextSubjectWindow {
298        let mut builder =
299            TextSubjectWindowBuilder::new(std::sync::Arc::new(TermDict::new()), with_graph);
300        for row in rows {
301            builder.push(row).expect("row interns");
302        }
303        builder.finish()
304    }
305
306    #[test]
307    fn interned_window_answers_membership_and_graphs() {
308        // Two graphs for one subject plus a second subject: the sorted
309        // (subject, graph) order must keep each subject's graphs contiguous
310        // and `graphs_for` must not leak a neighbour's graph.
311        let window = build(
312            true,
313            vec![row(1, Some(1)), row(1, Some(2)), row(2, Some(1))],
314        );
315        assert_eq!(window.len(), 3);
316        assert!(window.has_graph());
317        assert_eq!(
318            window.stored_ids(),
319            6,
320            "one subject id + one graph id per row"
321        );
322        assert!(window.contains_subject(&subject(1)));
323        assert!(window.contains_subject(&subject(2)));
324        assert!(
325            !window.contains_subject(&subject(3)),
326            "a foreign term is absent"
327        );
328        assert_eq!(
329            window.graphs_for(&subject(1)).unwrap(),
330            vec![graph(1), graph(2)]
331        );
332        assert_eq!(window.graphs_for(&subject(2)).unwrap(), vec![graph(1)]);
333        assert!(window.graphs_for(&subject(3)).unwrap().is_empty());
334        let rows: Vec<TextSubjectRow> = window
335            .rows()
336            .collect::<Result<Vec<_>, _>>()
337            .expect("every id resolves");
338        assert_eq!(rows.len(), 3);
339        assert_eq!(rows[0], row(1, Some(1)));
340        assert_eq!(rows[1], row(1, Some(2)));
341        assert_eq!(rows[2], row(2, Some(1)));
342    }
343
344    #[test]
345    fn subject_only_window_drops_a_stray_graph() {
346        // A subject-only request stores no graph id, so a graph the wire
347        // should not have sent must not inflate the budget or the window.
348        let window = build(false, vec![row(1, Some(7))]);
349        assert_eq!(window.len(), 1);
350        assert!(!window.has_graph());
351        assert_eq!(window.stored_ids(), 1);
352        assert!(window.graphs_for(&subject(1)).unwrap().is_empty());
353        assert_eq!(window.rows().next().unwrap().unwrap().graph, None);
354    }
355
356    #[test]
357    fn a_missing_graph_column_is_an_error() {
358        let mut builder = TextSubjectWindowBuilder::new(std::sync::Arc::new(TermDict::new()), true);
359        let err = builder
360            .push(row(1, None))
361            .expect_err("graph column required");
362        assert!(
363            err.to_string()
364                .contains("without its requested graph column"),
365            "{err}"
366        );
367    }
368
369    #[test]
370    fn rows_decode_across_the_chunk_boundary() {
371        // One row more than a decode chunk forces `rows()` to emit from two
372        // separately decoded batches; the order must still be the window's.
373        let count = DECODE_CHUNK + 1;
374        let window = build(false, (0..count).map(|n| row(n, None)).collect());
375        let rows: Vec<TextSubjectRow> = window
376            .rows()
377            .collect::<Result<Vec<_>, _>>()
378            .expect("every id resolves");
379        assert_eq!(rows.len(), count, "the chunk seam drops nothing");
380        assert_eq!(rows.first().unwrap().subject, subject(0));
381        assert_eq!(rows[DECODE_CHUNK].subject, subject(DECODE_CHUNK));
382        assert_eq!(rows.last().unwrap().subject, subject(count - 1));
383    }
384
385    /// A stored id that does not resolve is an ERROR, not a dropped row: the
386    /// subject form has no residual, so a partial window is a silent wrong
387    /// answer. The state is unreachable while the window holds its
388    /// `Arc<TermDict>` (the dictionary never evicts), so the test fabricates
389    /// the window to pin the error path.
390    #[test]
391    fn a_dangling_subject_id_is_an_error_not_a_dropped_row() {
392        let window = TextSubjectWindow {
393            dict: std::sync::Arc::new(TermDict::new()),
394            with_graph: false,
395            subjects: vec![TermId(9_999)],
396            graphs: Vec::new(),
397        };
398        let row = window.rows().next().expect("one row");
399        assert!(
400            matches!(
401                &row,
402                Err(ComputeError::Internal(message)) if message.contains("subject id")
403            ),
404            "{row:?}"
405        );
406    }
407
408    #[test]
409    fn a_dangling_graph_id_is_an_error_not_a_dropped_graph() {
410        let dict = std::sync::Arc::new(TermDict::new());
411        let subject_id = dict.intern(subject(1)).expect("subject interns");
412        let window = TextSubjectWindow {
413            dict,
414            with_graph: true,
415            subjects: vec![subject_id],
416            graphs: vec![TermId(9_999)],
417        };
418        // The subject resolves; its graph id does not.
419        let error = window
420            .graphs_for(&subject(1))
421            .expect_err("the graph id must resolve");
422        assert!(
423            matches!(&error, ComputeError::Internal(message) if message.contains("graph id")),
424            "{error}"
425        );
426        let row = window.rows().next().expect("one row");
427        assert!(
428            matches!(
429                &row,
430                Err(ComputeError::Internal(message)) if message.contains("graph id")
431            ),
432            "{row:?}"
433        );
434    }
435}