Skip to main content

waratah_exec/
join.rs

1//! Vectorized hash join over [`TermBatch`] TermId columns.
2//!
3//! Production compute uses [`hash_join_columnar`]. Scalar [`hash_join`] shares
4//! the same TermId kernel (kept for parity tests).
5//!
6//! Both share the same high-level steps: validate args → (optional) hash build →
7//! probe → soft-column reconcile → gather output columns.
8
9use std::hash::{Hash, Hasher};
10
11use rustc_hash::{FxHashMap, FxHasher};
12
13use crate::ExecError;
14use crate::column::{TermBatch, TermColumn};
15
16/// Reserve ceiling for join bucket maps, in distinct-key entries: the
17/// full capacity of 2^17 hashbrown buckets (~4–8 MB per build across
18/// key arities). A bucket map is keyed by distinct key values, so the
19/// build side's row count is only a tight bound for near-unique keys;
20/// on skewed keys a rows-sized reserve over-allocates unboundedly, and
21/// the clamp falls back to normal doubling above the ceiling.
22const JOIN_BUILD_RESERVE_MAX: usize = (1 << 17) / 8 * 7;
23
24fn validate_join_args(
25    left_batch: &TermBatch,
26    right_batch: &TermBatch,
27    left_col_keys: &[usize],
28    right_col_keys: &[usize],
29    right_carry: &[usize],
30    soft_pairs: &[(usize, usize)],
31) -> Result<(), ExecError> {
32    // Check if the join key arity is the same
33    if left_col_keys.len() != right_col_keys.len() {
34        return Err(ExecError::LengthMismatch(format!(
35            "join key arity {} vs {}",
36            left_col_keys.len(),
37            right_col_keys.len()
38        )));
39    }
40    // Loading left table columns simply to bubble an error if the columns don't exist
41    for &i in left_col_keys {
42        let _ = left_batch.column(i)?;
43    }
44    // Loading right table columns simply to bubble an error if the columns don't exist
45    for &i in right_col_keys.iter().chain(right_carry.iter()) {
46        let _ = right_batch.column(i)?;
47    }
48    // Same check for soft-pair columns (shared maybe-unbound vars reconciled after hash)
49    for &(l, r) in soft_pairs {
50        let _ = left_batch.column(l)?;
51        let _ = right_batch.column(r)?;
52    }
53    Ok(())
54}
55
56fn check_u32_rows(left: &TermBatch, right: &TermBatch) -> Result<(), ExecError> {
57    if left.len() > u32::MAX as usize || right.len() > u32::MAX as usize {
58        return Err(ExecError::LengthMismatch(format!(
59            "join side has more than {} rows",
60            u32::MAX
61        )));
62    }
63    Ok(())
64}
65
66/// Hash-join `left` with `right` (TermId keys; kept as a named alias of the
67/// production kernel for parity tests).
68///
69/// Production compute uses [`hash_join_columnar`].
70///
71/// - `left_keys` / `right_keys`: column indices forming the equality key
72///   (same length; compared via TermId).
73/// - `right_carry`: right-side columns appended to the output (typically
74///   non-join columns). Left columns are always kept in order.
75/// - `soft_pairs`: shared columns that may be unbound on one side; reconciled
76///   after hard-key matches (SPARQL compatible mappings).
77/// - Empty keys → cartesian product (then soft reconcile).
78///
79/// The smaller side is the build side. Output row order follows the probe side.
80pub fn hash_join(
81    left_batch: &TermBatch,
82    right_batch: &TermBatch,
83    left_col_keys: &[usize],
84    right_col_keys: &[usize],
85    right_carry: &[usize],
86    soft_pairs: &[(usize, usize)],
87) -> Result<TermBatch, ExecError> {
88    hash_join_columnar(
89        left_batch,
90        right_batch,
91        left_col_keys,
92        right_col_keys,
93        right_carry,
94        soft_pairs,
95    )
96}
97
98/// Columnar hash-join: TermId equality, `u32` gather indexes.
99///
100///  RULE
101/// hash_join_columnar may only run when:
102///
103/// left.len() <= u32::MAX
104/// right.len() <= u32::MAX
105/// (and thus all gathered output index arrays stay UInt32)
106/// If either side is larger → don’t call it; chunk (or fall back / error) first.
107pub fn hash_join_columnar(
108    left_batch: &TermBatch,
109    right_batch: &TermBatch,
110    left_col_keys: &[usize],
111    right_col_keys: &[usize],
112    right_carry: &[usize],
113    soft_pairs: &[(usize, usize)],
114) -> Result<TermBatch, ExecError> {
115    validate_join_args(
116        left_batch,
117        right_batch,
118        left_col_keys,
119        right_col_keys,
120        right_carry,
121        soft_pairs,
122    )?;
123    check_u32_rows(left_batch, right_batch)?;
124
125    // Inner join of an empty side is always empty (schema still needs right_carry cols).
126    if left_batch.is_empty() || right_batch.is_empty() {
127        return empty_join_batch(left_batch, right_carry);
128    }
129
130    // If there are no join keys, nothing to join on,
131    // No common cols between the left and right tables,
132    // return the cartesian product of the two tables
133    if left_col_keys.is_empty() {
134        return cartesian(left_batch, right_batch, right_carry, soft_pairs);
135    }
136
137    // If left is smaller than right, build on left, otherwise build on right
138    let build_on_left = left_batch.len() <= right_batch.len();
139    dispatch_inner_join(
140        left_batch,
141        right_batch,
142        left_col_keys,
143        right_col_keys,
144        right_carry,
145        soft_pairs,
146        build_on_left,
147    )
148}
149
150fn dispatch_inner_join(
151    left_batch: &TermBatch,
152    right_batch: &TermBatch,
153    left_col_keys: &[usize],
154    right_col_keys: &[usize],
155    right_carry: &[usize],
156    soft_pairs: &[(usize, usize)],
157    build_on_left: bool,
158) -> Result<TermBatch, ExecError> {
159    match left_col_keys.len() {
160        1 => inner_join_with(
161            left_batch,
162            right_batch,
163            left_col_keys,
164            right_col_keys,
165            right_carry,
166            soft_pairs,
167            build_on_left,
168            key1,
169        ),
170        2 => inner_join_with(
171            left_batch,
172            right_batch,
173            left_col_keys,
174            right_col_keys,
175            right_carry,
176            soft_pairs,
177            build_on_left,
178            key2,
179        ),
180        3 => inner_join_with(
181            left_batch,
182            right_batch,
183            left_col_keys,
184            right_col_keys,
185            right_carry,
186            soft_pairs,
187            build_on_left,
188            key3,
189        ),
190        4 => inner_join_with(
191            left_batch,
192            right_batch,
193            left_col_keys,
194            right_col_keys,
195            right_carry,
196            soft_pairs,
197            build_on_left,
198            key4,
199        ),
200        5..=8 => inner_join_with(
201            left_batch,
202            right_batch,
203            left_col_keys,
204            right_col_keys,
205            right_carry,
206            soft_pairs,
207            build_on_left,
208            key8,
209        ),
210        arity => Err(ExecError::JoinKeyTooWide { arity }),
211    }
212}
213
214#[allow(clippy::too_many_arguments)]
215fn inner_join_with<K, F>(
216    left_batch: &TermBatch,
217    right_batch: &TermBatch,
218    left_col_keys: &[usize],
219    right_col_keys: &[usize],
220    right_carry: &[usize],
221    soft_pairs: &[(usize, usize)],
222    build_on_left: bool,
223    extract: F,
224) -> Result<TermBatch, ExecError>
225where
226    K: Copy + Eq + Hash,
227    F: Fn(&TermBatch, &[usize], usize) -> Result<Option<K>, ExecError>,
228{
229    let (build, build_col_keys, probe, probe_col_keys) = if build_on_left {
230        // build on left, probe on right
231        (left_batch, left_col_keys, right_batch, right_col_keys)
232    } else {
233        // build on right, probe on left
234        (right_batch, right_col_keys, left_batch, left_col_keys)
235    };
236
237    // Create a bucket hashtable
238    // a hashmap to store the joining TermId (or TermId tuple)
239    // and the rows that share that key for the build side.
240    // Bucket count is bounded by build rows — at most one entry per
241    // distinct key — so reserving up front keeps hashbrown's doubling
242    // re-inserts out of every join build; the reserve clamps at
243    // `JOIN_BUILD_RESERVE_MAX` so skewed keys (few distinct values)
244    // cannot over-allocate.
245    let mut buckets: FxHashMap<K, Vec<u32>> = FxHashMap::with_capacity_and_hasher(
246        build.len().min(JOIN_BUILD_RESERVE_MAX),
247        Default::default(),
248    );
249    for build_row_idx in 0..build.len() {
250        // Skip unbound hard-key rows; they can never match on the probe side either
251        let Some(key) = extract(build, build_col_keys, build_row_idx)? else {
252            continue;
253        };
254        buckets.entry(key).or_default().push(build_row_idx as u32);
255    }
256    // Every build row had an unbound key → nothing can match → empty result
257    if buckets.is_empty() {
258        return empty_join_batch(left_batch, right_carry);
259    }
260
261    // Parallel u32 index lists: output row i is left_indices[i] ⋈ right_indices[i]
262    let mut left_indices = Vec::new();
263    let mut right_indices = Vec::new();
264    for probe_row_idx in 0..probe.len() {
265        let Some(compare_key) = extract(probe, probe_col_keys, probe_row_idx)? else {
266            continue;
267        };
268        // Get the rows from build-side that share the same TermId key as the probe row
269        let Some(matches) = buckets.get(&compare_key) else {
270            // This key is not in the build side, so we don't use this probe-side row.
271            continue;
272        };
273        for &build_match_row_idx in matches {
274            // Remap (build, probe) back to (left, right) depending on which side we built
275            let (l, r) = if build_on_left {
276                (build_match_row_idx, probe_row_idx as u32)
277            } else {
278                (probe_row_idx as u32, build_match_row_idx)
279            };
280            left_indices.push(l);
281            right_indices.push(r);
282        }
283    }
284
285    // Soft reconcile: drop candidate pairs that conflict on maybe-unbound shared cols
286    let (left_indices, right_indices) = filter_soft_compatible_u32(
287        left_batch,
288        right_batch,
289        left_indices,
290        right_indices,
291        soft_pairs,
292    )?;
293    gather_join_output_u32(
294        left_batch,
295        right_batch,
296        &left_indices,
297        &right_indices,
298        right_carry,
299        soft_pairs,
300    )
301}
302
303/// Every left row paired with every right row (no hard keys).
304/// Soft pairs still filter and coalesce afterwards.
305fn cartesian(
306    left: &TermBatch,
307    right: &TermBatch,
308    right_carry: &[usize],
309    soft_pairs: &[(usize, usize)],
310) -> Result<TermBatch, ExecError> {
311    if left.is_empty() || right.is_empty() {
312        return empty_join_batch(left, right_carry);
313    }
314    // Nested loops: for each left row, emit one candidate with every right row
315    let mut left_indices = Vec::with_capacity(left.len() * right.len());
316    let mut right_indices = Vec::with_capacity(left.len() * right.len());
317    for l in 0..left.len() as u32 {
318        for r in 0..right.len() as u32 {
319            left_indices.push(l);
320            right_indices.push(r);
321        }
322    }
323    let (left_indices, right_indices) =
324        filter_soft_compatible_u32(left, right, left_indices, right_indices, soft_pairs)?;
325    gather_join_output_u32(
326        left,
327        right,
328        &left_indices,
329        &right_indices,
330        right_carry,
331        soft_pairs,
332    )
333}
334
335/// Resume point while probing the left batch against a right-side hash table.
336///
337/// OpenNode / eager chunk joins interpret caller `n` as max **output** rows.
338/// `probe_row` is the next left row; `match_offset` is how many matching
339/// right rows of that left row have already been emitted. For a cartesian
340/// (empty hard keys), `match_offset` is the next right row index.
341#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
342pub struct JoinCursor {
343    /// Next left (probe) row to consider.
344    pub probe_row: usize,
345    /// Offset into the current left row's match list (or next right row
346    /// for cartesian).
347    pub match_offset: usize,
348}
349
350/// Right-side hash table for a capped inner join.
351///
352/// Built once per left×right pair via [`hash_join_build`]. [`JoinCursor`] only
353/// stores probe coordinates so it stays `Copy`. Drop this when the build
354/// relation is replaced (new allow-listed right) or the OpenNode dies — not
355/// between output pages of the same probe.
356///
357/// [`JoinBuild::right_rows`] records the row count of the relation the
358/// table was built over, and [`hash_join_columnar_capped`] debug-asserts
359/// the probe-side `right_batch` matches it: a caller reusing the slot
360/// against a DIFFERENT right relation (the star's verdict-flip shape — a
361/// page-filtered table probed with a whole-arm hash) fails loudly in
362/// debug runs instead of silently reading row ids from the wrong
363/// relation. Row count, not pointer identity: the `Arc` identity is lost
364/// at this crate boundary, and a length mismatch catches the whole
365/// observed bug class (a filtered subset of a built arm has a different
366/// length by construction).
367#[derive(Debug)]
368pub struct JoinBuild {
369    /// Rows in the right relation this table was built over (see the
370    /// type doc — the reuse guard).
371    right_rows: usize,
372    table: JoinTable,
373}
374
375#[derive(Debug)]
376enum JoinTable {
377    /// Cartesian (no hard keys), or every right hard key was unbound.
378    Empty,
379    /// One equality column.
380    Key1(BuildStore<u32>),
381    /// Two equality columns.
382    Key2(BuildStore<(u32, u32)>),
383    /// Three equality columns.
384    Key3(BuildStore<(u32, u32, u32)>),
385    /// Four equality columns.
386    Key4(BuildStore<(u32, u32, u32, u32)>),
387    /// Five to eight equality columns (`[u32; 8]` padded).
388    Key8(BuildStore<[u32; 8]>),
389}
390
391/// One arity's key → match-list storage, in either layout.
392///
393/// Both variants answer [`BuildStore::get`] with a slice of right-row ids
394/// in ASCENDING row order, which is the only contract the emission-bounded
395/// probe loop (`inner_join_capped_with`) relies on: the same loop serves
396/// both layouts, so they cannot diverge in emission order or cursor
397/// semantics — only in where the bytes live.
398#[derive(Debug)]
399enum BuildStore<K> {
400    /// `FxHashMap<key, Vec<u32>>` — one heap chunk per distinct key. The
401    /// original layout; default ([`JoinTableMode::Map`]).
402    Map(FxHashMap<K, Vec<u32>>),
403    /// Count-then-fill CSR — all ids in one flat array ([`JoinTableMode::Csr`]).
404    Csr(CsrBuild<K>),
405}
406
407impl<K> BuildStore<K> {
408    /// Whether zero distinct bound keys exist (parity with the map layout's
409    /// `wrap_build` emptiness check — an all-unbound or empty build).
410    /// Deliberately free of `K` bounds: it reads only container lengths,
411    /// so `wrap_build` stays generic the way it always was.
412    fn is_empty(&self) -> bool {
413        match self {
414            BuildStore::Map(map) => map.is_empty(),
415            BuildStore::Csr(csr) => csr.bucket_count() == 0,
416        }
417    }
418}
419
420impl<K> BuildStore<K>
421where
422    K: Copy + Eq + Hash,
423{
424    /// The right-row ids matching `key`, ascending; `None` when no bound
425    /// right row carried this key.
426    fn get(&self, key: &K) -> Option<&[u32]> {
427        match self {
428            BuildStore::Map(map) => map.get(key).map(Vec::as_slice),
429            BuildStore::Csr(csr) => csr.get(key),
430        }
431    }
432}
433
434/// Count-then-fill CSR (compressed sparse row) join table over one build
435/// relation — the default flat layout for join builds
436/// ([`JoinTableMode::Csr`]), replacing the map-of-`Vec` buckets.
437///
438/// Layout: `row_ids` holds every bound-key right-row id in ONE contiguous
439/// array, grouped by key; `offsets[b]..offsets[b+1]` slices bucket `b`'s
440/// ids out of it; `index` maps each distinct key to its bucket number. A
441/// build with D distinct keys and R bound rows costs roughly `index map
442/// (K + 4 B per slot) + 4·D B of offsets + 4·R B of row ids` — the map
443/// layout instead pays a 24-byte `Vec` header per map slot plus a
444/// separate heap chunk per distinct key (a 16-byte request the allocator
445/// rounds to its 32-byte minimum), so at millions of keys CSR removes
446/// hundreds of MB and D individual allocations that each fragment the
447/// heap and are freed one by one on drop.
448///
449/// Build is two linear passes with ONE hash per row (the map path hashes
450/// once per row too, in `fill_buckets`' `entry` call):
451///
452/// * Pass 1 assigns each distinct key a dense bucket number while counting
453///   its rows, and records each row's bucket in a temporary `row_bucket`
454///   array (`UNBOUND_ROW` marks an unbound-key row — it can never match
455///   and is excluded, exactly as `fill_buckets` skips it).
456/// * A prefix sum of the counts becomes `offsets`; a copy of it becomes
457///   the per-bucket write cursors.
458/// * Pass 2 walks the rows again in index order and scatters each id into
459///   its bucket's slice. Rows are visited ascending and each bucket's
460///   slice fills left to right, so the ids within a bucket are ASCENDING —
461///   byte-for-byte the order `fill_buckets` produces by pushing in row
462///   order. The probe loop cannot observe which layout built its slices.
463///
464/// `index` remains a hash map: keys must live somewhere for O(1) probes,
465/// and a 4-byte bucket number is the smallest mapped value that can be.
466/// (Sorting the keys and binary-searching would drop the map — ~12 B/key —
467/// at `log2(D)` scattered reads per probe; with millions of probes per
468/// query, the O(1) map is the right side of that trade.)
469#[derive(Debug)]
470struct CsrBuild<K> {
471    /// Distinct join key → dense bucket index (`0..bucket_count()`).
472    index: FxHashMap<K, u32>,
473    /// `bucket i`'s ids are `row_ids[offsets[i]..offsets[i+1]]`;
474    /// length is bucket count + 1.
475    offsets: Vec<u32>,
476    /// Every bound-key right-row id, grouped by bucket, ascending within
477    /// each bucket (see the type doc's pass-2 argument).
478    row_ids: Vec<u32>,
479}
480
481/// Sentinel for pass 1's per-row bucket record: an unbound-key right row.
482/// A real bucket index is `< right row count ≤ u32::MAX`, and there are
483/// at most that many buckets, so `u32::MAX` cannot collide with a real
484/// index for any build this crate accepts (the `u32::MAX` row-count gate
485/// in [`hash_join_build_with`] is what makes that airtight).
486const UNBOUND_ROW: u32 = u32::MAX;
487
488impl<K> CsrBuild<K> {
489    fn bucket_count(&self) -> usize {
490        self.offsets.len().saturating_sub(1)
491    }
492}
493
494impl<K> CsrBuild<K>
495where
496    K: Copy + Eq + Hash,
497{
498    fn build<F>(
499        right_batch: &TermBatch,
500        right_col_keys: &[usize],
501        extract: F,
502    ) -> Result<Self, ExecError>
503    where
504        F: Fn(&TermBatch, &[usize], usize) -> Result<Option<K>, ExecError>,
505    {
506        // Same reserve policy as `fill_buckets`: rows bound the key count
507        // only for near-unique keys, so clamp against skew and let the map
508        // double above the ceiling.
509        let mut index: FxHashMap<K, u32> = FxHashMap::with_capacity_and_hasher(
510            right_batch.len().min(JOIN_BUILD_RESERVE_MAX),
511            Default::default(),
512        );
513        let mut counts: Vec<u32> = Vec::new();
514        let mut row_bucket: Vec<u32> = Vec::with_capacity(right_batch.len());
515        for row in 0..right_batch.len() {
516            let Some(key) = extract(right_batch, right_col_keys, row)? else {
517                row_bucket.push(UNBOUND_ROW);
518                continue;
519            };
520            // `next_bucket` is the id a first-seen key would take; a key
521            // already present always holds a smaller one (assigned when
522            // `counts` was shorter), so equality means "inserted now".
523            let next_bucket = counts.len() as u32;
524            let bucket = *index.entry(key).or_insert(next_bucket);
525            if bucket == next_bucket {
526                counts.push(1);
527            } else {
528                counts[bucket as usize] += 1;
529            }
530            row_bucket.push(bucket);
531        }
532        // Prefix sum → offsets. `total` equals the bound-row count, which
533        // the row-count gate holds at or below u32::MAX, so the additions
534        // cannot overflow (debug builds still check).
535        let mut offsets: Vec<u32> = Vec::with_capacity(counts.len() + 1);
536        let mut total: u32 = 0;
537        offsets.push(0);
538        for &count in &counts {
539            total += count;
540            offsets.push(total);
541        }
542        // Scatter pass: write cursors start at each bucket's offset.
543        let mut cursors = offsets.clone();
544        let mut row_ids: Vec<u32> = vec![0; total as usize];
545        for (row, &bucket) in row_bucket.iter().enumerate() {
546            if bucket == UNBOUND_ROW {
547                continue;
548            }
549            let b = bucket as usize;
550            debug_assert!(
551                cursors[b] < offsets[b + 1],
552                "csr bucket {b} overfilled: pass-1 count disagrees with pass-2 scatter"
553            );
554            row_ids[cursors[b] as usize] = row as u32;
555            cursors[b] += 1;
556        }
557        debug_assert!(
558            cursors
559                .iter()
560                .zip(offsets.iter().skip(1))
561                .all(|(&cursor, &end)| cursor == end),
562            "csr scatter must fill every bucket exactly"
563        );
564        Ok(CsrBuild {
565            index,
566            offsets,
567            row_ids,
568        })
569    }
570
571    fn get(&self, key: &K) -> Option<&[u32]> {
572        let bucket = *self.index.get(key)?;
573        let start = self.offsets[bucket as usize] as usize;
574        let end = self.offsets[bucket as usize + 1] as usize;
575        Some(&self.row_ids[start..end])
576    }
577}
578
579/// Which backing layout [`hash_join_build_with`] constructs, selected
580/// process-wide by `WARATAH_JOIN_TABLE=map|csr` (default `csr` since the
581/// A/B concluded; `map` remains selectable for bisects and layout A/Bs).
582/// The switch governs only the threaded/emission-bounded [`JoinBuild`]
583/// path; `hash_join_columnar`'s per-call internal maps and the shuffle
584/// kernel's per-bucket maps are out of scope.
585#[derive(Debug, Clone, Copy, PartialEq, Eq)]
586pub enum JoinTableMode {
587    /// `FxHashMap<key, Vec<u32>>` buckets — the original layout, now the
588    /// opt-in alternative behind `WARATAH_JOIN_TABLE=map`.
589    Map,
590    /// Count-then-fill CSR — one flat `row_ids` array (see [`CsrBuild`]);
591    /// the default layout.
592    Csr,
593}
594
595/// Parse a `WARATAH_JOIN_TABLE` value: `map` or `csr`, case-insensitive,
596/// surrounding whitespace tolerated. `None` for anything else.
597pub fn parse_join_table_mode(raw: &str) -> Option<JoinTableMode> {
598    match raw.trim().to_ascii_lowercase().as_str() {
599        "map" => Some(JoinTableMode::Map),
600        "csr" => Some(JoinTableMode::Csr),
601        _ => None,
602    }
603}
604
605/// The process-wide join-build layout, read from `WARATAH_JOIN_TABLE`
606/// once (the first join build) and cached. An unrecognized value warns
607/// once on stderr and falls back to `csr`, so a typo can never select an
608/// unintended layout.
609fn join_table_mode() -> JoinTableMode {
610    static MODE: std::sync::OnceLock<JoinTableMode> = std::sync::OnceLock::new();
611    *MODE.get_or_init(|| {
612        match std::env::var("WARATAH_JOIN_TABLE") {
613            Ok(raw) => match parse_join_table_mode(&raw) {
614                Some(mode) => mode,
615                None => {
616                    eprintln!(
617                        "waratah: WARATAH_JOIN_TABLE={raw:?} not recognized (expected 'map' or 'csr'); using 'csr'"
618                    );
619                    JoinTableMode::Csr
620                }
621            },
622            Err(_) => JoinTableMode::Csr,
623        }
624    })
625}
626
627/// Build a right-side hash table for [`hash_join_columnar_capped`],
628/// using the process-wide layout from `WARATAH_JOIN_TABLE` (default
629/// `csr`; see [`JoinTableMode`]).
630///
631/// Empty `right_col_keys` (cartesian) or a right whose keys are all unbound
632/// yield [`JoinBuild::Empty`]. The HT lives for the life of this left×right
633/// pair; drop it when the build relation is replaced or the OpenNode dies.
634pub fn hash_join_build(
635    right_batch: &TermBatch,
636    right_col_keys: &[usize],
637) -> Result<JoinBuild, ExecError> {
638    hash_join_build_with(right_batch, right_col_keys, join_table_mode())
639}
640
641/// [`hash_join_build`] with an explicit layout — the deterministic entry
642/// point for A/B tests; production goes through the env-var default.
643pub fn hash_join_build_with(
644    right_batch: &TermBatch,
645    right_col_keys: &[usize],
646    mode: JoinTableMode,
647) -> Result<JoinBuild, ExecError> {
648    if right_batch.len() > u32::MAX as usize {
649        return Err(ExecError::LengthMismatch(format!(
650            "join side has more than {} rows",
651            u32::MAX
652        )));
653    }
654    for &i in right_col_keys {
655        let _ = right_batch.column(i)?;
656    }
657    if right_col_keys.is_empty() {
658        return Ok(JoinBuild::empty(right_batch.len()));
659    }
660    match right_col_keys.len() {
661        1 => Ok(wrap_build(
662            right_batch.len(),
663            build_store(right_batch, right_col_keys, mode, key1)?,
664            JoinTable::Key1,
665        )),
666        2 => Ok(wrap_build(
667            right_batch.len(),
668            build_store(right_batch, right_col_keys, mode, key2)?,
669            JoinTable::Key2,
670        )),
671        3 => Ok(wrap_build(
672            right_batch.len(),
673            build_store(right_batch, right_col_keys, mode, key3)?,
674            JoinTable::Key3,
675        )),
676        4 => Ok(wrap_build(
677            right_batch.len(),
678            build_store(right_batch, right_col_keys, mode, key4)?,
679            JoinTable::Key4,
680        )),
681        5..=8 => Ok(wrap_build(
682            right_batch.len(),
683            build_store(right_batch, right_col_keys, mode, key8)?,
684            JoinTable::Key8,
685        )),
686        arity => Err(ExecError::JoinKeyTooWide { arity }),
687    }
688}
689
690/// Build one arity's [`BuildStore`] in the requested layout. The two
691/// constructors take the same extractor; only the storage differs.
692fn build_store<K, F>(
693    right_batch: &TermBatch,
694    right_col_keys: &[usize],
695    mode: JoinTableMode,
696    extract: F,
697) -> Result<BuildStore<K>, ExecError>
698where
699    K: Copy + Eq + Hash,
700    F: Fn(&TermBatch, &[usize], usize) -> Result<Option<K>, ExecError>,
701{
702    Ok(match mode {
703        JoinTableMode::Map => BuildStore::Map(fill_buckets(right_batch, right_col_keys, extract)?),
704        JoinTableMode::Csr => {
705            BuildStore::Csr(CsrBuild::build(right_batch, right_col_keys, extract)?)
706        }
707    })
708}
709
710fn wrap_build<K>(
711    right_rows: usize,
712    store: BuildStore<K>,
713    variant: impl FnOnce(BuildStore<K>) -> JoinTable,
714) -> JoinBuild {
715    if store.is_empty() {
716        JoinBuild::empty(right_rows)
717    } else {
718        JoinBuild {
719            right_rows,
720            table: variant(store),
721        }
722    }
723}
724
725fn fill_buckets<K, F>(
726    right_batch: &TermBatch,
727    right_col_keys: &[usize],
728    extract: F,
729) -> Result<FxHashMap<K, Vec<u32>>, ExecError>
730where
731    K: Copy + Eq + Hash,
732    F: Fn(&TermBatch, &[usize], usize) -> Result<Option<K>, ExecError>,
733{
734    // Bucket count is bounded by build rows — at most one entry per
735    // distinct key — so reserving up front keeps hashbrown's doubling
736    // re-inserts out of every join build; the reserve clamps at
737    // `JOIN_BUILD_RESERVE_MAX` so skewed keys (few distinct values)
738    // cannot over-allocate.
739    let mut buckets: FxHashMap<K, Vec<u32>> = FxHashMap::with_capacity_and_hasher(
740        right_batch.len().min(JOIN_BUILD_RESERVE_MAX),
741        Default::default(),
742    );
743    for build_row_idx in 0..right_batch.len() {
744        // Skip unbound hard-key rows; they can never match on the probe side either
745        let Some(key) = extract(right_batch, right_col_keys, build_row_idx)? else {
746            continue;
747        };
748        buckets.entry(key).or_default().push(build_row_idx as u32);
749    }
750    Ok(buckets)
751}
752
753fn join_build_arity_mismatch(arity: usize, build: &JoinBuild) -> ExecError {
754    let got = match &build.table {
755        JoinTable::Empty => "Empty",
756        JoinTable::Key1(_) => "Key1",
757        JoinTable::Key2(_) => "Key2",
758        JoinTable::Key3(_) => "Key3",
759        JoinTable::Key4(_) => "Key4",
760        JoinTable::Key8(_) => "Key8",
761    };
762    ExecError::LengthMismatch(format!("JoinBuild {got} vs key arity {arity}"))
763}
764
765impl JoinBuild {
766    /// The cartesian / all-keys-unbound table (the map is empty, but the
767    /// right relation's row count is still recorded for the reuse guard).
768    fn empty(right_rows: usize) -> Self {
769        Self {
770            right_rows,
771            table: JoinTable::Empty,
772        }
773    }
774}
775
776/// Inner join that probes the left against a pre-built right HT, emitting at
777/// most `max_out` rows starting at `cursor`.
778///
779/// Returns the output page and the next cursor (`None` = this left×right pair
780/// is exhausted). Peak index-list length is `max_out` (or `max_out` plus the
781/// rest of the current bucket if a soft-incompatible pair is skipped inside
782/// the gather cap — we skip those without counting).
783///
784/// Unlike [`hash_join_columnar`], this does **not** pick the smaller side as
785/// build: demand-driven joins keep a stable left-row cursor. `right_batch`
786/// is still required for gather and soft-pair checks; the map only stores
787/// right row ids.
788#[allow(clippy::too_many_arguments)]
789pub fn hash_join_columnar_capped(
790    left_batch: &TermBatch,
791    right_batch: &TermBatch,
792    left_col_keys: &[usize],
793    right_col_keys: &[usize],
794    right_carry: &[usize],
795    soft_pairs: &[(usize, usize)],
796    max_out: usize,
797    cursor: JoinCursor,
798    build: &JoinBuild,
799) -> Result<(TermBatch, Option<JoinCursor>), ExecError> {
800    validate_join_args(
801        left_batch,
802        right_batch,
803        left_col_keys,
804        right_col_keys,
805        right_carry,
806        soft_pairs,
807    )?;
808    check_u32_rows(left_batch, right_batch)?;
809
810    if max_out == 0 || left_batch.is_empty() || right_batch.is_empty() {
811        return Ok((empty_join_batch(left_batch, right_carry)?, None));
812    }
813    if left_col_keys.is_empty() {
814        return cartesian_capped(
815            left_batch,
816            right_batch,
817            right_carry,
818            soft_pairs,
819            max_out,
820            cursor,
821        );
822    }
823    // Reuse guard (see the `JoinBuild` doc): the slot's table was built
824    // over exactly `right_rows` rows of ONE relation; probing it with a
825    // different relation's batch reads bucket row ids from the wrong
826    // table. Debug builds fail loudly; release builds proceed (the
827    // call-site identity gates are the production guard).
828    debug_assert_eq!(
829        build.right_rows,
830        right_batch.len(),
831        "join build slot reused against a different right relation (built over {} rows, probing {}): stale hash table",
832        build.right_rows,
833        right_batch.len(),
834    );
835    match (left_col_keys.len(), &build.table) {
836        (_, JoinTable::Empty) => Ok((empty_join_batch(left_batch, right_carry)?, None)),
837        (1, JoinTable::Key1(store)) => inner_join_capped_with(
838            left_batch,
839            right_batch,
840            left_col_keys,
841            right_carry,
842            soft_pairs,
843            max_out,
844            cursor,
845            store,
846            key1,
847        ),
848        (2, JoinTable::Key2(store)) => inner_join_capped_with(
849            left_batch,
850            right_batch,
851            left_col_keys,
852            right_carry,
853            soft_pairs,
854            max_out,
855            cursor,
856            store,
857            key2,
858        ),
859        (3, JoinTable::Key3(store)) => inner_join_capped_with(
860            left_batch,
861            right_batch,
862            left_col_keys,
863            right_carry,
864            soft_pairs,
865            max_out,
866            cursor,
867            store,
868            key3,
869        ),
870        (4, JoinTable::Key4(store)) => inner_join_capped_with(
871            left_batch,
872            right_batch,
873            left_col_keys,
874            right_carry,
875            soft_pairs,
876            max_out,
877            cursor,
878            store,
879            key4,
880        ),
881        (5..=8, JoinTable::Key8(store)) => inner_join_capped_with(
882            left_batch,
883            right_batch,
884            left_col_keys,
885            right_carry,
886            soft_pairs,
887            max_out,
888            cursor,
889            store,
890            key8,
891        ),
892        (arity @ 1..=8, _) => Err(join_build_arity_mismatch(arity, build)),
893        (arity, _) => Err(ExecError::JoinKeyTooWide { arity }),
894    }
895}
896
897#[allow(clippy::too_many_arguments)]
898fn inner_join_capped_with<K, F>(
899    left_batch: &TermBatch,
900    right_batch: &TermBatch,
901    left_col_keys: &[usize],
902    right_carry: &[usize],
903    soft_pairs: &[(usize, usize)],
904    max_out: usize,
905    cursor: JoinCursor,
906    store: &BuildStore<K>,
907    extract: F,
908) -> Result<(TermBatch, Option<JoinCursor>), ExecError>
909where
910    K: Copy + Eq + Hash,
911    F: Fn(&TermBatch, &[usize], usize) -> Result<Option<K>, ExecError>,
912{
913    let mut left_indices = Vec::new();
914    let mut right_indices = Vec::new();
915    let mut probe_row = cursor.probe_row;
916    let mut match_offset = cursor.match_offset;
917    if probe_row >= left_batch.len() {
918        return Ok((empty_join_batch(left_batch, right_carry)?, None));
919    }
920
921    while probe_row < left_batch.len() && left_indices.len() < max_out {
922        let Some(compare_key) = extract(left_batch, left_col_keys, probe_row)? else {
923            probe_row += 1;
924            match_offset = 0;
925            continue;
926        };
927        let Some(matches) = store.get(&compare_key) else {
928            probe_row += 1;
929            match_offset = 0;
930            continue;
931        };
932        while match_offset < matches.len() && left_indices.len() < max_out {
933            let build_match_row_idx = matches[match_offset];
934            match_offset += 1;
935            if soft_pair_compatible(
936                left_batch,
937                right_batch,
938                probe_row,
939                build_match_row_idx as usize,
940                soft_pairs,
941            )? {
942                left_indices.push(probe_row as u32);
943                right_indices.push(build_match_row_idx);
944            }
945        }
946        if match_offset < matches.len() {
947            let page = gather_join_output_u32(
948                left_batch,
949                right_batch,
950                &left_indices,
951                &right_indices,
952                right_carry,
953                soft_pairs,
954            )?;
955            return Ok((
956                page,
957                Some(JoinCursor {
958                    probe_row,
959                    match_offset,
960                }),
961            ));
962        }
963        probe_row += 1;
964        match_offset = 0;
965    }
966
967    let page = gather_join_output_u32(
968        left_batch,
969        right_batch,
970        &left_indices,
971        &right_indices,
972        right_carry,
973        soft_pairs,
974    )?;
975    let next = if probe_row >= left_batch.len() {
976        None
977    } else {
978        Some(JoinCursor {
979            probe_row,
980            match_offset: 0,
981        })
982    };
983    Ok((page, next))
984}
985
986fn cartesian_capped(
987    left: &TermBatch,
988    right: &TermBatch,
989    right_carry: &[usize],
990    soft_pairs: &[(usize, usize)],
991    max_out: usize,
992    cursor: JoinCursor,
993) -> Result<(TermBatch, Option<JoinCursor>), ExecError> {
994    let mut left_indices = Vec::new();
995    let mut right_indices = Vec::new();
996    let mut l = cursor.probe_row;
997    let mut r = cursor.match_offset;
998    if l >= left.len() {
999        return Ok((empty_join_batch(left, right_carry)?, None));
1000    }
1001    while l < left.len() && left_indices.len() < max_out {
1002        while r < right.len() && left_indices.len() < max_out {
1003            if soft_pair_compatible(left, right, l, r, soft_pairs)? {
1004                left_indices.push(l as u32);
1005                right_indices.push(r as u32);
1006            }
1007            r += 1;
1008        }
1009        if r < right.len() {
1010            let page = gather_join_output_u32(
1011                left,
1012                right,
1013                &left_indices,
1014                &right_indices,
1015                right_carry,
1016                soft_pairs,
1017            )?;
1018            return Ok((
1019                page,
1020                Some(JoinCursor {
1021                    probe_row: l,
1022                    match_offset: r,
1023                }),
1024            ));
1025        }
1026        l += 1;
1027        r = 0;
1028    }
1029    let page = gather_join_output_u32(
1030        left,
1031        right,
1032        &left_indices,
1033        &right_indices,
1034        right_carry,
1035        soft_pairs,
1036    )?;
1037    let next = if l >= left.len() {
1038        None
1039    } else {
1040        Some(JoinCursor {
1041            probe_row: l,
1042            match_offset: 0,
1043        })
1044    };
1045    Ok((page, next))
1046}
1047
1048/// Zero-row result with the same column layout as a successful join
1049/// (all left cols + one empty col per right_carry index).
1050fn empty_join_batch(left: &TermBatch, right_carry: &[usize]) -> Result<TermBatch, ExecError> {
1051    let mut cols: Vec<TermColumn> = left.columns().iter().map(|_| TermColumn::empty()).collect();
1052    for _ in right_carry {
1053        cols.push(TermColumn::empty());
1054    }
1055    TermBatch::try_new(cols)
1056}
1057
1058/// SPARQL-style soft-column check for one candidate pair.
1059///
1060/// Keep the pair when, for every soft shared column:
1061/// - either side is unbound, or
1062/// - both are bound and the TermIds are equal.
1063///
1064/// Reject only when both are bound and disagree.
1065fn soft_pair_compatible(
1066    left: &TermBatch,
1067    right: &TermBatch,
1068    left_row: usize,
1069    right_row: usize,
1070    soft_pairs: &[(usize, usize)],
1071) -> Result<bool, ExecError> {
1072    for &(l, r) in soft_pairs {
1073        let lid = left.column(l)?.id_at(left_row);
1074        let rid = right.column(r)?.id_at(right_row);
1075        match (lid, rid) {
1076            // One or both unbound → compatible (the bound side fills in at gather)
1077            (0, _) | (_, 0) => {}
1078            (a, b) if a == b => {}
1079            // Both bound, different values → conflict
1080            _ => return Ok(false),
1081        }
1082    }
1083    Ok(true)
1084}
1085
1086/// Drop hard-key candidate pairs that fail soft reconcile.
1087/// Fast path: empty soft_pairs means keep every candidate as-is.
1088fn filter_soft_compatible_u32(
1089    left: &TermBatch,
1090    right: &TermBatch,
1091    left_indices: Vec<u32>,
1092    right_indices: Vec<u32>,
1093    soft_pairs: &[(usize, usize)],
1094) -> Result<(Vec<u32>, Vec<u32>), ExecError> {
1095    if soft_pairs.is_empty() {
1096        return Ok((left_indices, right_indices));
1097    }
1098    let mut out_l = Vec::with_capacity(left_indices.len());
1099    let mut out_r = Vec::with_capacity(right_indices.len());
1100    for (&l, &r) in left_indices.iter().zip(right_indices.iter()) {
1101        if soft_pair_compatible(left, right, l as usize, r as usize, soft_pairs)? {
1102            out_l.push(l);
1103            out_r.push(r);
1104        }
1105    }
1106    Ok((out_l, out_r))
1107}
1108
1109/// Build the output TermBatch from parallel left/right index lists.
1110///
1111/// - Normal left cols: gather by left_indices
1112/// - Soft shared cols: coalesce left-if-bound else right (fills OPTIONAL holes)
1113/// - right_carry cols: gather by right_indices
1114fn gather_join_output_u32(
1115    left: &TermBatch,
1116    right: &TermBatch,
1117    left_indices: &[u32],
1118    right_indices: &[u32],
1119    right_carry: &[usize],
1120    soft_pairs: &[(usize, usize)],
1121) -> Result<TermBatch, ExecError> {
1122    // Create a new TermBatch to store the output columns
1123    // The mechanism is take all cols from the left batch, filter rows by left_indices,
1124    // then take the cols from the right batch, filtered rows by right_indices,
1125    // and then concatenate the columns together.
1126    // Soft shared cols coalesce (left if bound, else right) instead of a plain take.
1127    let mut out_cols = Vec::with_capacity(left.width() + right_carry.len());
1128    for (col_idx, col) in left.columns().iter().enumerate() {
1129        if let Some((_, right_col)) = soft_pairs.iter().find(|(l, _)| *l == col_idx) {
1130            out_cols.push(col.gather_coalesce(
1131                left_indices,
1132                right.column(*right_col)?,
1133                right_indices,
1134            )?);
1135        } else {
1136            out_cols.push(col.gather_take(left_indices));
1137        }
1138    }
1139    // Right-only columns (not join keys, not soft shared) appended in carry order
1140    for &c in right_carry {
1141        out_cols.push(right.column(c)?.gather_take(right_indices));
1142    }
1143    TermBatch::try_new(out_cols)
1144}
1145
1146fn key1(batch: &TermBatch, keys: &[usize], row: usize) -> Result<Option<u32>, ExecError> {
1147    let id = batch.column(keys[0])?.id_at(row);
1148    // Unbound join keys do not match (including other unbounds).
1149    Ok(if id == 0 { None } else { Some(id) })
1150}
1151
1152fn key2(batch: &TermBatch, keys: &[usize], row: usize) -> Result<Option<(u32, u32)>, ExecError> {
1153    let a = batch.column(keys[0])?.id_at(row);
1154    let b = batch.column(keys[1])?.id_at(row);
1155    Ok(if a == 0 || b == 0 { None } else { Some((a, b)) })
1156}
1157
1158fn key3(
1159    batch: &TermBatch,
1160    keys: &[usize],
1161    row: usize,
1162) -> Result<Option<(u32, u32, u32)>, ExecError> {
1163    let a = batch.column(keys[0])?.id_at(row);
1164    let b = batch.column(keys[1])?.id_at(row);
1165    let c = batch.column(keys[2])?.id_at(row);
1166    Ok(if a == 0 || b == 0 || c == 0 {
1167        None
1168    } else {
1169        Some((a, b, c))
1170    })
1171}
1172
1173fn key4(
1174    batch: &TermBatch,
1175    keys: &[usize],
1176    row: usize,
1177) -> Result<Option<(u32, u32, u32, u32)>, ExecError> {
1178    let a = batch.column(keys[0])?.id_at(row);
1179    let b = batch.column(keys[1])?.id_at(row);
1180    let c = batch.column(keys[2])?.id_at(row);
1181    let d = batch.column(keys[3])?.id_at(row);
1182    Ok(if a == 0 || b == 0 || c == 0 || d == 0 {
1183        None
1184    } else {
1185        Some((a, b, c, d))
1186    })
1187}
1188
1189fn key8(batch: &TermBatch, keys: &[usize], row: usize) -> Result<Option<[u32; 8]>, ExecError> {
1190    if keys.len() > 8 {
1191        return Err(ExecError::JoinKeyTooWide { arity: keys.len() });
1192    }
1193    // Unused [u32; 8] lanes stay 0 (unbound is never inserted, so they cannot
1194    // collide with a real id).
1195    let mut packed = [0u32; 8];
1196    for (i, &c) in keys.iter().enumerate() {
1197        let id = batch.column(c)?.id_at(row);
1198        if id == 0 {
1199            return Ok(None);
1200        }
1201        packed[i] = id;
1202    }
1203    Ok(Some(packed))
1204}
1205
1206/// Default partition count for [`shuffle_hash_join`].
1207pub const DEFAULT_SHUFFLE_PARTITIONS: usize = 8;
1208
1209/// Hash-partition both sides by join-key TermId, then vectorized-join each
1210/// partition (Phase 9b shuffle).
1211///
1212/// Idea: rows that could match must land in the same partition (same key hash).
1213/// Join each partition independently with [`hash_join_columnar`], then stack
1214/// the results with [`TermBatch::concat`].
1215///
1216/// Semantics match [`hash_join`]; empty keys fall back to a single cartesian.
1217pub fn shuffle_hash_join(
1218    left_batch: &TermBatch,
1219    right_batch: &TermBatch,
1220    left_col_keys: &[usize],
1221    right_col_keys: &[usize],
1222    right_carry: &[usize],
1223    soft_pairs: &[(usize, usize)],
1224    partitions: usize,
1225) -> Result<TermBatch, ExecError> {
1226    let partitions = partitions.max(1);
1227    if left_batch.is_empty() || right_batch.is_empty() {
1228        return empty_join_batch(left_batch, right_carry);
1229    }
1230    // No hard keys → nothing to partition on; one cartesian (via columnar join)
1231    if left_col_keys.is_empty() {
1232        return hash_join_columnar(
1233            left_batch,
1234            right_batch,
1235            left_col_keys,
1236            right_col_keys,
1237            right_carry,
1238            soft_pairs,
1239        );
1240    }
1241
1242    // Split each side into `partitions` buckets keyed by join-TermId hash
1243    let left_parts = partition_by_keys(left_batch, left_col_keys, partitions)?;
1244    let right_parts = partition_by_keys(right_batch, right_col_keys, partitions)?;
1245
1246    let out_width = left_batch.width() + right_carry.len();
1247    let mut parts = Vec::with_capacity(partitions);
1248    for (left_idx, right_idx) in left_parts.into_iter().zip(right_parts) {
1249        // Materialize the rows that belong to this partition, then join locally
1250        let left = gather_rows(left_batch, &left_idx)?;
1251        let right = gather_rows(right_batch, &right_idx)?;
1252        parts.push(hash_join_columnar(
1253            &left,
1254            &right,
1255            left_col_keys,
1256            right_col_keys,
1257            right_carry,
1258            soft_pairs,
1259        )?);
1260    }
1261    // Vertical concat of per-partition join outputs
1262    TermBatch::concat(out_width, parts)
1263}
1264
1265/// Encoded LeftJoin probe outcome for one (left, right) candidate.
1266///
1267/// `AcceptNeedsResolve` means the early FILTER cannot be decided on encoded
1268/// terms alone; compute must ground-eval that candidate after string resolve.
1269/// Immediate-gather paths ([`left_hash_join`], [`left_hash_join_columnar`]) treat
1270/// NeedsResolve as reject so unresolved early FILTERs are never silently kept —
1271/// production OPTIONAL+NeedsResolve uses [`left_hash_join_columnar_indices`].
1272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1273pub enum LeftJoinProbeDecision {
1274    /// Soft/FILTER reject — do not emit this pair.
1275    Reject,
1276    /// Early FILTER is EBV-true on encoded terms.
1277    AcceptKeep,
1278    /// Early FILTER needs string resolve before a final decision.
1279    AcceptNeedsResolve,
1280}
1281
1282/// Per emitted index-list entry from a Diff-once LeftJoin probe.
1283///
1284/// Aligned 1:1 with `(left_indices[i], right_indices[i])`.
1285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1286pub enum LeftJoinProbeMark {
1287    /// `right_indices[i]` is `None` (OPTIONAL unbound miss).
1288    Miss,
1289    /// Accepted match; early FILTER already Keep on encoded terms.
1290    EarlyKeep,
1291    /// Accepted match; early FILTER NeedsResolve (ground Diff-once may drop it).
1292    EarlyNeedsResolve,
1293}
1294
1295/// Optional LeftJoin probe predicate: `(left_row, right_row) → decision`.
1296///
1297/// Used to fold SPARQL `OPTIONAL { … FILTER(expr) }` into the join (Diff-once).
1298/// `waratah_exec` stays free of spargebra; compute supplies the closure.
1299pub type LeftJoinProbeFilter<'a> =
1300    dyn Fn(usize, usize) -> Result<LeftJoinProbeDecision, ExecError> + 'a;
1301
1302/// Soft reconcile plus optional LeftJoin `expr`.
1303///
1304/// Returns `None` when soft reconcile fails; otherwise the probe decision
1305/// (`AcceptKeep` when no `probe_filter`).
1306fn left_probe_decision(
1307    left_batch: &TermBatch,
1308    right_batch: &TermBatch,
1309    left_row: usize,
1310    right_row: usize,
1311    soft_pairs: &[(usize, usize)],
1312    probe_filter: Option<&LeftJoinProbeFilter<'_>>,
1313) -> Result<Option<LeftJoinProbeDecision>, ExecError> {
1314    if !soft_pair_compatible(left_batch, right_batch, left_row, right_row, soft_pairs)? {
1315        return Ok(None);
1316    }
1317    match probe_filter {
1318        None => Ok(Some(LeftJoinProbeDecision::AcceptKeep)),
1319        Some(pred) => Ok(Some(pred(left_row, right_row)?)),
1320    }
1321}
1322
1323/// Left outer hash join: every left row is kept; unmatched right columns are unbound.
1324///
1325/// Scalar reference for SPARQL `OPTIONAL` (Phase 9c); production uses
1326/// [`left_hash_join_columnar`]. Empty keys use a nested-loop Diff-once path:
1327/// compatible right rows pair as a cartesian; if every optional extension is
1328/// incompatible (soft pair or `probe_filter`), keep the left row with unbound
1329/// right-carry — not an inner-join drop.
1330pub fn left_hash_join(
1331    left_batch: &TermBatch,
1332    right_batch: &TermBatch,
1333    left_col_keys: &[usize],
1334    right_col_keys: &[usize],
1335    right_carry: &[usize],
1336    soft_pairs: &[(usize, usize)],
1337    probe_filter: Option<&LeftJoinProbeFilter<'_>>,
1338) -> Result<TermBatch, ExecError> {
1339    left_hash_join_columnar(
1340        left_batch,
1341        right_batch,
1342        left_col_keys,
1343        right_col_keys,
1344        right_carry,
1345        soft_pairs,
1346        probe_filter,
1347    )
1348}
1349
1350/// Columnar left outer hash join: same semantics as [`left_hash_join`].
1351///
1352/// Always builds on the right and probes every left row (including unbound-key
1353/// left rows, which emit unbound right-carry). Empty keys use the same Diff-once
1354/// nested loop as the scalar path: compatible pairs form a cartesian; if every
1355/// optional extension is incompatible, keep the left row with unbound right-carry.
1356///
1357/// Implemented as [`left_hash_join_columnar_indices`] (Diff-once probe) then
1358/// [`gather_left_join_indices_columnar`] so compute can insert a residual
1359/// FILTER pass on the index lists before gather.
1360pub fn left_hash_join_columnar(
1361    left_batch: &TermBatch,
1362    right_batch: &TermBatch,
1363    left_col_keys: &[usize],
1364    right_col_keys: &[usize],
1365    right_carry: &[usize],
1366    soft_pairs: &[(usize, usize)],
1367    probe_filter: Option<&LeftJoinProbeFilter<'_>>,
1368) -> Result<TermBatch, ExecError> {
1369    validate_join_args(
1370        left_batch,
1371        right_batch,
1372        left_col_keys,
1373        right_col_keys,
1374        right_carry,
1375        soft_pairs,
1376    )?;
1377
1378    // Empty required side → empty OPTIONAL result (nothing to keep)
1379    if left_batch.is_empty() {
1380        return empty_join_batch(left_batch, right_carry);
1381    }
1382
1383    // Empty keys, empty right, FILTER, and soft-miss all live in
1384    // `left_hash_join_columnar_indices` (Diff-once nested loop, not inner cartesian).
1385    let (left_indices, right_indices, marks) = left_hash_join_columnar_indices(
1386        left_batch,
1387        right_batch,
1388        left_col_keys,
1389        right_col_keys,
1390        soft_pairs,
1391        probe_filter,
1392    )?;
1393    // Immediate gather cannot ground NeedsResolve — fail closed (Diff-once miss).
1394    let (left_indices, right_indices) =
1395        drop_needs_resolve_for_immediate_gather(&left_indices, &right_indices, &marks);
1396    // Nullable right indices: None entries become unbound via gather_take_nullable
1397    gather_left_join_indices_columnar(
1398        left_batch,
1399        right_batch,
1400        &left_indices,
1401        &right_indices,
1402        right_carry,
1403        soft_pairs,
1404    )
1405}
1406
1407/// Diff-once LeftJoin index lists: left rows, nullable right rows, early marks.
1408pub type LeftJoinIndexLists = (Vec<u32>, Vec<Option<u32>>, Vec<LeftJoinProbeMark>);
1409
1410/// Diff-once LeftJoin index lists (`right_indices` `None` = unbound miss).
1411///
1412/// This is the probe half of [`left_hash_join_columnar`]: build on the optional
1413/// (right) side, probe every left row, soft-reconcile + optional `probe_filter`,
1414/// and emit parallel index lists + [`LeftJoinProbeMark`]s without gathering yet.
1415pub fn left_hash_join_columnar_indices(
1416    left_batch: &TermBatch,
1417    right_batch: &TermBatch,
1418    left_col_keys: &[usize],
1419    right_col_keys: &[usize],
1420    soft_pairs: &[(usize, usize)],
1421    probe_filter: Option<&LeftJoinProbeFilter<'_>>,
1422) -> Result<LeftJoinIndexLists, ExecError> {
1423    validate_join_args(
1424        left_batch,
1425        right_batch,
1426        left_col_keys,
1427        right_col_keys,
1428        &[],
1429        soft_pairs,
1430    )?;
1431    check_u32_rows(left_batch, right_batch)?;
1432
1433    // Empty required side → empty OPTIONAL result (nothing to keep)
1434    if left_batch.is_empty() {
1435        return Ok((Vec::new(), Vec::new(), Vec::new()));
1436    }
1437
1438    // Empty keys: nested-loop LeftJoin (not inner cartesian). Soft-incompatible
1439    // pairs and FILTER rejects are OPTIONAL misses; empty right pads unbound.
1440    if left_col_keys.is_empty() {
1441        // if left_col_keys is empty, then right_col_keys is also empty
1442        if right_batch.is_empty() {
1443            let n = left_batch.len() as u32;
1444            return Ok((
1445                (0..n).collect(),
1446                vec![None; n as usize],
1447                vec![LeftJoinProbeMark::Miss; n as usize],
1448            ));
1449        }
1450        return left_join_filtered_cartesian_indices(
1451            left_batch,
1452            right_batch,
1453            soft_pairs,
1454            probe_filter,
1455        );
1456    }
1457
1458    match left_col_keys.len() {
1459        1 => left_join_indices_with(
1460            left_batch,
1461            right_batch,
1462            left_col_keys,
1463            right_col_keys,
1464            soft_pairs,
1465            probe_filter,
1466            key1,
1467        ),
1468        2 => left_join_indices_with(
1469            left_batch,
1470            right_batch,
1471            left_col_keys,
1472            right_col_keys,
1473            soft_pairs,
1474            probe_filter,
1475            key2,
1476        ),
1477        3 => left_join_indices_with(
1478            left_batch,
1479            right_batch,
1480            left_col_keys,
1481            right_col_keys,
1482            soft_pairs,
1483            probe_filter,
1484            key3,
1485        ),
1486        4 => left_join_indices_with(
1487            left_batch,
1488            right_batch,
1489            left_col_keys,
1490            right_col_keys,
1491            soft_pairs,
1492            probe_filter,
1493            key4,
1494        ),
1495        5..=8 => left_join_indices_with(
1496            left_batch,
1497            right_batch,
1498            left_col_keys,
1499            right_col_keys,
1500            soft_pairs,
1501            probe_filter,
1502            key8,
1503        ),
1504        arity => Err(ExecError::JoinKeyTooWide { arity }),
1505    }
1506}
1507
1508fn left_join_indices_with<K, F>(
1509    left_batch: &TermBatch,
1510    right_batch: &TermBatch,
1511    left_col_keys: &[usize],
1512    right_col_keys: &[usize],
1513    soft_pairs: &[(usize, usize)],
1514    probe_filter: Option<&LeftJoinProbeFilter<'_>>,
1515    extract: F,
1516) -> Result<LeftJoinIndexLists, ExecError>
1517where
1518    K: Copy + Eq + Hash,
1519    F: Fn(&TermBatch, &[usize], usize) -> Result<Option<K>, ExecError>,
1520{
1521    // Build hash table on the optional (right) side only.
1522    // Unlike inner join we never flip build/probe: OPTIONAL always preserves left.
1523    // The reserve clamps at `JOIN_BUILD_RESERVE_MAX` so skewed keys
1524    // (few distinct values) cannot over-allocate.
1525    let mut buckets: FxHashMap<K, Vec<u32>> = FxHashMap::with_capacity_and_hasher(
1526        right_batch.len().min(JOIN_BUILD_RESERVE_MAX),
1527        Default::default(),
1528    );
1529    for right_row in 0..right_batch.len() {
1530        // Unbound right key can't match; skip (left will still emit via miss path)
1531        let Some(key) = extract(right_batch, right_col_keys, right_row)? else {
1532            continue;
1533        };
1534        buckets.entry(key).or_default().push(right_row as u32);
1535    }
1536
1537    let mut left_indices: Vec<u32> = Vec::new();
1538    let mut right_indices: Vec<Option<u32>> = Vec::new();
1539    let mut early_marks: Vec<LeftJoinProbeMark> = Vec::new();
1540    // Probe every left row so unmatched / unbound-key rows still appear.
1541    for left_row in 0..left_batch.len() as u32 {
1542        let Some(compare_key) = extract(left_batch, left_col_keys, left_row as usize)? else {
1543            // Left key unbound → keep with null right index
1544            left_indices.push(left_row);
1545            right_indices.push(None);
1546            early_marks.push(LeftJoinProbeMark::Miss);
1547            continue;
1548        };
1549        match buckets.get(&compare_key) {
1550            Some(matches) => {
1551                let mut any = false;
1552                for &right_row in matches {
1553                    // Soft pairs + optional FILTER can reject a hard-key candidate;
1554                    // try the whole bucket, then Diff-once if none accepted
1555                    match left_probe_decision(
1556                        left_batch,
1557                        right_batch,
1558                        left_row as usize,
1559                        right_row as usize,
1560                        soft_pairs,
1561                        probe_filter,
1562                    )? {
1563                        Some(LeftJoinProbeDecision::AcceptKeep) => {
1564                            left_indices.push(left_row);
1565                            right_indices.push(Some(right_row));
1566                            early_marks.push(LeftJoinProbeMark::EarlyKeep);
1567                            any = true;
1568                        }
1569                        Some(LeftJoinProbeDecision::AcceptNeedsResolve) => {
1570                            left_indices.push(left_row);
1571                            right_indices.push(Some(right_row));
1572                            early_marks.push(LeftJoinProbeMark::EarlyNeedsResolve);
1573                            any = true;
1574                        }
1575                        Some(LeftJoinProbeDecision::Reject) | None => {}
1576                    }
1577                }
1578                if !any {
1579                    // Hard key hit but soft/FILTER reconcile rejected every candidate
1580                    left_indices.push(left_row);
1581                    right_indices.push(None);
1582                    early_marks.push(LeftJoinProbeMark::Miss);
1583                }
1584            }
1585            None => {
1586                // No right row with this key → OPTIONAL miss
1587                left_indices.push(left_row);
1588                right_indices.push(None);
1589                early_marks.push(LeftJoinProbeMark::Miss);
1590            }
1591        }
1592    }
1593    Ok((left_indices, right_indices, early_marks))
1594}
1595
1596/// Gather LeftJoin output from Diff-once index lists.
1597///
1598/// Nullable right indices: `None` entries become unbound via
1599/// [`TermColumn::gather_take_nullable`].
1600pub fn gather_left_join_indices_columnar(
1601    left_batch: &TermBatch,
1602    right_batch: &TermBatch,
1603    left_indices: &[u32],
1604    right_indices: &[Option<u32>],
1605    right_carry: &[usize],
1606    soft_pairs: &[(usize, usize)],
1607) -> Result<TermBatch, ExecError> {
1608    let mut out_cols = Vec::with_capacity(left_batch.width() + right_carry.len());
1609    for (col_idx, col) in left_batch.columns().iter().enumerate() {
1610        if let Some((_, right_col)) = soft_pairs.iter().find(|(l, _)| *l == col_idx) {
1611            out_cols.push(col.gather_coalesce_nullable(
1612                left_indices,
1613                right_batch.column(*right_col)?,
1614                right_indices,
1615            )?);
1616        } else {
1617            out_cols.push(col.gather_take(left_indices));
1618        }
1619    }
1620    // Nullable right indices: null slots become unbound right-carry cells
1621    for &c in right_carry {
1622        out_cols.push(right_batch.column(c)?.gather_take_nullable(right_indices));
1623    }
1624    TermBatch::try_new(out_cols)
1625}
1626
1627/// Columnar empty-key LeftJoin: same Diff-once indices as scalar nested loop.
1628///
1629/// Generally when this is called, the right batch is the OPTIONAL {} side and
1630/// the left batch is the required side.
1631fn left_join_filtered_cartesian_indices(
1632    left_batch: &TermBatch,
1633    right_batch: &TermBatch,
1634    soft_pairs: &[(usize, usize)],
1635    probe_filter: Option<&LeftJoinProbeFilter<'_>>,
1636) -> Result<LeftJoinIndexLists, ExecError> {
1637    let mut left_indices = Vec::new();
1638    let mut right_indices: Vec<Option<u32>> = Vec::new();
1639    let mut early_marks: Vec<LeftJoinProbeMark> = Vec::new();
1640    for left_row in 0..left_batch.len() as u32 {
1641        let mut any = false;
1642        for right_row in 0..right_batch.len() as u32 {
1643            match left_probe_decision(
1644                left_batch,
1645                right_batch,
1646                left_row as usize,
1647                right_row as usize,
1648                soft_pairs,
1649                probe_filter,
1650            )? {
1651                Some(LeftJoinProbeDecision::AcceptKeep) => {
1652                    left_indices.push(left_row);
1653                    right_indices.push(Some(right_row));
1654                    early_marks.push(LeftJoinProbeMark::EarlyKeep);
1655                    any = true;
1656                }
1657                Some(LeftJoinProbeDecision::AcceptNeedsResolve) => {
1658                    left_indices.push(left_row);
1659                    right_indices.push(Some(right_row));
1660                    early_marks.push(LeftJoinProbeMark::EarlyNeedsResolve);
1661                    any = true;
1662                }
1663                Some(LeftJoinProbeDecision::Reject) | None => {}
1664            }
1665        }
1666        if !any {
1667            left_indices.push(left_row);
1668            right_indices.push(None);
1669            early_marks.push(LeftJoinProbeMark::Miss);
1670        }
1671    }
1672    Ok((left_indices, right_indices, early_marks))
1673}
1674
1675/// Drop `EarlyNeedsResolve` matches for immediate gather (fail closed without ground pass).
1676///
1677/// Per left-row group: keep `EarlyKeep`; if no `Some(right)` remain → one Miss.
1678fn drop_needs_resolve_for_immediate_gather(
1679    left_indices: &[u32],
1680    right_indices: &[Option<u32>],
1681    early_marks: &[LeftJoinProbeMark],
1682) -> (Vec<u32>, Vec<Option<u32>>) {
1683    let mut out_left = Vec::new();
1684    let mut out_right: Vec<Option<u32>> = Vec::new();
1685    let mut i = 0;
1686    while i < left_indices.len() {
1687        let left_row = left_indices[i];
1688        let start = i;
1689        while i < left_indices.len() && left_indices[i] == left_row {
1690            i += 1;
1691        }
1692        let mut any = false;
1693        for j in start..i {
1694            match early_marks[j] {
1695                LeftJoinProbeMark::EarlyKeep => {
1696                    out_left.push(left_indices[j]);
1697                    out_right.push(right_indices[j]);
1698                    any = true;
1699                }
1700                LeftJoinProbeMark::EarlyNeedsResolve => {}
1701                LeftJoinProbeMark::Miss => {
1702                    // Only emit miss if the whole group is miss / dropped NeedsResolve.
1703                }
1704            }
1705        }
1706        if !any {
1707            out_left.push(left_row);
1708            out_right.push(None);
1709        }
1710    }
1711    (out_left, out_right)
1712}
1713
1714/// Assign each row to a shuffle partition by hashing its join-key TermId tuple.
1715fn partition_by_keys(
1716    batch: &TermBatch,
1717    keys: &[usize],
1718    partitions: usize,
1719) -> Result<Vec<Vec<usize>>, ExecError> {
1720    let mut parts = vec![Vec::new(); partitions];
1721    for row in 0..batch.len() {
1722        let Some(packed) = key8(batch, keys, row)? else {
1723            // Unbound keys go to partition 0 (they never match in the join).
1724            parts[0].push(row);
1725            continue;
1726        };
1727        // FxHasher → partition id; matching keys on left and right get the same id
1728        let mut hasher = FxHasher::default();
1729        packed.hash(&mut hasher);
1730        let part = (hasher.finish() as usize) % partitions;
1731        parts[part].push(row);
1732    }
1733    Ok(parts)
1734}
1735
1736/// Slice a batch down to the rows listed in `indices` (used by shuffle buckets).
1737fn gather_rows(batch: &TermBatch, indices: &[usize]) -> Result<TermBatch, ExecError> {
1738    let cols = batch
1739        .columns()
1740        .iter()
1741        .map(|col| col.gather(indices))
1742        .collect();
1743    TermBatch::try_new(cols)
1744}
1745
1746#[cfg(test)]
1747mod tests {
1748    use super::*;
1749    use crate::column::TermColumn;
1750    use crate::term_dict::TermDict;
1751    use pretty_assertions::assert_eq;
1752    use waratah_storage::{EncodedTerm, Literal, NamedNode};
1753
1754    fn iri(local: &str) -> EncodedTerm {
1755        EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap())
1756    }
1757
1758    fn col(dict: &TermDict, terms: Vec<EncodedTerm>) -> TermColumn {
1759        TermColumn::from_terms(dict, terms).unwrap()
1760    }
1761
1762    fn term(dict: &TermDict, col: &TermColumn, row: usize) -> Option<EncodedTerm> {
1763        col.term_at(dict, row)
1764    }
1765
1766    #[test]
1767    fn hash_join_on_city() {
1768        let dict = TermDict::new();
1769        // left: person | city
1770        let left = TermBatch::try_new(vec![
1771            col(&dict, vec![iri("alice"), iri("bob")]),
1772            col(&dict, vec![iri("brisbane"), iri("hobart")]),
1773        ])
1774        .unwrap();
1775        // right: city | weather
1776        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
1777        let right = TermBatch::try_new(vec![
1778            col(&dict, vec![iri("brisbane")]),
1779            col(&dict, vec![sunny.clone()]),
1780        ])
1781        .unwrap();
1782
1783        // join on city (left 1, right 0), carry weather (right 1)
1784        let out = hash_join(&left, &right, &[1], &[0], &[1], &[]).unwrap();
1785        assert_eq!(out.width(), 3);
1786        assert_eq!(out.len(), 1);
1787        assert_eq!(term(&dict, out.column(0).unwrap(), 0), Some(iri("alice")));
1788        assert_eq!(term(&dict, out.column(2).unwrap(), 0), Some(sunny));
1789    }
1790
1791    #[test]
1792    fn unbound_join_keys_do_not_match() {
1793        let dict = TermDict::new();
1794        let left = TermBatch::try_new(vec![
1795            TermColumn::from_optional_terms(&dict, vec![Some(iri("alice")), Some(iri("bob"))])
1796                .unwrap(),
1797            TermColumn::from_optional_terms(&dict, vec![None, Some(iri("hobart"))]).unwrap(),
1798        ])
1799        .unwrap();
1800        let right = TermBatch::try_new(vec![
1801            TermColumn::from_optional_terms(&dict, vec![None, Some(iri("hobart"))]).unwrap(),
1802            TermColumn::from_terms(
1803                &dict,
1804                vec![
1805                    EncodedTerm::from(&Literal::from("X")),
1806                    EncodedTerm::from(&Literal::from("Cold")),
1807                ],
1808            )
1809            .unwrap(),
1810        ])
1811        .unwrap();
1812        let out = hash_join(&left, &right, &[1], &[0], &[1], &[]).unwrap();
1813        // Only bob⋈hobart; unbound keys never match (including unbound⋈unbound).
1814        assert_eq!(out.len(), 1);
1815        assert_eq!(term(&dict, out.column(0).unwrap(), 0), Some(iri("bob")));
1816    }
1817
1818    #[test]
1819    fn hash_join_independent_of_build_side() {
1820        let dict = TermDict::new();
1821        let left = TermBatch::try_new(vec![
1822            col(&dict, vec![iri("alice"), iri("bob"), iri("carol")]),
1823            col(&dict, vec![iri("brisbane"), iri("hobart"), iri("brisbane")]),
1824        ])
1825        .unwrap();
1826        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
1827        let right = TermBatch::try_new(vec![
1828            col(&dict, vec![iri("brisbane")]),
1829            col(&dict, vec![sunny]),
1830        ])
1831        .unwrap();
1832        let out = hash_join(&left, &right, &[1], &[0], &[1], &[]).unwrap();
1833        assert_eq!(out.len(), 2);
1834    }
1835
1836    #[test]
1837    fn cartesian_product() {
1838        let dict = TermDict::new();
1839        let left = TermBatch::try_new(vec![col(&dict, vec![iri("a")])]).unwrap();
1840        let right = TermBatch::try_new(vec![col(&dict, vec![iri("x"), iri("y")])]).unwrap();
1841        let out = hash_join(&left, &right, &[], &[], &[0], &[]).unwrap();
1842        assert_eq!(out.len(), 2);
1843        assert_eq!(out.width(), 2);
1844    }
1845
1846    #[test]
1847    fn termid_equality_kernel() {
1848        let dict = TermDict::new();
1849        let a = col(&dict, vec![iri("a"), iri("b")]);
1850        let b = col(&dict, vec![iri("a"), iri("c")]);
1851        assert_eq!(a.id_at(0), b.id_at(0));
1852        assert_ne!(a.id_at(1), b.id_at(1));
1853    }
1854
1855    #[test]
1856    fn hash_join_columnar_matches_scalar_on_city() {
1857        let dict = TermDict::new();
1858        let left = TermBatch::try_new(vec![
1859            col(&dict, vec![iri("alice"), iri("bob")]),
1860            col(&dict, vec![iri("brisbane"), iri("hobart")]),
1861        ])
1862        .unwrap();
1863        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
1864        let right = TermBatch::try_new(vec![
1865            col(&dict, vec![iri("brisbane")]),
1866            col(&dict, vec![sunny.clone()]),
1867        ])
1868        .unwrap();
1869
1870        let scalar = hash_join(&left, &right, &[1], &[0], &[1], &[]).unwrap();
1871        let columnar = hash_join_columnar(&left, &right, &[1], &[0], &[1], &[]).unwrap();
1872        assert_eq!(columnar, scalar);
1873        assert_eq!(
1874            term(&dict, columnar.column(0).unwrap(), 0),
1875            Some(iri("alice"))
1876        );
1877        assert_eq!(term(&dict, columnar.column(2).unwrap(), 0), Some(sunny));
1878    }
1879
1880    #[test]
1881    fn hash_join_columnar_skips_unbound_keys() {
1882        let dict = TermDict::new();
1883        let left = TermBatch::try_new(vec![
1884            TermColumn::from_optional_terms(&dict, vec![Some(iri("alice")), Some(iri("bob"))])
1885                .unwrap(),
1886            TermColumn::from_optional_terms(&dict, vec![None, Some(iri("hobart"))]).unwrap(),
1887        ])
1888        .unwrap();
1889        let right = TermBatch::try_new(vec![
1890            TermColumn::from_optional_terms(&dict, vec![None, Some(iri("hobart"))]).unwrap(),
1891            TermColumn::from_terms(
1892                &dict,
1893                vec![
1894                    EncodedTerm::from(&Literal::from("X")),
1895                    EncodedTerm::from(&Literal::from("Cold")),
1896                ],
1897            )
1898            .unwrap(),
1899        ])
1900        .unwrap();
1901        let scalar = hash_join(&left, &right, &[1], &[0], &[1], &[]).unwrap();
1902        let columnar = hash_join_columnar(&left, &right, &[1], &[0], &[1], &[]).unwrap();
1903        assert_eq!(columnar, scalar);
1904    }
1905
1906    #[test]
1907    fn hash_join_columnar_cartesian_matches_scalar() {
1908        let dict = TermDict::new();
1909        let left = TermBatch::try_new(vec![col(&dict, vec![iri("a")])]).unwrap();
1910        let right = TermBatch::try_new(vec![col(&dict, vec![iri("x"), iri("y")])]).unwrap();
1911        let scalar = hash_join(&left, &right, &[], &[], &[0], &[]).unwrap();
1912        let columnar = hash_join_columnar(&left, &right, &[], &[], &[0], &[]).unwrap();
1913        assert_eq!(columnar, scalar);
1914    }
1915
1916    #[test]
1917    fn gather_take_preserves_ids() {
1918        let dict = TermDict::new();
1919        let col = TermColumn::from_terms(&dict, vec![iri("a"), iri("b")]).unwrap();
1920        let taken = col.gather_take(&[1u32, 0]);
1921        assert_eq!(term(&dict, &taken, 0), Some(iri("b")));
1922        assert_eq!(term(&dict, &taken, 1), Some(iri("a")));
1923    }
1924
1925    #[test]
1926    fn shuffle_hash_join_matches_hash_join() {
1927        let dict = TermDict::new();
1928        let left = TermBatch::try_new(vec![
1929            col(&dict, vec![iri("alice"), iri("bob"), iri("carol")]),
1930            col(&dict, vec![iri("brisbane"), iri("hobart"), iri("brisbane")]),
1931        ])
1932        .unwrap();
1933        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
1934        let cold = EncodedTerm::from(&Literal::from("Cold"));
1935        let right = TermBatch::try_new(vec![
1936            col(&dict, vec![iri("brisbane"), iri("hobart")]),
1937            col(&dict, vec![sunny, cold]),
1938        ])
1939        .unwrap();
1940
1941        let direct = hash_join(&left, &right, &[1], &[0], &[1], &[]).unwrap();
1942        let shuffled = shuffle_hash_join(&left, &right, &[1], &[0], &[1], &[], 4).unwrap();
1943        assert_eq!(shuffled.len(), direct.len());
1944        // Same multiset of (person, city, weather) bindings.
1945        let mut direct_rows = direct.to_rows(&dict);
1946        let mut shuffled_rows = shuffled.to_rows(&dict);
1947        direct_rows.sort_by_key(|r| format!("{r:?}"));
1948        shuffled_rows.sort_by_key(|r| format!("{r:?}"));
1949        assert_eq!(shuffled_rows, direct_rows);
1950    }
1951
1952    #[test]
1953    fn shuffle_hash_join_rejects_arity_over_8() {
1954        let dict = TermDict::new();
1955        let cols: Vec<_> = (0..9)
1956            .map(|i| col(&dict, vec![iri(&format!("v{i}"))]))
1957            .collect();
1958        let left = TermBatch::try_new(cols.clone()).unwrap();
1959        let right = TermBatch::try_new(cols).unwrap();
1960        let keys: Vec<usize> = (0..9).collect();
1961        let err = shuffle_hash_join(&left, &right, &keys, &keys, &[], &[], 2).unwrap_err();
1962        assert_eq!(err, ExecError::JoinKeyTooWide { arity: 9 });
1963    }
1964
1965    #[test]
1966    fn left_hash_join_keeps_unmatched_left_rows() {
1967        let dict = TermDict::new();
1968        let left = TermBatch::try_new(vec![
1969            col(&dict, vec![iri("alice"), iri("bob")]),
1970            col(&dict, vec![iri("brisbane"), iri("hobart")]),
1971        ])
1972        .unwrap();
1973        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
1974        let right = TermBatch::try_new(vec![
1975            col(&dict, vec![iri("brisbane")]),
1976            col(&dict, vec![sunny.clone()]),
1977        ])
1978        .unwrap();
1979
1980        let out = left_hash_join(&left, &right, &[1], &[0], &[1], &[], None).unwrap();
1981        assert_eq!(out.len(), 2);
1982        assert_eq!(term(&dict, out.column(0).unwrap(), 0), Some(iri("alice")));
1983        assert_eq!(term(&dict, out.column(2).unwrap(), 0), Some(sunny));
1984        assert_eq!(term(&dict, out.column(0).unwrap(), 1), Some(iri("bob")));
1985        assert_eq!(term(&dict, out.column(2).unwrap(), 1), None);
1986    }
1987
1988    #[test]
1989    fn left_hash_join_columnar_matches_scalar() {
1990        let dict = TermDict::new();
1991        let left = TermBatch::try_new(vec![
1992            col(&dict, vec![iri("alice"), iri("bob")]),
1993            col(&dict, vec![iri("brisbane"), iri("hobart")]),
1994        ])
1995        .unwrap();
1996        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
1997        let right = TermBatch::try_new(vec![
1998            col(&dict, vec![iri("brisbane")]),
1999            col(&dict, vec![sunny.clone()]),
2000        ])
2001        .unwrap();
2002
2003        let scalar = left_hash_join(&left, &right, &[1], &[0], &[1], &[], None).unwrap();
2004        let columnar = left_hash_join_columnar(&left, &right, &[1], &[0], &[1], &[], None).unwrap();
2005        assert_eq!(columnar, scalar);
2006        assert_eq!(term(&dict, columnar.column(2).unwrap(), 0), Some(sunny));
2007        assert_eq!(term(&dict, columnar.column(2).unwrap(), 1), None);
2008    }
2009
2010    #[test]
2011    fn left_hash_join_columnar_keeps_unbound_left_keys() {
2012        let dict = TermDict::new();
2013        let left = TermBatch::try_new(vec![
2014            TermColumn::from_optional_terms(&dict, vec![Some(iri("alice")), Some(iri("bob"))])
2015                .unwrap(),
2016            TermColumn::from_optional_terms(&dict, vec![None, Some(iri("hobart"))]).unwrap(),
2017        ])
2018        .unwrap();
2019        let right = TermBatch::try_new(vec![
2020            TermColumn::from_optional_terms(&dict, vec![Some(iri("hobart"))]).unwrap(),
2021            TermColumn::from_terms(&dict, vec![EncodedTerm::from(&Literal::from("Cold"))]).unwrap(),
2022        ])
2023        .unwrap();
2024
2025        let scalar = left_hash_join(&left, &right, &[1], &[0], &[1], &[], None).unwrap();
2026        let columnar = left_hash_join_columnar(&left, &right, &[1], &[0], &[1], &[], None).unwrap();
2027        assert_eq!(columnar, scalar);
2028        assert_eq!(columnar.len(), 2);
2029        assert_eq!(term(&dict, columnar.column(2).unwrap(), 0), None);
2030        assert_eq!(
2031            term(&dict, columnar.column(2).unwrap(), 1),
2032            Some(EncodedTerm::from(&Literal::from("Cold")))
2033        );
2034    }
2035
2036    #[test]
2037    fn left_hash_join_columnar_empty_right_keeps_left() {
2038        let dict = TermDict::new();
2039        let left = TermBatch::try_new(vec![
2040            col(&dict, vec![iri("alice"), iri("bob")]),
2041            col(&dict, vec![iri("brisbane"), iri("hobart")]),
2042        ])
2043        .unwrap();
2044        let right = TermBatch::try_new(vec![
2045            TermColumn::from_terms(&dict, Vec::new()).unwrap(),
2046            TermColumn::from_terms(&dict, Vec::new()).unwrap(),
2047        ])
2048        .unwrap();
2049
2050        let scalar = left_hash_join(&left, &right, &[1], &[0], &[1], &[], None).unwrap();
2051        let columnar = left_hash_join_columnar(&left, &right, &[1], &[0], &[1], &[], None).unwrap();
2052        assert_eq!(columnar, scalar);
2053        assert_eq!(columnar.len(), 2);
2054        assert_eq!(term(&dict, columnar.column(2).unwrap(), 0), None);
2055        assert_eq!(term(&dict, columnar.column(2).unwrap(), 1), None);
2056    }
2057
2058    #[test]
2059    fn left_hash_join_columnar_cartesian_matches_scalar() {
2060        let dict = TermDict::new();
2061        let left = TermBatch::try_new(vec![col(&dict, vec![iri("a")])]).unwrap();
2062        let right = TermBatch::try_new(vec![col(&dict, vec![iri("x"), iri("y")])]).unwrap();
2063        let scalar = left_hash_join(&left, &right, &[], &[], &[0], &[], None).unwrap();
2064        let columnar = left_hash_join_columnar(&left, &right, &[], &[], &[0], &[], None).unwrap();
2065        assert_eq!(columnar, scalar);
2066        assert_eq!(columnar.len(), 2);
2067    }
2068
2069    #[test]
2070    fn left_hash_join_filtered_empty_keys_diff_once_on_reject() {
2071        let dict = TermDict::new();
2072        // Two left × two right, FILTER always false → one unbound miss per left (not 4).
2073        let left = TermBatch::try_new(vec![col(&dict, vec![iri("x1"), iri("x2")])]).unwrap();
2074        let right = TermBatch::try_new(vec![col(&dict, vec![iri("y1"), iri("y2")])]).unwrap();
2075        let reject = |_l: usize, _r: usize| Ok(LeftJoinProbeDecision::Reject);
2076        let scalar = left_hash_join(&left, &right, &[], &[], &[0], &[], Some(&reject)).unwrap();
2077        let columnar =
2078            left_hash_join_columnar(&left, &right, &[], &[], &[0], &[], Some(&reject)).unwrap();
2079        assert_eq!(columnar, scalar);
2080        assert_eq!(scalar.len(), 2);
2081        assert_eq!(term(&dict, scalar.column(1).unwrap(), 0), None);
2082        assert_eq!(term(&dict, scalar.column(1).unwrap(), 1), None);
2083    }
2084
2085    #[test]
2086    fn left_hash_join_filtered_empty_keys_keeps_matching_rights() {
2087        let dict = TermDict::new();
2088        // Left row 0 accepts only right 1; left row 1 accepts none → 1 match + 1 miss.
2089        let left = TermBatch::try_new(vec![col(&dict, vec![iri("x1"), iri("x2")])]).unwrap();
2090        let right = TermBatch::try_new(vec![col(&dict, vec![iri("y1"), iri("y2")])]).unwrap();
2091        let pred = |l: usize, r: usize| {
2092            Ok(if l == 0 && r == 1 {
2093                LeftJoinProbeDecision::AcceptKeep
2094            } else {
2095                LeftJoinProbeDecision::Reject
2096            })
2097        };
2098        let scalar = left_hash_join(&left, &right, &[], &[], &[0], &[], Some(&pred)).unwrap();
2099        let columnar =
2100            left_hash_join_columnar(&left, &right, &[], &[], &[0], &[], Some(&pred)).unwrap();
2101        assert_eq!(columnar, scalar);
2102        assert_eq!(scalar.len(), 2);
2103        assert_eq!(term(&dict, scalar.column(0).unwrap(), 0), Some(iri("x1")));
2104        assert_eq!(term(&dict, scalar.column(1).unwrap(), 0), Some(iri("y2")));
2105        assert_eq!(term(&dict, scalar.column(0).unwrap(), 1), Some(iri("x2")));
2106        assert_eq!(term(&dict, scalar.column(1).unwrap(), 1), None);
2107    }
2108
2109    #[test]
2110    fn left_hash_join_filtered_keyed_all_rejected_is_single_miss() {
2111        let dict = TermDict::new();
2112        // Same hard key, two rights, FILTER rejects both → one unbound miss.
2113        let left = TermBatch::try_new(vec![
2114            col(&dict, vec![iri("alice")]),
2115            col(&dict, vec![iri("brisbane")]),
2116        ])
2117        .unwrap();
2118        let right = TermBatch::try_new(vec![
2119            col(&dict, vec![iri("brisbane"), iri("brisbane")]),
2120            col(
2121                &dict,
2122                vec![
2123                    EncodedTerm::from(&Literal::from("Sunny")),
2124                    EncodedTerm::from(&Literal::from("Hot")),
2125                ],
2126            ),
2127        ])
2128        .unwrap();
2129        let reject = |_l: usize, _r: usize| Ok(LeftJoinProbeDecision::Reject);
2130        let scalar = left_hash_join(&left, &right, &[1], &[0], &[1], &[], Some(&reject)).unwrap();
2131        let columnar =
2132            left_hash_join_columnar(&left, &right, &[1], &[0], &[1], &[], Some(&reject)).unwrap();
2133        assert_eq!(columnar, scalar);
2134        assert_eq!(scalar.len(), 1);
2135        assert_eq!(term(&dict, scalar.column(2).unwrap(), 0), None);
2136    }
2137
2138    #[test]
2139    fn left_hash_join_indices_marks_align_with_right() {
2140        let dict = TermDict::new();
2141        let left = TermBatch::try_new(vec![col(&dict, vec![iri("x1"), iri("x2")])]).unwrap();
2142        let right = TermBatch::try_new(vec![col(&dict, vec![iri("y1"), iri("y2")])]).unwrap();
2143        let pred = |l: usize, r: usize| {
2144            Ok(if l == 0 && r == 1 {
2145                LeftJoinProbeDecision::AcceptKeep
2146            } else {
2147                LeftJoinProbeDecision::Reject
2148            })
2149        };
2150        let (left_idx, right_idx, marks) =
2151            left_hash_join_columnar_indices(&left, &right, &[], &[], &[], Some(&pred)).unwrap();
2152        assert_eq!(left_idx.len(), right_idx.len());
2153        assert_eq!(left_idx.len(), marks.len());
2154        for (ri, mark) in right_idx.iter().zip(marks.iter()) {
2155            match (ri, mark) {
2156                (None, LeftJoinProbeMark::Miss) => {}
2157                (Some(_), LeftJoinProbeMark::EarlyKeep) => {}
2158                (Some(_), LeftJoinProbeMark::EarlyNeedsResolve) => {}
2159                other => panic!("misaligned mark/right: {other:?}"),
2160            }
2161        }
2162        assert!(marks.contains(&LeftJoinProbeMark::EarlyKeep));
2163        assert!(marks.contains(&LeftJoinProbeMark::Miss));
2164    }
2165
2166    #[test]
2167    fn left_hash_join_indices_preserves_needs_resolve_mark() {
2168        let dict = TermDict::new();
2169        let left = TermBatch::try_new(vec![col(&dict, vec![iri("x1")])]).unwrap();
2170        let right = TermBatch::try_new(vec![col(&dict, vec![iri("y1")])]).unwrap();
2171        let needs = |_l: usize, _r: usize| Ok(LeftJoinProbeDecision::AcceptNeedsResolve);
2172        let (_l, right_idx, marks) =
2173            left_hash_join_columnar_indices(&left, &right, &[], &[], &[], Some(&needs)).unwrap();
2174        assert_eq!(right_idx, vec![Some(0)]);
2175        assert_eq!(marks, vec![LeftJoinProbeMark::EarlyNeedsResolve]);
2176    }
2177
2178    #[test]
2179    fn soft_shared_unbound_left_coalesces_from_right() {
2180        let dict = TermDict::new();
2181        // Left after OPTIONAL: ?s always, ?x maybe unbound. Right: ?x :r ?y.
2182        // Hard keys empty; soft pair is ?x (left col 1, right col 0).
2183        let left = TermBatch::try_new(vec![
2184            TermColumn::from_optional_terms(&dict, vec![Some(iri("a")), Some(iri("b"))]).unwrap(),
2185            TermColumn::from_optional_terms(&dict, vec![None, Some(iri("x1"))]).unwrap(),
2186        ])
2187        .unwrap();
2188        let right = TermBatch::try_new(vec![
2189            TermColumn::from_terms(&dict, vec![iri("x1"), iri("x2")]).unwrap(),
2190            TermColumn::from_terms(&dict, vec![iri("y1"), iri("y2")]).unwrap(),
2191        ])
2192        .unwrap();
2193
2194        let soft = &[(1usize, 0usize)];
2195        let scalar = hash_join(&left, &right, &[], &[], &[1], soft).unwrap();
2196        let columnar = hash_join_columnar(&left, &right, &[], &[], &[1], soft).unwrap();
2197        assert_eq!(columnar, scalar);
2198        // Row a (unbound ?x) joins every right; row b (?x=x1) joins only x1.
2199        assert_eq!(scalar.len(), 3);
2200        let xs: Vec<_> = (0..scalar.len())
2201            .map(|i| term(&dict, scalar.column(1).unwrap(), i))
2202            .collect();
2203        assert!(xs.contains(&Some(iri("x2"))));
2204        assert!(xs.iter().filter(|x| **x == Some(iri("x1"))).count() >= 1);
2205    }
2206
2207    #[test]
2208    fn soft_shared_both_bound_unequal_rejects() {
2209        let dict = TermDict::new();
2210        let left = TermBatch::try_new(vec![
2211            col(&dict, vec![iri("a")]),
2212            col(&dict, vec![iri("x1")]),
2213        ])
2214        .unwrap();
2215        let right = TermBatch::try_new(vec![
2216            col(&dict, vec![iri("x2")]),
2217            col(&dict, vec![iri("y2")]),
2218        ])
2219        .unwrap();
2220        let soft = &[(1usize, 0usize)];
2221        let scalar = hash_join(&left, &right, &[], &[], &[1], soft).unwrap();
2222        let columnar = hash_join_columnar(&left, &right, &[], &[], &[1], soft).unwrap();
2223        assert_eq!(columnar, scalar);
2224        assert_eq!(scalar.len(), 0);
2225    }
2226
2227    #[test]
2228    fn left_join_empty_keys_soft_incompatible_keeps_left() {
2229        let dict = TermDict::new();
2230        // nested-opt-1 outer LeftJoin: empty hard keys, soft ?v (1 vs 2).
2231        // Inner cartesian would drop the pair; OPTIONAL must keep left, unbound right-carry.
2232        let left = TermBatch::try_new(vec![col(&dict, vec![iri("v1")])]).unwrap();
2233        let right = TermBatch::try_new(vec![
2234            col(&dict, vec![iri("v2")]),
2235            col(&dict, vec![iri("w3")]),
2236        ])
2237        .unwrap();
2238        let soft = &[(0usize, 0usize)];
2239        let scalar = left_hash_join(&left, &right, &[], &[], &[1], soft, None).unwrap();
2240        let columnar = left_hash_join_columnar(&left, &right, &[], &[], &[1], soft, None).unwrap();
2241        assert_eq!(columnar, scalar);
2242        assert_eq!(scalar.len(), 1);
2243        assert_eq!(term(&dict, scalar.column(0).unwrap(), 0), Some(iri("v1")));
2244        assert_eq!(term(&dict, scalar.column(1).unwrap(), 0), None);
2245    }
2246
2247    #[test]
2248    fn left_join_empty_keys_soft_mixed_match_and_miss() {
2249        let dict = TermDict::new();
2250        // Left ?v=v1 conflicts with right ?v=v2; left ?v=v2 matches.
2251        let left = TermBatch::try_new(vec![col(&dict, vec![iri("v1"), iri("v2")])]).unwrap();
2252        let right = TermBatch::try_new(vec![
2253            col(&dict, vec![iri("v2")]),
2254            col(&dict, vec![iri("w3")]),
2255        ])
2256        .unwrap();
2257        let soft = &[(0usize, 0usize)];
2258        let scalar = left_hash_join(&left, &right, &[], &[], &[1], soft, None).unwrap();
2259        let columnar = left_hash_join_columnar(&left, &right, &[], &[], &[1], soft, None).unwrap();
2260        assert_eq!(columnar, scalar);
2261        assert_eq!(scalar.len(), 2);
2262        let rows: Vec<_> = (0..scalar.len())
2263            .map(|i| {
2264                (
2265                    term(&dict, scalar.column(0).unwrap(), i),
2266                    term(&dict, scalar.column(1).unwrap(), i),
2267                )
2268            })
2269            .collect();
2270        assert!(rows.contains(&(Some(iri("v1")), None)));
2271        assert!(rows.contains(&(Some(iri("v2")), Some(iri("w3")))));
2272    }
2273
2274    #[test]
2275    fn gather_take_nullable_unbound_on_null_index() {
2276        let dict = TermDict::new();
2277        let col = TermColumn::from_terms(&dict, vec![iri("a"), iri("b")]).unwrap();
2278        let indices = vec![Some(1u32), None, Some(0)];
2279        let taken = col.gather_take_nullable(&indices);
2280        assert_eq!(term(&dict, &taken, 0), Some(iri("b")));
2281        assert_eq!(term(&dict, &taken, 1), None);
2282        assert_eq!(term(&dict, &taken, 2), Some(iri("a")));
2283        assert_eq!(taken.id_at(1), 0);
2284    }
2285
2286    #[test]
2287    fn capped_inner_join_resumes_mid_bucket() {
2288        let dict = TermDict::new();
2289        // One left key matches three right rows; max_out=2 must resume at match 2.
2290        let left = TermBatch::try_new(vec![col(&dict, vec![iri("k")])]).unwrap();
2291        let right = TermBatch::try_new(vec![
2292            col(&dict, vec![iri("k"), iri("k"), iri("k")]),
2293            col(&dict, vec![iri("a"), iri("b"), iri("c")]),
2294        ])
2295        .unwrap();
2296        let build = hash_join_build(&right, &[0]).unwrap();
2297        let (page1, cur1) = hash_join_columnar_capped(
2298            &left,
2299            &right,
2300            &[0],
2301            &[0],
2302            &[1],
2303            &[],
2304            2,
2305            JoinCursor::default(),
2306            &build,
2307        )
2308        .unwrap();
2309        assert_eq!(page1.len(), 2);
2310        let cur1 = cur1.expect("bucket not exhausted");
2311        let (page2, cur2) =
2312            hash_join_columnar_capped(&left, &right, &[0], &[0], &[1], &[], 2, cur1, &build)
2313                .unwrap();
2314        assert_eq!(page2.len(), 1);
2315        assert!(cur2.is_none());
2316        let full = hash_join_columnar(&left, &right, &[0], &[0], &[1], &[]).unwrap();
2317        let stacked = TermBatch::concat(2, [page1, page2]).unwrap();
2318        assert_eq!(stacked.len(), full.len());
2319    }
2320
2321    #[test]
2322    fn capped_cartesian_pages_without_full_product() {
2323        let dict = TermDict::new();
2324        let left = TermBatch::try_new(vec![col(&dict, vec![iri("l1"), iri("l2")])]).unwrap();
2325        let right =
2326            TermBatch::try_new(vec![col(&dict, vec![iri("r1"), iri("r2"), iri("r3")])]).unwrap();
2327        let mut cursor = JoinCursor::default();
2328        let mut n = 0usize;
2329        loop {
2330            let (page, next) = hash_join_columnar_capped(
2331                &left,
2332                &right,
2333                &[],
2334                &[],
2335                &[0],
2336                &[],
2337                2,
2338                cursor,
2339                &JoinBuild::empty(3),
2340            )
2341            .unwrap();
2342            n += page.len();
2343            match next {
2344                Some(c) => cursor = c,
2345                None => break,
2346            }
2347        }
2348        assert_eq!(n, 6);
2349    }
2350
2351    /// The reuse guard: a build slot made over one right relation must
2352    /// never be probed with a different relation's batch — bucket row
2353    /// ids index the BUILD table, so the probe would read rows from the
2354    /// wrong relation (the star's verdict-flip bug class). The row-count
2355    /// debug assert fails loudly instead.
2356    #[cfg(debug_assertions)]
2357    #[test]
2358    #[should_panic(expected = "stale hash table")]
2359    fn build_slot_reuse_against_a_different_right_fails_loudly() {
2360        let dict = TermDict::new();
2361        let left = TermBatch::try_new(vec![col(&dict, vec![iri("l1"), iri("l2")])]).unwrap();
2362        // Built over a 2-row right (both keys bind)...
2363        let built_right = TermBatch::try_new(vec![col(&dict, vec![iri("k1"), iri("k2")])]).unwrap();
2364        let build = hash_join_build(&built_right, &[0]).unwrap();
2365        // ...probed with a 3-row right: the lengths disagree, the guard
2366        // fires before any row id can be misread.
2367        let wrong_right =
2368            TermBatch::try_new(vec![col(&dict, vec![iri("k1"), iri("k2"), iri("k3")])]).unwrap();
2369        let _ = hash_join_columnar_capped(
2370            &left,
2371            &wrong_right,
2372            &[0],
2373            &[0],
2374            &[0],
2375            &[],
2376            2,
2377            JoinCursor::default(),
2378            &build,
2379        );
2380    }
2381}
2382
2383/// Differential battery for the CSR join-table layout (`JoinTableMode::Csr`)
2384/// against the map layout (`JoinTableMode::Map`). The load-bearing property
2385/// is parity: both layouts must answer every probe with the SAME slices
2386/// (same keys, same ids, same ascending order), because
2387/// `inner_join_capped_with` is one shared loop — if the stores agree on
2388/// `get`, the entire emission and cursor protocol agrees with it, which
2389/// `capped_probe_is_identical_across_layouts` pins end to end.
2390#[cfg(test)]
2391mod csr_join_table_tests {
2392    use super::*;
2393    use crate::column::TermColumn;
2394    use crate::term_dict::TermDict;
2395    use waratah_storage::{EncodedTerm, NamedNode};
2396
2397    fn iri(local: &str) -> EncodedTerm {
2398        EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap())
2399    }
2400
2401    fn col(dict: &TermDict, terms: Vec<EncodedTerm>) -> TermColumn {
2402        TermColumn::from_terms(dict, terms).unwrap()
2403    }
2404
2405    fn opt_col(dict: &TermDict, terms: Vec<Option<EncodedTerm>>) -> TermColumn {
2406        TermColumn::from_optional_terms(dict, terms).unwrap()
2407    }
2408
2409    /// Assert the two layouts of one build are observationally equal: same
2410    /// key universe, same `get` slice per key, same emptiness. Keys are
2411    /// collected into sorted order so comparison is order-independent.
2412    fn assert_stores_agree<K>(map: &BuildStore<K>, csr: &BuildStore<K>, keys: &[K])
2413    where
2414        K: Copy + Ord + Eq + Hash + std::fmt::Debug,
2415    {
2416        assert_eq!(
2417            map.is_empty(),
2418            csr.is_empty(),
2419            "emptiness must agree (all-unbound parity)"
2420        );
2421        let (BuildStore::Map(map), BuildStore::Csr(csr)) = (map, csr) else {
2422            panic!("test must be handed the map store then the csr store");
2423        };
2424        let map_keys: std::collections::BTreeSet<K> = map.keys().copied().collect();
2425        let csr_keys: std::collections::BTreeSet<K> = csr.index.keys().copied().collect();
2426        assert_eq!(map_keys, csr_keys, "key universes must be identical");
2427        for key in keys {
2428            let map_slice = map.get(key).map(Vec::as_slice);
2429            let csr_slice = csr.get(key);
2430            assert_eq!(
2431                map_slice, csr_slice,
2432                "slice for key {key:?} must be identical across layouts"
2433            );
2434            let assert_ascending =
2435                |slice: Option<&[u32]>| slice.is_none_or(|s| s.windows(2).all(|w| w[0] < w[1]));
2436            assert!(
2437                assert_ascending(map_slice),
2438                "map slices are ascending by construction"
2439            );
2440            assert!(
2441                assert_ascending(csr_slice),
2442                "csr slices must be ascending (pass 2 walks rows in order)"
2443            );
2444        }
2445    }
2446
2447    /// Right batch over one join column with: repeated keys, unbound keys
2448    /// interleaved (never match, must be excluded), and late-arriving keys
2449    /// (first sight at the end, exercising bucket assignment order).
2450    fn tricky_right(dict: &TermDict) -> TermBatch {
2451        // key column:      k0,  —,   k1,  k0,  k2,  —,   k1,  k3
2452        // payload column:  p0,  p1,  p2,  p3,  p4,  p5,  p6,  p7
2453        TermBatch::try_new(vec![
2454            opt_col(
2455                dict,
2456                vec![
2457                    Some(iri("k0")),
2458                    None,
2459                    Some(iri("k1")),
2460                    Some(iri("k0")),
2461                    Some(iri("k2")),
2462                    None,
2463                    Some(iri("k1")),
2464                    Some(iri("k3")),
2465                ],
2466            ),
2467            col(dict, (0..8).map(|i| iri(&format!("p{i}"))).collect()),
2468        ])
2469        .unwrap()
2470    }
2471
2472    #[test]
2473    fn csr_store_matches_map_store_single_key() {
2474        let dict = TermDict::new();
2475        let right = tricky_right(&dict);
2476        let map = build_store(&right, &[0], JoinTableMode::Map, key1).unwrap();
2477        let csr = build_store(&right, &[0], JoinTableMode::Csr, key1).unwrap();
2478        let key_of = |row: usize| right.column(0).unwrap().id_at(row);
2479        let keys: Vec<u32> = (0..right.len()).map(key_of).filter(|&id| id != 0).collect();
2480        assert_stores_agree(&map, &csr, &keys);
2481        // Spot-check the documented order semantics: k0 lives at rows 0,3
2482        // and k1 at rows 2,6 — ascending within the bucket.
2483        let k0 = key_of(0);
2484        assert_eq!(map.get(&k0), Some(&[0u32, 3][..]));
2485        assert_eq!(csr.get(&k0), Some(&[0u32, 3][..]));
2486    }
2487
2488    #[test]
2489    fn csr_store_matches_map_store_wide_keys() {
2490        let dict = TermDict::new();
2491        // Two key columns plus one unbound key row; duplicates across the
2492        // pair, distinct in each column alone, so only the tuple keys
2493        // dedupe — and key8's padded representation exercises the widest
2494        // key form.
2495        let right = TermBatch::try_new(vec![
2496            opt_col(
2497                &dict,
2498                vec![
2499                    Some(iri("a")),
2500                    Some(iri("a")),
2501                    Some(iri("b")),
2502                    None,
2503                    Some(iri("b")),
2504                ],
2505            ),
2506            opt_col(
2507                &dict,
2508                vec![
2509                    Some(iri("x")),
2510                    Some(iri("y")),
2511                    Some(iri("x")),
2512                    Some(iri("z")),
2513                    Some(iri("x")),
2514                ],
2515            ),
2516            col(&dict, (0..5).map(|i| iri(&format!("v{i}"))).collect()),
2517        ])
2518        .unwrap();
2519        for (keys, probe_keys) in [
2520            (&[0usize, 1][..], vec![(1u32, 2u32), (1, 3), (2, 2)]),
2521            (&[0usize, 1][..], vec![(0u32, 1u32), (0, 2), (2, 2), (4, 2)]),
2522        ] {
2523            let map = build_store(&right, keys, JoinTableMode::Map, key2).unwrap();
2524            let csr = build_store(&right, keys, JoinTableMode::Csr, key2).unwrap();
2525            assert_stores_agree(&map, &csr, &probe_keys);
2526        }
2527        // Padded [u32; 8] keys through key8 over the same two columns.
2528        let map8 = build_store(&right, &[0, 1], JoinTableMode::Map, key8).unwrap();
2529        let csr8 = build_store(&right, &[0, 1], JoinTableMode::Csr, key8).unwrap();
2530        let mut wide_keys = Vec::new();
2531        for row in [0usize, 1, 2, 4] {
2532            wide_keys.push(key8(&right, &[0, 1], row).unwrap().unwrap());
2533        }
2534        assert_stores_agree(&map8, &csr8, &wide_keys);
2535    }
2536
2537    /// The end-to-end pin: paginate the emission-bounded probe through the
2538    /// SAME (left, right, soft pairs, max_out) under both layouts and
2539    /// require the full (page, cursor) stream to be byte-identical —
2540    /// pages compared as raw id columns, cursors compared by value.
2541    #[test]
2542    fn capped_probe_is_identical_across_layouts() {
2543        let dict = TermDict::new();
2544        // left: key | tag — one unbound key (never matches), duplicate
2545        // keys, tags that conflict with some right rows (soft rejects).
2546        let left = TermBatch::try_new(vec![
2547            opt_col(
2548                &dict,
2549                vec![
2550                    Some(iri("k0")),
2551                    None,
2552                    Some(iri("k1")),
2553                    Some(iri("k0")),
2554                    Some(iri("k9")),
2555                    Some(iri("k1")),
2556                ],
2557            ),
2558            opt_col(
2559                &dict,
2560                vec![
2561                    Some(iri("t1")),
2562                    Some(iri("t1")),
2563                    Some(iri("t2")),
2564                    None,
2565                    Some(iri("t1")),
2566                    Some(iri("t9")),
2567                ],
2568            ),
2569        ])
2570        .unwrap();
2571        // right: key | payload | tag — duplicate keys so buckets hold
2572        // several ids, one unbound key row, tag conflicts against left.
2573        let right = TermBatch::try_new(vec![
2574            opt_col(
2575                &dict,
2576                vec![
2577                    Some(iri("k0")),
2578                    Some(iri("k0")),
2579                    None,
2580                    Some(iri("k1")),
2581                    Some(iri("k0")),
2582                    Some(iri("k1")),
2583                ],
2584            ),
2585            col(&dict, (0..6).map(|i| iri(&format!("r{i}"))).collect()),
2586            opt_col(
2587                &dict,
2588                vec![
2589                    Some(iri("t1")),
2590                    Some(iri("t2")),
2591                    Some(iri("t1")),
2592                    Some(iri("t2")),
2593                    None,
2594                    Some(iri("t2")),
2595                ],
2596            ),
2597        ])
2598        .unwrap();
2599        // soft pair (left tag col 1, right tag col 2): bound-bound pairs
2600        // must agree; unbound on either side passes (fill-in at gather).
2601        let soft_pairs = [(1usize, 2usize)];
2602
2603        let run = |mode: JoinTableMode| -> Vec<(Vec<Vec<u32>>, Option<JoinCursor>)> {
2604            let build = hash_join_build_with(&right, &[0], mode).unwrap();
2605            let mut cursor = JoinCursor::default();
2606            let mut steps = Vec::new();
2607            loop {
2608                let (page, next) = hash_join_columnar_capped(
2609                    &left,
2610                    &right,
2611                    &[0],
2612                    &[0],
2613                    &[1],
2614                    &soft_pairs,
2615                    2,
2616                    cursor,
2617                    &build,
2618                )
2619                .unwrap();
2620                let cols: Vec<Vec<u32>> = (0..page.width())
2621                    .map(|c| page.column(c).unwrap().ids().to_vec())
2622                    .collect();
2623                assert_eq!(page.len(), cols.first().map(Vec::len).unwrap_or(0));
2624                let done = next.is_none();
2625                steps.push((cols, next));
2626                if done {
2627                    return steps;
2628                }
2629                cursor = next.unwrap();
2630            }
2631        };
2632
2633        let map_steps = run(JoinTableMode::Map);
2634        let csr_steps = run(JoinTableMode::Csr);
2635        assert_eq!(
2636            map_steps, csr_steps,
2637            "both layouts must drive the shared probe loop identically"
2638        );
2639        // The harness must actually exercise the interesting paths: several
2640        // pages, a mid-bucket resume, and soft-pair rejections.
2641        assert!(map_steps.len() >= 3, "expected multi-page pagination");
2642        assert!(
2643            map_steps
2644                .iter()
2645                .any(|(_, cur)| cur.is_some_and(|c| c.match_offset > 0)),
2646            "expected a cursor resuming mid-bucket"
2647        );
2648        // Expected multiset pinned by hand: k0 rows {0,1,4} × left k0 rows
2649        // {0 (t1), 3 (unbound tag)} with soft (t1|—|t1/t2/—) and k1 rows
2650        // {3,5} × left k1 rows {2 (t2), 5 (t9 — conflicts with both)}.
2651        let total: usize = map_steps
2652            .iter()
2653            .map(|(cols, _)| cols.first().map(Vec::len).unwrap_or(0))
2654            .sum();
2655        // left k0×right k0: (0,t1): r0(t1)✓ r1(t2)✗ r4(—)✓ → 2
2656        //                   (3,—):  all three pass → 3
2657        // left k1×right k1: (2,t2): r3(t2)✓ r5(t2)✓ → 2 ; (5,t9): both ✗ → 0
2658        assert_eq!(total, 7, "hand-computed join cardinality with soft pairs");
2659    }
2660
2661    #[test]
2662    fn csr_row_ids_are_ascending_within_bucket() {
2663        let dict = TermDict::new();
2664        // One key owning five rows, with unbound rows interleaved — pass 2
2665        // must still record the five ids in ascending row order.
2666        let mut key_terms = Vec::new();
2667        for row in 0..9 {
2668            key_terms.push((row % 2 == 0).then(|| iri("k")));
2669        }
2670        let right = TermBatch::try_new(vec![
2671            opt_col(&dict, key_terms),
2672            col(&dict, (0..9).map(|i| iri(&format!("x{i}"))).collect()),
2673        ])
2674        .unwrap();
2675        let csr = build_store(&right, &[0], JoinTableMode::Csr, key1).unwrap();
2676        let k = right.column(0).unwrap().id_at(0);
2677        assert_eq!(csr.get(&k), Some(&[0u32, 2, 4, 6, 8][..]));
2678    }
2679
2680    #[test]
2681    fn all_unbound_or_empty_builds_yield_empty_table_in_both_modes() {
2682        let dict = TermDict::new();
2683        let all_unbound = TermBatch::try_new(vec![
2684            opt_col(&dict, vec![None, None, None]),
2685            col(&dict, vec![iri("a"), iri("b"), iri("c")]),
2686        ])
2687        .unwrap();
2688        for mode in [JoinTableMode::Map, JoinTableMode::Csr] {
2689            let build = hash_join_build_with(&all_unbound, &[0], mode).unwrap();
2690            assert!(
2691                matches!(build.table, JoinTable::Empty),
2692                "{mode:?} all-unbound"
2693            );
2694            assert_eq!(build.right_rows, 3, "reuse guard keeps row count");
2695        }
2696        let empty =
2697            TermBatch::try_new(vec![TermColumn::from_terms(&dict, vec![]).unwrap()]).unwrap();
2698        for mode in [JoinTableMode::Map, JoinTableMode::Csr] {
2699            let build = hash_join_build_with(&empty, &[0], mode).unwrap();
2700            assert!(
2701                matches!(build.table, JoinTable::Empty),
2702                "{mode:?} empty right"
2703            );
2704        }
2705    }
2706
2707    #[test]
2708    fn build_with_selects_the_requested_layout() {
2709        let dict = TermDict::new();
2710        let right = TermBatch::try_new(vec![col(&dict, vec![iri("k"), iri("k")])]).unwrap();
2711        let map = hash_join_build_with(&right, &[0], JoinTableMode::Map).unwrap();
2712        assert!(matches!(map.table, JoinTable::Key1(BuildStore::Map(_))));
2713        let csr = hash_join_build_with(&right, &[0], JoinTableMode::Csr).unwrap();
2714        assert!(matches!(csr.table, JoinTable::Key1(BuildStore::Csr(_))));
2715    }
2716
2717    #[test]
2718    fn join_table_mode_parsing() {
2719        assert_eq!(parse_join_table_mode("map"), Some(JoinTableMode::Map));
2720        assert_eq!(parse_join_table_mode("CSR"), Some(JoinTableMode::Csr));
2721        assert_eq!(parse_join_table_mode(" csr "), Some(JoinTableMode::Csr));
2722        assert_eq!(parse_join_table_mode("bogus"), None);
2723        assert_eq!(parse_join_table_mode(""), None);
2724    }
2725}