Skip to main content

waratah_exec/
semi_join.rs

1//! Key-only semi-join / anti-semi-join over TermId columns.
2//!
3//! The build side stores distinct bound correlation keys (no payload). Probe
4//! returns keep/drop indexes into the probe batch. Unbound keys never match.
5
6use rustc_hash::FxHashSet;
7
8use crate::ExecError;
9use crate::column::{TermBatch, TermColumn};
10use crate::distinct::{key_wide, key1, key2, key3, key4, key5, key6, key7};
11
12/// Distinct bound key set for EXISTS / NOT EXISTS semi-join.
13pub struct SemiJoinSet {
14    inner: SemiJoinInner,
15}
16
17enum SemiJoinInner {
18    Empty(bool),
19    Key1(FxHashSet<u32>),
20    Key2(FxHashSet<(u32, u32)>),
21    Key3(FxHashSet<(u32, u32, u32)>),
22    Key4(FxHashSet<(u32, u32, u32, u32)>),
23    Key5(FxHashSet<(u32, u32, u32, u32, u32)>),
24    Key6(FxHashSet<(u32, u32, u32, u32, u32, u32)>),
25    Key7(FxHashSet<(u32, u32, u32, u32, u32, u32, u32)>),
26    Wide(FxHashSet<Box<[u32]>>),
27}
28
29impl SemiJoinSet {
30    /// Empty key set for `n_keys` correlation columns (`0` = any inner row).
31    pub fn new(n_keys: usize) -> Self {
32        let inner = match n_keys {
33            0 => SemiJoinInner::Empty(false),
34            1 => SemiJoinInner::Key1(FxHashSet::default()),
35            2 => SemiJoinInner::Key2(FxHashSet::default()),
36            3 => SemiJoinInner::Key3(FxHashSet::default()),
37            4 => SemiJoinInner::Key4(FxHashSet::default()),
38            5 => SemiJoinInner::Key5(FxHashSet::default()),
39            6 => SemiJoinInner::Key6(FxHashSet::default()),
40            7 => SemiJoinInner::Key7(FxHashSet::default()),
41            _ => SemiJoinInner::Wide(FxHashSet::default()),
42        };
43        Self { inner }
44    }
45
46    /// Insert bound keys from `batch`. Returns how many **new** keys landed.
47    pub fn insert_batch(
48        &mut self,
49        batch: &TermBatch,
50        key_cols: &[&TermColumn],
51    ) -> Result<usize, ExecError> {
52        let n = batch.len();
53        let mut added = 0;
54        match &mut self.inner {
55            SemiJoinInner::Empty(seen) => {
56                if !key_cols.is_empty() {
57                    return Err(ExecError::LengthMismatch(format!(
58                        "semi-join empty-key state vs {} columns",
59                        key_cols.len()
60                    )));
61                }
62                if n > 0 && !*seen {
63                    *seen = true;
64                    added = 1;
65                }
66            }
67            SemiJoinInner::Key1(seen) => {
68                let [c0] = exact_cols(key_cols)?;
69                for row in 0..n {
70                    if c0.id_at(row) == 0 {
71                        continue;
72                    }
73                    if seen.insert(key1(c0, row)) {
74                        added += 1;
75                    }
76                }
77            }
78            SemiJoinInner::Key2(seen) => {
79                let [c0, c1] = exact_cols(key_cols)?;
80                for row in 0..n {
81                    if c0.id_at(row) == 0 || c1.id_at(row) == 0 {
82                        continue;
83                    }
84                    if seen.insert(key2(c0, c1, row)) {
85                        added += 1;
86                    }
87                }
88            }
89            SemiJoinInner::Key3(seen) => {
90                let [c0, c1, c2] = exact_cols(key_cols)?;
91                for row in 0..n {
92                    if unbound3(c0, c1, c2, row) {
93                        continue;
94                    }
95                    if seen.insert(key3(c0, c1, c2, row)) {
96                        added += 1;
97                    }
98                }
99            }
100            SemiJoinInner::Key4(seen) => {
101                let [c0, c1, c2, c3] = exact_cols(key_cols)?;
102                for row in 0..n {
103                    if unbound4(c0, c1, c2, c3, row) {
104                        continue;
105                    }
106                    if seen.insert(key4(c0, c1, c2, c3, row)) {
107                        added += 1;
108                    }
109                }
110            }
111            SemiJoinInner::Key5(seen) => {
112                let [c0, c1, c2, c3, c4] = exact_cols(key_cols)?;
113                for row in 0..n {
114                    if unbound_n(key_cols, row) {
115                        continue;
116                    }
117                    if seen.insert(key5(c0, c1, c2, c3, c4, row)) {
118                        added += 1;
119                    }
120                }
121            }
122            SemiJoinInner::Key6(seen) => {
123                let [c0, c1, c2, c3, c4, c5] = exact_cols(key_cols)?;
124                for row in 0..n {
125                    if unbound_n(key_cols, row) {
126                        continue;
127                    }
128                    if seen.insert(key6(c0, c1, c2, c3, c4, c5, row)) {
129                        added += 1;
130                    }
131                }
132            }
133            SemiJoinInner::Key7(seen) => {
134                let [c0, c1, c2, c3, c4, c5, c6] = exact_cols(key_cols)?;
135                for row in 0..n {
136                    if unbound_n(key_cols, row) {
137                        continue;
138                    }
139                    if seen.insert(key7(c0, c1, c2, c3, c4, c5, c6, row)) {
140                        added += 1;
141                    }
142                }
143            }
144            SemiJoinInner::Wide(seen) => {
145                if key_cols.len() < 8 {
146                    return Err(ExecError::LengthMismatch(format!(
147                        "semi-join wide state vs {} columns",
148                        key_cols.len()
149                    )));
150                }
151                for row in 0..n {
152                    if unbound_n(key_cols, row) {
153                        continue;
154                    }
155                    if seen.insert(key_wide(key_cols, row)) {
156                        added += 1;
157                    }
158                }
159            }
160        }
161        Ok(added)
162    }
163
164    /// Whether this probe row's bound key is in the set. Unbound is a miss.
165    pub fn contains_row(&self, key_cols: &[&TermColumn], row: usize) -> Result<bool, ExecError> {
166        match &self.inner {
167            SemiJoinInner::Empty(seen) => {
168                if !key_cols.is_empty() {
169                    return Err(ExecError::LengthMismatch(format!(
170                        "semi-join empty-key state vs {} columns",
171                        key_cols.len()
172                    )));
173                }
174                Ok(*seen)
175            }
176            SemiJoinInner::Key1(seen) => {
177                let [c0] = exact_cols(key_cols)?;
178                if c0.id_at(row) == 0 {
179                    return Ok(false);
180                }
181                Ok(seen.contains(&key1(c0, row)))
182            }
183            SemiJoinInner::Key2(seen) => {
184                let [c0, c1] = exact_cols(key_cols)?;
185                if c0.id_at(row) == 0 || c1.id_at(row) == 0 {
186                    return Ok(false);
187                }
188                Ok(seen.contains(&key2(c0, c1, row)))
189            }
190            SemiJoinInner::Key3(seen) => {
191                let [c0, c1, c2] = exact_cols(key_cols)?;
192                if unbound3(c0, c1, c2, row) {
193                    return Ok(false);
194                }
195                Ok(seen.contains(&key3(c0, c1, c2, row)))
196            }
197            SemiJoinInner::Key4(seen) => {
198                let [c0, c1, c2, c3] = exact_cols(key_cols)?;
199                if unbound4(c0, c1, c2, c3, row) {
200                    return Ok(false);
201                }
202                Ok(seen.contains(&key4(c0, c1, c2, c3, row)))
203            }
204            SemiJoinInner::Key5(seen) => {
205                let [c0, c1, c2, c3, c4] = exact_cols(key_cols)?;
206                if unbound_n(key_cols, row) {
207                    return Ok(false);
208                }
209                Ok(seen.contains(&key5(c0, c1, c2, c3, c4, row)))
210            }
211            SemiJoinInner::Key6(seen) => {
212                let [c0, c1, c2, c3, c4, c5] = exact_cols(key_cols)?;
213                if unbound_n(key_cols, row) {
214                    return Ok(false);
215                }
216                Ok(seen.contains(&key6(c0, c1, c2, c3, c4, c5, row)))
217            }
218            SemiJoinInner::Key7(seen) => {
219                let [c0, c1, c2, c3, c4, c5, c6] = exact_cols(key_cols)?;
220                if unbound_n(key_cols, row) {
221                    return Ok(false);
222                }
223                Ok(seen.contains(&key7(c0, c1, c2, c3, c4, c5, c6, row)))
224            }
225            SemiJoinInner::Wide(seen) => {
226                if key_cols.len() < 8 {
227                    return Err(ExecError::LengthMismatch(format!(
228                        "semi-join wide state vs {} columns",
229                        key_cols.len()
230                    )));
231                }
232                if unbound_n(key_cols, row) {
233                    return Ok(false);
234                }
235                Ok(seen.contains(&key_wide(key_cols, row)))
236            }
237        }
238    }
239
240    /// Probe-side row indexes to keep. `anti` is NOT EXISTS (keep misses).
241    ///
242    /// Unbound probe keys are never a hit; callers that implement SPARQL
243    /// substitution for unbound correlation must handle those rows themselves.
244    pub fn probe_keep(
245        &self,
246        batch: &TermBatch,
247        key_cols: &[&TermColumn],
248        anti: bool,
249    ) -> Result<Vec<usize>, ExecError> {
250        let mut keep = Vec::new();
251        for row in 0..batch.len() {
252            let hit = self.contains_row(key_cols, row)?;
253            if hit ^ anti {
254                keep.push(row);
255            }
256        }
257        Ok(keep)
258    }
259
260    /// Approximate RAM for the key set.
261    pub fn estimated_bytes(&self) -> u64 {
262        const SLOT: u64 = 16;
263        match &self.inner {
264            SemiJoinInner::Empty(_) => 1,
265            SemiJoinInner::Key1(s) => s.len() as u64 * (4 + SLOT),
266            SemiJoinInner::Key2(s) => s.len() as u64 * (8 + SLOT),
267            SemiJoinInner::Key3(s) => s.len() as u64 * (12 + SLOT),
268            SemiJoinInner::Key4(s) => s.len() as u64 * (16 + SLOT),
269            SemiJoinInner::Key5(s) => s.len() as u64 * (20 + SLOT),
270            SemiJoinInner::Key6(s) => s.len() as u64 * (24 + SLOT),
271            SemiJoinInner::Key7(s) => s.len() as u64 * (28 + SLOT),
272            SemiJoinInner::Wide(s) => s
273                .iter()
274                .map(|k| k.len() as u64 * 4 + SLOT)
275                .sum::<u64>()
276                .max(1),
277        }
278    }
279
280    /// Whether the set holds any bound key (or, for 0-keys, any inner row).
281    pub fn is_empty(&self) -> bool {
282        match &self.inner {
283            SemiJoinInner::Empty(seen) => !*seen,
284            SemiJoinInner::Key1(s) => s.is_empty(),
285            SemiJoinInner::Key2(s) => s.is_empty(),
286            SemiJoinInner::Key3(s) => s.is_empty(),
287            SemiJoinInner::Key4(s) => s.is_empty(),
288            SemiJoinInner::Key5(s) => s.is_empty(),
289            SemiJoinInner::Key6(s) => s.is_empty(),
290            SemiJoinInner::Key7(s) => s.is_empty(),
291            SemiJoinInner::Wide(s) => s.is_empty(),
292        }
293    }
294
295    /// Distinct bound keys stored.
296    pub fn len(&self) -> usize {
297        match &self.inner {
298            SemiJoinInner::Empty(seen) => usize::from(*seen),
299            SemiJoinInner::Key1(s) => s.len(),
300            SemiJoinInner::Key2(s) => s.len(),
301            SemiJoinInner::Key3(s) => s.len(),
302            SemiJoinInner::Key4(s) => s.len(),
303            SemiJoinInner::Key5(s) => s.len(),
304            SemiJoinInner::Key6(s) => s.len(),
305            SemiJoinInner::Key7(s) => s.len(),
306            SemiJoinInner::Wide(s) => s.len(),
307        }
308    }
309}
310
311fn exact_cols<'a, const N: usize>(
312    key_cols: &'a [&TermColumn],
313) -> Result<[&'a TermColumn; N], ExecError> {
314    key_cols.try_into().map_err(|_| {
315        ExecError::LengthMismatch(format!(
316            "semi-join expected {N} key columns, got {}",
317            key_cols.len()
318        ))
319    })
320}
321
322fn unbound3(c0: &TermColumn, c1: &TermColumn, c2: &TermColumn, row: usize) -> bool {
323    c0.id_at(row) == 0 || c1.id_at(row) == 0 || c2.id_at(row) == 0
324}
325
326fn unbound4(
327    c0: &TermColumn,
328    c1: &TermColumn,
329    c2: &TermColumn,
330    c3: &TermColumn,
331    row: usize,
332) -> bool {
333    c0.id_at(row) == 0 || c1.id_at(row) == 0 || c2.id_at(row) == 0 || c3.id_at(row) == 0
334}
335
336fn unbound_n(key_cols: &[&TermColumn], row: usize) -> bool {
337    key_cols.iter().any(|col| col.id_at(row) == 0)
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343    use crate::column::TermColumn;
344    use crate::term_dict::TermDict;
345    use waratah_storage::{EncodedTerm, NamedNode};
346
347    fn iri(local: &str) -> EncodedTerm {
348        EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap())
349    }
350
351    fn col(dict: &TermDict, terms: Vec<EncodedTerm>) -> TermColumn {
352        TermColumn::from_terms(dict, terms).unwrap()
353    }
354
355    #[test]
356    fn key_only_ht_drops_payload_and_unbound() {
357        let dict = TermDict::new();
358        let inner = TermBatch::try_new(vec![
359            col(&dict, vec![iri("a"), iri("b"), iri("a")]),
360            col(&dict, vec![iri("x"), iri("y"), iri("z")]),
361        ])
362        .unwrap();
363        let mut set = SemiJoinSet::new(1);
364        let key = [inner.column(0).unwrap()];
365        set.insert_batch(&inner, &key).unwrap();
366        assert_eq!(set.len(), 2);
367
368        let outer = TermBatch::try_new(vec![
369            TermColumn::from_optional_terms(
370                &dict,
371                vec![Some(iri("a")), Some(iri("c")), None, Some(iri("b"))],
372            )
373            .unwrap(),
374        ])
375        .unwrap();
376        let probe = [outer.column(0).unwrap()];
377        let exists = set.probe_keep(&outer, &probe, false).unwrap();
378        assert_eq!(exists, vec![0, 3]);
379        let not_exists = set.probe_keep(&outer, &probe, true).unwrap();
380        assert_eq!(not_exists, vec![1, 2]);
381    }
382}