Skip to main content

fp_join/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(rustdoc::broken_intra_doc_links)]
3
4//! Merge / join engine for **frankenpandas** — implements
5//! pandas-shape `pd.merge` / `pd.merge_ordered` / `pd.merge_asof`
6//! / `Series.join` for DataFrame and Series operands.
7//!
8//! ## Why a separate crate
9//!
10//! Joins have substantial machinery — hash-build phases, asof
11//! search, validate-mode integrity checks, bumpalo-backed
12//! intermediate buffers — that doesn't belong inside fp-frame's
13//! row/column primitives. fp-join layers on top of fp-columnar /
14//! fp-index / fp-frame and exposes a merge surface matching the
15//! pandas API shape.
16//!
17//! ## Top-level entry points
18//!
19//! - [`join_series`] / [`join_series_with_options`]: pandas
20//!   `Series.join(other, how=...)`. Returns a [`JoinedSeries`].
21//! - [`merge_dataframes`]: index-on-index merge (pandas
22//!   `df.merge(other, left_index=True, right_index=True)`).
23//! - [`merge_dataframes_on`] / [`merge_dataframes_on_with`] /
24//!   [`merge_dataframes_on_with_options`]: column-key merge
25//!   (`pd.merge(left, right, on=...)`). Returns a
26//!   [`MergedDataFrame`].
27//! - [`merge_ordered`]: pandas `pd.merge_ordered(left, right,
28//!   on=...)` — preserves ordering for time-series merges.
29//! - [`merge_asof`] / [`merge_asof_with_options`]: pandas
30//!   `pd.merge_asof(left, right, on=..., direction=...)` for
31//!   nearest-key time-aware merges. [`AsofDirection`] /
32//!   [`MergeAsofOptions`] tune the search.
33//!
34//! ## DataFrame extension trait
35//!
36//! [`DataFrameMergeExt`] adds `df.merge(...)` / `df.join(...)`
37//! method-style entry points so callers get fluent chaining
38//! after `use fp_join::DataFrameMergeExt;`.
39//!
40//! ## Tunables
41//!
42//! - [`JoinType`]: `Inner` / `Left` / `Right` / `Outer` /
43//!   `Cross`.
44//! - [`MergeValidateMode`]: pandas `validate='one_to_one' |
45//!   'one_to_many' | 'many_to_one' | 'many_to_many'` integrity
46//!   check before producing the result.
47//! - [`JoinExecutionOptions`] / [`MergeExecutionOptions`]:
48//!   per-call knobs (suffixes for overlapping columns, indicator
49//!   column, sort policy, ...).
50//!
51//! ## Error reporting
52//!
53//! [`JoinError`] enumerates the failure modes (key column
54//! mismatch, validate-mode violation, dtype mismatch on key
55//! column, ...).
56//!
57//! ## Cross-crate relationships
58//!
59//! - **fp-columnar** ([`Column`], [`ColumnError`]) for column
60//!   storage operations.
61//! - **fp-frame** for the `DataFrame` / `Series` value types.
62//! - **fp-index** for row alignment plans + label types.
63//! - **fp-types** for the underlying scalar machinery.
64
65use std::{
66    cmp::Ordering,
67    collections::{HashMap, HashSet},
68    mem::size_of,
69    sync::{Arc, OnceLock},
70};
71
72use bumpalo::{Bump, collections::Vec as BumpVec};
73use fp_columnar::{
74    Column, ColumnError, Int64DenseCycleWitness, Utf8LowerHexSequence, ValidityMask,
75};
76use fp_frame::{ColumnStore, FrameError, Series};
77use fp_index::{Index, IndexLabel};
78use fp_types::{DType, NullKind, Scalar, TypeError};
79// Join build maps key on &IndexLabel / &CompositeJoinKey and are LOOKUP-only:
80// output row order comes from probe-side iteration and per-key insertion-order
81// position Vecs, never from map iteration. So SipHash -> FxHash (rustc-hash,
82// pure safe Rust) is observationally invisible. SipHash over these label/key
83// byte images is pathologically slow (cf. fp-index dedup 3-4x); FxHash collapses
84// the build+probe hashing cost on the merge hot path.
85use rustc_hash::{FxHashMap, FxHashSet};
86use thiserror::Error;
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum JoinType {
90    Inner,
91    Left,
92    Right,
93    Outer,
94    Cross,
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum MergeValidateMode {
99    OneToOne,
100    OneToMany,
101    ManyToOne,
102    ManyToMany,
103}
104
105impl MergeValidateMode {
106    fn as_str(self) -> &'static str {
107        match self {
108            Self::OneToOne => "one_to_one",
109            Self::OneToMany => "one_to_many",
110            Self::ManyToOne => "many_to_one",
111            Self::ManyToMany => "many_to_many",
112        }
113    }
114}
115
116#[derive(Debug, Clone, PartialEq)]
117pub struct JoinedSeries {
118    pub index: Index,
119    pub left_values: Column,
120    pub right_values: Column,
121}
122
123#[derive(Debug, Error)]
124pub enum JoinError {
125    #[error(transparent)]
126    Frame(#[from] FrameError),
127    #[error(transparent)]
128    Column(#[from] ColumnError),
129}
130
131pub const DEFAULT_ARENA_BUDGET_BYTES: usize = 256 * 1024 * 1024;
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub struct JoinExecutionOptions {
135    pub use_arena: bool,
136    pub arena_budget_bytes: usize,
137}
138
139impl Default for JoinExecutionOptions {
140    fn default() -> Self {
141        Self {
142            use_arena: true,
143            arena_budget_bytes: DEFAULT_ARENA_BUDGET_BYTES,
144        }
145    }
146}
147
148#[derive(Debug, Clone, Default, PartialEq, Eq)]
149pub struct MergeExecutionOptions {
150    pub indicator_name: Option<String>,
151    pub validate_mode: Option<MergeValidateMode>,
152    pub suffixes: Option<[Option<String>; 2]>,
153    pub sort: bool,
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157struct JoinExecutionTrace {
158    used_arena: bool,
159    output_rows: usize,
160    estimated_bytes: usize,
161}
162
163pub fn join_series(
164    left: &Series,
165    right: &Series,
166    join_type: JoinType,
167) -> Result<JoinedSeries, JoinError> {
168    join_series_with_options(left, right, join_type, JoinExecutionOptions::default())
169}
170
171pub fn join_series_with_options(
172    left: &Series,
173    right: &Series,
174    join_type: JoinType,
175    options: JoinExecutionOptions,
176) -> Result<JoinedSeries, JoinError> {
177    let (joined, _) = join_series_with_trace(left, right, join_type, options)?;
178    Ok(joined)
179}
180
181fn join_series_with_trace(
182    left: &Series,
183    right: &Series,
184    join_type: JoinType,
185    options: JoinExecutionOptions,
186) -> Result<(JoinedSeries, JoinExecutionTrace), JoinError> {
187    // AG-02: borrowed-key HashMap eliminates right-index label clones during build phase.
188    let right_map = if matches!(join_type, JoinType::Right) {
189        FxHashMap::<&IndexLabel, Vec<usize>>::default()
190    } else {
191        let mut m = FxHashMap::<&IndexLabel, Vec<usize>>::default();
192        for (pos, label) in right.index().labels().iter().enumerate() {
193            m.entry(label).or_default().push(pos);
194        }
195        m
196    };
197
198    // For Right/Outer joins, also build a left_map.
199    let left_map = if matches!(join_type, JoinType::Right | JoinType::Outer) {
200        let mut m = FxHashMap::<&IndexLabel, Vec<usize>>::default();
201        for (pos, label) in left.index().labels().iter().enumerate() {
202            m.entry(label).or_default().push(pos);
203        }
204        Some(m)
205    } else {
206        None
207    };
208
209    let output_rows = estimate_output_rows(left, right, &right_map, left_map.as_ref(), join_type);
210    let estimated_bytes = estimate_intermediate_bytes(output_rows);
211    let use_arena = options.use_arena && estimated_bytes <= options.arena_budget_bytes;
212
213    let joined = if use_arena {
214        join_series_with_arena(
215            left,
216            right,
217            join_type,
218            &right_map,
219            left_map.as_ref(),
220            output_rows,
221        )?
222    } else {
223        join_series_with_global_allocator(
224            left,
225            right,
226            join_type,
227            &right_map,
228            left_map.as_ref(),
229            output_rows,
230        )?
231    };
232
233    Ok((
234        joined,
235        JoinExecutionTrace {
236            used_arena: use_arena,
237            output_rows,
238            estimated_bytes,
239        },
240    ))
241}
242
243fn estimate_output_rows(
244    left: &Series,
245    right: &Series,
246    right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
247    left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
248    join_type: JoinType,
249) -> usize {
250    if matches!(join_type, JoinType::Right) {
251        return right
252            .index()
253            .labels()
254            .iter()
255            .map(|label| match left_map.as_ref().and_then(|m| m.get(label)) {
256                Some(matches) => matches.len(),
257                None => 1,
258            })
259            .sum();
260    }
261
262    let left_matched: usize = left
263        .index()
264        .labels()
265        .iter()
266        .map(|label| match right_map.get(label) {
267            Some(matches) => matches.len(),
268            None if matches!(join_type, JoinType::Left | JoinType::Outer) => 1,
269            None => 0,
270        })
271        .sum();
272
273    match join_type {
274        JoinType::Inner | JoinType::Left => left_matched,
275        JoinType::Right => left_matched,
276        JoinType::Cross => left
277            .index()
278            .labels()
279            .len()
280            .saturating_mul(right.index().labels().len()),
281        JoinType::Outer => {
282            // Left-matched rows + unmatched right rows
283            let right_unmatched: usize = right
284                .index()
285                .labels()
286                .iter()
287                .filter(|label| {
288                    !left_map
289                        .as_ref()
290                        .expect("Outer needs left_map")
291                        .contains_key(*label)
292                })
293                .count();
294            left_matched + right_unmatched
295        }
296    }
297}
298
299fn estimate_intermediate_bytes(output_rows: usize) -> usize {
300    output_rows.saturating_mul(
301        size_of::<Option<usize>>()
302            .saturating_mul(2)
303            .saturating_add(size_of::<IndexLabel>()),
304    )
305}
306
307/// Gather a join/merge output column, applying pandas' widening when the join
308/// INVENTS a gap in it.
309///
310/// MEASURED, live pandas 2.2.3. The rule is driven by whether a gap actually
311/// lands in THIS column, not by the join type:
312///
313/// ```text
314/// l = DataFrame({'l': [10, 20, 30]}, index=[1,2,3]);  r = DataFrame({'r': [200]}, index=[2])
315///   l.join(r, how='left')   -> l int64 [10,20,30]     r float64 [nan, 200.0, nan]
316///   l.join(r, how='outer')  -> l int64 [10,20,30]     r float64 [nan, 200.0, nan]
317///   l.join(r, how='right')  -> l int64 [20]           r int64   [200]
318///   l.join(r, how='inner')  -> l int64 [20]           r int64   [200]
319/// ```
320///
321/// `l` keeps int64 on a LEFT join because it gains no gap; `r` widens on both
322/// left and outer because it does. right/inner invent nothing, so nothing
323/// widens. This function was previously called only for `JoinType::Outer`,
324/// which is why a left merge left `Int64` + `Null(Null)` where pandas has
325/// `float64` + `nan`. (br-frankenpandas-nywa8)
326///
327/// The all-valid guard is the same condition concat needed: a column that
328/// ALREADY carried a missing value is nullable, and a nullable int CAN hold the
329/// gap, so pandas keeps it. Measured:
330///
331/// ```text
332/// rv as numpy int64        , left merge -> float64 [nan, 5.0, 7.0]
333/// rv as nullable  Int64    , left merge -> Int64   [<NA>, 5, <NA>]
334/// ```
335fn reindex_join_column_with_invented_gap(
336    column: &Column,
337    positions: &[Option<usize>],
338) -> Result<Column, JoinError> {
339    if !matches!(
340        column.dtype(),
341        fp_types::DType::Int64 | fp_types::DType::Float64
342    ) {
343        return Ok(reindex_non_numeric_join_column_with_invented_gap(
344            column, positions,
345        )?);
346    }
347
348    let has_missing = positions
349        .iter()
350        .any(|slot| slot.is_none_or(|idx| idx >= column.len()));
351    if !has_missing {
352        return Ok(column.reindex_by_positions(positions)?);
353    }
354
355    // A source that already carries a gap is NULLABLE; pandas keeps the dtype
356    // and fills with NA rather than widening. Only an all-valid numpy column
357    // has to widen to hold the invented gap. Its mask answers (every cell was
358    // made a Scalar to be asked: merge on two indexes, outer, 0.26x pandas;
359    // br-frankenpandas-m3z4g).
360    if !column.validity().all() {
361        return Ok(column.reindex_by_positions(positions)?);
362    }
363
364    // Typed Float64-promote gather (br-frankenpandas-1bvcl): all-valid
365    // Int64/Float64 sources skip the per-row Scalar clone + cast +
366    // Column::new revalidation below — bit-identical (see the method's
367    // isomorphism notes in fp-columnar).
368    if let Some(column) = column.reindex_promote_float64_by_optional_positions(positions) {
369        return Ok(column);
370    }
371
372    let values = positions
373        .iter()
374        .map(|slot| match slot {
375            Some(idx) => column
376                .values()
377                .get(*idx)
378                .cloned()
379                .unwrap_or(fp_types::Scalar::Null(fp_types::NullKind::NaN)),
380            None => fp_types::Scalar::Null(fp_types::NullKind::NaN),
381        })
382        .map(|value| {
383            fp_types::cast_scalar_owned(value, fp_types::DType::Float64).map_err(ColumnError::from)
384        })
385        .collect::<Result<Vec<_>, ColumnError>>()?;
386
387    Ok(Column::new(fp_types::DType::Float64, values)?)
388}
389
390/// Gather a NON-numeric join/merge output column, minting the gap marker pandas
391/// uses for that dtype rather than the column's canonical missing.
392///
393/// A merge that invents a gap does NOT get to fill it with the dtype's own
394/// missing value. MEASURED, live pandas 2.2.3, one row invented on each side of
395/// `DataFrame({'id':[1,2,3]}).merge(DataFrame({'id':[2],'w':...}), how='left')`:
396///
397/// ```text
398///   w object/str   -> dtype object          [nan, 'x', nan]        float nan
399///   w bool         -> dtype object          [nan, True, nan]       float nan
400///   w category     -> dtype category        [nan, 'x', nan]        float nan
401///   w datetime64   -> dtype datetime64[ns]  [NaT, Timestamp, NaT]  NaT
402///   w timedelta64  -> dtype timedelta64[ns] [NaT, Timedelta, NaT]  NaT
403/// ```
404///
405/// So the temporal dtypes already agree with `Scalar::missing_for_dtype` (NaT)
406/// and keep the plain gather. The string/bool/categorical lanes do not: their
407/// canonical missing is `Null(Null)`, which is right for a SUPPLIED None
408/// (nywa8 Rule 2 — object is the dtype that can store one) and wrong for a gap
409/// the join INVENTED (Rule 1 — pandas writes a float nan even into an object
410/// column). Only this site knows which it is minting, which is the same reason
411/// the promotion above could not move into `infer_dtype`.
412///
413/// THE TWO RULES MEET INSIDE A SINGLE COLUMN, which is what makes a dtype-level
414/// table unable to express this. Measured on the composite outer merge behind
415/// `fp_p2d_033_dataframe_merge_composite_left_right_alias_outer_hardened`, with
416/// `lk2 = ['a', None, 'c']` against `rk2 = ['a', None, 'd']`:
417///
418/// ```text
419///   lk2 dtype object, kinds ['str', 'NoneType', 'str', 'float']
420///                                     ^ supplied        ^ invented
421/// ```
422///
423/// Row 1's `None` is data and survives; row 3's gap is the join's and is a nan.
424/// Copying the source cell through unchanged and substituting only for an absent
425/// position gives exactly that split, so no all-valid guard belongs here — that
426/// guard governs the numeric WIDENING above, not the marker.
427///
428/// ⚠️ pandas ALSO widens a numpy `bool` lane to object when it takes a gap. That
429/// is a dtype change FrankenPandas does not make (it keeps `DType::Bool` with the
430/// position invalid), and no fixture covers it; only the marker is corrected
431/// here. Left as-is deliberately rather than folded in unmeasured — widening bool
432/// touches br-frankenpandas-lufpu's bool-family contract and needs its own probe.
433///
434/// (br-frankenpandas-nywa8)
435fn reindex_non_numeric_join_column_with_invented_gap(
436    column: &Column,
437    positions: &[Option<usize>],
438) -> Result<Column, ColumnError> {
439    if !matches!(
440        column.dtype(),
441        fp_types::DType::Utf8 | fp_types::DType::Bool | fp_types::DType::Categorical
442    ) {
443        return column.reindex_by_positions(positions);
444    }
445
446    column.reindex_by_positions_with_absent_scalar(
447        positions,
448        fp_types::Scalar::Null(fp_types::NullKind::NaN),
449    )
450}
451
452fn coalesce_utf8_contiguous_key_column(
453    left_key_col: &Column,
454    right_key_col: &Column,
455    left_positions: &[Option<usize>],
456    right_positions: &[Option<usize>],
457) -> Option<Column> {
458    let (left_bytes, left_offsets) = left_key_col.as_utf8_contiguous()?;
459    let (right_bytes, right_offsets) = right_key_col.as_utf8_contiguous()?;
460    if left_positions.len() != right_positions.len() {
461        return None;
462    }
463
464    let mut byte_len = 0usize;
465    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
466        let (bytes, offsets, pos) = match (left_pos, right_pos) {
467            (Some(pos), _) => (left_bytes, left_offsets, *pos),
468            (None, Some(pos)) => (right_bytes, right_offsets, *pos),
469            (None, None) => return None,
470        };
471        let end = pos.checked_add(1)?;
472        let start_offset = *offsets.get(pos)?;
473        let end_offset = *offsets.get(end)?;
474        if end_offset < start_offset || end_offset > bytes.len() {
475            return None;
476        }
477        byte_len = byte_len.checked_add(end_offset - start_offset)?;
478    }
479
480    let mut bytes = Vec::with_capacity(byte_len);
481    let mut offsets = Vec::with_capacity(left_positions.len() + 1);
482    offsets.push(0);
483    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
484        let (source_bytes, source_offsets, pos) = match (left_pos, right_pos) {
485            (Some(pos), _) => (left_bytes, left_offsets, *pos),
486            (None, Some(pos)) => (right_bytes, right_offsets, *pos),
487            (None, None) => return None,
488        };
489        let start = *source_offsets.get(pos)?;
490        let end = *source_offsets.get(pos.checked_add(1)?)?;
491        bytes.extend_from_slice(source_bytes.get(start..end)?);
492        offsets.push(bytes.len());
493    }
494    Some(Column::from_utf8_contiguous(bytes, offsets))
495}
496
497/// Coalesce an all-valid temporal OUTER key directly over raw nanoseconds.
498///
499/// The optional position tapes already define output order and matched-row
500/// precedence. Any malformed tape, nullable input, mixed dtype, out-of-bounds
501/// position, or selected NaT declines to the existing Scalar fallback.
502fn coalesce_temporal_i64_key_column(
503    left_key_col: &Column,
504    right_key_col: &Column,
505    left_positions: &[Option<usize>],
506    right_positions: &[Option<usize>],
507) -> Option<Column> {
508    if left_positions.len() != right_positions.len()
509        || !left_key_col.validity().all()
510        || !right_key_col.validity().all()
511    {
512        return None;
513    }
514
515    let (left_keys, right_keys, nat, datetime_dtype) =
516        match (left_key_col.dtype(), right_key_col.dtype()) {
517            (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
518                if left_tz == right_tz =>
519            {
520                (
521                    left_key_col.as_datetime64_slice()?,
522                    right_key_col.as_datetime64_slice()?,
523                    fp_types::Timestamp::NAT,
524                    Some(DType::Datetime64 { tz: left_tz }),
525                )
526            }
527            (DType::Timedelta64, DType::Timedelta64) => (
528                left_key_col.as_timedelta64_slice()?,
529                right_key_col.as_timedelta64_slice()?,
530                fp_types::Timedelta::NAT,
531                None,
532            ),
533            _ => return None,
534        };
535
536    let mut data = Vec::with_capacity(left_positions.len());
537    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
538        let value = match (*left_pos, *right_pos) {
539            (Some(pos), _) => *left_keys.get(pos)?,
540            (None, Some(pos)) => *right_keys.get(pos)?,
541            (None, None) => return None,
542        };
543        if value == nat {
544            return None;
545        }
546        data.push(value);
547    }
548
549    let validity = ValidityMask::all_valid(data.len());
550    Some(if let Some(dtype) = datetime_dtype {
551        Column::from_datetime64_values_with_validity(data, validity).with_dtype(dtype)
552    } else {
553        Column::from_timedelta64_values_with_validity(data, validity)
554    })
555}
556
557enum SharedOptionalUtf8GatherPlan {
558    NullableRange {
559        null_prefix: usize,
560        source_start: usize,
561        source_len: usize,
562        null_suffix: usize,
563    },
564    Positions {
565        positions: Arc<[usize]>,
566        validity: ValidityMask,
567    },
568}
569
570fn shared_optional_utf8_gather_plan(
571    positions: &[Option<usize>],
572    source_len: usize,
573) -> Option<SharedOptionalUtf8GatherPlan> {
574    let mut first_valid = None;
575    let mut last_valid_exclusive = 0usize;
576    let mut has_missing = false;
577    for (out_idx, slot) in positions.iter().enumerate() {
578        match slot {
579            Some(idx) if *idx < source_len => {
580                first_valid.get_or_insert(out_idx);
581                last_valid_exclusive = out_idx + 1;
582            }
583            _ => has_missing = true,
584        }
585    }
586    if !has_missing {
587        return None;
588    }
589    if let Some(first_valid) = first_valid {
590        let source_start = positions.get(first_valid).copied().flatten()?;
591        let valid_len = last_valid_exclusive - first_valid;
592        let valid_window = positions.get(first_valid..last_valid_exclusive)?;
593        let contiguous = valid_window
594            .iter()
595            .enumerate()
596            .all(|(offset, slot)| *slot == Some(source_start + offset));
597        if contiguous
598            && source_start
599                .checked_add(valid_len)
600                .is_some_and(|end| end <= source_len)
601        {
602            return Some(SharedOptionalUtf8GatherPlan::NullableRange {
603                null_prefix: first_valid,
604                source_start,
605                source_len: valid_len,
606                null_suffix: positions.len() - last_valid_exclusive,
607            });
608        }
609    } else {
610        return Some(SharedOptionalUtf8GatherPlan::NullableRange {
611            null_prefix: positions.len(),
612            source_start: 0,
613            source_len: 0,
614            null_suffix: 0,
615        });
616    }
617
618    let mut plan = Vec::with_capacity(positions.len());
619    let mut words = vec![0_u64; positions.len().div_ceil(64)];
620    for (out_idx, slot) in positions.iter().enumerate() {
621        match slot {
622            Some(idx) if *idx < source_len => {
623                plan.push(*idx);
624                words[out_idx / 64] |= 1_u64 << (out_idx % 64);
625            }
626            _ => plan.push(usize::MAX),
627        }
628    }
629    Some(SharedOptionalUtf8GatherPlan::Positions {
630        positions: Arc::from(plan),
631        validity: ValidityMask::from_words(words, positions.len()),
632    })
633}
634
635fn reindex_with_shared_utf8_plan(
636    column: &Column,
637    positions: &[Option<usize>],
638    plan: Option<&SharedOptionalUtf8GatherPlan>,
639) -> Result<Column, JoinError> {
640    if let Some(column) = plan.and_then(|plan| reindex_eager_utf8_with_plan(column, plan)) {
641        return Ok(column);
642    }
643    // A gap here is one the join invents: NaN, as pandas (it was None;
644    // br-frankenpandas-7u2td).
645    Ok(reindex_non_numeric_join_column_with_invented_gap(
646        column, positions,
647    )?)
648}
649
650fn reindex_outer_with_shared_utf8_plan(
651    column: &Column,
652    positions: &[Option<usize>],
653    plan: Option<&SharedOptionalUtf8GatherPlan>,
654) -> Result<Column, JoinError> {
655    if let Some(column) = plan.and_then(|plan| reindex_eager_utf8_with_plan(column, plan)) {
656        return Ok(column);
657    }
658    reindex_join_column_with_invented_gap(column, positions)
659}
660
661fn reindex_eager_utf8_with_plan(
662    column: &Column,
663    plan: &SharedOptionalUtf8GatherPlan,
664) -> Option<Column> {
665    match plan {
666        SharedOptionalUtf8GatherPlan::NullableRange {
667            null_prefix,
668            source_start,
669            source_len,
670            null_suffix,
671        } => column.reindex_eager_utf8_with_nullable_range(
672            *null_prefix,
673            *source_start,
674            *source_len,
675            *null_suffix,
676        ),
677        SharedOptionalUtf8GatherPlan::Positions {
678            positions,
679            validity,
680        } => column.reindex_eager_utf8_with_shared_plan(Arc::clone(positions), validity.clone()),
681    }
682}
683
684fn sort_outer_join_rows(
685    out_labels: &mut Vec<IndexLabel>,
686    left_positions: &mut [Option<usize>],
687    right_positions: &mut [Option<usize>],
688) {
689    if out_labels.len() <= 1 {
690        return;
691    }
692
693    let mut rows = out_labels
694        .drain(..)
695        .zip(left_positions.iter().copied())
696        .zip(right_positions.iter().copied())
697        .map(|((label, left_pos), right_pos)| (label, left_pos, right_pos))
698        .collect::<Vec<_>>();
699    rows.sort_by(|left, right| left.0.cmp(&right.0));
700
701    for (idx, (label, left_pos, right_pos)) in rows.into_iter().enumerate() {
702        out_labels.push(label);
703        left_positions[idx] = left_pos;
704        right_positions[idx] = right_pos;
705    }
706}
707
708fn join_series_with_global_allocator(
709    left: &Series,
710    right: &Series,
711    join_type: JoinType,
712    right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
713    left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
714    output_rows: usize,
715) -> Result<JoinedSeries, JoinError> {
716    let mut out_labels = Vec::with_capacity(output_rows);
717    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_rows);
718    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_rows);
719
720    match join_type {
721        JoinType::Inner | JoinType::Left | JoinType::Outer => {
722            // Iterate left labels: emit matches and (for Left/Outer) unmatched left rows.
723            for (left_pos, label) in left.index().labels().iter().enumerate() {
724                if let Some(matches) = right_map.get(label) {
725                    for right_pos in matches {
726                        out_labels.push(label.clone());
727                        left_positions.push(Some(left_pos));
728                        right_positions.push(Some(*right_pos));
729                    }
730                    continue;
731                }
732
733                if matches!(join_type, JoinType::Left | JoinType::Outer) {
734                    out_labels.push(label.clone());
735                    left_positions.push(Some(left_pos));
736                    right_positions.push(None);
737                }
738            }
739
740            // For Outer: append right labels that have no match in left.
741            if matches!(join_type, JoinType::Outer) {
742                let left_map = left_map.as_ref().expect("left_map required for Outer join");
743                for (right_pos, label) in right.index().labels().iter().enumerate() {
744                    if !left_map.contains_key(label) {
745                        out_labels.push(label.clone());
746                        left_positions.push(None);
747                        right_positions.push(Some(right_pos));
748                    }
749                }
750            }
751        }
752        JoinType::Right => {
753            // Iterate right labels: emit matches and unmatched right rows.
754            let left_map = left_map.expect("left_map required for Right join");
755            for (right_pos, label) in right.index().labels().iter().enumerate() {
756                if let Some(matches) = left_map.get(label) {
757                    for left_pos in matches {
758                        out_labels.push(label.clone());
759                        left_positions.push(Some(*left_pos));
760                        right_positions.push(Some(right_pos));
761                    }
762                    continue;
763                }
764
765                out_labels.push(label.clone());
766                left_positions.push(None);
767                right_positions.push(Some(right_pos));
768            }
769        }
770        JoinType::Cross => {
771            for (left_pos, left_label) in left.index().labels().iter().enumerate() {
772                for (right_pos, _) in right.index().labels().iter().enumerate() {
773                    out_labels.push(left_label.clone());
774                    left_positions.push(Some(left_pos));
775                    right_positions.push(Some(right_pos));
776                }
777            }
778        }
779    }
780
781    if matches!(join_type, JoinType::Outer) {
782        sort_outer_join_rows(&mut out_labels, &mut left_positions, &mut right_positions);
783    }
784
785    // Every join type, not just Outer: the widening is caused by a gap landing
786    // in THIS column, and a left join invents gaps on the right side just as an
787    // outer join does. The helper is a no-op when no gap is invented, so
788    // right/inner are unaffected. (br-frankenpandas-nywa8)
789    let left_values = reindex_join_column_with_invented_gap(left.column(), &left_positions)?;
790    let right_values = reindex_join_column_with_invented_gap(right.column(), &right_positions)?;
791
792    // Per br-frankenpandas-wp0n6: pandas Series.join preserves shared
793    // index name (preserved when both operands agree, None when they differ).
794    let shared_name = if left.index().name().eq(&right.index().name()) {
795        left.index().name().cloned()
796    } else {
797        None
798    };
799    Ok(JoinedSeries {
800        index: Index::new(out_labels).rename_index(shared_name),
801        left_values,
802        right_values,
803    })
804}
805
806fn join_series_with_arena(
807    left: &Series,
808    right: &Series,
809    join_type: JoinType,
810    right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
811    left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
812    output_rows: usize,
813) -> Result<JoinedSeries, JoinError> {
814    let arena = Bump::new();
815    let mut out_labels = Vec::with_capacity(output_rows);
816    let mut left_positions = BumpVec::<Option<usize>>::with_capacity_in(output_rows, &arena);
817    let mut right_positions = BumpVec::<Option<usize>>::with_capacity_in(output_rows, &arena);
818
819    match join_type {
820        JoinType::Inner | JoinType::Left | JoinType::Outer => {
821            for (left_pos, label) in left.index().labels().iter().enumerate() {
822                if let Some(matches) = right_map.get(label) {
823                    for right_pos in matches {
824                        out_labels.push(label.clone());
825                        left_positions.push(Some(left_pos));
826                        right_positions.push(Some(*right_pos));
827                    }
828                    continue;
829                }
830
831                if matches!(join_type, JoinType::Left | JoinType::Outer) {
832                    out_labels.push(label.clone());
833                    left_positions.push(Some(left_pos));
834                    right_positions.push(None);
835                }
836            }
837
838            if matches!(join_type, JoinType::Outer) {
839                let left_map = left_map.as_ref().expect("left_map required for Outer join");
840                for (right_pos, label) in right.index().labels().iter().enumerate() {
841                    if !left_map.contains_key(label) {
842                        out_labels.push(label.clone());
843                        left_positions.push(None);
844                        right_positions.push(Some(right_pos));
845                    }
846                }
847            }
848        }
849        JoinType::Right => {
850            let left_map = left_map.expect("left_map required for Right join");
851            for (right_pos, label) in right.index().labels().iter().enumerate() {
852                if let Some(matches) = left_map.get(label) {
853                    for left_pos in matches {
854                        out_labels.push(label.clone());
855                        left_positions.push(Some(*left_pos));
856                        right_positions.push(Some(right_pos));
857                    }
858                    continue;
859                }
860
861                out_labels.push(label.clone());
862                left_positions.push(None);
863                right_positions.push(Some(right_pos));
864            }
865        }
866        JoinType::Cross => {
867            for (left_pos, left_label) in left.index().labels().iter().enumerate() {
868                for (right_pos, _) in right.index().labels().iter().enumerate() {
869                    out_labels.push(left_label.clone());
870                    left_positions.push(Some(left_pos));
871                    right_positions.push(Some(right_pos));
872                }
873            }
874        }
875    }
876
877    if matches!(join_type, JoinType::Outer) {
878        sort_outer_join_rows(
879            &mut out_labels,
880            left_positions.as_mut_slice(),
881            right_positions.as_mut_slice(),
882        );
883    }
884
885    // Every join type — see the sibling site above (br-frankenpandas-nywa8).
886    let left_values =
887        reindex_join_column_with_invented_gap(left.column(), left_positions.as_slice())?;
888    let right_values =
889        reindex_join_column_with_invented_gap(right.column(), right_positions.as_slice())?;
890
891    // Per br-frankenpandas-ceces: pandas Series.join preserves shared
892    // index name. Sister to join_series fix (wp0n6).
893    let shared_name = if left.index().name().eq(&right.index().name()) {
894        left.index().name().cloned()
895    } else {
896        None
897    };
898    Ok(JoinedSeries {
899        index: Index::new(out_labels).rename_index(shared_name),
900        left_values,
901        right_values,
902    })
903}
904
905/// Result of a DataFrame merge operation.
906#[derive(Debug, Clone, PartialEq)]
907pub struct MergedDataFrame {
908    pub index: Index,
909    /// br-frankenpandas-u387a: a `ColumnStore`, not a `BTreeMap`. Merge suffix
910    /// collisions are one of the pandas cases the duplicate-label work
911    /// (br-frankenpandas-ih4t0) has to support, so a map here would just be
912    /// the same leak one crate over — it cannot represent the repeated labels
913    /// a collision produces.
914    pub columns: ColumnStore,
915    /// Output column order in pandas' convention (key/left columns in their
916    /// source order, then right non-key columns). The `columns` map is sorted,
917    /// so this Vec carries the real order for materialization — br-691lh.
918    pub column_order: Vec<String>,
919}
920
921#[derive(Debug, Clone, PartialEq, Eq, Hash)]
922enum JoinKeyComponent {
923    Present(IndexLabel),
924    FloatBits(u64),
925    Missing,
926}
927
928impl Ord for JoinKeyComponent {
929    fn cmp(&self, other: &Self) -> Ordering {
930        use JoinKeyComponent::{FloatBits, Missing, Present};
931        match (self, other) {
932            (Missing, Missing) => Ordering::Equal,
933            (Missing, _) => Ordering::Greater,
934            (_, Missing) => Ordering::Less,
935            (Present(IndexLabel::Int64(a)), Present(IndexLabel::Int64(b))) => a.cmp(b),
936            (Present(IndexLabel::Utf8(a)), Present(IndexLabel::Utf8(b))) => a.cmp(b),
937            (Present(IndexLabel::Timedelta64(a)), Present(IndexLabel::Timedelta64(b))) => a.cmp(b),
938            (Present(IndexLabel::Datetime64(a)), Present(IndexLabel::Datetime64(b))) => a.cmp(b),
939            // Typed-null labels sort after every concrete label (nulls-last,
940            // consistent with the derived IndexLabel Ord) but before Missing.
941            // Unreachable today: join key extraction maps missing to Missing,
942            // never Present(Null).
943            (Present(IndexLabel::Null(a)), Present(IndexLabel::Null(b))) => a.cmp(b),
944            (Present(IndexLabel::Null(_)), Present(_)) => Ordering::Greater,
945            (Present(_), Present(IndexLabel::Null(_))) => Ordering::Less,
946            (Present(IndexLabel::Null(_)), FloatBits(_)) => Ordering::Greater,
947            (FloatBits(_), Present(IndexLabel::Null(_))) => Ordering::Less,
948            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Less,
949            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Int64(_))) => Ordering::Greater,
950            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Int64(_))) => {
951                Ordering::Greater
952            }
953            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Utf8(_))) => {
954                Ordering::Greater
955            }
956            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
957            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
958            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Int64(_))) => {
959                Ordering::Greater
960            }
961            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Greater,
962            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Timedelta64(_))) => {
963                Ordering::Greater
964            }
965            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
966            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
967            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Datetime64(_))) => {
968                Ordering::Less
969            }
970            (Present(IndexLabel::Int64(a)), FloatBits(bits)) => {
971                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
972                if ord == Ordering::Equal {
973                    Ordering::Less
974                } else {
975                    ord
976                }
977            }
978            (FloatBits(bits), Present(IndexLabel::Int64(a))) => {
979                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
980                if ord == Ordering::Equal {
981                    Ordering::Greater
982                } else {
983                    ord
984                }
985            }
986            (Present(IndexLabel::Timedelta64(a)), FloatBits(bits)) => {
987                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
988                if ord == Ordering::Equal {
989                    Ordering::Less
990                } else {
991                    ord
992                }
993            }
994            (FloatBits(bits), Present(IndexLabel::Timedelta64(a))) => {
995                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
996                if ord == Ordering::Equal {
997                    Ordering::Greater
998                } else {
999                    ord
1000                }
1001            }
1002            (Present(IndexLabel::Datetime64(a)), FloatBits(bits)) => {
1003                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
1004                if ord == Ordering::Equal {
1005                    Ordering::Less
1006                } else {
1007                    ord
1008                }
1009            }
1010            (FloatBits(bits), Present(IndexLabel::Datetime64(a))) => {
1011                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
1012                if ord == Ordering::Equal {
1013                    Ordering::Greater
1014                } else {
1015                    ord
1016                }
1017            }
1018            (FloatBits(a_bits), FloatBits(b_bits)) => {
1019                f64::from_bits(*a_bits).total_cmp(&f64::from_bits(*b_bits))
1020            }
1021            (FloatBits(_), Present(IndexLabel::Utf8(_))) => Ordering::Less,
1022            (Present(IndexLabel::Utf8(_)), FloatBits(_)) => Ordering::Greater,
1023            // Float64/Bool index labels (br-frankenpandas-i10en). Join key
1024            // extraction maps float keys to FloatBits and bool keys to Int64, so
1025            // a Present(Float64)/Present(Bool) join key is unreachable today;
1026            // these arms only keep the manual `Ord` total (same-variant compares
1027            // by value, cross-variant by a stable variant rank).
1028            (Present(IndexLabel::Float64(a)), Present(IndexLabel::Float64(b))) => a.cmp(b),
1029            (Present(IndexLabel::Bool(a)), Present(IndexLabel::Bool(b))) => a.cmp(b),
1030            (Present(IndexLabel::Object(a)), Present(IndexLabel::Object(b))) => a.cmp(b),
1031            (a, b) => join_component_rank(a).cmp(&join_component_rank(b)),
1032        }
1033    }
1034}
1035
1036/// Stable per-variant rank used only as the cross-variant fallback for the
1037/// (unreachable) Float64/Bool join-key cases above, keeping `Ord` total.
1038fn join_component_rank(c: &JoinKeyComponent) -> u8 {
1039    use JoinKeyComponent::{FloatBits, Missing, Present};
1040    match c {
1041        Present(IndexLabel::Int64(_)) => 0,
1042        Present(IndexLabel::Float64(_)) => 1,
1043        Present(IndexLabel::Bool(_)) => 2,
1044        Present(IndexLabel::Utf8(_)) => 3,
1045        Present(IndexLabel::Timedelta64(_)) => 4,
1046        Present(IndexLabel::Datetime64(_)) => 5,
1047        Present(IndexLabel::Object(_)) => 6,
1048        Present(IndexLabel::Period(_)) => 7,
1049        Present(IndexLabel::Interval(_)) => 8,
1050        Present(IndexLabel::Null(_)) => 9,
1051        FloatBits(_) => 10,
1052        Missing => 11,
1053    }
1054}
1055
1056impl PartialOrd for JoinKeyComponent {
1057    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1058        Some(self.cmp(other))
1059    }
1060}
1061
1062fn scalar_to_key_component(s: &fp_types::Scalar) -> JoinKeyComponent {
1063    match s {
1064        fp_types::Scalar::Int64(v) => JoinKeyComponent::Present(IndexLabel::Int64(*v)),
1065        fp_types::Scalar::Float64(v) if !v.is_nan() => {
1066            if *v == v.trunc() && *v >= i64::MIN as f64 && *v < 9223372036854775808.0 {
1067                JoinKeyComponent::Present(IndexLabel::Int64(*v as i64))
1068            } else {
1069                JoinKeyComponent::FloatBits(v.to_bits())
1070            }
1071        }
1072        fp_types::Scalar::Utf8(v) => JoinKeyComponent::Present(IndexLabel::Utf8(v.clone())),
1073        fp_types::Scalar::Bool(b) => JoinKeyComponent::Present(IndexLabel::Int64(i64::from(*b))),
1074        fp_types::Scalar::Timedelta64(v) if *v != fp_types::Timedelta::NAT => {
1075            JoinKeyComponent::Present(IndexLabel::Timedelta64(*v))
1076        }
1077        fp_types::Scalar::Datetime64(v) if *v != fp_types::Timestamp::NAT => {
1078            JoinKeyComponent::Present(IndexLabel::Datetime64(*v))
1079        }
1080        fp_types::Scalar::Object(object @ fp_types::ObjectValue::Bytes(_)) => {
1081            JoinKeyComponent::Present(IndexLabel::Object(object.clone()))
1082        }
1083        _ => JoinKeyComponent::Missing, // Null, NaN, NaT
1084    }
1085}
1086
1087/// A row's composite join key. Inline storage for the single-key case (the
1088/// overwhelmingly common join shape) avoids a heap allocation per row during
1089/// key extraction; multi-column keys spill to the heap as before. `SmallVec`
1090/// shares `Vec`'s `Hash`/`Eq`/`Ord`/`Deref<[T]>` semantics, so the join result
1091/// (key equality, grouping, output order) is bit-identical.
1092type CompositeJoinKey = smallvec::SmallVec<[JoinKeyComponent; 1]>;
1093
1094/// `(left_positions, right_positions, out_row_keys)` produced by the merge
1095/// position-computation phase. `out_row_keys` is `Some` only when the rows must
1096/// be reordered by join key (sort or outer join).
1097type MergeRowPositions = (
1098    Vec<Option<usize>>,
1099    Vec<Option<usize>>,
1100    Option<Vec<CompositeJoinKey>>,
1101);
1102type JoinPositionBucket = smallvec::SmallVec<[usize; 1]>;
1103
1104/// Unsupported object keys must fail before either a typed fast path or the
1105/// generic key collector can mistake them for missing values. Matching the
1106/// variant avoids calling an opaque host object's repr, hash or equality.
1107fn validate_object_join_keys(column: &Column) -> Result<(), JoinError> {
1108    // These representations hold only text and missing markers. Preserve the
1109    // typed string fast paths without allocating a Scalar/String per key.
1110    if column.as_utf8_window().is_some() || column.as_nullable_utf8_contiguous().is_some() {
1111        return Ok(());
1112    }
1113    if matches!(column.dtype(), DType::Utf8 | DType::Categorical)
1114        && column.values().iter().any(|value| {
1115            matches!(
1116                value,
1117                Scalar::Object(fp_types::ObjectValue::List(_) | fp_types::ObjectValue::Host(_))
1118            )
1119        })
1120    {
1121        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1122            "list and host object join keys are unsupported; bytes keys are supported".to_owned(),
1123        )));
1124    }
1125    Ok(())
1126}
1127
1128fn collect_join_key_columns<'a>(
1129    frame: &'a fp_frame::DataFrame,
1130    on: &[&str],
1131    side: &str,
1132) -> Result<Vec<&'a Column>, JoinError> {
1133    let mut key_columns = Vec::with_capacity(on.len());
1134    for key_name in on {
1135        let key_column = frame.column(key_name).ok_or_else(|| {
1136            JoinError::Frame(FrameError::CompatibilityRejected(format!(
1137                "{side} DataFrame missing key column '{key_name}'"
1138            )))
1139        })?;
1140        validate_object_join_keys(key_column)?;
1141        key_columns.push(key_column);
1142    }
1143    Ok(key_columns)
1144}
1145
1146fn collect_composite_keys(key_columns: &[&Column]) -> Vec<CompositeJoinKey> {
1147    let row_count = key_columns.first().map_or(0, |column| column.len());
1148    let mut out = Vec::with_capacity(row_count);
1149
1150    for row in 0..row_count {
1151        let mut parts: CompositeJoinKey = smallvec::SmallVec::with_capacity(key_columns.len());
1152        for column in key_columns {
1153            parts.push(scalar_to_key_component(&column.values()[row]));
1154        }
1155        out.push(parts);
1156    }
1157
1158    out
1159}
1160
1161fn collect_single_join_keys(column: &Column) -> Vec<JoinKeyComponent> {
1162    column
1163        .values()
1164        .iter()
1165        .map(scalar_to_key_component)
1166        .collect()
1167}
1168
1169fn has_duplicate_composite_keys(keys: &[CompositeJoinKey]) -> bool {
1170    let mut seen = FxHashSet::with_capacity_and_hasher(keys.len(), Default::default());
1171    for key in keys {
1172        if !seen.insert(key) {
1173            return true;
1174        }
1175    }
1176    false
1177}
1178
1179/// validate='one_to_one' with repeated keys on both sides, which pandas
1180/// reports as 'not unique in either left or right dataset'.
1181const ONE_TO_ONE_BOTH_SIDES_DUPLICATED: &str =
1182    "merge validate='one_to_one' failed: left and right keys are not unique";
1183
1184fn validate_merge_cardinality(
1185    validate_mode: MergeValidateMode,
1186    left_keys: &[CompositeJoinKey],
1187    right_keys: &[CompositeJoinKey],
1188) -> Result<(), JoinError> {
1189    let fail = |message: &str| {
1190        Err(JoinError::Frame(FrameError::CompatibilityRejected(
1191            message.to_owned(),
1192        )))
1193    };
1194
1195    match validate_mode {
1196        MergeValidateMode::OneToOne => {
1197            // pandas names both sides when neither is unique ('not unique in
1198            // either left or right dataset'), else the one that is not (the
1199            // left failure was reported first whatever the right held;
1200            // br-frankenpandas-z6jxh).
1201            match (
1202                has_duplicate_composite_keys(left_keys),
1203                has_duplicate_composite_keys(right_keys),
1204            ) {
1205                (true, true) => return fail(ONE_TO_ONE_BOTH_SIDES_DUPLICATED),
1206                (true, false) => {
1207                    return fail("merge validate='one_to_one' failed: left keys are not unique");
1208                }
1209                (false, true) => {
1210                    return fail("merge validate='one_to_one' failed: right keys are not unique");
1211                }
1212                (false, false) => {}
1213            }
1214        }
1215        MergeValidateMode::OneToMany => {
1216            if has_duplicate_composite_keys(left_keys) {
1217                return fail("merge validate='one_to_many' failed: left keys are not unique");
1218            }
1219        }
1220        MergeValidateMode::ManyToOne => {
1221            if has_duplicate_composite_keys(right_keys) {
1222                return fail("merge validate='many_to_one' failed: right keys are not unique");
1223            }
1224        }
1225        MergeValidateMode::ManyToMany => {}
1226    }
1227
1228    Ok(())
1229}
1230
1231fn validate_mode_allows_fast_positions(validate_mode: Option<MergeValidateMode>) -> bool {
1232    matches!(validate_mode, None | Some(MergeValidateMode::ManyToMany))
1233}
1234
1235/// Duplicate detection straight off a single all-valid `Int64` key buffer.
1236///
1237/// br-frankenpandas-uza04. `has_duplicate_composite_keys` needs a
1238/// `Vec<CompositeJoinKey>`, which `collect_composite_keys` builds by reading
1239/// `column.values()[row]` — the 32 B/elem `Scalar` spine plus a `SmallVec` per
1240/// row. For one all-valid Int64 column the same question is an `FxHashSet<i64>`
1241/// over the contiguous buffer, pre-sized so the build side never rehashes.
1242///
1243/// Returns `None` when this shape does not apply (more than one key column, a
1244/// non-`Int64` dtype, or any missing value — `as_i64_slice` answers only for
1245/// all-valid `DType::Int64`), and the caller keeps the generic path, which is
1246/// also where null-key duplicate semantics stay owned.
1247fn typed_single_int64_key_has_duplicates(key_columns: &[&Column]) -> Option<bool> {
1248    let [column] = key_columns else {
1249        return None;
1250    };
1251    let data = column.as_i64_slice()?;
1252    let mut seen = FxHashSet::with_capacity_and_hasher(data.len(), Default::default());
1253    Some(!data.iter().all(|&key| seen.insert(key)))
1254}
1255
1256/// Typed sibling of [`validate_merge_cardinality`]: enforce the mode off raw
1257/// key buffers, and report whether it was able to.
1258///
1259/// `Ok(true)` means the mode was fully enforced here and PASSED, so the caller
1260/// may use the fast positions paths. `Ok(false)` means this shape is not
1261/// covered and the generic path must still run `validate_merge_cardinality`.
1262/// `Err` is a real validation failure and carries the SAME message the generic
1263/// checker produces, because the two must be indistinguishable to a caller.
1264///
1265/// Precedence matters and is preserved: `OneToOne` reports a left-side failure
1266/// before looking at the right, exactly as the generic checker does. It also
1267/// declines outright unless BOTH sides are typed, so it can never report a
1268/// right-side failure that the generic checker would have pre-empted with a
1269/// left-side one it could not see.
1270fn typed_validate_merge_cardinality(
1271    validate_mode: MergeValidateMode,
1272    left_key_columns: &[&Column],
1273    right_key_columns: &[&Column],
1274) -> Result<bool, JoinError> {
1275    let fail = |message: &str| {
1276        Err(JoinError::Frame(FrameError::CompatibilityRejected(
1277            message.to_owned(),
1278        )))
1279    };
1280
1281    match validate_mode {
1282        MergeValidateMode::ManyToMany => Ok(true),
1283        MergeValidateMode::OneToMany => {
1284            match typed_single_int64_key_has_duplicates(left_key_columns) {
1285                Some(true) => fail("merge validate='one_to_many' failed: left keys are not unique"),
1286                Some(false) => Ok(true),
1287                None => Ok(false),
1288            }
1289        }
1290        MergeValidateMode::ManyToOne => {
1291            match typed_single_int64_key_has_duplicates(right_key_columns) {
1292                Some(true) => {
1293                    fail("merge validate='many_to_one' failed: right keys are not unique")
1294                }
1295                Some(false) => Ok(true),
1296                None => Ok(false),
1297            }
1298        }
1299        MergeValidateMode::OneToOne => {
1300            // Both sides must be typed before deciding anything: the failure
1301            // names each side that repeats, so answering from one side alone
1302            // could surface the wrong message.
1303            let Some(left_duplicated) = typed_single_int64_key_has_duplicates(left_key_columns)
1304            else {
1305                return Ok(false);
1306            };
1307            let Some(right_duplicated) = typed_single_int64_key_has_duplicates(right_key_columns)
1308            else {
1309                return Ok(false);
1310            };
1311            match (left_duplicated, right_duplicated) {
1312                (true, true) => fail(ONE_TO_ONE_BOTH_SIDES_DUPLICATED),
1313                (true, false) => {
1314                    fail("merge validate='one_to_one' failed: left keys are not unique")
1315                }
1316                (false, true) => {
1317                    fail("merge validate='one_to_one' failed: right keys are not unique")
1318                }
1319                (false, false) => Ok(true),
1320            }
1321        }
1322    }
1323}
1324
1325fn reorder_vec_by_index<T: Clone>(values: &mut Vec<T>, order: &[usize]) {
1326    let existing = values.clone();
1327    values.clear();
1328    values.reserve(order.len());
1329    for &idx in order {
1330        values.push(existing[idx].clone());
1331    }
1332}
1333
1334fn sort_merge_rows_by_join_keys(
1335    left_keys: &[CompositeJoinKey],
1336    right_keys: &[CompositeJoinKey],
1337    left_positions: &mut Vec<Option<usize>>,
1338    right_positions: &mut Vec<Option<usize>>,
1339) {
1340    let n = left_positions.len();
1341    if n <= 1 {
1342        return;
1343    }
1344    // pandas sorts merge output by the join key. The naive O(n·log n) COMPARISON
1345    // sort re-compares full keys (string compares for Utf8) on every step. Instead
1346    // FACTORIZE the keys to dense ranks (sort only the DISTINCT keys once, d≪n)
1347    // then STABLE counting-sort the rows by rank — O(n + d·log d). Crucially, each
1348    // output row's key is read BY REFERENCE from the already-built left_keys /
1349    // right_keys via its position (matched / unmatched-left rows take the left key,
1350    // unmatched-right rows take the right key — exactly what the removed per-row
1351    // `out_row_keys` clone stored), so the ~n String-owning CompositeJoinKey clones
1352    // that dominated outer merge are gone. Bit-identical to the prior path: same
1353    // per-row key, same `cmp`-ordered ranks (over a superset of distinct keys —
1354    // unused ranks are just empty counting-sort buckets), same stable
1355    // ascending-index emission within each rank.
1356    let mut distinct: Vec<&CompositeJoinKey> = {
1357        let mut set = FxHashSet::default();
1358        left_keys
1359            .iter()
1360            .chain(right_keys.iter())
1361            .filter(|k| set.insert(*k))
1362            .collect()
1363    };
1364    distinct.sort_unstable();
1365    let d = distinct.len();
1366    let mut rank_of: FxHashMap<&CompositeJoinKey, u32> = FxHashMap::default();
1367    rank_of.reserve(d);
1368    for (r, k) in distinct.iter().enumerate() {
1369        rank_of.insert(*k, r as u32);
1370    }
1371    let left_rank: Vec<u32> = left_keys.iter().map(|k| rank_of[k]).collect();
1372    let right_rank: Vec<u32> = right_keys.iter().map(|k| rank_of[k]).collect();
1373    let ranks: Vec<u32> = left_positions
1374        .iter()
1375        .zip(right_positions.iter())
1376        .map(|(lp, rp)| match lp {
1377            Some(p) => left_rank[*p],
1378            None => right_rank[rp.expect("an unmatched merge row has a right position")],
1379        })
1380        .collect();
1381    let mut counts = vec![0usize; d + 1];
1382    for &r in &ranks {
1383        counts[r as usize + 1] += 1;
1384    }
1385    for i in 0..d {
1386        counts[i + 1] += counts[i];
1387    }
1388    // `order[new_slot] = old_idx`, matching the comparison sort's permutation —
1389    // stable because rows are scattered in ascending original-index order.
1390    let mut cursor = counts;
1391    let mut order = vec![0usize; n];
1392    for (i, &r) in ranks.iter().enumerate() {
1393        let slot = cursor[r as usize];
1394        order[slot] = i;
1395        cursor[r as usize] = slot + 1;
1396    }
1397    reorder_vec_by_index(left_positions, &order);
1398    reorder_vec_by_index(right_positions, &order);
1399}
1400
1401fn push_merge_row_key(out_row_keys: &mut Option<Vec<CompositeJoinKey>>, key: &CompositeJoinKey) {
1402    if let Some(out_row_keys) = out_row_keys {
1403        out_row_keys.push(key.clone());
1404    }
1405}
1406
1407#[derive(Debug, Clone, PartialEq, Eq)]
1408struct ResolvedMergeSuffixes {
1409    left: Option<String>,
1410    right: Option<String>,
1411}
1412
1413impl Default for ResolvedMergeSuffixes {
1414    fn default() -> Self {
1415        Self {
1416            left: Some("_x".to_owned()),
1417            right: Some("_y".to_owned()),
1418        }
1419    }
1420}
1421
1422fn resolve_merge_suffixes(suffixes: Option<[Option<String>; 2]>) -> ResolvedMergeSuffixes {
1423    match suffixes {
1424        Some([left, right]) => ResolvedMergeSuffixes { left, right },
1425        None => ResolvedMergeSuffixes::default(),
1426    }
1427}
1428
1429fn suffix_is_present(suffix: Option<&str>) -> bool {
1430    suffix.is_some_and(|value| !value.is_empty())
1431}
1432
1433fn apply_merge_suffix(name: &str, suffix: Option<&str>) -> String {
1434    match suffix {
1435        Some(value) if !value.is_empty() => format!("{name}{value}"),
1436        _ => name.to_owned(),
1437    }
1438}
1439
1440fn collect_overlapping_column_names(
1441    left_col_names: &HashSet<&String>,
1442    right_col_names: &HashSet<&String>,
1443    excluded_names: &HashSet<&str>,
1444) -> Vec<String> {
1445    let mut overlaps = left_col_names
1446        .iter()
1447        .filter(|name| right_col_names.contains(*name) && !excluded_names.contains(name.as_str()))
1448        .map(|name| (*name).clone())
1449        .collect::<Vec<_>>();
1450    overlaps.sort();
1451    overlaps
1452}
1453
1454const SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT: usize = 8;
1455
1456fn column_name_lookup_contains(
1457    names: &[&String],
1458    hashed_names: Option<&HashSet<&str>>,
1459    target: &str,
1460) -> bool {
1461    if let Some(hashed_names) = hashed_names {
1462        hashed_names.contains(target)
1463    } else {
1464        names.iter().any(|name| name.as_str() == target)
1465    }
1466}
1467
1468fn ensure_merge_suffixes_for_overlaps(
1469    overlap_names: &[String],
1470    suffixes: &ResolvedMergeSuffixes,
1471) -> Result<(), JoinError> {
1472    if overlap_names.is_empty() {
1473        return Ok(());
1474    }
1475    if !suffix_is_present(suffixes.left.as_deref()) && !suffix_is_present(suffixes.right.as_deref())
1476    {
1477        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1478            format!(
1479                "columns overlap but no suffix specified: {}",
1480                overlap_names.join(", ")
1481            ),
1482        )));
1483    }
1484    Ok(())
1485}
1486
1487fn validate_merge_suffixes_intra_frame(
1488    left_cols: &[&String],
1489    right_cols: &[&String],
1490    shared_key_names: &HashSet<&str>,
1491    suffixes: &ResolvedMergeSuffixes,
1492) -> Result<(), JoinError> {
1493    let left_col_names: HashSet<&String> = left_cols.iter().copied().collect();
1494    let right_col_names: HashSet<&String> = right_cols.iter().copied().collect();
1495    let overlap_names =
1496        collect_overlapping_column_names(&left_col_names, &right_col_names, shared_key_names);
1497    ensure_merge_suffixes_for_overlaps(&overlap_names, suffixes)?;
1498
1499    let overlap_set: HashSet<&str> = overlap_names.iter().map(|s| s.as_str()).collect();
1500    let mut dups = Vec::new();
1501
1502    // Check left frame for duplicates caused by suffixes
1503    let mut left_seen_orig = HashSet::new();
1504    let mut left_orig_dups = HashSet::new();
1505    for &name in left_cols {
1506        if !left_seen_orig.insert(name.as_str()) {
1507            left_orig_dups.insert(name.as_str());
1508        }
1509    }
1510
1511    let mut left_renamed_seen = HashSet::new();
1512    for &name in left_cols {
1513        let renamed = if overlap_set.contains(name.as_str()) {
1514            apply_merge_suffix(name, suffixes.left.as_deref())
1515        } else {
1516            name.clone()
1517        };
1518        if !left_renamed_seen.insert(renamed.clone()) && !left_orig_dups.contains(name.as_str()) {
1519            dups.push(renamed);
1520        }
1521    }
1522
1523    // Check right frame for duplicates caused by suffixes (excluding shared keys dropped from right output)
1524    let right_output_cols: Vec<&String> = right_cols
1525        .iter()
1526        .copied()
1527        .filter(|name| !shared_key_names.contains(name.as_str()))
1528        .collect();
1529
1530    let mut right_seen_orig = HashSet::new();
1531    let mut right_orig_dups = HashSet::new();
1532    for &name in &right_output_cols {
1533        if !right_seen_orig.insert(name.as_str()) {
1534            right_orig_dups.insert(name.as_str());
1535        }
1536    }
1537
1538    let mut right_renamed_seen = HashSet::new();
1539    for &name in &right_output_cols {
1540        let renamed = if overlap_set.contains(name.as_str()) {
1541            apply_merge_suffix(name, suffixes.right.as_deref())
1542        } else {
1543            (*name).clone()
1544        };
1545        if !right_renamed_seen.insert(renamed.clone()) && !right_orig_dups.contains(name.as_str()) {
1546            dups.push(renamed);
1547        }
1548    }
1549
1550    if !dups.is_empty() {
1551        dups.sort();
1552        dups.dedup();
1553        let formatted = format!(
1554            "{{{}}}",
1555            dups.iter()
1556                .map(|d| format!("'{d}'"))
1557                .collect::<Vec<_>>()
1558                .join(", ")
1559        );
1560        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1561            format!("Passing 'suffixes' which cause duplicate columns {formatted} is not allowed."),
1562        )));
1563    }
1564
1565    Ok(())
1566}
1567
1568fn insert_merged_output_column(
1569    output_columns: &mut ColumnStore,
1570    order: &mut Vec<String>,
1571    name: String,
1572    column: Column,
1573) -> Result<(), JoinError> {
1574    order.push(name.clone());
1575    output_columns.push(name, column);
1576    Ok(())
1577}
1578
1579fn ordered_identity_int64_keys_match(left_key: &Column, right_key: &Column) -> bool {
1580    if left_key.len() != right_key.len()
1581        || !matches!(left_key.dtype(), DType::Int64)
1582        || !matches!(right_key.dtype(), DType::Int64)
1583        || !left_key.validity().all()
1584        || !right_key.validity().all()
1585    {
1586        return false;
1587    }
1588
1589    if let (Some(left), Some(right)) = (left_key.as_i64_slice(), right_key.as_i64_slice()) {
1590        let mut previous = None;
1591        let mut strictly_increasing = true;
1592        for (&left_value, &right_value) in left.iter().zip(right) {
1593            if left_value != right_value {
1594                return false;
1595            }
1596            if previous.is_some_and(|previous| left_value <= previous) {
1597                strictly_increasing = false;
1598                break;
1599            }
1600            previous = Some(left_value);
1601        }
1602        if strictly_increasing {
1603            return true;
1604        }
1605    }
1606
1607    // The identity fast path emits a 1:1 positional merge, which is only correct
1608    // when keys are UNIQUE. With duplicate keys pandas multiplies cardinality
1609    // (each duplicate on the left cross-joins every duplicate on the right), so
1610    // identical-but-duplicated keys must fall through to the general cartesian
1611    // path. (br-frankenpandas-jdupk)
1612    let mut seen = FxHashSet::<i64>::with_capacity_and_hasher(left_key.len(), Default::default());
1613    for (left, right) in left_key.values().iter().zip(right_key.values()) {
1614        match (left, right) {
1615            (Scalar::Int64(left), Scalar::Int64(right))
1616                if matches!(left.cmp(right), Ordering::Equal) =>
1617            {
1618                if !seen.insert(*left) {
1619                    return false;
1620                }
1621            }
1622            _ => return false,
1623        }
1624    }
1625    true
1626}
1627
1628fn strictly_increasing_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1629    if column.dtype() != DType::Int64 || !column.validity().all() {
1630        return None;
1631    }
1632
1633    let values = column.values();
1634    let mut previous = None;
1635    for value in values {
1636        let current = match value {
1637            Scalar::Int64(value) => *value,
1638            _ => return None,
1639        };
1640        if previous.is_some_and(|previous| current <= previous) {
1641            return None;
1642        }
1643        previous = Some(current);
1644    }
1645    Some(values)
1646}
1647
1648fn all_valid_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1649    if column.dtype() != DType::Int64 || !column.validity().all() {
1650        return None;
1651    }
1652
1653    let values = column.values();
1654    if values.iter().all(|value| matches!(value, Scalar::Int64(_))) {
1655        Some(values)
1656    } else {
1657        None
1658    }
1659}
1660
1661#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1662struct PositiveAffineI64Witness {
1663    start: i128,
1664    step: i128,
1665    len: usize,
1666}
1667
1668#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1669struct AffineInnerPositionPlan {
1670    left_start: usize,
1671    left_step: usize,
1672    right_start: usize,
1673    right_step: usize,
1674    len: usize,
1675}
1676
1677const AFFINE_I64_INNER_MAX_MORSELS: usize = 64;
1678
1679fn affine_inner_worker_count() -> usize {
1680    fp_columnar::cached_available_parallelism().min(AFFINE_I64_INNER_MAX_MORSELS)
1681}
1682
1683fn balanced_partition(total: usize, index: usize, parts: usize) -> (usize, usize) {
1684    debug_assert!(parts > 0);
1685    debug_assert!(index < parts);
1686    let base = total / parts;
1687    let remainder = total % parts;
1688    let start = index * base + index.min(remainder);
1689    let end = start + base + usize::from(index < remainder);
1690    (start, end)
1691}
1692
1693fn positive_affine_i64_shape(values: &[i64]) -> Option<PositiveAffineI64Witness> {
1694    if values.len() < 2 {
1695        return None;
1696    }
1697    let start = i128::from(values[0]);
1698    let step = i128::from(values[1]) - start;
1699    // Keeping the step within positive i64 makes every CRT intermediate below
1700    // fit i128. Rarer two-point sequences spanning more than i64::MAX retain
1701    // the existing ordered/hash route.
1702    if step <= 0 || step > i128::from(i64::MAX) {
1703        return None;
1704    }
1705    Some(PositiveAffineI64Witness {
1706        start,
1707        step,
1708        len: values.len(),
1709    })
1710}
1711
1712/// Prove two positive affine i64 key sequences with independent row morsels.
1713///
1714/// Every adjacent edge is checked exactly once, including boundaries between
1715/// morsels. A failed proof simply declines the affine route; no result is
1716/// emitted from speculative work. Large ordered joins therefore replace two
1717/// serial O(n) order scans with up to 64 shared-nothing scans while preserving
1718/// the exact strict-unique certificate required by pandas inner-join semantics.
1719fn certify_positive_affine_i64_pair(
1720    left: &[i64],
1721    right: &[i64],
1722) -> Option<(PositiveAffineI64Witness, PositiveAffineI64Witness)> {
1723    let left_shape = positive_affine_i64_shape(left)?;
1724    let right_shape = positive_affine_i64_shape(right)?;
1725    let left_edges = left.len() - 1;
1726    let right_edges = right.len() - 1;
1727    let max_edges = left_edges.max(right_edges);
1728    let worker_count = affine_inner_worker_count().min(max_edges.max(1));
1729
1730    let matches_shape = |values: &[i64], shape: PositiveAffineI64Witness| {
1731        values
1732            .windows(2)
1733            .all(|pair| i128::from(pair[1]) - i128::from(pair[0]) == shape.step)
1734    };
1735    if max_edges < DENSE_I64_INNER_PARALLEL_MIN_VALUES || worker_count < 2 {
1736        return (matches_shape(left, left_shape) && matches_shape(right, right_shape))
1737            .then_some((left_shape, right_shape));
1738    }
1739
1740    let proved = std::thread::scope(|scope| {
1741        let mut handles = Vec::with_capacity(worker_count);
1742        for worker in 0..worker_count {
1743            handles.push(scope.spawn(move || {
1744                let (left_start, left_end) = balanced_partition(left_edges, worker, worker_count);
1745                let (right_start, right_end) =
1746                    balanced_partition(right_edges, worker, worker_count);
1747                let left_ok = (left_start..left_end).all(|idx| {
1748                    i128::from(left[idx + 1]) - i128::from(left[idx]) == left_shape.step
1749                });
1750                let right_ok = (right_start..right_end).all(|idx| {
1751                    i128::from(right[idx + 1]) - i128::from(right[idx]) == right_shape.step
1752                });
1753                left_ok && right_ok
1754            }));
1755        }
1756        handles
1757            .into_iter()
1758            .all(|handle| handle.join().expect("affine join proof worker panicked"))
1759    });
1760    proved.then_some((left_shape, right_shape))
1761}
1762
1763fn positive_i128_gcd(mut left: i128, mut right: i128) -> i128 {
1764    debug_assert!(left > 0 && right > 0);
1765    while right != 0 {
1766        let remainder = left % right;
1767        left = right;
1768        right = remainder;
1769    }
1770    left
1771}
1772
1773fn coprime_mod_inverse(value: i128, modulus: i128) -> Option<i128> {
1774    debug_assert!(value > 0 && modulus > 1);
1775    let (mut old_remainder, mut remainder) = (value, modulus);
1776    let (mut old_coefficient, mut coefficient) = (1i128, 0i128);
1777    while remainder != 0 {
1778        let quotient = old_remainder / remainder;
1779        (old_remainder, remainder) = (
1780            remainder,
1781            old_remainder.checked_sub(quotient.checked_mul(remainder)?)?,
1782        );
1783        (old_coefficient, coefficient) = (
1784            coefficient,
1785            old_coefficient.checked_sub(quotient.checked_mul(coefficient)?)?,
1786        );
1787    }
1788    (old_remainder == 1).then(|| old_coefficient.rem_euclid(modulus))
1789}
1790
1791fn empty_affine_inner_position_plan() -> AffineInnerPositionPlan {
1792    AffineInnerPositionPlan {
1793        left_start: 0,
1794        left_step: 1,
1795        right_start: 0,
1796        right_step: 1,
1797        len: 0,
1798    }
1799}
1800
1801/// Intersect two certified positive affine sequences analytically.
1802///
1803/// The generalized CRT yields the first shared key and the common step. Those
1804/// map back to affine row selections on each input, so the join needs neither
1805/// the serial two-pointer merge nor its two O(matches) position vectors.
1806fn affine_i64_inner_position_plan(
1807    left: PositiveAffineI64Witness,
1808    right: PositiveAffineI64Witness,
1809) -> Option<AffineInnerPositionPlan> {
1810    let left_last = left
1811        .start
1812        .checked_add(left.step.checked_mul(i128::try_from(left.len - 1).ok()?)?)?;
1813    let right_last = right.start.checked_add(
1814        right
1815            .step
1816            .checked_mul(i128::try_from(right.len - 1).ok()?)?,
1817    )?;
1818    let low = left.start.max(right.start);
1819    let high = left_last.min(right_last);
1820    if low > high {
1821        return Some(empty_affine_inner_position_plan());
1822    }
1823
1824    let gcd = positive_i128_gcd(left.step, right.step);
1825    let difference = right.start.checked_sub(left.start)?;
1826    if difference % gcd != 0 {
1827        return Some(empty_affine_inner_position_plan());
1828    }
1829    let left_reduced = left.step / gcd;
1830    let right_reduced = right.step / gcd;
1831    let left_solution = if right_reduced == 1 {
1832        0
1833    } else {
1834        let inverse = coprime_mod_inverse(left_reduced.rem_euclid(right_reduced), right_reduced)?;
1835        difference
1836            .checked_div(gcd)?
1837            .checked_mul(inverse)?
1838            .rem_euclid(right_reduced)
1839    };
1840    let common_step = left.step.checked_mul(right_reduced)?;
1841    let mut first = left
1842        .start
1843        .checked_add(left.step.checked_mul(left_solution)?)?;
1844    if first < low {
1845        let delta = low.checked_sub(first)?;
1846        let jumps = delta
1847            .checked_add(common_step - 1)?
1848            .checked_div(common_step)?;
1849        first = first.checked_add(jumps.checked_mul(common_step)?)?;
1850    }
1851    if first > high {
1852        return Some(empty_affine_inner_position_plan());
1853    }
1854
1855    let len = usize::try_from((high - first) / common_step + 1).ok()?;
1856    let left_start = usize::try_from((first - left.start) / left.step).ok()?;
1857    let right_start = usize::try_from((first - right.start) / right.step).ok()?;
1858    let left_step = usize::try_from(common_step / left.step).ok()?;
1859    let right_step = usize::try_from(common_step / right.step).ok()?;
1860    debug_assert!(
1861        left_start
1862            .checked_add(left_step.saturating_mul(len.saturating_sub(1)))
1863            .is_some_and(|last| last < left.len)
1864    );
1865    debug_assert!(
1866        right_start
1867            .checked_add(right_step.saturating_mul(len.saturating_sub(1)))
1868            .is_some_and(|last| last < right.len)
1869    );
1870    Some(AffineInnerPositionPlan {
1871        left_start,
1872        left_step,
1873        right_start,
1874        right_step,
1875        len,
1876    })
1877}
1878
1879enum AffineInnerOutputLane<'a> {
1880    Int64 {
1881        source: &'a [i64],
1882        start: usize,
1883        step: usize,
1884    },
1885    Built(Box<Column>),
1886}
1887
1888struct AffineInnerOutputSpec<'a> {
1889    name: String,
1890    lane: AffineInnerOutputLane<'a>,
1891}
1892
1893fn affine_selection_positions(start: usize, step: usize, len: usize) -> Vec<usize> {
1894    (0..len).map(|idx| start + idx * step).collect()
1895}
1896
1897fn affine_inner_output_lane<'a>(
1898    column: &'a Column,
1899    start: usize,
1900    step: usize,
1901    len: usize,
1902) -> Option<AffineInnerOutputLane<'a>> {
1903    if let Some(source) = column.as_i64_slice() {
1904        return Some(AffineInnerOutputLane::Int64 {
1905            source,
1906            start,
1907            step,
1908        });
1909    }
1910    column.as_f64_slice()?;
1911    let built = if len == 0 {
1912        Column::from_f64_values(Vec::new())
1913    } else if let Some(view) = isize::try_from(step).ok().and_then(|step| {
1914        column.take_affine_positions_without_materialized_positions(start, step, len)
1915    }) {
1916        view
1917    } else {
1918        let positions = affine_selection_positions(start, step, len);
1919        column.take_positions(&positions)
1920    };
1921    Some(AffineInnerOutputLane::Built(Box::new(built)))
1922}
1923
1924/// Zero-copy Int64 output for a unit-stride side of an affine match.
1925///
1926/// Shared inner-join keys are byte-identical on both sides. If either side's
1927/// matched rows form one contiguous range, reuse that immutable Arc-backed
1928/// range as a one-chunk output instead of filling an O(matches) key buffer.
1929fn affine_unit_stride_i64_view(
1930    column: &Column,
1931    start: usize,
1932    step: usize,
1933    len: usize,
1934) -> Option<Column> {
1935    if len == 0 {
1936        return Some(Column::from_i64_values_owned(Vec::new()));
1937    }
1938    if step != 1 {
1939        return None;
1940    }
1941    let (data, base) = column.as_i64_arc_view_source()?;
1942    let view_start = base.checked_add(start)?;
1943    view_start
1944        .checked_add(len)
1945        .filter(|&end| end <= data.len())?;
1946    Some(Column::from_i64_all_valid_chunks(
1947        vec![(data, view_start, len)],
1948        len,
1949    ))
1950}
1951
1952/// Fill all Int64 affine output lanes by row morsel into disjoint buffers.
1953/// Float64 lanes are descriptor-only strided views and never enter this fill.
1954fn build_affine_inner_i64_lanes(sources: &[(&[i64], usize, usize)], len: usize) -> Vec<Vec<i64>> {
1955    let mut output: Vec<Vec<i64>> = sources.iter().map(|_| vec![0i64; len]).collect();
1956    if sources.is_empty() || len == 0 {
1957        return output;
1958    }
1959    let worker_count = affine_inner_worker_count().min(len);
1960    if len < DENSE_I64_INNER_PARALLEL_MIN_VALUES || worker_count < 2 {
1961        for (lane, &(source, start, step)) in output.iter_mut().zip(sources) {
1962            for (row, value) in lane.iter_mut().enumerate() {
1963                *value = source[start + row * step];
1964            }
1965        }
1966        return output;
1967    }
1968
1969    let mut bundles: Vec<Vec<&mut [i64]>> = (0..worker_count)
1970        .map(|_| Vec::with_capacity(output.len()))
1971        .collect();
1972    for lane in &mut output {
1973        let mut remainder = lane.as_mut_slice();
1974        for (worker, bundle) in bundles.iter_mut().enumerate() {
1975            let (row_start, row_end) = balanced_partition(len, worker, worker_count);
1976            let (chunk, tail) = remainder.split_at_mut(row_end - row_start);
1977            bundle.push(chunk);
1978            remainder = tail;
1979        }
1980    }
1981
1982    std::thread::scope(|scope| {
1983        for (worker, mut bundle) in bundles.into_iter().enumerate() {
1984            let (row_start, _) = balanced_partition(len, worker, worker_count);
1985            scope.spawn(move || {
1986                for (lane, &(source, start, step)) in bundle.iter_mut().zip(sources) {
1987                    for (local_row, value) in lane.iter_mut().enumerate() {
1988                        *value = source[start + (row_start + local_row) * step];
1989                    }
1990                }
1991            });
1992        }
1993    });
1994    output
1995}
1996
1997/// Shared-nothing affine Int64 inner merge.
1998///
1999/// This is deliberately narrow but structural: all-valid typed Int64 keys are
2000/// certified as positive affine sequences; every carried lane must be an
2001/// all-valid Int64 or Float64. The match relation is then a pair of affine row
2002/// selections. Float64 payloads become zero-copy strided views, while all
2003/// Int64 lanes are filled together across row morsels. Any unsupported shape
2004/// falls through to the general ordered/dense/hash implementations.
2005fn build_single_key_affine_i64_inner_merge_output(
2006    left: &fp_frame::DataFrame,
2007    right: &fp_frame::DataFrame,
2008    left_on: &[&str],
2009    right_on: &[&str],
2010    left_key: &Column,
2011    right_key: &Column,
2012    suffixes: &ResolvedMergeSuffixes,
2013) -> Result<Option<MergedDataFrame>, JoinError> {
2014    debug_assert_eq!(left_on.len(), 1);
2015    debug_assert_eq!(right_on.len(), 1);
2016    let (Some(left_keys), Some(right_keys)) = (left_key.as_i64_slice(), right_key.as_i64_slice())
2017    else {
2018        return Ok(None);
2019    };
2020    let Some((left_shape, right_shape)) = certify_positive_affine_i64_pair(left_keys, right_keys)
2021    else {
2022        return Ok(None);
2023    };
2024    let Some(plan) = affine_i64_inner_position_plan(left_shape, right_shape) else {
2025        return Ok(None);
2026    };
2027
2028    let left_col_names: HashSet<&String> = left.columns().keys().collect();
2029    let right_col_names: HashSet<&String> = right.columns().keys().collect();
2030    let shared_key_names = if left_on[0] == right_on[0] {
2031        [left_on[0]].into_iter().collect::<HashSet<&str>>()
2032    } else {
2033        HashSet::new()
2034    };
2035    let overlapping_names =
2036        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
2037    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
2038
2039    let mut specs = Vec::<AffineInnerOutputSpec<'_>>::new();
2040    for name in left.column_names() {
2041        let column = left
2042            .columns()
2043            .get(name)
2044            .expect("left column listed in column_names must exist");
2045        let out_name = if name.as_str() == left_on[0] {
2046            name.clone()
2047        } else if right_col_names.contains(name) {
2048            apply_merge_suffix(name, suffixes.left.as_deref())
2049        } else {
2050            name.clone()
2051        };
2052        let shared_key_view = (name.as_str() == left_on[0] && left_on[0] == right_on[0])
2053            .then(|| {
2054                affine_unit_stride_i64_view(left_key, plan.left_start, plan.left_step, plan.len)
2055                    .or_else(|| {
2056                        affine_unit_stride_i64_view(
2057                            right_key,
2058                            plan.right_start,
2059                            plan.right_step,
2060                            plan.len,
2061                        )
2062                    })
2063                    .map(Box::new)
2064                    .map(AffineInnerOutputLane::Built)
2065            })
2066            .flatten();
2067        let Some(lane) = shared_key_view.or_else(|| {
2068            affine_inner_output_lane(column, plan.left_start, plan.left_step, plan.len)
2069        }) else {
2070            return Ok(None);
2071        };
2072        specs.push(AffineInnerOutputSpec {
2073            name: out_name,
2074            lane,
2075        });
2076    }
2077    for name in right.column_names() {
2078        if name.as_str() == right_on[0] && shared_key_names.contains(name.as_str()) {
2079            continue;
2080        }
2081        let column = right
2082            .columns()
2083            .get(name)
2084            .expect("right column listed in column_names must exist");
2085        let out_name = if left_col_names.contains(name) {
2086            apply_merge_suffix(name, suffixes.right.as_deref())
2087        } else {
2088            name.clone()
2089        };
2090        let Some(lane) =
2091            affine_inner_output_lane(column, plan.right_start, plan.right_step, plan.len)
2092        else {
2093            return Ok(None);
2094        };
2095        specs.push(AffineInnerOutputSpec {
2096            name: out_name,
2097            lane,
2098        });
2099    }
2100
2101    let i64_sources: Vec<(&[i64], usize, usize)> = specs
2102        .iter()
2103        .filter_map(|spec| match &spec.lane {
2104            AffineInnerOutputLane::Int64 {
2105                source,
2106                start,
2107                step,
2108            } => Some((*source, *start, *step)),
2109            AffineInnerOutputLane::Built(_) => None,
2110        })
2111        .collect();
2112    let mut i64_lanes = build_affine_inner_i64_lanes(&i64_sources, plan.len).into_iter();
2113    let index = Index::new_known_unique_int64_unit_range(0, plan.len);
2114    let mut columns = ColumnStore::new();
2115    let mut column_order = Vec::with_capacity(specs.len());
2116    for spec in specs {
2117        let column = match spec.lane {
2118            AffineInnerOutputLane::Int64 { .. } => Column::from_i64_values_owned(
2119                i64_lanes
2120                    .next()
2121                    .expect("one filled lane for every affine Int64 output"),
2122            ),
2123            AffineInnerOutputLane::Built(column) => *column,
2124        };
2125        debug_assert_eq!(column.len(), plan.len);
2126        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
2127    }
2128    Ok(Some(MergedDataFrame {
2129        index,
2130        columns,
2131        column_order,
2132    }))
2133}
2134
2135fn ordered_unique_int64_inner_positions(
2136    left_key: &Column,
2137    right_key: &Column,
2138) -> Option<(Vec<usize>, Vec<usize>)> {
2139    // Typed fast path (see ordered_unique_int64_left_match_positions): walk the
2140    // ordered intersection over raw &[i64] when both keys carry a contiguous
2141    // Int64 backing, skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB
2142    // per merge at 1M rows). Bit-identical: same strictly-increasing gate and
2143    // the same monotone merge emitting the same (left_idx, right_idx) pairs.
2144    if let (Some(left_values), Some(right_values)) = (
2145        strictly_increasing_i64_slice(left_key),
2146        strictly_increasing_i64_slice(right_key),
2147    ) {
2148        let mut left_positions =
2149            Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
2150        let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2151        let (mut left_idx, mut right_idx) = (0usize, 0usize);
2152        while left_idx < left_values.len() && right_idx < right_values.len() {
2153            match left_values[left_idx].cmp(&right_values[right_idx]) {
2154                Ordering::Equal => {
2155                    left_positions.push(left_idx);
2156                    right_positions.push(right_idx);
2157                    left_idx += 1;
2158                    right_idx += 1;
2159                }
2160                Ordering::Less => left_idx += 1,
2161                Ordering::Greater => right_idx += 1,
2162            }
2163        }
2164        return Some((left_positions, right_positions));
2165    }
2166
2167    let left_values = strictly_increasing_int64_key_values(left_key)?;
2168    let right_values = strictly_increasing_int64_key_values(right_key)?;
2169
2170    let mut left_positions = Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
2171    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2172    let mut left_idx = 0usize;
2173    let mut right_idx = 0usize;
2174
2175    while left_idx < left_values.len() && right_idx < right_values.len() {
2176        let left_value = match &left_values[left_idx] {
2177            Scalar::Int64(value) => *value,
2178            _ => return None,
2179        };
2180        let right_value = match &right_values[right_idx] {
2181            Scalar::Int64(value) => *value,
2182            _ => return None,
2183        };
2184
2185        match left_value.cmp(&right_value) {
2186            Ordering::Equal => {
2187                left_positions.push(left_idx);
2188                right_positions.push(right_idx);
2189                left_idx += 1;
2190                right_idx += 1;
2191            }
2192            Ordering::Less => left_idx += 1,
2193            Ordering::Greater => right_idx += 1,
2194        }
2195    }
2196
2197    Some((left_positions, right_positions))
2198}
2199
2200fn strictly_increasing_utf8_key_spans(column: &Column) -> Option<(&[u8], &[usize])> {
2201    column.as_strictly_increasing_utf8_contiguous()
2202}
2203
2204fn utf8_span<'a>(bytes: &'a [u8], offsets: &[usize], pos: usize) -> &'a [u8] {
2205    &bytes[offsets[pos]..offsets[pos + 1]]
2206}
2207
2208fn utf8_offsets_are_sorted(bytes: &[u8], offsets: &[usize]) -> bool {
2209    offsets
2210        .windows(3)
2211        .all(|window| bytes[window[0]..window[1]] <= bytes[window[1]..window[2]])
2212}
2213
2214fn sorted_contiguous_utf8_inner_positions(
2215    left_bytes: &[u8],
2216    left_offsets: &[usize],
2217    right_bytes: &[u8],
2218    right_offsets: &[usize],
2219) -> Option<(Vec<usize>, Vec<usize>)> {
2220    if !utf8_offsets_are_sorted(left_bytes, left_offsets)
2221        || !utf8_offsets_are_sorted(right_bytes, right_offsets)
2222    {
2223        return None;
2224    }
2225
2226    let left_n = left_offsets.len() - 1;
2227    let right_n = right_offsets.len() - 1;
2228    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
2229    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2230    let mut left_pos = 0usize;
2231    let mut right_pos = 0usize;
2232
2233    while left_pos < left_n && right_pos < right_n {
2234        let left_span = utf8_span(left_bytes, left_offsets, left_pos);
2235        let right_span = utf8_span(right_bytes, right_offsets, right_pos);
2236        match left_span.cmp(right_span) {
2237            Ordering::Less => left_pos += 1,
2238            Ordering::Greater => right_pos += 1,
2239            Ordering::Equal => {
2240                let left_start = left_pos;
2241                let right_start = right_pos;
2242                while left_pos < left_n
2243                    && utf8_span(left_bytes, left_offsets, left_pos) == left_span
2244                {
2245                    left_pos += 1;
2246                }
2247                while right_pos < right_n
2248                    && utf8_span(right_bytes, right_offsets, right_pos) == right_span
2249                {
2250                    right_pos += 1;
2251                }
2252                for matched_left in left_start..left_pos {
2253                    for matched_right in right_start..right_pos {
2254                        left_positions.push(matched_left);
2255                        right_positions.push(matched_right);
2256                    }
2257                }
2258            }
2259        }
2260    }
2261
2262    Some((left_positions, right_positions))
2263}
2264
2265fn utf8_span_lower_bound(bytes: &[u8], offsets: &[usize], needle: &[u8]) -> usize {
2266    let mut lo = 0usize;
2267    let mut hi = offsets.len() - 1;
2268    while lo < hi {
2269        let mid = lo + (hi - lo) / 2;
2270        if utf8_span(bytes, offsets, mid) < needle {
2271            lo = mid + 1;
2272        } else {
2273            hi = mid;
2274        }
2275    }
2276    lo
2277}
2278
2279fn ordered_unique_utf8_fixed_width(left_key: &Column, right_key: &Column) -> Option<usize> {
2280    let (_, _, left_width) = left_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
2281    let (_, _, right_width) = right_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
2282    (left_width == right_width && left_width > 0).then_some(left_width)
2283}
2284
2285fn ordered_utf8_lower_hex_overlap_len(
2286    left_cert: Utf8LowerHexSequence,
2287    right_cert: Utf8LowerHexSequence,
2288    left_idx: usize,
2289    left_n: usize,
2290    right_idx: usize,
2291    right_n: usize,
2292) -> Option<usize> {
2293    if !left_cert.same_shape(right_cert) {
2294        return None;
2295    }
2296    let left_value = left_cert.value_at(left_idx)?;
2297    let right_value = right_cert.value_at(right_idx)?;
2298    if left_value != right_value {
2299        return None;
2300    }
2301    Some(left_n.saturating_sub(left_idx).min(right_n - right_idx))
2302}
2303
2304fn lower_hex_overlap_plan_from_certificates(
2305    left_key: &Column,
2306    right_key: &Column,
2307) -> Option<InnerPositionPlan> {
2308    let (left_prefix, left_cert, left_n) = left_key.as_lower_hex_sequence_utf8()?;
2309    let (right_prefix, right_cert, right_n) = right_key.as_lower_hex_sequence_utf8()?;
2310    if !left_cert.same_shape(right_cert) {
2311        return None;
2312    }
2313    if left_prefix != right_prefix {
2314        return None;
2315    }
2316
2317    let left_n = u64::try_from(left_n).ok()?;
2318    let right_n = u64::try_from(right_n).ok()?;
2319    if left_n == 0 || right_n == 0 {
2320        return Some(InnerPositionPlan::Gather {
2321            left_positions: Vec::new(),
2322            right_positions: Vec::new(),
2323        });
2324    }
2325
2326    let left_start_value = left_cert.start();
2327    let right_start_value = right_cert.start();
2328    let left_end_value = left_start_value.checked_add(left_n)?;
2329    let right_end_value = right_start_value.checked_add(right_n)?;
2330    let overlap_start = left_start_value.max(right_start_value);
2331    let overlap_end = left_end_value.min(right_end_value);
2332    if overlap_start >= overlap_end {
2333        return Some(InnerPositionPlan::Gather {
2334            left_positions: Vec::new(),
2335            right_positions: Vec::new(),
2336        });
2337    }
2338
2339    let len = usize::try_from(overlap_end.checked_sub(overlap_start)?).ok()?;
2340    let left_start = usize::try_from(overlap_start.checked_sub(left_start_value)?).ok()?;
2341    let right_start = usize::try_from(overlap_start.checked_sub(right_start_value)?).ok()?;
2342    let left_len = usize::try_from(left_n).ok()?;
2343    let right_len = usize::try_from(right_n).ok()?;
2344    let left_end = left_start.checked_add(len)?;
2345    let right_end = right_start.checked_add(len)?;
2346    if left_end > left_len || right_end > right_len {
2347        return None;
2348    }
2349
2350    Some(InnerPositionPlan::ContiguousRanges {
2351        left_start,
2352        right_start,
2353        len,
2354    })
2355}
2356
2357#[derive(Debug, Clone, PartialEq, Eq)]
2358enum InnerPositionPlan {
2359    Gather {
2360        left_positions: Vec<usize>,
2361        right_positions: Vec<usize>,
2362    },
2363    ContiguousRanges {
2364        left_start: usize,
2365        right_start: usize,
2366        len: usize,
2367    },
2368}
2369
2370impl InnerPositionPlan {
2371    #[cfg(test)]
2372    fn into_positions(self) -> (Vec<usize>, Vec<usize>) {
2373        match self {
2374            Self::Gather {
2375                left_positions,
2376                right_positions,
2377            } => (left_positions, right_positions),
2378            Self::ContiguousRanges {
2379                left_start,
2380                right_start,
2381                len,
2382            } => (
2383                (left_start..left_start + len).collect(),
2384                (right_start..right_start + len).collect(),
2385            ),
2386        }
2387    }
2388}
2389
2390/// Hash-free ordered merge for all-valid, strictly increasing contiguous-Utf8
2391/// keys. This is the string-key analogue of
2392/// [`ordered_unique_int64_inner_positions`]: each side is unique and already in
2393/// key order, so a two-cursor byte-span merge emits the exact same 1:1
2394/// `(left_pos, right_pos)` pairs as the hash path while skipping hash table
2395/// build/probe entirely. Duplicate or unsorted inputs fall back to the
2396/// left-major byte-span hash path, preserving pandas row order.
2397fn ordered_unique_utf8_inner_position_plan(
2398    left_key: &Column,
2399    right_key: &Column,
2400) -> Option<InnerPositionPlan> {
2401    if let Some(plan) = lower_hex_overlap_plan_from_certificates(left_key, right_key) {
2402        return Some(plan);
2403    }
2404
2405    let (left_bytes, left_offsets) = strictly_increasing_utf8_key_spans(left_key)?;
2406    let (right_bytes, right_offsets) = strictly_increasing_utf8_key_spans(right_key)?;
2407    let left_n = left_offsets.len() - 1;
2408    let right_n = right_offsets.len() - 1;
2409    let fixed_width = ordered_unique_utf8_fixed_width(left_key, right_key);
2410
2411    if left_n == 0 || right_n == 0 {
2412        return Some(InnerPositionPlan::Gather {
2413            left_positions: Vec::new(),
2414            right_positions: Vec::new(),
2415        });
2416    }
2417
2418    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
2419    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2420
2421    let first_left = utf8_span(left_bytes, left_offsets, 0);
2422    let last_left = utf8_span(left_bytes, left_offsets, left_n - 1);
2423    let first_right = utf8_span(right_bytes, right_offsets, 0);
2424    let last_right = utf8_span(right_bytes, right_offsets, right_n - 1);
2425    if last_left < first_right || last_right < first_left {
2426        return Some(InnerPositionPlan::Gather {
2427            left_positions,
2428            right_positions,
2429        });
2430    }
2431
2432    let mut left_idx = utf8_span_lower_bound(left_bytes, left_offsets, first_right);
2433    let mut right_idx = if left_idx < left_n {
2434        utf8_span_lower_bound(
2435            right_bytes,
2436            right_offsets,
2437            utf8_span(left_bytes, left_offsets, left_idx),
2438        )
2439    } else {
2440        right_n
2441    };
2442    let mut fixed_width_bulk_attempted = false;
2443
2444    while left_idx < left_n && right_idx < right_n {
2445        let left_span = utf8_span(left_bytes, left_offsets, left_idx);
2446        let right_span = utf8_span(right_bytes, right_offsets, right_idx);
2447
2448        match left_span.cmp(right_span) {
2449            Ordering::Equal => {
2450                if let Some(width) = fixed_width
2451                    && !fixed_width_bulk_attempted
2452                {
2453                    fixed_width_bulk_attempted = true;
2454                    // This branch is reached only after the current left/right
2455                    // key spans compare equal. Matching lower-hex shapes then
2456                    // prove the remaining shifted windows without a full
2457                    // byte-window memcmp.
2458                    let lower_hex_sequences = match (
2459                        left_key.as_lower_hex_sequence_utf8_contiguous(),
2460                        right_key.as_lower_hex_sequence_utf8_contiguous(),
2461                    ) {
2462                        (Some((_, _, left_cert)), Some((_, _, right_cert))) => {
2463                            Some((left_cert, right_cert))
2464                        }
2465                        _ => None,
2466                    };
2467                    if let Some((left_cert, right_cert)) = lower_hex_sequences
2468                        && let Some(run_len) = ordered_utf8_lower_hex_overlap_len(
2469                            left_cert, right_cert, left_idx, left_n, right_idx, right_n,
2470                        )
2471                        && run_len > 1
2472                    {
2473                        if left_positions.is_empty() {
2474                            return Some(InnerPositionPlan::ContiguousRanges {
2475                                left_start: left_idx,
2476                                right_start: right_idx,
2477                                len: run_len,
2478                            });
2479                        }
2480                        left_positions.extend(left_idx..left_idx + run_len);
2481                        right_positions.extend(right_idx..right_idx + run_len);
2482                        left_idx += run_len;
2483                        right_idx += run_len;
2484                        continue;
2485                    }
2486                    let run_len = left_n.saturating_sub(left_idx).min(right_n - right_idx);
2487                    if run_len > 1
2488                        && let Some(byte_len) = run_len.checked_mul(width)
2489                    {
2490                        let left_start = left_offsets[left_idx];
2491                        let right_start = right_offsets[right_idx];
2492                        let left_end = left_start + byte_len;
2493                        let right_end = right_start + byte_len;
2494                        if left_end <= left_bytes.len()
2495                            && right_end <= right_bytes.len()
2496                            && left_bytes[left_start..left_end]
2497                                == right_bytes[right_start..right_end]
2498                        {
2499                            if left_positions.is_empty() {
2500                                return Some(InnerPositionPlan::ContiguousRanges {
2501                                    left_start: left_idx,
2502                                    right_start: right_idx,
2503                                    len: run_len,
2504                                });
2505                            }
2506                            left_positions.extend(left_idx..left_idx + run_len);
2507                            right_positions.extend(right_idx..right_idx + run_len);
2508                            left_idx += run_len;
2509                            right_idx += run_len;
2510                            continue;
2511                        }
2512                    }
2513                }
2514                left_positions.push(left_idx);
2515                right_positions.push(right_idx);
2516                left_idx += 1;
2517                right_idx += 1;
2518            }
2519            Ordering::Less => left_idx += 1,
2520            Ordering::Greater => right_idx += 1,
2521        }
2522    }
2523
2524    Some(InnerPositionPlan::Gather {
2525        left_positions,
2526        right_positions,
2527    })
2528}
2529
2530#[cfg(test)]
2531fn ordered_unique_utf8_inner_positions(
2532    left_key: &Column,
2533    right_key: &Column,
2534) -> Option<(Vec<usize>, Vec<usize>)> {
2535    ordered_unique_utf8_inner_position_plan(left_key, right_key)
2536        .map(InnerPositionPlan::into_positions)
2537}
2538
2539/// Strictly-increasing check over a column's contiguous `&[i64]` backing,
2540/// returning the raw slice. The typed analogue of
2541/// `strictly_increasing_int64_key_values` that skips the `Vec<Scalar>`
2542/// materialization (32 B/elem) — `as_i64_slice` is `Some` only for an
2543/// all-valid contiguous Int64 column, the same gate as the Scalar version
2544/// (dtype Int64 + `validity().all()` + every value `Scalar::Int64`).
2545fn strictly_increasing_i64_slice(column: &Column) -> Option<&[i64]> {
2546    let data = column.as_i64_slice()?;
2547    if data.windows(2).any(|pair| pair[1] <= pair[0]) {
2548        return None;
2549    }
2550    Some(data)
2551}
2552
2553fn ordered_unique_int64_left_match_positions(
2554    left_key: &Column,
2555    right_key: &Column,
2556) -> Option<Vec<Option<usize>>> {
2557    // Typed fast path: both keys carry a contiguous Int64 backing, so run the
2558    // ordered two-pointer match over raw `&[i64]` (8 B/elem, cache-friendly)
2559    // instead of materializing two `Vec<Scalar>` (32 B/elem — ~32 MB per side
2560    // at 1M rows, the tax that left-join paid but the typed inner path did
2561    // not). Bit-identical: same strictly-increasing gate and the same
2562    // monotone walk producing the same `right_idx` per left row.
2563    if let (Some(left_values), Some(right_values)) = (
2564        strictly_increasing_i64_slice(left_key),
2565        strictly_increasing_i64_slice(right_key),
2566    ) {
2567        let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2568        let mut right_idx = 0usize;
2569        for &left_value in left_values {
2570            while right_idx < right_values.len() && right_values[right_idx] < left_value {
2571                right_idx += 1;
2572            }
2573            let matched = match right_values.get(right_idx) {
2574                Some(&right_value) if right_value == left_value => Some(right_idx),
2575                _ => None,
2576            };
2577            right_positions.push(matched);
2578        }
2579        return Some(right_positions);
2580    }
2581
2582    let left_values = strictly_increasing_int64_key_values(left_key)?;
2583    let right_values = strictly_increasing_int64_key_values(right_key)?;
2584
2585    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2586    let mut right_idx = 0usize;
2587
2588    for left_value in left_values {
2589        let Scalar::Int64(left_value) = left_value else {
2590            return None;
2591        };
2592        while let Some(Scalar::Int64(right_value)) = right_values.get(right_idx)
2593            && right_value < left_value
2594        {
2595            right_idx += 1;
2596        }
2597
2598        let matched = match right_values.get(right_idx) {
2599            Some(Scalar::Int64(right_value)) if right_value == left_value => Some(right_idx),
2600            Some(Scalar::Int64(_)) | None => None,
2601            Some(_) => return None,
2602        };
2603        right_positions.push(matched);
2604    }
2605
2606    Some(right_positions)
2607}
2608
2609fn ordered_unique_int64_right_match_positions(
2610    left_key: &Column,
2611    right_key: &Column,
2612) -> Option<Vec<Option<usize>>> {
2613    // Typed fast path (mirror of ordered_unique_int64_left_match_positions):
2614    // walk over raw &[i64] when both keys carry a contiguous Int64 backing,
2615    // skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB per merge at
2616    // 1M rows). Bit-identical: same strictly-increasing gate and the same
2617    // monotone walk producing the same left_idx per right row.
2618    if let (Some(left_values), Some(right_values)) = (
2619        strictly_increasing_i64_slice(left_key),
2620        strictly_increasing_i64_slice(right_key),
2621    ) {
2622        let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2623        let mut left_idx = 0usize;
2624        for &right_value in right_values {
2625            while left_idx < left_values.len() && left_values[left_idx] < right_value {
2626                left_idx += 1;
2627            }
2628            let matched = match left_values.get(left_idx) {
2629                Some(&left_value) if left_value == right_value => Some(left_idx),
2630                _ => None,
2631            };
2632            left_positions.push(matched);
2633        }
2634        return Some(left_positions);
2635    }
2636
2637    let left_values = strictly_increasing_int64_key_values(left_key)?;
2638    let right_values = strictly_increasing_int64_key_values(right_key)?;
2639
2640    let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2641    let mut left_idx = 0usize;
2642
2643    for right_value in right_values {
2644        let Scalar::Int64(right_value) = right_value else {
2645            return None;
2646        };
2647        while let Some(Scalar::Int64(left_value)) = left_values.get(left_idx)
2648            && left_value < right_value
2649        {
2650            left_idx += 1;
2651        }
2652
2653        let matched = match left_values.get(left_idx) {
2654            Some(Scalar::Int64(left_value)) if left_value == right_value => Some(left_idx),
2655            Some(Scalar::Int64(_)) | None => None,
2656            Some(_) => return None,
2657        };
2658        left_positions.push(matched);
2659    }
2660
2661    Some(left_positions)
2662}
2663
2664type OptionalJoinPositions = (Vec<Option<usize>>, Vec<Option<usize>>);
2665
2666/// Direct-address unique-key fast path for a bounded-span Int64 left/inner
2667/// join. When the right keys are *unique* within their value span, the
2668/// counting-sort CSR (count + prefix-sum + scatter + per-bucket emit, over
2669/// several span-sized `usize` arrays) collapses to a single fill pass over one
2670/// compact `u32` table (`pos+1`, `0` == empty) plus a single probe pass — ~14x
2671/// faster at 1M (and faster than open-addressing hashing, no hash/probe).
2672///
2673/// Returns `None` (caller falls back to the CSR path) when: a key column is not
2674/// a contiguous `&[i64]`, the right side is empty, the span exceeds the dense
2675/// gate, the row count would overflow `u32`, or a *duplicate* right key is seen
2676/// (then the CSR path's per-bucket emission is required). For unique right keys
2677/// the emitted `(Some(left_pos), match)` pairs are byte-identical to the CSR
2678/// path: one row per left key in left order, matching the single right position
2679/// in its bucket (or `None` when absent / out of span).
2680fn dense_int64_unique_right_left_positions(
2681    left_key: &Column,
2682    right_key: &Column,
2683) -> Option<OptionalJoinPositions> {
2684    let left_values = left_key.as_i64_slice()?;
2685    let right_values = right_key.as_i64_slice()?;
2686    if right_values.is_empty() || left_values.len() > u32::MAX as usize {
2687        return None;
2688    }
2689
2690    let mut min_key = i64::MAX;
2691    let mut max_key = i64::MIN;
2692    for &key in right_values {
2693        min_key = min_key.min(key);
2694        max_key = max_key.max(key);
2695    }
2696
2697    let span = i128::from(max_key)
2698        .checked_sub(i128::from(min_key))?
2699        .checked_add(1)?;
2700    let row_count = left_values.len().saturating_add(right_values.len());
2701    let max_dense_span = row_count.saturating_mul(4).max(1024);
2702    if span > max_dense_span as i128 {
2703        return None;
2704    }
2705    let span = usize::try_from(span).ok()?;
2706    let span_i128 = i128::try_from(span).ok()?;
2707
2708    // Fill the direct-address table; a non-empty slot means a duplicate right
2709    // key, so bail to the CSR path (which handles many-to-many emission).
2710    let mut table = vec![0u32; span];
2711    for (pos, &key) in right_values.iter().enumerate() {
2712        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2713        if table[bucket] != 0 {
2714            return None;
2715        }
2716        table[bucket] = (pos as u32).checked_add(1)?;
2717    }
2718
2719    let mut left_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2720    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2721    for (left_pos, &key) in left_values.iter().enumerate() {
2722        let offset = i128::from(key) - i128::from(min_key);
2723        let matched = if (0..span_i128).contains(&offset) {
2724            match table[offset as usize] {
2725                0 => None,
2726                slot => Some(slot as usize - 1),
2727            }
2728        } else {
2729            None
2730        };
2731        left_positions.push(Some(left_pos));
2732        right_positions.push(matched);
2733    }
2734
2735    Some((left_positions, right_positions))
2736}
2737
2738fn dense_int64_left_positions(
2739    left_key: &Column,
2740    right_key: &Column,
2741) -> Option<OptionalJoinPositions> {
2742    if let Some(direct) = dense_int64_unique_right_left_positions(left_key, right_key) {
2743        return Some(direct);
2744    }
2745    let left_values = all_valid_int64_key_values(left_key)?;
2746    let right_values = all_valid_int64_key_values(right_key)?;
2747
2748    if right_values.is_empty() {
2749        let left_positions = (0..left_values.len()).map(Some).collect::<Vec<_>>();
2750        let right_positions = vec![None; left_values.len()];
2751        return Some((left_positions, right_positions));
2752    }
2753
2754    let mut min_key = i64::MAX;
2755    let mut max_key = i64::MIN;
2756    for value in right_values {
2757        let Scalar::Int64(key) = value else {
2758            return None;
2759        };
2760        min_key = min_key.min(*key);
2761        max_key = max_key.max(*key);
2762    }
2763
2764    let span = i128::from(max_key)
2765        .checked_sub(i128::from(min_key))?
2766        .checked_add(1)?;
2767    let row_count = left_values.len().saturating_add(right_values.len());
2768    let max_dense_span = row_count.saturating_mul(4).max(1024);
2769    if span > max_dense_span as i128 {
2770        return None;
2771    }
2772    let span = usize::try_from(span).ok()?;
2773    let span_i128 = i128::try_from(span).ok()?;
2774
2775    let mut right_counts = vec![0usize; span];
2776    for value in right_values {
2777        let Scalar::Int64(key) = value else {
2778            return None;
2779        };
2780        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2781        right_counts[bucket] = right_counts[bucket].checked_add(1)?;
2782    }
2783
2784    let mut right_offsets = Vec::<usize>::with_capacity(span + 1);
2785    right_offsets.push(0);
2786    let mut running = 0usize;
2787    for count in &right_counts {
2788        running = running.checked_add(*count)?;
2789        right_offsets.push(running);
2790    }
2791
2792    let mut write_offsets = right_offsets[..span].to_vec();
2793    let mut right_positions_by_bucket = vec![0usize; right_values.len()];
2794    for (pos, value) in right_values.iter().enumerate() {
2795        let Scalar::Int64(key) = value else {
2796            return None;
2797        };
2798        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2799        let write_idx = write_offsets[bucket];
2800        right_positions_by_bucket[write_idx] = pos;
2801        write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
2802    }
2803
2804    let mut output_len = 0usize;
2805    for value in left_values {
2806        let Scalar::Int64(key) = value else {
2807            return None;
2808        };
2809        let offset = i128::from(*key) - i128::from(min_key);
2810        let bucket_rows = if (0..span_i128).contains(&offset) {
2811            let bucket = usize::try_from(offset).ok()?;
2812            right_counts[bucket].max(1)
2813        } else {
2814            1
2815        };
2816        output_len = output_len.checked_add(bucket_rows)?;
2817    }
2818
2819    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
2820    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
2821    for (left_pos, value) in left_values.iter().enumerate() {
2822        let Scalar::Int64(key) = value else {
2823            return None;
2824        };
2825        let offset = i128::from(*key) - i128::from(min_key);
2826        if (0..span_i128).contains(&offset) {
2827            let bucket = usize::try_from(offset).ok()?;
2828            let start = right_offsets[bucket];
2829            let end = right_offsets[bucket + 1];
2830            if start != end {
2831                for &right_pos in &right_positions_by_bucket[start..end] {
2832                    left_positions.push(Some(left_pos));
2833                    right_positions.push(Some(right_pos));
2834                }
2835                continue;
2836            }
2837        }
2838        left_positions.push(Some(left_pos));
2839        right_positions.push(None);
2840    }
2841
2842    Some((left_positions, right_positions))
2843}
2844
2845/// Direct-address unique-key fast path for a bounded-span Int64 right join —
2846/// the mirror of [`dense_int64_unique_right_left_positions`]. When the *left*
2847/// (build-side) keys are unique within their span, a single fill + single probe
2848/// over one compact `u32` table replaces the CSR. Keeps every right row; bails
2849/// (caller falls back to the CSR path) on a duplicate left key, non-contiguous
2850/// backing, empty left, oversized span, or `u32` row overflow.
2851fn dense_int64_unique_left_right_positions(
2852    left_key: &Column,
2853    right_key: &Column,
2854) -> Option<OptionalJoinPositions> {
2855    let left_values = left_key.as_i64_slice()?;
2856    let right_values = right_key.as_i64_slice()?;
2857    if left_values.is_empty() || left_values.len() > u32::MAX as usize {
2858        return None;
2859    }
2860
2861    let mut min_key = i64::MAX;
2862    let mut max_key = i64::MIN;
2863    for &key in left_values {
2864        min_key = min_key.min(key);
2865        max_key = max_key.max(key);
2866    }
2867
2868    let span = i128::from(max_key)
2869        .checked_sub(i128::from(min_key))?
2870        .checked_add(1)?;
2871    let row_count = left_values.len().saturating_add(right_values.len());
2872    let max_dense_span = row_count.saturating_mul(4).max(1024);
2873    if span > max_dense_span as i128 {
2874        return None;
2875    }
2876    let span = usize::try_from(span).ok()?;
2877    let span_i128 = i128::try_from(span).ok()?;
2878
2879    let mut table = vec![0u32; span];
2880    for (pos, &key) in left_values.iter().enumerate() {
2881        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2882        if table[bucket] != 0 {
2883            return None;
2884        }
2885        table[bucket] = (pos as u32).checked_add(1)?;
2886    }
2887
2888    let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2889    let mut right_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2890    for (right_pos, &key) in right_values.iter().enumerate() {
2891        let offset = i128::from(key) - i128::from(min_key);
2892        let matched = if (0..span_i128).contains(&offset) {
2893            match table[offset as usize] {
2894                0 => None,
2895                slot => Some(slot as usize - 1),
2896            }
2897        } else {
2898            None
2899        };
2900        left_positions.push(matched);
2901        right_positions.push(Some(right_pos));
2902    }
2903
2904    Some((left_positions, right_positions))
2905}
2906
2907fn dense_int64_right_positions(
2908    left_key: &Column,
2909    right_key: &Column,
2910) -> Option<OptionalJoinPositions> {
2911    if let Some(direct) = dense_int64_unique_left_right_positions(left_key, right_key) {
2912        return Some(direct);
2913    }
2914    let left_values = all_valid_int64_key_values(left_key)?;
2915    let right_values = all_valid_int64_key_values(right_key)?;
2916
2917    if left_values.is_empty() {
2918        let left_positions = vec![None; right_values.len()];
2919        let right_positions = (0..right_values.len()).map(Some).collect::<Vec<_>>();
2920        return Some((left_positions, right_positions));
2921    }
2922
2923    let mut min_key = i64::MAX;
2924    let mut max_key = i64::MIN;
2925    for value in left_values {
2926        let Scalar::Int64(key) = value else {
2927            return None;
2928        };
2929        min_key = min_key.min(*key);
2930        max_key = max_key.max(*key);
2931    }
2932
2933    let span = i128::from(max_key)
2934        .checked_sub(i128::from(min_key))?
2935        .checked_add(1)?;
2936    let row_count = left_values.len().saturating_add(right_values.len());
2937    let max_dense_span = row_count.saturating_mul(4).max(1024);
2938    if span > max_dense_span as i128 {
2939        return None;
2940    }
2941    let span = usize::try_from(span).ok()?;
2942    let span_i128 = i128::try_from(span).ok()?;
2943
2944    let mut left_counts = vec![0usize; span];
2945    for value in left_values {
2946        let Scalar::Int64(key) = value else {
2947            return None;
2948        };
2949        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2950        left_counts[bucket] = left_counts[bucket].checked_add(1)?;
2951    }
2952
2953    let mut left_offsets = Vec::<usize>::with_capacity(span + 1);
2954    left_offsets.push(0);
2955    let mut running = 0usize;
2956    for count in &left_counts {
2957        running = running.checked_add(*count)?;
2958        left_offsets.push(running);
2959    }
2960
2961    let mut write_offsets = left_offsets[..span].to_vec();
2962    let mut left_positions_by_bucket = vec![0usize; left_values.len()];
2963    for (pos, value) in left_values.iter().enumerate() {
2964        let Scalar::Int64(key) = value else {
2965            return None;
2966        };
2967        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2968        let write_idx = write_offsets[bucket];
2969        left_positions_by_bucket[write_idx] = pos;
2970        write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
2971    }
2972
2973    let mut output_len = 0usize;
2974    for value in right_values {
2975        let Scalar::Int64(key) = value else {
2976            return None;
2977        };
2978        let offset = i128::from(*key) - i128::from(min_key);
2979        let bucket_rows = if (0..span_i128).contains(&offset) {
2980            let bucket = usize::try_from(offset).ok()?;
2981            left_counts[bucket].max(1)
2982        } else {
2983            1
2984        };
2985        output_len = output_len.checked_add(bucket_rows)?;
2986    }
2987
2988    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
2989    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
2990    for (right_pos, value) in right_values.iter().enumerate() {
2991        let Scalar::Int64(key) = value else {
2992            return None;
2993        };
2994        let offset = i128::from(*key) - i128::from(min_key);
2995        if (0..span_i128).contains(&offset) {
2996            let bucket = usize::try_from(offset).ok()?;
2997            let start = left_offsets[bucket];
2998            let end = left_offsets[bucket + 1];
2999            if start != end {
3000                for &left_pos in &left_positions_by_bucket[start..end] {
3001                    left_positions.push(Some(left_pos));
3002                    right_positions.push(Some(right_pos));
3003                }
3004                continue;
3005            }
3006        }
3007        left_positions.push(None);
3008        right_positions.push(Some(right_pos));
3009    }
3010
3011    Some((left_positions, right_positions))
3012}
3013
3014/// Direct-address unique-key fast path for a bounded-span Int64 full-outer join.
3015/// When BOTH key sides are unique within the joint span, two compact `u32`
3016/// tables (`pos+1`, `0` == empty) plus a single ascending scan over `0..span`
3017/// replace the CSR's `Vec<Vec<usize>>` (one heap `Vec` per bucket — `span`
3018/// allocations) and the `Vec<Scalar>` materialization. Bails (caller falls back
3019/// to the bucket-list CSR) on a duplicate key on either side, non-contiguous
3020/// backing, oversized span, or `u32` row overflow.
3021///
3022/// Bit-identical for unique keys: the CSR emits one row per bucket in ascending
3023/// key (bucket) order — matched `(Some,Some)`, left-only `(Some,None)`,
3024/// right-only `(None,Some)` — which is exactly the per-bucket scan here.
3025fn dense_int64_unique_outer_positions(
3026    left_key: &Column,
3027    right_key: &Column,
3028) -> Option<OptionalJoinPositions> {
3029    let left_values = left_key.as_i64_slice()?;
3030    let right_values = right_key.as_i64_slice()?;
3031    if left_values.len() > u32::MAX as usize || right_values.len() > u32::MAX as usize {
3032        return None;
3033    }
3034
3035    let mut min_key = i64::MAX;
3036    let mut max_key = i64::MIN;
3037    let mut any = false;
3038    for &key in left_values.iter().chain(right_values.iter()) {
3039        min_key = min_key.min(key);
3040        max_key = max_key.max(key);
3041        any = true;
3042    }
3043    if !any {
3044        return Some((Vec::new(), Vec::new()));
3045    }
3046
3047    let span = i128::from(max_key)
3048        .checked_sub(i128::from(min_key))?
3049        .checked_add(1)?;
3050    let row_count = left_values.len().saturating_add(right_values.len());
3051    let max_dense_span = row_count.saturating_mul(4).max(1024);
3052    if span > max_dense_span as i128 {
3053        return None;
3054    }
3055    let span = usize::try_from(span).ok()?;
3056
3057    let mut left_table = vec![0u32; span];
3058    let mut right_table = vec![0u32; span];
3059    for (pos, &key) in left_values.iter().enumerate() {
3060        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
3061        if left_table[bucket] != 0 {
3062            return None;
3063        }
3064        left_table[bucket] = (pos as u32).checked_add(1)?;
3065    }
3066    for (pos, &key) in right_values.iter().enumerate() {
3067        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
3068        if right_table[bucket] != 0 {
3069            return None;
3070        }
3071        right_table[bucket] = (pos as u32).checked_add(1)?;
3072    }
3073
3074    let mut left_positions = Vec::<Option<usize>>::new();
3075    let mut right_positions = Vec::<Option<usize>>::new();
3076    for bucket in 0..span {
3077        match (left_table[bucket], right_table[bucket]) {
3078            (0, 0) => {}
3079            (l, 0) => {
3080                left_positions.push(Some(l as usize - 1));
3081                right_positions.push(None);
3082            }
3083            (0, r) => {
3084                left_positions.push(None);
3085                right_positions.push(Some(r as usize - 1));
3086            }
3087            (l, r) => {
3088                left_positions.push(Some(l as usize - 1));
3089                right_positions.push(Some(r as usize - 1));
3090            }
3091        }
3092    }
3093
3094    Some((left_positions, right_positions))
3095}
3096
3097fn dense_int64_outer_positions(
3098    left_key: &Column,
3099    right_key: &Column,
3100) -> Option<OptionalJoinPositions> {
3101    if let Some(direct) = dense_int64_unique_outer_positions(left_key, right_key) {
3102        return Some(direct);
3103    }
3104    let left_values = int64_key_values(left_key)?;
3105    let right_values = int64_key_values(right_key)?;
3106
3107    let fold_span = |(lo, hi): (i64, i64), &key: &i64| (lo.min(key), hi.max(key));
3108    let (min_key, max_key) = left_values
3109        .iter()
3110        .chain(right_values.iter())
3111        .fold((i64::MAX, i64::MIN), fold_span);
3112    if min_key > max_key {
3113        return Some((Vec::new(), Vec::new()));
3114    }
3115    let span = i128::from(max_key)
3116        .checked_sub(i128::from(min_key))?
3117        .checked_add(1)?;
3118    let row_count = left_values.len().saturating_add(right_values.len());
3119    let max_dense_span = row_count.saturating_mul(4).max(1024);
3120    if span > max_dense_span as i128 {
3121        return None;
3122    }
3123    let span = usize::try_from(span).ok()?;
3124    let bucket_of = |key: i64| (i128::from(key) - i128::from(min_key)) as usize;
3125
3126    // Each side's rows grouped by key in one counting pass - a bucket's
3127    // start in `starts`, its rows in position order in `rows` - where a Vec
3128    // a key was allocated, two per possible key, over the keys made Scalars
3129    // (an outer merge of 50k rows 0.75x pandas; br-frankenpandas-e186m).
3130    // The pairs come out exactly as before: keys ascending, a key's left
3131    // rows in order, each with its right rows in order.
3132    let grouped = |values: &[i64]| {
3133        let mut starts = vec![0_usize; span + 1];
3134        for &key in values {
3135            starts[bucket_of(key) + 1] += 1;
3136        }
3137        for bucket in 0..span {
3138            starts[bucket + 1] += starts[bucket];
3139        }
3140        let mut cursor = starts.clone();
3141        let mut rows = vec![0_usize; values.len()];
3142        for (pos, &key) in values.iter().enumerate() {
3143            let slot = &mut cursor[bucket_of(key)];
3144            rows[*slot] = pos;
3145            *slot += 1;
3146        }
3147        (starts, rows)
3148    };
3149    let (left_starts, left_rows) = grouped(&left_values);
3150    let (right_starts, right_rows) = grouped(&right_values);
3151
3152    let mut output_len = 0usize;
3153    for at in 0..span {
3154        let (lefts, rights) = (
3155            left_starts[at + 1] - left_starts[at],
3156            right_starts[at + 1] - right_starts[at],
3157        );
3158        let bucket_rows = match (lefts, rights) {
3159            (0, rights) => rights,
3160            (lefts, 0) => lefts,
3161            (lefts, rights) => lefts.checked_mul(rights)?,
3162        };
3163        output_len = output_len.checked_add(bucket_rows)?;
3164    }
3165
3166    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
3167    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
3168    for at in 0..span {
3169        let lefts = &left_rows[left_starts[at]..left_starts[at + 1]];
3170        let rights = &right_rows[right_starts[at]..right_starts[at + 1]];
3171        match (lefts.is_empty(), rights.is_empty()) {
3172            (false, false) => {
3173                for &left_pos in lefts {
3174                    for &right_pos in rights {
3175                        left_positions.push(Some(left_pos));
3176                        right_positions.push(Some(right_pos));
3177                    }
3178                }
3179            }
3180            (false, true) => {
3181                for &left_pos in lefts {
3182                    left_positions.push(Some(left_pos));
3183                    right_positions.push(None);
3184                }
3185            }
3186            (true, false) => {
3187                for &right_pos in rights {
3188                    left_positions.push(None);
3189                    right_positions.push(Some(right_pos));
3190                }
3191            }
3192            (true, true) => {}
3193        }
3194    }
3195
3196    Some((left_positions, right_positions))
3197}
3198
3199/// An all-valid int64 key column's values: its typed buffer, or its Scalar
3200/// view's ints ([`all_valid_int64_key_values`]).
3201fn int64_key_values(column: &Column) -> Option<std::borrow::Cow<'_, [i64]>> {
3202    if column.dtype() != DType::Int64 {
3203        return None;
3204    }
3205    if let Some(values) = column.as_i64_slice() {
3206        return Some(std::borrow::Cow::Borrowed(values));
3207    }
3208    let values = all_valid_int64_key_values(column)?;
3209    values
3210        .iter()
3211        .map(|value| match value {
3212            Scalar::Int64(key) => Some(*key),
3213            _ => None,
3214        })
3215        .collect::<Option<Vec<i64>>>()
3216        .map(std::borrow::Cow::Owned)
3217}
3218
3219fn ordered_unique_int64_outer_positions(
3220    left_key: &Column,
3221    right_key: &Column,
3222) -> Option<OptionalJoinPositions> {
3223    // Typed fast path (see ordered_unique_int64_left_match_positions): merge the
3224    // ordered union over raw &[i64] when both keys carry a contiguous Int64
3225    // backing, skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB per
3226    // merge at 1M rows). Bit-identical: same strictly-increasing gate and the
3227    // same three-way merge emitting the same (Option,Option) position pairs and
3228    // the same drain order.
3229    if let (Some(left_values), Some(right_values)) = (
3230        strictly_increasing_i64_slice(left_key),
3231        strictly_increasing_i64_slice(right_key),
3232    ) {
3233        let cap = left_values.len().saturating_add(right_values.len());
3234        // Branch-free steps: each side taken where its key is the smaller
3235        // (both when equal) and advanced by that flag - the three-way match
3236        // mispredicted on interleaved keys (two stepped 200k indexes' outer
3237        // merge 57% of 6.7 ms, 0.47x pandas; br-frankenpandas-m3z4g). The
3238        // steps counted first, then each side's positions collected over
3239        // that many steps, written in place: a push a row spilled both
3240        // vectors' lengths.
3241        let (mut left_idx, mut right_idx) = (0usize, 0usize);
3242        let mut steps = 0_usize;
3243        while left_idx < left_values.len() && right_idx < right_values.len() {
3244            let (left_value, right_value) = (left_values[left_idx], right_values[right_idx]);
3245            left_idx += usize::from(left_value <= right_value);
3246            right_idx += usize::from(right_value <= left_value);
3247            steps += 1;
3248        }
3249        let side = |left_side: bool| {
3250            let mut positions = Vec::<Option<usize>>::with_capacity(cap);
3251            let (mut left_at, mut right_at) = (0usize, 0usize);
3252            positions.extend((0..steps).map(|_| {
3253                let (left_value, right_value) = (left_values[left_at], right_values[right_at]);
3254                let take_left = left_value <= right_value;
3255                let take_right = right_value <= left_value;
3256                let taken = if left_side {
3257                    take_left.then_some(left_at)
3258                } else {
3259                    take_right.then_some(right_at)
3260                };
3261                left_at += usize::from(take_left);
3262                right_at += usize::from(take_right);
3263                taken
3264            }));
3265            positions
3266        };
3267        let mut left_positions = side(true);
3268        let mut right_positions = side(false);
3269        // The tails (one of them empty) in bulk: a push a row spilled both
3270        // lengths, and an outer join of two disjoint indexes is all tail
3271        // (br-frankenpandas-m3z4g).
3272        let left_rest = left_values.len() - left_idx;
3273        left_positions.extend((left_idx..left_values.len()).map(Some));
3274        right_positions.extend(std::iter::repeat_n(None, left_rest));
3275        let right_rest = right_values.len() - right_idx;
3276        left_positions.extend(std::iter::repeat_n(None, right_rest));
3277        right_positions.extend((right_idx..right_values.len()).map(Some));
3278        return Some((left_positions, right_positions));
3279    }
3280
3281    let left_values = strictly_increasing_int64_key_values(left_key)?;
3282    let right_values = strictly_increasing_int64_key_values(right_key)?;
3283
3284    let mut left_positions =
3285        Vec::<Option<usize>>::with_capacity(left_values.len().saturating_add(right_values.len()));
3286    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_positions.capacity());
3287    let mut left_idx = 0usize;
3288    let mut right_idx = 0usize;
3289
3290    while left_idx < left_values.len() && right_idx < right_values.len() {
3291        let left_value = match &left_values[left_idx] {
3292            Scalar::Int64(value) => *value,
3293            _ => return None,
3294        };
3295        let right_value = match &right_values[right_idx] {
3296            Scalar::Int64(value) => *value,
3297            _ => return None,
3298        };
3299
3300        match left_value.cmp(&right_value) {
3301            Ordering::Equal => {
3302                left_positions.push(Some(left_idx));
3303                right_positions.push(Some(right_idx));
3304                left_idx += 1;
3305                right_idx += 1;
3306            }
3307            Ordering::Less => {
3308                left_positions.push(Some(left_idx));
3309                right_positions.push(None);
3310                left_idx += 1;
3311            }
3312            Ordering::Greater => {
3313                left_positions.push(None);
3314                right_positions.push(Some(right_idx));
3315                right_idx += 1;
3316            }
3317        }
3318    }
3319
3320    while left_idx < left_values.len() {
3321        left_positions.push(Some(left_idx));
3322        right_positions.push(None);
3323        left_idx += 1;
3324    }
3325    while right_idx < right_values.len() {
3326        left_positions.push(None);
3327        right_positions.push(Some(right_idx));
3328        right_idx += 1;
3329    }
3330
3331    Some((left_positions, right_positions))
3332}
3333
3334fn identity_merge_column(
3335    column: &Column,
3336    row_count: usize,
3337    identity_positions: &mut Option<Vec<usize>>,
3338) -> Column {
3339    if column.validity().all() {
3340        return column.clone();
3341    }
3342
3343    let positions = identity_positions.get_or_insert_with(|| (0..row_count).collect());
3344    column.take_positions(positions)
3345}
3346
3347fn resolve_merge_indicator_name(indicator_name: Option<&str>) -> Result<Option<String>, JoinError> {
3348    let Some(name) = indicator_name else {
3349        return Ok(None);
3350    };
3351    if name.trim().is_empty() {
3352        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
3353            "merge indicator column name must be non-empty".to_owned(),
3354        )));
3355    }
3356    Ok(Some(name.to_owned()))
3357}
3358
3359fn build_merge_indicator_column(
3360    left_positions: &[Option<usize>],
3361    right_positions: &[Option<usize>],
3362) -> Column {
3363    // pandas makes `_merge` a category with the fixed categories
3364    // [left_only, right_only, both] - all three, in that order, whichever rows
3365    // appear (br-frankenpandas-hrxn9; it was an object column) - held as each
3366    // row's code into them, as pandas' Categorical: a String a row made a
3367    // Scalar-backed categorical every reader re-scanned (the merge paid
3368    // 10.7 ms for it at 190k rows, `_merge == 'both'` 0.00x pandas;
3369    // br-frankenpandas-fl3f0).
3370    let codes = left_positions
3371        .iter()
3372        .zip(right_positions.iter())
3373        .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
3374            (Some(_), None) => 0,
3375            (None, Some(_)) => 1,
3376            (Some(_), Some(_)) => 2,
3377            (None, None) => -1,
3378        })
3379        .collect::<Vec<i32>>();
3380    let categories = ["left_only", "right_only", "both"]
3381        .map(|category| fp_types::Scalar::Utf8(category.to_owned()))
3382        .to_vec();
3383    Column::from_categorical_codes(codes, fp_types::CategoricalMetadata::new(categories, false))
3384}
3385
3386fn ensure_indicator_name_available(
3387    indicator_name: &str,
3388    left_col_names: &HashSet<&String>,
3389    right_col_names: &HashSet<&String>,
3390    output_columns: &ColumnStore,
3391) -> Result<(), JoinError> {
3392    if left_col_names
3393        .iter()
3394        .any(|name| name.as_str() == indicator_name)
3395        || right_col_names
3396            .iter()
3397            .any(|name| name.as_str() == indicator_name)
3398        || output_columns.contains_key(indicator_name)
3399    {
3400        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
3401            format!("merge indicator column '{indicator_name}' conflicts with an existing column"),
3402        )));
3403    }
3404    Ok(())
3405}
3406
3407/// Positional gather that keeps an all-valid Int64 output column TYPED.
3408///
3409/// `Column::take_positions` already typed-fast-paths all-valid Float64 (it
3410/// gathers into a contiguous `Vec<f64>` behind `lazy_all_valid_float64`), but
3411/// for all-valid Int64 it materializes a `Vec<Scalar::Int64>` (32 B/elem). On
3412/// the inner-merge output build — one gather per carried column — that Scalar
3413/// rebuild dominates for integer payloads. Here we gather the contiguous `i64`
3414/// buffer directly and hand it to `from_i64_values`, which yields the same
3415/// lazy-typed all-valid Int64 column.
3416///
3417/// Bit-identical to `take_positions`: for an all-valid Int64 column the latter
3418/// produces `Scalar::Int64(slice[pos])` at every output slot with an all-valid
3419/// mask; `from_i64_values(gathered)` materializes exactly those scalars with the
3420/// same all-valid mask (no NaN coercion path for i64), and `Column` equality
3421/// ignores the internal data cache. `as_i64_slice` returns `Some` only for an
3422/// all-valid, typed-backed Int64 column, so every other dtype / any-missing
3423/// column falls through to the unchanged `take_positions`.
3424fn take_positions_typed(column: &Column, positions: &[usize]) -> Column {
3425    if let Some(slice) = column.as_i64_slice() {
3426        let mut data = Vec::with_capacity(positions.len());
3427        for &pos in positions {
3428            data.push(slice[pos]);
3429        }
3430        return Column::from_i64_values(data);
3431    }
3432    column.take_positions(positions)
3433}
3434
3435#[derive(Clone, Copy)]
3436enum PositionSelection<'a> {
3437    Positions(&'a [usize]),
3438    ContiguousRange { start: usize, len: usize },
3439}
3440
3441impl PositionSelection<'_> {
3442    fn len(self) -> usize {
3443        match self {
3444            Self::Positions(positions) => positions.len(),
3445            Self::ContiguousRange { len, .. } => len,
3446        }
3447    }
3448}
3449
3450fn take_position_selection_typed(column: &Column, selection: PositionSelection<'_>) -> Column {
3451    match selection {
3452        PositionSelection::Positions(positions) => take_positions_typed(column, positions),
3453        PositionSelection::ContiguousRange { start, len } => {
3454            column.take_contiguous_range(start, len)
3455        }
3456    }
3457}
3458
3459fn take_lower_hex_sequence_range(column: &Column, start: usize, len: usize) -> Option<Column> {
3460    let (prefix, certificate, source_len) = column.as_lower_hex_sequence_utf8()?;
3461    let end = start.checked_add(len)?;
3462    if end > source_len {
3463        return None;
3464    }
3465    let start_value = certificate.value_at(start)?;
3466    Column::from_lower_hex_sequence_utf8(prefix, start_value, len, certificate.hex_width())
3467}
3468
3469#[derive(Clone, Copy)]
3470enum FusedInt64Side {
3471    Left,
3472    Right,
3473}
3474
3475struct FusedInt64OutputColumn<'a> {
3476    name: String,
3477    side: FusedInt64Side,
3478    values: &'a [i64],
3479}
3480
3481struct FusedInt64MergeOptions<'a> {
3482    suffixes: &'a ResolvedMergeSuffixes,
3483    require_all_left_keys_matched: bool,
3484}
3485
3486#[cfg(not(test))]
3487const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1 << 18;
3488#[cfg(test)]
3489const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1;
3490const DENSE_I64_INNER_PARALLEL_MAX_CHUNKS: usize = 16;
3491
3492fn join_parallel_thread_count() -> usize {
3493    static THREAD_COUNT: OnceLock<usize> = OnceLock::new();
3494    *THREAD_COUNT.get_or_init(|| {
3495        fp_columnar::cached_available_parallelism().min(DENSE_I64_INNER_PARALLEL_MAX_CHUNKS)
3496    })
3497}
3498
3499struct DenseI64InnerOutputPlan<'a> {
3500    left_keys: &'a [i64],
3501    min: i64,
3502    max: i64,
3503    offsets: &'a [usize],
3504    positions: &'a [usize],
3505    output_len: usize,
3506}
3507
3508/// One output lane of the dense i64 inner merge.
3509enum DenseI64LaneData {
3510    /// Left lane carried as per-run values plus a shared run-length descriptor
3511    /// — O(matched) memory, expanded lazily by column consumers
3512    /// (br-frankenpandas-3ad4n, br-frankenpandas-l4adm).
3513    RepeatRunLengths {
3514        values: Vec<i64>,
3515        run_lens: Arc<[usize]>,
3516    },
3517    /// Right lane carried as repeated slices of one bucket-order value tape —
3518    /// O(right + matched) memory until a consumer forces a contiguous view.
3519    RepeatedSlices {
3520        data: Vec<i64>,
3521        segments: Arc<[(usize, usize)]>,
3522    },
3523    /// Fully materialized contiguous values.
3524    Full(Vec<i64>),
3525}
3526
3527/// Row-chunked disjoint-write fill (br-frankenpandas-6bsw3) with lazy
3528/// repeat-run left lanes (br-frankenpandas-3ad4n).
3529///
3530/// One probe walk records every matched left row as `(left_pos,
3531/// bucket_start, run_len)`. Left lanes are pure repeat runs (each left value
3532/// repeated `run_len` times), so when the average fanout is >= 2 they are
3533/// emitted as `(value, run_len)` pairs — O(matched) memory instead of
3534/// O(output) — and expanded only if a downstream consumer reads the values.
3535/// Remaining lanes (right lanes always; left lanes too on low-fanout joins
3536/// where a 16 B run would exceed the expanded bytes) are materialized by the
3537/// 6bsw3 scheme: up to [`DENSE_I64_INNER_PARALLEL_MAX_CHUNKS`] output-size-
3538/// balanced chunks of the matched list, each worker filling its disjoint
3539/// `split_at_mut` slice of every full lane (left repeat-runs via
3540/// `slice::fill`, right bucket ranges via `copy_from_slice` from the shared
3541/// muis1 value tapes).
3542///
3543/// Bit-identical: the matched list IS the left probe order; expanding a
3544/// `RepeatRunLengths` lane reproduces exactly the values the `Full` fill
3545/// writes, and chunks partition the matched list so concatenated output equals
3546/// the single-threaded walk byte for byte.
3547fn build_dense_i64_inner_output_data(
3548    specs: &[FusedInt64OutputColumn<'_>],
3549    plan: &DenseI64InnerOutputPlan<'_>,
3550) -> Vec<DenseI64LaneData> {
3551    // Single probe walk shared by every lane: matched left rows in probe
3552    // order as (left_pos, bucket_start, run_len).
3553    let mut matched: Vec<(usize, usize, usize)> = Vec::new();
3554    for (left_pos, &v) in plan.left_keys.iter().enumerate() {
3555        if v < plan.min || v > plan.max {
3556            continue;
3557        }
3558        let bucket = (v - plan.min) as usize;
3559        if bucket + 1 >= plan.offsets.len() {
3560            continue;
3561        }
3562        let start = plan.offsets[bucket];
3563        let run_len = plan.offsets[bucket + 1] - start;
3564        if run_len == 0 {
3565            continue;
3566        }
3567        matched.push((left_pos, start, run_len));
3568    }
3569    debug_assert_eq!(
3570        matched
3571            .iter()
3572            .map(|&(_, _, run_len)| run_len)
3573            .sum::<usize>(),
3574        plan.output_len
3575    );
3576
3577    // A (value, run_len) pair is 16 B vs 8 B x run_len expanded: repeat runs
3578    // only pay when the average fanout is >= 2 (1:1 joins stay materialized).
3579    let use_repeat_runs = plan.output_len >= matched.len().saturating_mul(2);
3580
3581    let use_repeated_slices = use_repeat_runs;
3582    let repeat_run_lens: Option<Arc<[usize]>> = if use_repeat_runs {
3583        Some(
3584            matched
3585                .iter()
3586                .map(|&(_, _, run_len)| run_len)
3587                .collect::<Vec<_>>()
3588                .into(),
3589        )
3590    } else {
3591        None
3592    };
3593    let repeated_segments: Option<Arc<[(usize, usize)]>> = if use_repeated_slices {
3594        Some(
3595            matched
3596                .iter()
3597                .map(|&(_, start, run_len)| (start, run_len))
3598                .collect::<Vec<_>>()
3599                .into(),
3600        )
3601    } else {
3602        None
3603    };
3604
3605    let full_specs: Vec<usize> = specs
3606        .iter()
3607        .enumerate()
3608        .filter(|(_, spec)| {
3609            !(use_repeat_runs && matches!(spec.side, FusedInt64Side::Left))
3610                && !(use_repeated_slices && matches!(spec.side, FusedInt64Side::Right))
3611        })
3612        .map(|(idx, _)| idx)
3613        .collect();
3614
3615    // Fill the full lanes first (right lanes always; left lanes on
3616    // low-fanout joins).
3617    let mut full_data: Vec<Vec<i64>> = Vec::new();
3618    let thread_count = join_parallel_thread_count();
3619    if !full_specs.is_empty()
3620        && plan.output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES
3621        && thread_count > 1
3622    {
3623        // Replay buckets from a value tape per right-side column (one gather
3624        // of right values into bucket order, per br-frankenpandas-muis1),
3625        // shared read-only across all chunk workers.
3626        let tapes: Vec<Option<Vec<i64>>> = full_specs
3627            .iter()
3628            .map(|&spec_idx| match specs[spec_idx].side {
3629                FusedInt64Side::Left => None,
3630                FusedInt64Side::Right => Some(
3631                    plan.positions
3632                        .iter()
3633                        .map(|&right_pos| specs[spec_idx].values[right_pos])
3634                        .collect(),
3635                ),
3636            })
3637            .collect();
3638
3639        // Chunk boundaries (matched_idx, out_pos), balanced by OUTPUT size
3640        // so a few hot buckets cannot starve the other workers.
3641        let target = plan.output_len.div_ceil(thread_count).max(1);
3642        let mut boundaries = vec![(0usize, 0usize)];
3643        let mut cumulative = 0usize;
3644        let mut next_target = target;
3645        for (matched_idx, &(_, _, run_len)) in matched.iter().enumerate() {
3646            cumulative += run_len;
3647            if cumulative >= next_target && matched_idx + 1 < matched.len() {
3648                boundaries.push((matched_idx + 1, cumulative));
3649                next_target = cumulative.saturating_add(target);
3650            }
3651        }
3652        boundaries.push((matched.len(), plan.output_len));
3653        let chunk_count = boundaries.len() - 1;
3654
3655        // Pre-size every full lane, then hand each chunk worker its disjoint
3656        // slice of every lane via progressive split_at_mut.
3657        let mut column_bufs: Vec<Vec<i64>> = full_specs
3658            .iter()
3659            .map(|_| vec![0i64; plan.output_len])
3660            .collect();
3661        let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
3662            .map(|_| Vec::with_capacity(full_specs.len()))
3663            .collect();
3664        for buf in &mut column_bufs {
3665            let mut rest: &mut [i64] = buf.as_mut_slice();
3666            let mut prev = 0usize;
3667            for (chunk_idx, window) in boundaries.windows(2).enumerate() {
3668                let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
3669                prev = window[1].1;
3670                rest = tail;
3671                bundles[chunk_idx].push(chunk_slice);
3672            }
3673        }
3674
3675        let matched = &matched;
3676        let full_specs = &full_specs;
3677        std::thread::scope(|scope| {
3678            let mut handles = Vec::with_capacity(chunk_count);
3679            for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
3680                let (matched_start, out_start) = boundaries[chunk_idx];
3681                let (matched_end, out_end) = boundaries[chunk_idx + 1];
3682                let tapes = &tapes;
3683                handles.push(scope.spawn(move || {
3684                    let mut cursor = 0usize;
3685                    for &(left_pos, start, run_len) in &matched[matched_start..matched_end] {
3686                        for (slice, (&spec_idx, tape)) in
3687                            bundle.iter_mut().zip(full_specs.iter().zip(tapes.iter()))
3688                        {
3689                            match specs[spec_idx].side {
3690                                FusedInt64Side::Left => {
3691                                    slice[cursor..cursor + run_len]
3692                                        .fill(specs[spec_idx].values[left_pos]);
3693                                }
3694                                FusedInt64Side::Right => {
3695                                    slice[cursor..cursor + run_len].copy_from_slice(
3696                                        &tape.as_ref().expect("right spec must have a bucket tape")
3697                                            [start..start + run_len],
3698                                    );
3699                                }
3700                            }
3701                        }
3702                        cursor += run_len;
3703                    }
3704                    debug_assert_eq!(cursor, out_end - out_start);
3705                }));
3706            }
3707            for handle in handles {
3708                handle
3709                    .join()
3710                    .expect("dense i64 output worker must not panic");
3711            }
3712        });
3713        full_data = column_bufs;
3714    } else if !full_specs.is_empty() {
3715        full_data = full_specs
3716            .iter()
3717            .map(|_| Vec::<i64>::with_capacity(plan.output_len))
3718            .collect();
3719        for &(left_pos, start, run_len) in &matched {
3720            for (out, &spec_idx) in full_data.iter_mut().zip(full_specs.iter()) {
3721                match specs[spec_idx].side {
3722                    FusedInt64Side::Left => {
3723                        out.resize(out.len() + run_len, specs[spec_idx].values[left_pos]);
3724                    }
3725                    FusedInt64Side::Right => {
3726                        for &right_pos in &plan.positions[start..start + run_len] {
3727                            out.push(specs[spec_idx].values[right_pos]);
3728                        }
3729                    }
3730                }
3731            }
3732        }
3733        debug_assert!(full_data.iter().all(|data| data.len() == plan.output_len));
3734    }
3735
3736    // Assemble lanes in spec order: repeat runs for the lazy left lanes,
3737    // filled buffers for everything else.
3738    let mut full_iter = full_data.into_iter();
3739    specs
3740        .iter()
3741        .map(|spec| {
3742            if use_repeat_runs && matches!(spec.side, FusedInt64Side::Left) {
3743                DenseI64LaneData::RepeatRunLengths {
3744                    values: matched
3745                        .iter()
3746                        .map(|&(left_pos, _, _)| spec.values[left_pos])
3747                        .collect(),
3748                    run_lens: Arc::clone(
3749                        repeat_run_lens
3750                            .as_ref()
3751                            .expect("repeat run lengths must exist"),
3752                    ),
3753                }
3754            } else if use_repeated_slices && matches!(spec.side, FusedInt64Side::Right) {
3755                DenseI64LaneData::RepeatedSlices {
3756                    data: plan
3757                        .positions
3758                        .iter()
3759                        .map(|&right_pos| spec.values[right_pos])
3760                        .collect(),
3761                    segments: Arc::clone(
3762                        repeated_segments
3763                            .as_ref()
3764                            .expect("repeated slice segments must exist"),
3765                    ),
3766                }
3767            } else {
3768                DenseI64LaneData::Full(
3769                    full_iter
3770                        .next()
3771                        .expect("full lane buffer must exist for every non-run spec"),
3772                )
3773            }
3774        })
3775        .collect()
3776}
3777
3778/// Which typed lane an output column of the dense inner merge uses, recorded in
3779/// column-encounter order so the i64 (lazy) and f64 (materialized) builds can be
3780/// re-interleaved into the original column order (br-frankenpandas-jzrem).
3781enum DenseInnerSpecKind {
3782    I64,
3783    F64,
3784}
3785
3786/// One Float64 output lane of the dense inner merge (br-frankenpandas-jzrem).
3787struct FusedF64OutputColumn<'a> {
3788    name: String,
3789    side: FusedInt64Side,
3790    values: &'a [f64],
3791}
3792
3793/// The matched-left-row list `(left_pos, bucket_start, run_len)` in probe order
3794/// — identical to the walk inside [`build_dense_i64_inner_output_data`], so the
3795/// Float64 lanes materialize in the exact same row order as the i64 lanes and
3796/// the flat `take_positions` path.
3797fn dense_inner_matched_runs(plan: &DenseI64InnerOutputPlan<'_>) -> Vec<(usize, usize, usize)> {
3798    let mut matched = Vec::new();
3799    for (left_pos, &v) in plan.left_keys.iter().enumerate() {
3800        if v < plan.min || v > plan.max {
3801            continue;
3802        }
3803        let bucket = (v - plan.min) as usize;
3804        if bucket + 1 >= plan.offsets.len() {
3805            continue;
3806        }
3807        let start = plan.offsets[bucket];
3808        let run_len = plan.offsets[bucket + 1] - start;
3809        if run_len == 0 {
3810            continue;
3811        }
3812        matched.push((left_pos, start, run_len));
3813    }
3814    matched
3815}
3816
3817/// Build one Float64 inner-merge output column as a LAZY representation
3818/// (br-frankenpandas-jzrem) — O(matched + right_len), never the O(output_len)
3819/// materialization:
3820///   * a Left column becomes a repeat-values lane: one value per matched run
3821///     (`values[left_pos]`) over the shared `run_lens` descriptor;
3822///   * a Right column becomes a repeated-slices lane over the bucket-ordered
3823///     value tape (`values` gathered by `positions`, one scattered pass) with
3824///     the shared `segments` descriptor.
3825///
3826/// Both materialize, only when a consumer reads them, to exactly the values
3827/// `take_position_selection_typed` would produce on the flat `(left_positions,
3828/// right_positions)` vectors — same values, same row order (matched-run probe
3829/// order == flat position order). Mirrors the i64 lazy lanes the all-Int64 path
3830/// already emits, so a join whose output is only sized (not consumed) stays
3831/// near-free instead of writing the whole fanned-out column.
3832fn build_dense_inner_f64_column(
3833    side: FusedInt64Side,
3834    values: &[f64],
3835    matched: &[(usize, usize, usize)],
3836    positions: &[usize],
3837    run_lens: &Arc<[usize]>,
3838    segments: &Arc<[(usize, usize)]>,
3839    output_len: usize,
3840) -> Column {
3841    match side {
3842        FusedInt64Side::Left => {
3843            let run_values: Vec<f64> = matched
3844                .iter()
3845                .map(|&(left_pos, _, _)| values[left_pos])
3846                .collect();
3847            Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
3848        }
3849        FusedInt64Side::Right => {
3850            let tape: Vec<f64> = positions.iter().map(|&p| values[p]).collect();
3851            Column::from_f64_repeated_slices_shared(tape, Arc::clone(segments), output_len)
3852        }
3853    }
3854}
3855
3856/// Build every Float64 inner-merge output column, one worker per column when the
3857/// pool is worth it (the fu8f5 column-parallel pattern). Returns `(name, column)`
3858/// pairs in `specs` order. `run_lens`/`segments` are the shared lazy-lane
3859/// descriptors derived from the matched-run list (one per matched run).
3860fn build_dense_inner_f64_columns(
3861    specs: Vec<FusedF64OutputColumn<'_>>,
3862    matched: &[(usize, usize, usize)],
3863    positions: &[usize],
3864    output_len: usize,
3865) -> Vec<(String, Column)> {
3866    if specs.is_empty() {
3867        return Vec::new();
3868    }
3869    let run_lens: Arc<[usize]> = matched.iter().map(|&(_, _, run_len)| run_len).collect();
3870    let segments: Arc<[(usize, usize)]> = matched
3871        .iter()
3872        .map(|&(_, bucket_start, run_len)| (bucket_start, run_len))
3873        .collect();
3874
3875    let worker_count = join_parallel_thread_count().min(specs.len());
3876    if worker_count < 2 {
3877        return specs
3878            .into_iter()
3879            .map(|s| {
3880                (
3881                    s.name,
3882                    build_dense_inner_f64_column(
3883                        s.side, s.values, matched, positions, &run_lens, &segments, output_len,
3884                    ),
3885                )
3886            })
3887            .collect();
3888    }
3889
3890    let next = std::sync::atomic::AtomicUsize::new(0);
3891    let specs_ref = &specs;
3892    let run_lens_ref = &run_lens;
3893    let segments_ref = &segments;
3894    let built_by_worker = std::thread::scope(|scope| {
3895        let mut handles = Vec::with_capacity(worker_count);
3896        for _ in 0..worker_count {
3897            let next = &next;
3898            handles.push(scope.spawn(move || {
3899                let mut local: Vec<(usize, Column)> = Vec::new();
3900                loop {
3901                    let idx = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3902                    if idx >= specs_ref.len() {
3903                        break;
3904                    }
3905                    let s = &specs_ref[idx];
3906                    local.push((
3907                        idx,
3908                        build_dense_inner_f64_column(
3909                            s.side,
3910                            s.values,
3911                            matched,
3912                            positions,
3913                            run_lens_ref,
3914                            segments_ref,
3915                            output_len,
3916                        ),
3917                    ));
3918                }
3919                local
3920            }));
3921        }
3922        let mut all: Vec<(usize, Column)> = Vec::new();
3923        for handle in handles {
3924            all.extend(
3925                handle
3926                    .join()
3927                    .expect("f64 inner-merge column worker panicked"),
3928            );
3929        }
3930        all
3931    });
3932
3933    let mut built: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
3934    for (idx, column) in built_by_worker {
3935        built[idx] = Some(column);
3936    }
3937    specs
3938        .into_iter()
3939        .zip(built)
3940        .map(|(s, column)| {
3941            (
3942                s.name,
3943                column.expect("every f64 column index is built once"),
3944            )
3945        })
3946        .collect()
3947}
3948
3949fn build_single_key_dense_i64_inner_merge_output(
3950    left: &fp_frame::DataFrame,
3951    right: &fp_frame::DataFrame,
3952    left_on: &[&str],
3953    right_on: &[&str],
3954    left_key: &Column,
3955    right_key: &Column,
3956    options: FusedInt64MergeOptions<'_>,
3957) -> Result<Option<MergedDataFrame>, JoinError> {
3958    debug_assert_eq!(left_on.len(), 1);
3959    debug_assert_eq!(right_on.len(), 1);
3960
3961    let Some(left_keys) = left_key.as_i64_slice() else {
3962        return Ok(None);
3963    };
3964    let Some(right_keys) = right_key.as_i64_slice() else {
3965        return Ok(None);
3966    };
3967
3968    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
3969    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
3970    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
3971    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
3972    let shared_key_names = if left_on[0] == right_on[0] {
3973        [left_on[0]].into_iter().collect::<HashSet<&str>>()
3974    } else {
3975        HashSet::new()
3976    };
3977    let overlapping_names =
3978        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
3979
3980    // Collect output specs in column-encounter order, accepting BOTH typed
3981    // all-valid Int64 and typed all-valid Float64 columns (br-frankenpandas-jzrem).
3982    // Int64 columns keep the lazy repeat-run / repeated-slice representation;
3983    // Float64 columns are materialized cache-efficiently below. Any other dtype,
3984    // a nullable column, or a NaN-bearing Float64 (as_f64_slice gates on
3985    // validity.all()) declines the whole fast path (Ok(None)) and falls back to
3986    // the flat gather, exactly as before.
3987    let mut i64_specs = Vec::<FusedInt64OutputColumn<'_>>::new();
3988    let mut f64_specs = Vec::<FusedF64OutputColumn<'_>>::new();
3989    let mut order_kinds = Vec::<DenseInnerSpecKind>::new();
3990
3991    for name in left.column_names() {
3992        let col = left
3993            .columns()
3994            .get(name)
3995            .expect("left column listed in column_names must exist");
3996        let out_name = if left_key_name_set.contains(name.as_str()) {
3997            name.clone()
3998        } else if right_col_names.contains(name) {
3999            apply_merge_suffix(name, options.suffixes.left.as_deref())
4000        } else {
4001            name.clone()
4002        };
4003        if let Some(values) = col.as_i64_slice() {
4004            i64_specs.push(FusedInt64OutputColumn {
4005                name: out_name,
4006                side: FusedInt64Side::Left,
4007                values,
4008            });
4009            order_kinds.push(DenseInnerSpecKind::I64);
4010        } else if let Some(values) = col.as_f64_slice() {
4011            f64_specs.push(FusedF64OutputColumn {
4012                name: out_name,
4013                side: FusedInt64Side::Left,
4014                values,
4015            });
4016            order_kinds.push(DenseInnerSpecKind::F64);
4017        } else {
4018            return Ok(None);
4019        }
4020    }
4021
4022    for name in right.column_names() {
4023        let col = right
4024            .columns()
4025            .get(name)
4026            .expect("right column listed in column_names must exist");
4027        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4028            continue;
4029        }
4030        let out_name = if left_col_names.contains(name) {
4031            apply_merge_suffix(name, options.suffixes.right.as_deref())
4032        } else {
4033            name.clone()
4034        };
4035        if let Some(values) = col.as_i64_slice() {
4036            i64_specs.push(FusedInt64OutputColumn {
4037                name: out_name,
4038                side: FusedInt64Side::Right,
4039                values,
4040            });
4041            order_kinds.push(DenseInnerSpecKind::I64);
4042        } else if let Some(values) = col.as_f64_slice() {
4043            f64_specs.push(FusedF64OutputColumn {
4044                name: out_name,
4045                side: FusedInt64Side::Right,
4046                values,
4047            });
4048            order_kinds.push(DenseInnerSpecKind::F64);
4049        } else {
4050            return Ok(None);
4051        }
4052    }
4053
4054    ensure_merge_suffixes_for_overlaps(&overlapping_names, options.suffixes)?;
4055
4056    if left_keys.is_empty() || right_keys.is_empty() {
4057        if options.require_all_left_keys_matched && !left_keys.is_empty() {
4058            return Ok(None);
4059        }
4060        let mut columns = ColumnStore::new();
4061        let mut column_order = Vec::with_capacity(order_kinds.len());
4062        let mut i64_it = i64_specs.into_iter();
4063        let mut f64_it = f64_specs.into_iter();
4064        for kind in &order_kinds {
4065            match kind {
4066                DenseInnerSpecKind::I64 => {
4067                    let spec = i64_it.next().expect("i64 spec for each I64 kind");
4068                    insert_merged_output_column(
4069                        &mut columns,
4070                        &mut column_order,
4071                        spec.name,
4072                        Column::from_i64_values(Vec::new()),
4073                    )?;
4074                }
4075                DenseInnerSpecKind::F64 => {
4076                    let spec = f64_it.next().expect("f64 spec for each F64 kind");
4077                    insert_merged_output_column(
4078                        &mut columns,
4079                        &mut column_order,
4080                        spec.name,
4081                        Column::from_f64_values(Vec::new()),
4082                    )?;
4083                }
4084            }
4085        }
4086        return Ok(Some(MergedDataFrame {
4087            index: Index::new(Vec::new()),
4088            columns,
4089            column_order,
4090        }));
4091    }
4092
4093    let mut min = right_keys[0];
4094    let mut max = right_keys[0];
4095    for &v in right_keys {
4096        if v < min {
4097            min = v;
4098        }
4099        if v > max {
4100            max = v;
4101        }
4102    }
4103    let span = (max as i128) - (min as i128) + 1;
4104    if span > (1i128 << 24) || span > 16 * (right_keys.len() as i128) {
4105        return Ok(None);
4106    }
4107    let range = span as usize;
4108
4109    let mut offsets = vec![0usize; range + 1];
4110    for &v in right_keys {
4111        offsets[(v - min) as usize + 1] += 1;
4112    }
4113    for i in 0..range {
4114        offsets[i + 1] += offsets[i];
4115    }
4116    let mut positions = vec![0usize; right_keys.len()];
4117    let mut cursor = offsets.clone();
4118    for (pos, &v) in right_keys.iter().enumerate() {
4119        let bucket = (v - min) as usize;
4120        positions[cursor[bucket]] = pos;
4121        cursor[bucket] += 1;
4122    }
4123
4124    let mut output_len = 0usize;
4125    for &v in left_keys {
4126        if v < min || v > max {
4127            if options.require_all_left_keys_matched {
4128                return Ok(None);
4129            }
4130            continue;
4131        }
4132        let bucket = (v - min) as usize;
4133        let bucket_len = offsets[bucket + 1] - offsets[bucket];
4134        if bucket_len == 0 {
4135            if options.require_all_left_keys_matched {
4136                return Ok(None);
4137            }
4138            continue;
4139        }
4140        let Some(new_output_len) = output_len.checked_add(bucket_len) else {
4141            return Ok(None);
4142        };
4143        output_len = new_output_len;
4144    }
4145
4146    let output_plan = DenseI64InnerOutputPlan {
4147        left_keys,
4148        min,
4149        max,
4150        offsets: &offsets,
4151        positions: &positions,
4152        output_len,
4153    };
4154    let i64_lanes = build_dense_i64_inner_output_data(&i64_specs, &output_plan);
4155    // Float64 lanes materialized cache-efficiently in the same probe row order
4156    // (br-frankenpandas-jzrem); the matched-run walk is only needed when there
4157    // are Float64 columns to build.
4158    let matched = if f64_specs.is_empty() {
4159        Vec::new()
4160    } else {
4161        dense_inner_matched_runs(&output_plan)
4162    };
4163    let f64_columns = build_dense_inner_f64_columns(f64_specs, &matched, &positions, output_len);
4164
4165    // Lazy unit-range output index: identical labels (0..output_len as
4166    // IndexLabel::Int64, materialized on demand), pre-proven unique and
4167    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
4168    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4169    let mut columns = ColumnStore::new();
4170    let mut column_order = Vec::with_capacity(order_kinds.len());
4171    let mut i64_it = i64_specs.into_iter().zip(i64_lanes);
4172    let mut f64_it = f64_columns.into_iter();
4173    for kind in &order_kinds {
4174        match kind {
4175            DenseInnerSpecKind::I64 => {
4176                let (spec, lane) = i64_it.next().expect("i64 lane for each I64 kind");
4177                let column = match lane {
4178                    DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
4179                        Column::from_i64_repeat_values_run_lengths(values, run_lens)
4180                    }
4181                    DenseI64LaneData::RepeatedSlices { data, segments } => {
4182                        Column::from_i64_repeated_slices_shared(data, segments, output_len)
4183                    }
4184                    DenseI64LaneData::Full(data) => Column::from_i64_values(data),
4185                };
4186                debug_assert_eq!(column.len(), output_len);
4187                insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
4188            }
4189            DenseInnerSpecKind::F64 => {
4190                let (name, column) = f64_it.next().expect("f64 column for each F64 kind");
4191                debug_assert_eq!(column.len(), output_len);
4192                insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
4193            }
4194        }
4195    }
4196
4197    Ok(Some(MergedDataFrame {
4198        index,
4199        columns,
4200        column_order,
4201    }))
4202}
4203
4204fn push_join_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
4205    if len == 0 {
4206        return;
4207    }
4208    if let Some((last_start, last_len)) = ranges.last_mut()
4209        && last_start.checked_add(*last_len) == Some(start)
4210    {
4211        *last_len += len;
4212        return;
4213    }
4214    ranges.push((start, len));
4215}
4216
4217fn dense_cycle_key_at(witness: Int64DenseCycleWitness, row: usize) -> Option<i64> {
4218    let offset = i64::try_from(row % witness.period).ok()?;
4219    witness.start.checked_add(offset)
4220}
4221
4222fn dense_cycle_left_join_shape(
4223    left_witness: Int64DenseCycleWitness,
4224    right_witness: Int64DenseCycleWitness,
4225) -> Option<(usize, ValidityMask)> {
4226    let mut output_len = 0usize;
4227    let mut invalid_ranges = Vec::<(usize, usize)>::new();
4228    for left_pos in 0..left_witness.len {
4229        let key = dense_cycle_key_at(left_witness, left_pos)?;
4230        if let Some((_, right_count)) = right_witness.offset_count_for_key(key) {
4231            output_len = output_len.checked_add(right_count)?;
4232        } else {
4233            push_join_invalid_range(&mut invalid_ranges, output_len, 1);
4234            output_len = output_len.checked_add(1)?;
4235        }
4236    }
4237    let right_validity = ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len);
4238    Some((output_len, right_validity))
4239}
4240
4241/// Dense-cycle LEFT merge builder (br-frankenpandas-yq96z).
4242///
4243/// For certified `key[row] = start + (row % period)` Int64 keys, the previous
4244/// high-fanout left path still built an O(left_rows) plan, right segment tape,
4245/// and one repeat-run descriptor per left lane. This path keeps the same
4246/// left-major pandas order but stores only the two key witnesses:
4247///
4248/// - output length/right validity are derived by scanning the left witness once;
4249/// - left lanes read `source[left_pos]` and repeat by the matching right count;
4250/// - right lanes replay positions `right_offset + k * right_period`;
4251/// - unmatched left rows emit one right null at the same output slot.
4252///
4253/// The route accepts only all-valid Int64 columns. Any other dtype/null shape
4254/// falls back to the existing materialized-plan builder.
4255fn build_single_key_dense_cycle_i64_left_merge_output(
4256    left: &fp_frame::DataFrame,
4257    right: &fp_frame::DataFrame,
4258    left_on: &[&str],
4259    right_on: &[&str],
4260    left_key: &Column,
4261    right_key: &Column,
4262    suffixes: &ResolvedMergeSuffixes,
4263) -> Result<Option<MergedDataFrame>, JoinError> {
4264    debug_assert_eq!(left_on.len(), 1);
4265    debug_assert_eq!(right_on.len(), 1);
4266
4267    let Some(left_witness) = left_key
4268        .int64_dense_cycle_witness()
4269        .filter(|witness| witness.len == left_key.len())
4270    else {
4271        return Ok(None);
4272    };
4273    let Some(right_witness) = right_key
4274        .int64_dense_cycle_witness()
4275        .filter(|witness| witness.len == right_key.len())
4276    else {
4277        return Ok(None);
4278    };
4279    let Some((output_len, right_validity)) =
4280        dense_cycle_left_join_shape(left_witness, right_witness)
4281    else {
4282        return Ok(None);
4283    };
4284    if !right_validity.all() {
4285        // The generic gather promotes all-valid Int64 lanes when this join
4286        // invents a gap. This lazy i64-only representation cannot do so.
4287        return Ok(None);
4288    }
4289
4290    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4291    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4292    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4293    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4294    let shared_key_names = if left_on[0] == right_on[0] {
4295        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4296    } else {
4297        HashSet::new()
4298    };
4299    let overlapping_names =
4300        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4301
4302    enum DenseCycleLeftLane {
4303        Left,
4304        Right,
4305    }
4306    let mut spec_names = Vec::<String>::new();
4307    let mut spec_kinds = Vec::<DenseCycleLeftLane>::new();
4308    let mut spec_sources = Vec::<Arc<[i64]>>::new();
4309
4310    for name in left.column_names() {
4311        let col = left
4312            .columns()
4313            .get(name)
4314            .expect("left column listed in column_names must exist");
4315        let Some(source) = col.as_i64_arc() else {
4316            return Ok(None);
4317        };
4318        let out_name = if left_key_name_set.contains(name.as_str()) {
4319            name.clone()
4320        } else if right_col_names.contains(name) {
4321            apply_merge_suffix(name, suffixes.left.as_deref())
4322        } else {
4323            name.clone()
4324        };
4325        spec_names.push(out_name);
4326        spec_kinds.push(DenseCycleLeftLane::Left);
4327        spec_sources.push(source);
4328    }
4329
4330    for name in right.column_names() {
4331        let col = right
4332            .columns()
4333            .get(name)
4334            .expect("right column listed in column_names must exist");
4335        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4336            continue;
4337        }
4338        let Some(source) = col.as_i64_arc() else {
4339            return Ok(None);
4340        };
4341        let out_name = if left_col_names.contains(name) {
4342            apply_merge_suffix(name, suffixes.right.as_deref())
4343        } else {
4344            name.clone()
4345        };
4346        spec_names.push(out_name);
4347        spec_kinds.push(DenseCycleLeftLane::Right);
4348        spec_sources.push(source);
4349    }
4350    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4351
4352    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4353    let mut columns = ColumnStore::new();
4354    let mut column_order = Vec::with_capacity(spec_names.len());
4355    for ((name, kind), source) in spec_names.into_iter().zip(spec_kinds).zip(spec_sources) {
4356        let column = match kind {
4357            DenseCycleLeftLane::Left => Column::from_i64_left_join_dense_cycle_left(
4358                source,
4359                left_witness,
4360                right_witness,
4361                output_len,
4362            ),
4363            DenseCycleLeftLane::Right => Column::from_i64_left_join_dense_cycle_right_nullable(
4364                source,
4365                left_witness,
4366                right_witness,
4367                right_validity.clone(),
4368                output_len,
4369            ),
4370        };
4371        debug_assert_eq!(column.len(), output_len);
4372        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
4373    }
4374
4375    Ok(Some(MergedDataFrame {
4376        index,
4377        columns,
4378        column_order,
4379    }))
4380}
4381
4382/// Fused dense-i64 LEFT merge builder (br-frankenpandas-7wxoc).
4383///
4384/// The partial-match left join previously materialized TWO
4385/// `Vec<Option<usize>>` of output length (16 B/slot each — ~627 MB of
4386/// intermediate on a 19.6M-row join) in `dense_int64_left_positions`, then
4387/// re-walked them per column through `reindex_by_positions`. Here the probe
4388/// emits a compact matched plan (`(left_pos, bucket_start, run_len)`, with
4389/// `usize::MAX` as the bucket sentinel for unmatched left rows that emit one
4390/// null-right row), and the output lanes are built with the proven inner-
4391/// builder machinery: muis1 right value tapes, 6bsw3 row-chunked disjoint
4392/// `split_at_mut` fills, 3ad4n lazy repeat-run left lanes, plus ONE shared
4393/// validity mask for every right lane (the null pattern is identical across
4394/// them — word-wise run fills, cloned per lane).
4395///
4396/// Bit-identical to the position-vector path: the plan is the same left
4397/// probe order; matched runs replay the same CSR bucket ranges; right lanes
4398/// keep dtype Int64 with `Null(NullKind::Null)` at unmatched rows (exactly
4399/// `reindex_by_positions`' missing semantics); left lanes repeat the left
4400/// value `run_len` times as `take_positions` would.
4401fn build_single_key_dense_i64_left_merge_output(
4402    left: &fp_frame::DataFrame,
4403    right: &fp_frame::DataFrame,
4404    left_on: &[&str],
4405    right_on: &[&str],
4406    left_key: &Column,
4407    right_key: &Column,
4408    suffixes: &ResolvedMergeSuffixes,
4409) -> Result<Option<MergedDataFrame>, JoinError> {
4410    debug_assert_eq!(left_on.len(), 1);
4411    debug_assert_eq!(right_on.len(), 1);
4412
4413    let Some(left_keys) = left_key.as_i64_slice() else {
4414        return Ok(None);
4415    };
4416    let Some(right_keys) = right_key.as_i64_slice() else {
4417        return Ok(None);
4418    };
4419    // Empty sides are rare and the position-vector path handles their edge
4420    // semantics; the dense-span gate below also needs a non-empty right.
4421    if left_keys.is_empty() || right_keys.is_empty() {
4422        return Ok(None);
4423    }
4424
4425    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4426    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4427    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4428    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4429    let shared_key_names = if left_on[0] == right_on[0] {
4430        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4431    } else {
4432        HashSet::new()
4433    };
4434    let overlapping_names =
4435        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4436
4437    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
4438    let mut sources = Vec::<Arc<[i64]>>::new();
4439    for name in left.column_names() {
4440        let col = left
4441            .columns()
4442            .get(name)
4443            .expect("left column listed in column_names must exist");
4444        let Some(values) = col.as_i64_slice() else {
4445            return Ok(None);
4446        };
4447        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4448        let out_name = if left_key_name_set.contains(name.as_str()) {
4449            name.clone()
4450        } else if right_col_names.contains(name) {
4451            apply_merge_suffix(name, suffixes.left.as_deref())
4452        } else {
4453            name.clone()
4454        };
4455        specs.push(FusedInt64OutputColumn {
4456            name: out_name,
4457            side: FusedInt64Side::Left,
4458            values,
4459        });
4460        sources.push(source);
4461    }
4462    for name in right.column_names() {
4463        let col = right
4464            .columns()
4465            .get(name)
4466            .expect("right column listed in column_names must exist");
4467        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4468            continue;
4469        }
4470        let Some(values) = col.as_i64_slice() else {
4471            return Ok(None);
4472        };
4473        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4474        let out_name = if left_col_names.contains(name) {
4475            apply_merge_suffix(name, suffixes.right.as_deref())
4476        } else {
4477            name.clone()
4478        };
4479        specs.push(FusedInt64OutputColumn {
4480            name: out_name,
4481            side: FusedInt64Side::Right,
4482            values,
4483        });
4484        sources.push(source);
4485    }
4486    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4487
4488    let row_count = left_keys.len().saturating_add(right_keys.len());
4489    let max_dense_span = row_count.saturating_mul(4).max(1024);
4490    let left_witness = left_key
4491        .int64_dense_cycle_witness()
4492        .filter(|witness| witness.len == left_keys.len());
4493    let right_witness = right_key
4494        .int64_dense_cycle_witness()
4495        .filter(|witness| witness.len == right_keys.len());
4496    if let (Some(left_witness), Some(right_witness), Some((right_min, right_max))) = (
4497        left_witness,
4498        right_witness,
4499        right_witness.and_then(dense_cycle_domain),
4500    ) {
4501        let right_span = i128::from(right_max) - i128::from(right_min) + 1;
4502        if right_span <= max_dense_span as i128
4503            && let Some((output_len, right_validity)) =
4504                dense_cycle_probe_output_len_and_validity(left_witness, right_witness)
4505        {
4506            if !right_validity.all() {
4507                // Fall through to the typed gather below, which widens the
4508                // gap-bearing Int64 lanes to Float64 like pandas.
4509            } else {
4510                let index = Index::new_known_unique_int64_unit_range(0, output_len);
4511                let mut columns = ColumnStore::new();
4512                let mut column_order = Vec::with_capacity(specs.len());
4513                for (spec, source) in specs.into_iter().zip(sources) {
4514                    let column = match spec.side {
4515                        FusedInt64Side::Left => Column::from_i64_dense_cycle_probe_repeat(
4516                            source,
4517                            left_witness,
4518                            right_witness,
4519                            output_len,
4520                        ),
4521                        FusedInt64Side::Right => {
4522                            Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
4523                                source,
4524                                left_witness,
4525                                right_witness,
4526                                right_validity.clone(),
4527                                output_len,
4528                            )
4529                        }
4530                    };
4531                    debug_assert_eq!(column.len(), output_len);
4532                    insert_merged_output_column(
4533                        &mut columns,
4534                        &mut column_order,
4535                        spec.name,
4536                        column,
4537                    )?;
4538                }
4539                return Ok(Some(MergedDataFrame {
4540                    index,
4541                    columns,
4542                    column_order,
4543                }));
4544            }
4545        }
4546    }
4547
4548    // Dense CSR over the RIGHT key range — same gate as the position path
4549    // (span <= 4*(rows)+1024) so routing between fused/fallback matches
4550    // dense_int64_left_positions' accept set.
4551    let mut min_key = right_keys[0];
4552    let mut max_key = right_keys[0];
4553    for &key in right_keys {
4554        min_key = min_key.min(key);
4555        max_key = max_key.max(key);
4556    }
4557    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
4558    if span > max_dense_span as i128 {
4559        return Ok(None);
4560    }
4561    let span = usize::try_from(span).expect("span bounded by max_dense_span");
4562
4563    let mut offsets = vec![0usize; span + 1];
4564    for &key in right_keys {
4565        offsets[(key - min_key) as usize + 1] += 1;
4566    }
4567    for i in 0..span {
4568        offsets[i + 1] += offsets[i];
4569    }
4570    let mut positions = vec![0usize; right_keys.len()];
4571    let mut cursor = offsets[..span].to_vec();
4572    for (pos, &key) in right_keys.iter().enumerate() {
4573        let bucket = (key - min_key) as usize;
4574        positions[cursor[bucket]] = pos;
4575        cursor[bucket] += 1;
4576    }
4577
4578    // Matched plan: (left_pos, bucket_start, run_len); bucket_start ==
4579    // usize::MAX marks an unmatched left row (one output row, null right).
4580    const UNMATCHED: usize = usize::MAX;
4581    let mut plan = Vec::<(usize, usize, usize)>::with_capacity(left_keys.len());
4582    let mut output_len = 0usize;
4583    for (left_pos, &key) in left_keys.iter().enumerate() {
4584        let offset = i128::from(key) - i128::from(min_key);
4585        let run = if offset >= 0 && offset < span as i128 {
4586            let bucket = offset as usize;
4587            let start = offsets[bucket];
4588            let len = offsets[bucket + 1] - start;
4589            if len == 0 {
4590                (left_pos, UNMATCHED, 1)
4591            } else {
4592                (left_pos, start, len)
4593            }
4594        } else {
4595            (left_pos, UNMATCHED, 1)
4596        };
4597        let Some(new_len) = output_len.checked_add(run.2) else {
4598            return Ok(None);
4599        };
4600        output_len = new_len;
4601        plan.push(run);
4602    }
4603    if plan.iter().any(|&(_, start, _)| start == UNMATCHED) {
4604        return Ok(None);
4605    }
4606
4607    // Shared right-lane segment descriptor (br-frankenpandas-yiqv5): the plan's
4608    // `(bucket_start, run_len)` pairs are exactly the nullable repeated-slices
4609    // segment format (`bucket_start == usize::MAX` == UNMATCHED ⇒ a null run), so
4610    // every right lane is emitted as a LAZY `LazyNullableRepeatedSlicesInt64`
4611    // over its bucket-order value tape instead of a materialized O(output_len)
4612    // buffer. The validity mask is rebuilt from these segments inside the column
4613    // ctor (matched runs valid, unmatched rows null) — identical to the prior
4614    // word-wise fill.
4615    let right_segments: Arc<[(usize, usize)]> = plan
4616        .iter()
4617        .map(|&(_, start, run_len)| (start, run_len))
4618        .collect();
4619
4620    // Left lanes as lazy repeat runs when the average fanout pays (3ad4n
4621    // gate); unmatched rows are singleton runs so the representation is
4622    // uniform.
4623    let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
4624
4625    // Only LOW-FANOUT LEFT lanes still materialize into O(output_len) buffers;
4626    // right lanes are always lazy (nullable repeated-slices) and high-fanout
4627    // left lanes are lazy repeat runs.
4628    let full_specs: Vec<usize> = specs
4629        .iter()
4630        .enumerate()
4631        .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Left) && !use_repeat_runs)
4632        .map(|(idx, _)| idx)
4633        .collect();
4634
4635    let mut full_data: Vec<Vec<i64>> = Vec::new();
4636    let thread_count = join_parallel_thread_count();
4637    if !full_specs.is_empty() {
4638        // Right value tapes in bucket order (muis1), shared read-only.
4639        let tapes: Vec<Option<Vec<i64>>> = full_specs
4640            .iter()
4641            .map(|&spec_idx| match specs[spec_idx].side {
4642                FusedInt64Side::Left => None,
4643                FusedInt64Side::Right => Some(
4644                    positions
4645                        .iter()
4646                        .map(|&right_pos| specs[spec_idx].values[right_pos])
4647                        .collect(),
4648                ),
4649            })
4650            .collect();
4651
4652        if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
4653            // Output-balanced chunk boundaries over the plan (6bsw3).
4654            let target = output_len.div_ceil(thread_count).max(1);
4655            let mut boundaries = vec![(0usize, 0usize)];
4656            let mut cumulative = 0usize;
4657            let mut next_target = target;
4658            for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
4659                cumulative += run_len;
4660                if cumulative >= next_target && plan_idx + 1 < plan.len() {
4661                    boundaries.push((plan_idx + 1, cumulative));
4662                    next_target = cumulative.saturating_add(target);
4663                }
4664            }
4665            boundaries.push((plan.len(), output_len));
4666            let chunk_count = boundaries.len() - 1;
4667
4668            let mut column_bufs: Vec<Vec<i64>> =
4669                full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4670            let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
4671                .map(|_| Vec::with_capacity(full_specs.len()))
4672                .collect();
4673            for buf in &mut column_bufs {
4674                let mut rest: &mut [i64] = buf.as_mut_slice();
4675                let mut prev = 0usize;
4676                for (chunk_idx, window) in boundaries.windows(2).enumerate() {
4677                    let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
4678                    prev = window[1].1;
4679                    rest = tail;
4680                    bundles[chunk_idx].push(chunk_slice);
4681                }
4682            }
4683
4684            let plan = &plan;
4685            let specs_ref = &specs;
4686            let full_specs_ref = &full_specs;
4687            std::thread::scope(|scope| {
4688                let mut handles = Vec::with_capacity(chunk_count);
4689                for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
4690                    let (plan_start, out_start) = boundaries[chunk_idx];
4691                    let (plan_end, out_end) = boundaries[chunk_idx + 1];
4692                    let tapes = &tapes;
4693                    handles.push(scope.spawn(move || {
4694                        let mut cursor = 0usize;
4695                        for &(left_pos, start, run_len) in &plan[plan_start..plan_end] {
4696                            for (slice, (&spec_idx, tape)) in bundle
4697                                .iter_mut()
4698                                .zip(full_specs_ref.iter().zip(tapes.iter()))
4699                            {
4700                                match specs_ref[spec_idx].side {
4701                                    FusedInt64Side::Left => {
4702                                        slice[cursor..cursor + run_len]
4703                                            .fill(specs_ref[spec_idx].values[left_pos]);
4704                                    }
4705                                    FusedInt64Side::Right => {
4706                                        if start != UNMATCHED {
4707                                            slice[cursor..cursor + run_len].copy_from_slice(
4708                                                &tape
4709                                                    .as_ref()
4710                                                    .expect("right spec must have a bucket tape")
4711                                                    [start..start + run_len],
4712                                            );
4713                                        }
4714                                        // Unmatched rows keep the zeroed
4715                                        // datum; the shared validity mask
4716                                        // marks them null.
4717                                    }
4718                                }
4719                            }
4720                            cursor += run_len;
4721                        }
4722                        debug_assert_eq!(cursor, out_end - out_start);
4723                    }));
4724                }
4725                for handle in handles {
4726                    handle
4727                        .join()
4728                        .expect("dense i64 left output worker must not panic");
4729                }
4730            });
4731            full_data = column_bufs;
4732        } else {
4733            full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4734            let mut cursor = 0usize;
4735            for &(left_pos, start, run_len) in &plan {
4736                for (buf, (&spec_idx, tape)) in full_data
4737                    .iter_mut()
4738                    .zip(full_specs.iter().zip(tapes.iter()))
4739                {
4740                    match specs[spec_idx].side {
4741                        FusedInt64Side::Left => {
4742                            buf[cursor..cursor + run_len].fill(specs[spec_idx].values[left_pos]);
4743                        }
4744                        FusedInt64Side::Right => {
4745                            if start != UNMATCHED {
4746                                buf[cursor..cursor + run_len].copy_from_slice(
4747                                    &tape.as_ref().expect("right spec must have a bucket tape")
4748                                        [start..start + run_len],
4749                                );
4750                            }
4751                        }
4752                    }
4753                }
4754                cursor += run_len;
4755            }
4756            debug_assert_eq!(cursor, output_len);
4757        }
4758    }
4759
4760    // Lazy unit-range output index (see build_single_key_dense_i64 site).
4761    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4762    let mut columns = ColumnStore::new();
4763    let mut column_order = Vec::with_capacity(specs.len());
4764    let mut full_iter = full_data.into_iter();
4765    for spec in specs {
4766        let column = match spec.side {
4767            FusedInt64Side::Right => {
4768                // Lazy nullable repeated-slices over the bucket-order tape
4769                // (br-frankenpandas-yiqv5): O(matched) descriptor, no O(output)
4770                // materialization.
4771                let tape: Vec<i64> = positions
4772                    .iter()
4773                    .map(|&right_pos| spec.values[right_pos])
4774                    .collect();
4775                Column::from_i64_nullable_repeated_slices_shared(
4776                    tape,
4777                    Arc::clone(&right_segments),
4778                    output_len,
4779                )
4780            }
4781            FusedInt64Side::Left if use_repeat_runs => Column::from_i64_repeat_runs(
4782                plan.iter()
4783                    .map(|&(left_pos, _, run_len)| (spec.values[left_pos], run_len))
4784                    .collect(),
4785            ),
4786            FusedInt64Side::Left => {
4787                let data = full_iter
4788                    .next()
4789                    .expect("full lane buffer must exist for every non-run left spec");
4790                Column::from_i64_values(data)
4791            }
4792        };
4793        debug_assert_eq!(column.len(), output_len);
4794        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
4795    }
4796
4797    Ok(Some(MergedDataFrame {
4798        index,
4799        columns,
4800        column_order,
4801    }))
4802}
4803
4804/// Fused dense-i64 RIGHT merge builder (br-frankenpandas-4p3ie) — the
4805/// side-swapped mirror of [`build_single_key_dense_i64_left_merge_output`]:
4806/// the probe walks RIGHT keys in probe order against a dense CSR over the
4807/// LEFT key range, emitting `(right_pos, left_bucket_start, run_len)` plan
4808/// rows (`usize::MAX` sentinel = unmatched right row, one null-left output
4809/// row). Right lanes (including the shared key column, which pandas fills
4810/// from the RIGHT side under the LEFT name) are all-valid repeat runs; left
4811/// lanes fill from muis1-style left value tapes with ONE shared validity
4812/// mask and keep dtype Int64 with `Null(NullKind::Null)` at unmatched rows
4813/// (`reindex_by_positions` missing semantics — NOT Float64-promoted).
4814fn build_single_key_dense_i64_right_merge_output(
4815    left: &fp_frame::DataFrame,
4816    right: &fp_frame::DataFrame,
4817    left_on: &[&str],
4818    right_on: &[&str],
4819    left_key: &Column,
4820    right_key: &Column,
4821    suffixes: &ResolvedMergeSuffixes,
4822) -> Result<Option<MergedDataFrame>, JoinError> {
4823    debug_assert_eq!(left_on.len(), 1);
4824    debug_assert_eq!(right_on.len(), 1);
4825
4826    let Some(left_keys) = left_key.as_i64_slice() else {
4827        return Ok(None);
4828    };
4829    let Some(right_keys) = right_key.as_i64_slice() else {
4830        return Ok(None);
4831    };
4832    if left_keys.is_empty() || right_keys.is_empty() {
4833        return Ok(None);
4834    }
4835
4836    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4837    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4838    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4839    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4840    let shared_key_names = if left_on[0] == right_on[0] {
4841        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4842    } else {
4843        HashSet::new()
4844    };
4845    let overlapping_names =
4846        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4847
4848    // Lane specs in output order. The shared key slot keeps the LEFT name
4849    // but carries RIGHT key values (all output rows have a right row), so it
4850    // is a Right-side lane on right_keys.
4851    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
4852    let mut sources = Vec::<Arc<[i64]>>::new();
4853    for name in left.column_names() {
4854        let col = left
4855            .columns()
4856            .get(name)
4857            .expect("left column listed in column_names must exist");
4858        let Some(values) = col.as_i64_slice() else {
4859            return Ok(None);
4860        };
4861        if left_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4862            let right_key_col = right
4863                .columns()
4864                .get(right_on[0])
4865                .expect("right key column must exist");
4866            let source = right_key_col
4867                .as_i64_arc()
4868                .unwrap_or_else(|| Arc::from(right_keys));
4869            specs.push(FusedInt64OutputColumn {
4870                name: name.clone(),
4871                side: FusedInt64Side::Right,
4872                values: right_keys,
4873            });
4874            sources.push(source);
4875            continue;
4876        }
4877        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4878        let out_name = if left_key_name_set.contains(name.as_str()) {
4879            name.clone()
4880        } else if right_col_names.contains(name) {
4881            apply_merge_suffix(name, suffixes.left.as_deref())
4882        } else {
4883            name.clone()
4884        };
4885        specs.push(FusedInt64OutputColumn {
4886            name: out_name,
4887            side: FusedInt64Side::Left,
4888            values,
4889        });
4890        sources.push(source);
4891    }
4892    for name in right.column_names() {
4893        let col = right
4894            .columns()
4895            .get(name)
4896            .expect("right column listed in column_names must exist");
4897        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4898            continue;
4899        }
4900        let Some(values) = col.as_i64_slice() else {
4901            return Ok(None);
4902        };
4903        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4904        let out_name = if left_col_names.contains(name) {
4905            apply_merge_suffix(name, suffixes.right.as_deref())
4906        } else {
4907            name.clone()
4908        };
4909        specs.push(FusedInt64OutputColumn {
4910            name: out_name,
4911            side: FusedInt64Side::Right,
4912            values,
4913        });
4914        sources.push(source);
4915    }
4916    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4917
4918    let row_count = left_keys.len().saturating_add(right_keys.len());
4919    let max_dense_span = row_count.saturating_mul(4).max(1024);
4920    let left_witness = left_key
4921        .int64_dense_cycle_witness()
4922        .filter(|witness| witness.len == left_keys.len());
4923    let right_witness = right_key
4924        .int64_dense_cycle_witness()
4925        .filter(|witness| witness.len == right_keys.len());
4926    if let (Some(left_witness), Some(right_witness), Some((left_min, left_max))) = (
4927        left_witness,
4928        right_witness,
4929        left_witness.and_then(dense_cycle_domain),
4930    ) {
4931        let left_span = i128::from(left_max) - i128::from(left_min) + 1;
4932        if left_span <= max_dense_span as i128
4933            && let Some((output_len, left_validity)) =
4934                dense_cycle_probe_output_len_and_validity(right_witness, left_witness)
4935        {
4936            if !left_validity.all() {
4937                // See the LEFT merge mirror: only the typed gather can
4938                // preserve pandas' Int64-to-Float64 widening for a new gap.
4939            } else {
4940                let index = Index::new_known_unique_int64_unit_range(0, output_len);
4941                let mut columns = ColumnStore::new();
4942                let mut column_order = Vec::with_capacity(specs.len());
4943                for (spec, source) in specs.into_iter().zip(sources) {
4944                    let column = match spec.side {
4945                        FusedInt64Side::Left => {
4946                            Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
4947                                source,
4948                                right_witness,
4949                                left_witness,
4950                                left_validity.clone(),
4951                                output_len,
4952                            )
4953                        }
4954                        FusedInt64Side::Right => Column::from_i64_dense_cycle_probe_repeat(
4955                            source,
4956                            right_witness,
4957                            left_witness,
4958                            output_len,
4959                        ),
4960                    };
4961                    debug_assert_eq!(column.len(), output_len);
4962                    insert_merged_output_column(
4963                        &mut columns,
4964                        &mut column_order,
4965                        spec.name,
4966                        column,
4967                    )?;
4968                }
4969                return Ok(Some(MergedDataFrame {
4970                    index,
4971                    columns,
4972                    column_order,
4973                }));
4974            }
4975        }
4976    }
4977
4978    // Dense CSR over the LEFT key range — same gate as
4979    // dense_int64_right_positions (span <= 4*rows+1024).
4980    let mut min_key = left_keys[0];
4981    let mut max_key = left_keys[0];
4982    for &key in left_keys {
4983        min_key = min_key.min(key);
4984        max_key = max_key.max(key);
4985    }
4986    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
4987    if span > max_dense_span as i128 {
4988        return Ok(None);
4989    }
4990    let span = usize::try_from(span).expect("span bounded by max_dense_span");
4991
4992    let mut offsets = vec![0usize; span + 1];
4993    for &key in left_keys {
4994        offsets[(key - min_key) as usize + 1] += 1;
4995    }
4996    for i in 0..span {
4997        offsets[i + 1] += offsets[i];
4998    }
4999    let mut positions = vec![0usize; left_keys.len()];
5000    let mut cursor = offsets[..span].to_vec();
5001    for (pos, &key) in left_keys.iter().enumerate() {
5002        let bucket = (key - min_key) as usize;
5003        positions[cursor[bucket]] = pos;
5004        cursor[bucket] += 1;
5005    }
5006
5007    // Plan over RIGHT probe order: (right_pos, left_bucket_start, run_len);
5008    // usize::MAX = unmatched right row (one null-left output row).
5009    const UNMATCHED: usize = usize::MAX;
5010    let mut plan = Vec::<(usize, usize, usize)>::with_capacity(right_keys.len());
5011    let mut output_len = 0usize;
5012    for (right_pos, &key) in right_keys.iter().enumerate() {
5013        let offset = i128::from(key) - i128::from(min_key);
5014        let run = if offset >= 0 && offset < span as i128 {
5015            let bucket = offset as usize;
5016            let start = offsets[bucket];
5017            let len = offsets[bucket + 1] - start;
5018            if len == 0 {
5019                (right_pos, UNMATCHED, 1)
5020            } else {
5021                (right_pos, start, len)
5022            }
5023        } else {
5024            (right_pos, UNMATCHED, 1)
5025        };
5026        let Some(new_len) = output_len.checked_add(run.2) else {
5027            return Ok(None);
5028        };
5029        output_len = new_len;
5030        plan.push(run);
5031    }
5032    if plan.iter().any(|&(_, start, _)| start == UNMATCHED) {
5033        return Ok(None);
5034    }
5035
5036    // One shared validity mask for every left lane.
5037    // Shared left-lane segment descriptor (br-frankenpandas-yiqv5): mirror of
5038    // the left builder — every null-introduced LEFT lane is a LAZY
5039    // `LazyNullableRepeatedSlicesInt64` over its bucket-order tape (plan's
5040    // `(bucket_start, run_len)`, `usize::MAX` ⇒ null run) instead of a
5041    // materialized O(output_len) buffer; validity rebuilt in the ctor.
5042    let left_segments: Arc<[(usize, usize)]> = plan
5043        .iter()
5044        .map(|&(_, start, run_len)| (start, run_len))
5045        .collect();
5046
5047    // Right lanes (all-valid) as lazy repeat runs when the fanout pays.
5048    let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
5049
5050    // Only LOW-FANOUT RIGHT lanes still materialize; left lanes are always lazy
5051    // (nullable repeated-slices) and high-fanout right lanes are lazy repeat runs.
5052    let full_specs: Vec<usize> = specs
5053        .iter()
5054        .enumerate()
5055        .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Right) && !use_repeat_runs)
5056        .map(|(idx, _)| idx)
5057        .collect();
5058
5059    let mut full_data: Vec<Vec<i64>> = Vec::new();
5060    let thread_count = join_parallel_thread_count();
5061    if !full_specs.is_empty() {
5062        // LEFT value tapes in bucket order, shared read-only.
5063        let tapes: Vec<Option<Vec<i64>>> = full_specs
5064            .iter()
5065            .map(|&spec_idx| match specs[spec_idx].side {
5066                FusedInt64Side::Right => None,
5067                FusedInt64Side::Left => Some(
5068                    positions
5069                        .iter()
5070                        .map(|&left_pos| specs[spec_idx].values[left_pos])
5071                        .collect(),
5072                ),
5073            })
5074            .collect();
5075
5076        if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
5077            let target = output_len.div_ceil(thread_count).max(1);
5078            let mut boundaries = vec![(0usize, 0usize)];
5079            let mut cumulative = 0usize;
5080            let mut next_target = target;
5081            for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
5082                cumulative += run_len;
5083                if cumulative >= next_target && plan_idx + 1 < plan.len() {
5084                    boundaries.push((plan_idx + 1, cumulative));
5085                    next_target = cumulative.saturating_add(target);
5086                }
5087            }
5088            boundaries.push((plan.len(), output_len));
5089            let chunk_count = boundaries.len() - 1;
5090
5091            let mut column_bufs: Vec<Vec<i64>> =
5092                full_specs.iter().map(|_| vec![0i64; output_len]).collect();
5093            let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
5094                .map(|_| Vec::with_capacity(full_specs.len()))
5095                .collect();
5096            for buf in &mut column_bufs {
5097                let mut rest: &mut [i64] = buf.as_mut_slice();
5098                let mut prev = 0usize;
5099                for (chunk_idx, window) in boundaries.windows(2).enumerate() {
5100                    let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
5101                    prev = window[1].1;
5102                    rest = tail;
5103                    bundles[chunk_idx].push(chunk_slice);
5104                }
5105            }
5106
5107            let plan = &plan;
5108            let specs_ref = &specs;
5109            let full_specs_ref = &full_specs;
5110            std::thread::scope(|scope| {
5111                let mut handles = Vec::with_capacity(chunk_count);
5112                for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
5113                    let (plan_start, out_start) = boundaries[chunk_idx];
5114                    let (plan_end, out_end) = boundaries[chunk_idx + 1];
5115                    let tapes = &tapes;
5116                    handles.push(scope.spawn(move || {
5117                        let mut cursor = 0usize;
5118                        for &(right_pos, start, run_len) in &plan[plan_start..plan_end] {
5119                            for (slice, (&spec_idx, tape)) in bundle
5120                                .iter_mut()
5121                                .zip(full_specs_ref.iter().zip(tapes.iter()))
5122                            {
5123                                match specs_ref[spec_idx].side {
5124                                    FusedInt64Side::Right => {
5125                                        slice[cursor..cursor + run_len]
5126                                            .fill(specs_ref[spec_idx].values[right_pos]);
5127                                    }
5128                                    FusedInt64Side::Left => {
5129                                        if start != UNMATCHED {
5130                                            slice[cursor..cursor + run_len].copy_from_slice(
5131                                                &tape
5132                                                    .as_ref()
5133                                                    .expect("left spec must have a bucket tape")
5134                                                    [start..start + run_len],
5135                                            );
5136                                        }
5137                                    }
5138                                }
5139                            }
5140                            cursor += run_len;
5141                        }
5142                        debug_assert_eq!(cursor, out_end - out_start);
5143                    }));
5144                }
5145                for handle in handles {
5146                    handle
5147                        .join()
5148                        .expect("dense i64 right output worker must not panic");
5149                }
5150            });
5151            full_data = column_bufs;
5152        } else {
5153            full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
5154            let mut cursor = 0usize;
5155            for &(right_pos, start, run_len) in &plan {
5156                for (buf, (&spec_idx, tape)) in full_data
5157                    .iter_mut()
5158                    .zip(full_specs.iter().zip(tapes.iter()))
5159                {
5160                    match specs[spec_idx].side {
5161                        FusedInt64Side::Right => {
5162                            buf[cursor..cursor + run_len].fill(specs[spec_idx].values[right_pos]);
5163                        }
5164                        FusedInt64Side::Left => {
5165                            if start != UNMATCHED {
5166                                buf[cursor..cursor + run_len].copy_from_slice(
5167                                    &tape.as_ref().expect("left spec must have a bucket tape")
5168                                        [start..start + run_len],
5169                                );
5170                            }
5171                        }
5172                    }
5173                }
5174                cursor += run_len;
5175            }
5176            debug_assert_eq!(cursor, output_len);
5177        }
5178    }
5179
5180    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5181    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5182    let mut columns = ColumnStore::new();
5183    let mut column_order = Vec::with_capacity(specs.len());
5184    let mut full_iter = full_data.into_iter();
5185    for spec in specs {
5186        let column = match spec.side {
5187            FusedInt64Side::Left => {
5188                // Lazy nullable repeated-slices over the left bucket-order tape
5189                // (br-frankenpandas-yiqv5). When no left row is missing the
5190                // segments carry no `usize::MAX` sentinel, so the ctor yields an
5191                // all-valid mask — identical to the prior `from_i64_values`.
5192                let tape: Vec<i64> = positions
5193                    .iter()
5194                    .map(|&left_pos| spec.values[left_pos])
5195                    .collect();
5196                Column::from_i64_nullable_repeated_slices_shared(
5197                    tape,
5198                    Arc::clone(&left_segments),
5199                    output_len,
5200                )
5201            }
5202            FusedInt64Side::Right if use_repeat_runs => Column::from_i64_repeat_runs(
5203                plan.iter()
5204                    .map(|&(right_pos, _, run_len)| (spec.values[right_pos], run_len))
5205                    .collect(),
5206            ),
5207            FusedInt64Side::Right => {
5208                let data = full_iter
5209                    .next()
5210                    .expect("full lane buffer must exist for every non-run right spec");
5211                Column::from_i64_values(data)
5212            }
5213        };
5214        debug_assert_eq!(column.len(), output_len);
5215        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
5216    }
5217
5218    Ok(Some(MergedDataFrame {
5219        index,
5220        columns,
5221        column_order,
5222    }))
5223}
5224
5225fn dense_cycle_domain(witness: Int64DenseCycleWitness) -> Option<(i64, i64)> {
5226    let last_offset = i64::try_from(witness.period.checked_sub(1)?).ok()?;
5227    Some((witness.start, witness.start.checked_add(last_offset)?))
5228}
5229
5230fn dense_cycle_probe_output_len_and_validity(
5231    probe_witness: Int64DenseCycleWitness,
5232    build_witness: Int64DenseCycleWitness,
5233) -> Option<(usize, ValidityMask)> {
5234    let mut output_len = 0usize;
5235    let mut invalid_ranges = Vec::<(usize, usize)>::new();
5236    for probe_pos in 0..probe_witness.len {
5237        let offset = i64::try_from(probe_pos % probe_witness.period).ok()?;
5238        let key = probe_witness.start.checked_add(offset)?;
5239        let run_len = build_witness
5240            .offset_count_for_key(key)
5241            .map_or(1, |(_, count)| count);
5242        if build_witness.offset_count_for_key(key).is_none() {
5243            push_dense_outer_invalid_range(&mut invalid_ranges, output_len, 1);
5244        }
5245        output_len = output_len.checked_add(run_len)?;
5246    }
5247    Some((
5248        output_len,
5249        ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len),
5250    ))
5251}
5252
5253struct DenseOuterRunTape {
5254    run_lens: Option<Arc<[usize]>>,
5255    left_run_valid: Option<Arc<[bool]>>,
5256    left_run_positions: Option<Arc<[usize]>>,
5257    right_positions_csr: Option<Arc<[usize]>>,
5258    right_segments: Option<Arc<[(usize, usize)]>>,
5259    key_runs: Vec<(i64, usize)>,
5260    left_sparse_validity: ValidityMask,
5261    right_sparse_validity: ValidityMask,
5262    output_len: usize,
5263    has_left_missing: bool,
5264    has_right_missing: bool,
5265}
5266
5267fn push_dense_outer_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
5268    if len == 0 {
5269        return;
5270    }
5271    if let Some((last_start, last_len)) = ranges.last_mut()
5272        && last_start.checked_add(*last_len) == Some(start)
5273    {
5274        *last_len += len;
5275        return;
5276    }
5277    ranges.push((start, len));
5278}
5279
5280fn append_dense_cycle_positions(
5281    positions: &mut Vec<usize>,
5282    witness: Int64DenseCycleWitness,
5283    key: i64,
5284) -> Option<usize> {
5285    let (mut pos, count) = witness.offset_count_for_key(key)?;
5286    for _ in 0..count {
5287        positions.push(pos);
5288        pos = pos.checked_add(witness.period)?;
5289    }
5290    Some(count)
5291}
5292
5293fn build_dense_cycle_outer_run_tape(
5294    left_witness: Int64DenseCycleWitness,
5295    right_witness: Int64DenseCycleWitness,
5296    min_key: i64,
5297    span: usize,
5298) -> Option<DenseOuterRunTape> {
5299    let mut run_count = 0usize;
5300    let mut active_key_count = 0usize;
5301    let mut output_len = 0usize;
5302    let mut has_left_missing = false;
5303    let mut has_right_missing = false;
5304    for bucket in 0..span {
5305        let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5306        let ll = left_witness
5307            .offset_count_for_key(key)
5308            .map_or(0, |(_, count)| count);
5309        let rl = right_witness
5310            .offset_count_for_key(key)
5311            .map_or(0, |(_, count)| count);
5312        let rows = match (ll > 0, rl > 0) {
5313            (true, true) => {
5314                run_count = run_count.checked_add(ll)?;
5315                ll.checked_mul(rl)?
5316            }
5317            (true, false) => {
5318                has_right_missing = true;
5319                run_count = run_count.checked_add(ll)?;
5320                ll
5321            }
5322            (false, true) => {
5323                has_left_missing = true;
5324                run_count = run_count.checked_add(1)?;
5325                rl
5326            }
5327            (false, false) => continue,
5328        };
5329        active_key_count = active_key_count.checked_add(1)?;
5330        output_len = output_len.checked_add(rows)?;
5331    }
5332
5333    let build_left_tape = !has_left_missing;
5334    let mut run_lens = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5335    let mut left_run_valid = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5336    let mut left_run_positions = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5337    let mut right_positions_csr = Vec::with_capacity(right_witness.len);
5338    let mut right_segments = Vec::with_capacity(run_count);
5339    let mut key_runs = Vec::with_capacity(active_key_count);
5340    let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
5341    let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
5342    let mut out_pos = 0usize;
5343    let build_right_tape = !has_right_missing;
5344    for bucket in 0..span {
5345        let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5346        let left_span = left_witness.offset_count_for_key(key);
5347        let right_span = right_witness.offset_count_for_key(key);
5348        let ll = left_span.map_or(0, |(_, count)| count);
5349        let rl = right_span.map_or(0, |(_, count)| count);
5350        if ll == 0 && rl == 0 {
5351            continue;
5352        }
5353
5354        let right_start = if rl > 0 {
5355            if build_right_tape {
5356                let start = right_positions_csr.len();
5357                let appended =
5358                    append_dense_cycle_positions(&mut right_positions_csr, right_witness, key)?;
5359                debug_assert_eq!(appended, rl);
5360                start
5361            } else {
5362                0
5363            }
5364        } else {
5365            usize::MAX
5366        };
5367
5368        let rows = match (left_span, right_span) {
5369            (Some((mut left_pos, left_count)), Some((_, right_count))) => {
5370                let rows = left_count.checked_mul(right_count)?;
5371                if build_left_tape {
5372                    run_lens.extend(std::iter::repeat_n(right_count, left_count));
5373                    left_run_valid.extend(std::iter::repeat_n(true, left_count));
5374                }
5375                if build_right_tape {
5376                    right_segments
5377                        .extend(std::iter::repeat_n((right_start, right_count), left_count));
5378                }
5379                if build_left_tape {
5380                    for _ in 0..left_count {
5381                        left_run_positions.push(left_pos);
5382                        left_pos = left_pos.checked_add(left_witness.period)?;
5383                    }
5384                }
5385                rows
5386            }
5387            (Some((mut left_pos, left_count)), None) => {
5388                push_dense_outer_invalid_range(&mut right_invalid_ranges, out_pos, left_count);
5389                if build_left_tape {
5390                    run_lens.extend(std::iter::repeat_n(1, left_count));
5391                    left_run_valid.extend(std::iter::repeat_n(true, left_count));
5392                }
5393                if build_right_tape {
5394                    right_segments.extend(std::iter::repeat_n((usize::MAX, 1), left_count));
5395                }
5396                if build_left_tape {
5397                    for _ in 0..left_count {
5398                        left_run_positions.push(left_pos);
5399                        left_pos = left_pos.checked_add(left_witness.period)?;
5400                    }
5401                }
5402                left_count
5403            }
5404            (None, Some((_, right_count))) => {
5405                push_dense_outer_invalid_range(&mut left_invalid_ranges, out_pos, right_count);
5406                if build_left_tape {
5407                    run_lens.push(right_count);
5408                    left_run_valid.push(false);
5409                    left_run_positions.push(0);
5410                }
5411                if build_right_tape {
5412                    right_segments.push((right_start, right_count));
5413                }
5414                right_count
5415            }
5416            (None, None) => unreachable!("empty buckets are skipped above"),
5417        };
5418        key_runs.push((key, rows));
5419        out_pos = out_pos.checked_add(rows)?;
5420    }
5421    if out_pos != output_len
5422        || (build_left_tape
5423            && (run_lens.len() != run_count
5424                || left_run_valid.len() != run_count
5425                || left_run_positions.len() != run_count))
5426        || (!build_left_tape
5427            && (!run_lens.is_empty()
5428                || !left_run_valid.is_empty()
5429                || !left_run_positions.is_empty()))
5430        || (build_right_tape
5431            && (right_segments.len() != run_count
5432                || right_positions_csr.len() != right_witness.len))
5433        || (!build_right_tape && (!right_segments.is_empty() || !right_positions_csr.is_empty()))
5434    {
5435        return None;
5436    }
5437
5438    Some(DenseOuterRunTape {
5439        run_lens: build_left_tape.then(|| Arc::from(run_lens)),
5440        left_run_valid: build_left_tape.then(|| Arc::from(left_run_valid)),
5441        left_run_positions: build_left_tape.then(|| Arc::from(left_run_positions)),
5442        right_positions_csr: build_right_tape.then(|| Arc::from(right_positions_csr)),
5443        right_segments: build_right_tape.then(|| Arc::from(right_segments)),
5444        key_runs,
5445        left_sparse_validity: ValidityMask::from_invalid_ranges(
5446            Arc::from(left_invalid_ranges),
5447            output_len,
5448        ),
5449        right_sparse_validity: ValidityMask::from_invalid_ranges(
5450            Arc::from(right_invalid_ranges),
5451            output_len,
5452        ),
5453        output_len,
5454        has_left_missing,
5455        has_right_missing,
5456    })
5457}
5458
5459/// Fused dense-i64 OUTER merge builder (br-frankenpandas-343ho).
5460///
5461/// `dense_int64_outer_positions` + the position-vector outer builder cost:
5462/// per-bucket `Vec<Vec<usize>>` heap allocs, two `Vec<Option<usize>>` of
5463/// output length, a per-row Scalar coalesce for the shared key column, and
5464/// per-column reindex walks. Here the bucket walk (ascending key order —
5465/// the dense outer output IS bucket order) emits a compact plan
5466/// (`(left_pos | MAX, right_bucket_start | MAX, run_len)`), and:
5467///
5468/// - the SHARED KEY lane is synthesized as `(min_key + bucket, bucket_rows)`
5469///   repeat runs — every row in a bucket has the bucket's key, whichever
5470///   side it came from, so the coalesce is a closed form (all-valid Int64);
5471/// - left lanes promote to nullable Float64 ONLY when right-only buckets
5472///   exist, right lanes ONLY when left-only rows exist — matching
5473///   `reindex_join_column_with_invented_gap`'s per-positions `has_missing` check (a
5474///   side with no missing rows keeps dtype Int64 via the all-present
5475///   take_positions path);
5476/// - per-side shared validity masks are word-filled once from the plan and
5477///   cloned per lane;
5478/// - lanes fill via the 6bsw3 row-chunked disjoint `split_at_mut` scheme
5479///   (an i64 group and an f64 group, sharing plan/boundaries), with muis1
5480///   right value tapes (i64, plus a once-cast f64 tape for promoted lanes).
5481///
5482/// Bit-identical: bucket walk order == `dense_int64_outer_positions`
5483/// (cross products left-major, then left-only rows, then right-only rows,
5484/// per ascending bucket); promoted slots use `v as f64` + the 0.0-datum
5485/// gap (`Null(NaN)`), preserved slots `Null(NullKind::Null)` — the exact
5486/// eager semantics per br-frankenpandas-1bvcl/lt5qx.
5487fn build_single_key_dense_i64_outer_merge_output(
5488    left: &fp_frame::DataFrame,
5489    right: &fp_frame::DataFrame,
5490    left_on: &[&str],
5491    right_on: &[&str],
5492    left_key: &Column,
5493    right_key: &Column,
5494    suffixes: &ResolvedMergeSuffixes,
5495) -> Result<Option<MergedDataFrame>, JoinError> {
5496    debug_assert_eq!(left_on.len(), 1);
5497    debug_assert_eq!(right_on.len(), 1);
5498
5499    // The closed-form key lane needs the coalesced shared-key shape; the
5500    // non-shared-name variant keeps the position-vector path.
5501    if left_on[0] != right_on[0] {
5502        return Ok(None);
5503    }
5504    let Some(left_keys) = left_key.as_i64_slice() else {
5505        return Ok(None);
5506    };
5507    let Some(right_keys) = right_key.as_i64_slice() else {
5508        return Ok(None);
5509    };
5510    if left_keys.is_empty() || right_keys.is_empty() {
5511        return Ok(None);
5512    }
5513
5514    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5515    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5516    let key_name = left_on[0];
5517    let shared_key_names = [key_name].into_iter().collect::<HashSet<&str>>();
5518    let overlapping_names =
5519        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5520
5521    // Lane specs in output order: left columns (the key slot handled as the
5522    // synthetic coalesced lane), then right non-key columns.
5523    enum OuterLaneKind {
5524        SharedKey,
5525        Lane(FusedInt64Side),
5526    }
5527    let mut spec_names = Vec::<String>::new();
5528    let mut spec_kinds = Vec::<OuterLaneKind>::new();
5529    let mut spec_values = Vec::<&[i64]>::new();
5530    let mut spec_sources = Vec::<Arc<[i64]>>::new();
5531    for name in left.column_names() {
5532        let col = left
5533            .columns()
5534            .get(name)
5535            .expect("left column listed in column_names must exist");
5536        let Some(values) = col.as_i64_slice() else {
5537            return Ok(None);
5538        };
5539        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
5540        if name.as_str() == key_name {
5541            spec_names.push(name.clone());
5542            spec_kinds.push(OuterLaneKind::SharedKey);
5543            spec_values.push(values);
5544            spec_sources.push(Arc::clone(&source));
5545            continue;
5546        }
5547        let out_name = if right_col_names.contains(name) {
5548            apply_merge_suffix(name, suffixes.left.as_deref())
5549        } else {
5550            name.clone()
5551        };
5552        spec_names.push(out_name);
5553        spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Left));
5554        spec_values.push(values);
5555        spec_sources.push(source);
5556    }
5557    for name in right.column_names() {
5558        let col = right
5559            .columns()
5560            .get(name)
5561            .expect("right column listed in column_names must exist");
5562        let Some(values) = col.as_i64_slice() else {
5563            return Ok(None);
5564        };
5565        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
5566        if name.as_str() == key_name {
5567            continue;
5568        }
5569        let out_name = if left_col_names.contains(name) {
5570            apply_merge_suffix(name, suffixes.right.as_deref())
5571        } else {
5572            name.clone()
5573        };
5574        spec_names.push(out_name);
5575        spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Right));
5576        spec_values.push(values);
5577        spec_sources.push(source);
5578    }
5579    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5580
5581    // Dense span over BOTH key sets (same gate as dense_int64_outer_positions
5582    // so fused/fallback routing matches).
5583    let left_witness = left_key
5584        .int64_dense_cycle_witness()
5585        .filter(|witness| witness.len == left_keys.len());
5586    let right_witness = right_key
5587        .int64_dense_cycle_witness()
5588        .filter(|witness| witness.len == right_keys.len());
5589    let (min_key, max_key) = match (
5590        left_witness.and_then(dense_cycle_domain),
5591        right_witness.and_then(dense_cycle_domain),
5592    ) {
5593        (Some((left_min, left_max)), Some((right_min, right_max))) => {
5594            (left_min.min(right_min), left_max.max(right_max))
5595        }
5596        _ => {
5597            let mut min_key = left_keys[0];
5598            let mut max_key = left_keys[0];
5599            for &key in left_keys.iter().chain(right_keys.iter()) {
5600                min_key = min_key.min(key);
5601                max_key = max_key.max(key);
5602            }
5603            (min_key, max_key)
5604        }
5605    };
5606    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
5607    let row_count = left_keys.len().saturating_add(right_keys.len());
5608    let max_dense_span = row_count.saturating_mul(4).max(1024);
5609    if span > max_dense_span as i128 {
5610        return Ok(None);
5611    }
5612    let span = usize::try_from(span).expect("span bounded by max_dense_span");
5613
5614    const NONE_POS: usize = usize::MAX;
5615    let Some(DenseOuterRunTape {
5616        run_lens,
5617        left_run_valid,
5618        left_run_positions,
5619        right_positions_csr,
5620        right_segments,
5621        key_runs,
5622        left_sparse_validity,
5623        right_sparse_validity,
5624        output_len,
5625        has_left_missing,
5626        has_right_missing,
5627    }) = (match (left_witness, right_witness) {
5628        (Some(left_witness), Some(right_witness)) => {
5629            build_dense_cycle_outer_run_tape(left_witness, right_witness, min_key, span)
5630        }
5631        _ => None,
5632    })
5633    .or_else(|| {
5634        // CSR layouts for both sides (replaces the per-bucket Vec<Vec<usize>>).
5635        let build_dense_cycle_csr =
5636            |witness: Int64DenseCycleWitness| -> Option<(Vec<usize>, Vec<usize>)> {
5637                let mut offsets = Vec::with_capacity(span + 1);
5638                offsets.push(0);
5639                let mut total = 0usize;
5640                for bucket in 0..span {
5641                    let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5642                    let count = witness
5643                        .offset_count_for_key(key)
5644                        .map_or(0, |(_, count)| count);
5645                    total = total.checked_add(count)?;
5646                    offsets.push(total);
5647                }
5648                if total != witness.len {
5649                    return None;
5650                }
5651                let mut positions = Vec::with_capacity(witness.len);
5652                for bucket in 0..span {
5653                    let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5654                    let appended =
5655                        append_dense_cycle_positions(&mut positions, witness, key).unwrap_or(0);
5656                    debug_assert_eq!(
5657                        appended,
5658                        witness
5659                            .offset_count_for_key(key)
5660                            .map_or(0, |(_, count)| count)
5661                    );
5662                }
5663                (positions.len() == witness.len).then_some((offsets, positions))
5664            };
5665        let build_csr = |keys: &[i64], witness: Option<Int64DenseCycleWitness>| {
5666            if let Some(csr) = witness
5667                .filter(|witness| witness.len == keys.len())
5668                .and_then(&build_dense_cycle_csr)
5669            {
5670                return csr;
5671            }
5672            let mut offsets = vec![0usize; span + 1];
5673            for &key in keys {
5674                offsets[(key - min_key) as usize + 1] += 1;
5675            }
5676            for i in 0..span {
5677                offsets[i + 1] += offsets[i];
5678            }
5679            let mut positions = vec![0usize; keys.len()];
5680            let mut cursor = offsets[..span].to_vec();
5681            for (pos, &key) in keys.iter().enumerate() {
5682                let bucket = (key - min_key) as usize;
5683                positions[cursor[bucket]] = pos;
5684                cursor[bucket] += 1;
5685            }
5686            (offsets, positions)
5687        };
5688        let (left_offsets, left_positions_csr) = build_csr(left_keys, left_witness);
5689        let (right_offsets, right_positions_csr) = build_csr(right_keys, right_witness);
5690
5691        // Bucket walk -> compact plan + closed-form key runs + output length.
5692        let mut plan = Vec::<(usize, usize, usize)>::new();
5693        let mut key_runs = Vec::<(i64, usize)>::new();
5694        let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
5695        let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
5696        let mut output_len = 0usize;
5697        let mut has_left_missing = false; // right-only buckets exist
5698        let mut has_right_missing = false; // left-only rows exist
5699        for bucket in 0..span {
5700            let ll = left_offsets[bucket + 1] - left_offsets[bucket];
5701            let rl = right_offsets[bucket + 1] - right_offsets[bucket];
5702            let bucket_rows = match (ll > 0, rl > 0) {
5703                (true, true) => {
5704                    let rows = ll.checked_mul(rl)?;
5705                    let rs = right_offsets[bucket];
5706                    for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
5707                        plan.push((lp, rs, rl));
5708                    }
5709                    rows
5710                }
5711                (true, false) => {
5712                    has_right_missing = true;
5713                    push_dense_outer_invalid_range(&mut right_invalid_ranges, output_len, ll);
5714                    for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
5715                        plan.push((lp, NONE_POS, 1));
5716                    }
5717                    ll
5718                }
5719                (false, true) => {
5720                    has_left_missing = true;
5721                    push_dense_outer_invalid_range(&mut left_invalid_ranges, output_len, rl);
5722                    plan.push((NONE_POS, right_offsets[bucket], rl));
5723                    rl
5724                }
5725                (false, false) => continue,
5726            };
5727            output_len = output_len.checked_add(bucket_rows)?;
5728            key_runs.push((min_key + bucket as i64, bucket_rows));
5729        }
5730
5731        // Shared lazy-lane descriptors (br-frankenpandas-yiqv5): the plan drives
5732        // every value lane as a LAZY column rather than an O(output_len)
5733        // materialized buffer. The kept side stays all-valid; the promoted
5734        // side becomes the matching nullable lazy lane.
5735        let run_lens: Arc<[usize]> = plan.iter().map(|&(_, _, run_len)| run_len).collect();
5736        let left_run_valid: Arc<[bool]> = plan.iter().map(|&(lp, _, _)| lp < NONE_POS).collect();
5737        let left_run_positions: Arc<[usize]> = plan
5738            .iter()
5739            .map(|&(lp, _, _)| if lp == NONE_POS { 0 } else { lp })
5740            .collect();
5741        let right_segments: Arc<[(usize, usize)]> =
5742            plan.iter().map(|&(_, rs, run_len)| (rs, run_len)).collect();
5743        Some(DenseOuterRunTape {
5744            run_lens: Some(run_lens),
5745            left_run_valid: Some(left_run_valid),
5746            left_run_positions: Some(left_run_positions),
5747            right_positions_csr: Some(Arc::from(right_positions_csr)),
5748            right_segments: Some(right_segments),
5749            key_runs,
5750            left_sparse_validity: ValidityMask::from_invalid_ranges(
5751                Arc::from(left_invalid_ranges),
5752                output_len,
5753            ),
5754            right_sparse_validity: ValidityMask::from_invalid_ranges(
5755                Arc::from(right_invalid_ranges),
5756                output_len,
5757            ),
5758            output_len,
5759            has_left_missing,
5760            has_right_missing,
5761        })
5762    })
5763    else {
5764        return Ok(None);
5765    };
5766
5767    // Promoted (nullable Float64) when that side has missing rows, preserved
5768    // (all-valid Int64) otherwise.
5769    let promoted = |side: FusedInt64Side| match side {
5770        FusedInt64Side::Left => has_left_missing,
5771        FusedInt64Side::Right => has_right_missing,
5772    };
5773
5774    // Left broadcast run values (one per run): i64 (preserved) or f64 (promoted).
5775    let left_run_values_i64 = |idx: usize| -> Option<Vec<i64>> {
5776        Some(
5777            left_run_positions
5778                .as_ref()?
5779                .iter()
5780                .zip(left_run_valid.as_ref()?.iter())
5781                .map(|(&lp, &valid)| if valid { spec_values[idx][lp] } else { 0 })
5782                .collect(),
5783        )
5784    };
5785    // Assemble columns in spec order, each a lazy lane.
5786    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5787    let mut columns = ColumnStore::new();
5788    let mut column_order = Vec::with_capacity(spec_names.len());
5789    for (idx, (name, kind)) in spec_names.into_iter().zip(spec_kinds.iter()).enumerate() {
5790        let column = match kind {
5791            OuterLaneKind::SharedKey => {
5792                // Closed-form coalesced key: all-valid, bucket key repeated in
5793                // ascending bucket order. Lazy repeat-runs when the fanout pays.
5794                if output_len >= key_runs.len().saturating_mul(2) {
5795                    Column::from_i64_repeat_runs(key_runs.clone())
5796                } else {
5797                    let mut data = Vec::with_capacity(output_len);
5798                    for &(key, run_len) in &key_runs {
5799                        data.resize(data.len() + run_len, key);
5800                    }
5801                    Column::from_i64_values(data)
5802                }
5803            }
5804            OuterLaneKind::Lane(side) => match (side, promoted(*side)) {
5805                (FusedInt64Side::Left, false) => {
5806                    let Some(run_lens) = run_lens.as_ref() else {
5807                        return Ok(None);
5808                    };
5809                    let Some(run_values) = left_run_values_i64(idx) else {
5810                        return Ok(None);
5811                    };
5812                    Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
5813                }
5814                (FusedInt64Side::Left, true) => {
5815                    if left_run_positions.is_none()
5816                        && let (Some(left_witness), Some(right_witness)) =
5817                            (left_witness, right_witness)
5818                    {
5819                        Column::from_i64_nullable_dense_cycle_left_as_f64_with_sparse_validity(
5820                            Arc::clone(&spec_sources[idx]),
5821                            left_witness,
5822                            right_witness,
5823                            min_key,
5824                            span,
5825                            left_sparse_validity.clone(),
5826                            output_len,
5827                        )
5828                    } else {
5829                        let Some(run_lens) = run_lens.as_ref() else {
5830                            return Ok(None);
5831                        };
5832                        let Some(left_run_positions) = left_run_positions.as_ref() else {
5833                            return Ok(None);
5834                        };
5835                        let Some(left_run_valid) = left_run_valid.as_ref() else {
5836                            return Ok(None);
5837                        };
5838                        Column::from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
5839                            Arc::clone(&spec_sources[idx]),
5840                            Arc::clone(left_run_positions),
5841                            Arc::clone(left_run_valid),
5842                            Arc::clone(run_lens),
5843                            left_sparse_validity.clone(),
5844                            output_len,
5845                        )
5846                    }
5847                }
5848                (FusedInt64Side::Right, false) => {
5849                    let Some(right_positions_csr) = right_positions_csr.as_ref() else {
5850                        return Ok(None);
5851                    };
5852                    let Some(right_segments) = right_segments.as_ref() else {
5853                        return Ok(None);
5854                    };
5855                    let tape_i64 = right_positions_csr
5856                        .iter()
5857                        .map(|&pos| spec_values[idx][pos])
5858                        .collect();
5859                    Column::from_i64_repeated_slices_shared(
5860                        tape_i64,
5861                        Arc::clone(right_segments),
5862                        output_len,
5863                    )
5864                }
5865                (FusedInt64Side::Right, true) => {
5866                    if right_positions_csr.is_none()
5867                        && let (Some(left_witness), Some(right_witness)) =
5868                            (left_witness, right_witness)
5869                    {
5870                        Column::from_i64_nullable_dense_cycle_right_as_f64_with_sparse_validity(
5871                            Arc::clone(&spec_sources[idx]),
5872                            left_witness,
5873                            right_witness,
5874                            min_key,
5875                            span,
5876                            right_sparse_validity.clone(),
5877                            output_len,
5878                        )
5879                    } else {
5880                        let Some(right_positions_csr) = right_positions_csr.as_ref() else {
5881                            return Ok(None);
5882                        };
5883                        let Some(right_segments) = right_segments.as_ref() else {
5884                            return Ok(None);
5885                        };
5886                        Column::from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
5887                            Arc::clone(&spec_sources[idx]),
5888                            Arc::clone(right_positions_csr),
5889                            Arc::clone(right_segments),
5890                            right_sparse_validity.clone(),
5891                            output_len,
5892                        )
5893                    }
5894                }
5895            },
5896        };
5897        debug_assert_eq!(column.len(), output_len);
5898        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
5899    }
5900
5901    Ok(Some(MergedDataFrame {
5902        index,
5903        columns,
5904        column_order,
5905    }))
5906}
5907
5908fn build_single_key_dense_i64_right_all_matched_merge_output(
5909    left: &fp_frame::DataFrame,
5910    right: &fp_frame::DataFrame,
5911    left_on: &[&str],
5912    right_on: &[&str],
5913    left_key: &Column,
5914    right_key: &Column,
5915    suffixes: &ResolvedMergeSuffixes,
5916) -> Result<Option<MergedDataFrame>, JoinError> {
5917    debug_assert_eq!(left_on.len(), 1);
5918    debug_assert_eq!(right_on.len(), 1);
5919
5920    let Some(left_keys) = left_key.as_i64_slice() else {
5921        return Ok(None);
5922    };
5923    let Some(right_keys) = right_key.as_i64_slice() else {
5924        return Ok(None);
5925    };
5926
5927    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5928    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5929    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5930    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5931    let shared_key_names = if left_on[0] == right_on[0] {
5932        [left_on[0]].into_iter().collect::<HashSet<&str>>()
5933    } else {
5934        HashSet::new()
5935    };
5936    let overlapping_names =
5937        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5938
5939    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
5940    for name in left.column_names() {
5941        let col = left
5942            .columns()
5943            .get(name)
5944            .expect("left column listed in column_names must exist");
5945        let (values, side) = if left_key_name_set.contains(name.as_str())
5946            && shared_key_names.contains(name.as_str())
5947        {
5948            let right_key_col = right
5949                .columns()
5950                .get(right_on[0])
5951                .expect("right key column must exist");
5952            let Some(values) = right_key_col.as_i64_slice() else {
5953                return Ok(None);
5954            };
5955            (values, FusedInt64Side::Right)
5956        } else {
5957            let Some(values) = col.as_i64_slice() else {
5958                return Ok(None);
5959            };
5960            (values, FusedInt64Side::Left)
5961        };
5962        let out_name = if left_key_name_set.contains(name.as_str()) {
5963            name.clone()
5964        } else if right_col_names.contains(name) {
5965            apply_merge_suffix(name, suffixes.left.as_deref())
5966        } else {
5967            name.clone()
5968        };
5969        specs.push(FusedInt64OutputColumn {
5970            name: out_name,
5971            side,
5972            values,
5973        });
5974    }
5975
5976    for name in right.column_names() {
5977        let col = right
5978            .columns()
5979            .get(name)
5980            .expect("right column listed in column_names must exist");
5981        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5982            continue;
5983        }
5984        let Some(values) = col.as_i64_slice() else {
5985            return Ok(None);
5986        };
5987        let out_name = if left_col_names.contains(name) {
5988            apply_merge_suffix(name, suffixes.right.as_deref())
5989        } else {
5990            name.clone()
5991        };
5992        specs.push(FusedInt64OutputColumn {
5993            name: out_name,
5994            side: FusedInt64Side::Right,
5995            values,
5996        });
5997    }
5998
5999    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6000
6001    if right_keys.is_empty() {
6002        let mut columns = ColumnStore::new();
6003        let mut column_order = Vec::with_capacity(specs.len());
6004        for spec in specs {
6005            insert_merged_output_column(
6006                &mut columns,
6007                &mut column_order,
6008                spec.name,
6009                Column::from_i64_values(Vec::new()),
6010            )?;
6011        }
6012        return Ok(Some(MergedDataFrame {
6013            index: Index::new(Vec::new()),
6014            columns,
6015            column_order,
6016        }));
6017    }
6018    if left_keys.is_empty() {
6019        return Ok(None);
6020    }
6021
6022    let mut min = left_keys[0];
6023    let mut max = left_keys[0];
6024    for &v in left_keys {
6025        if v < min {
6026            min = v;
6027        }
6028        if v > max {
6029            max = v;
6030        }
6031    }
6032    let span = (max as i128) - (min as i128) + 1;
6033    if span > (1i128 << 24) || span > 16 * (left_keys.len() as i128) {
6034        return Ok(None);
6035    }
6036    let range = span as usize;
6037
6038    let mut offsets = vec![0usize; range + 1];
6039    for &v in left_keys {
6040        offsets[(v - min) as usize + 1] += 1;
6041    }
6042    for i in 0..range {
6043        offsets[i + 1] += offsets[i];
6044    }
6045    let mut positions = vec![0usize; left_keys.len()];
6046    let mut cursor = offsets.clone();
6047    for (pos, &v) in left_keys.iter().enumerate() {
6048        let bucket = (v - min) as usize;
6049        positions[cursor[bucket]] = pos;
6050        cursor[bucket] += 1;
6051    }
6052
6053    let mut output_len = 0usize;
6054    for &v in right_keys {
6055        if v < min || v > max {
6056            return Ok(None);
6057        }
6058        let bucket = (v - min) as usize;
6059        let bucket_len = offsets[bucket + 1] - offsets[bucket];
6060        if bucket_len == 0 {
6061            return Ok(None);
6062        }
6063        let Some(new_output_len) = output_len.checked_add(bucket_len) else {
6064            return Ok(None);
6065        };
6066        output_len = new_output_len;
6067    }
6068
6069    let mut output_data = specs
6070        .iter()
6071        .map(|_| Vec::<i64>::with_capacity(output_len))
6072        .collect::<Vec<_>>();
6073    for (right_pos, &v) in right_keys.iter().enumerate() {
6074        let bucket = (v - min) as usize;
6075        for &left_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
6076            for (out, spec) in output_data.iter_mut().zip(specs.iter()) {
6077                match spec.side {
6078                    FusedInt64Side::Left => out.push(spec.values[left_pos]),
6079                    FusedInt64Side::Right => out.push(spec.values[right_pos]),
6080                }
6081            }
6082        }
6083    }
6084
6085    // Lazy unit-range output index: identical labels (0..output_len as
6086    // IndexLabel::Int64, materialized on demand), pre-proven unique and
6087    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
6088    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6089    let mut columns = ColumnStore::new();
6090    let mut column_order = Vec::with_capacity(specs.len());
6091    for (spec, data) in specs.into_iter().zip(output_data) {
6092        debug_assert_eq!(data.len(), output_len);
6093        insert_merged_output_column(
6094            &mut columns,
6095            &mut column_order,
6096            spec.name,
6097            Column::from_i64_values(data),
6098        )?;
6099    }
6100
6101    Ok(Some(MergedDataFrame {
6102        index,
6103        columns,
6104        column_order,
6105    }))
6106}
6107
6108fn build_single_key_dense_i64_outer_all_matched_merge_output(
6109    left: &fp_frame::DataFrame,
6110    right: &fp_frame::DataFrame,
6111    left_on: &[&str],
6112    right_on: &[&str],
6113    left_key: &Column,
6114    right_key: &Column,
6115    suffixes: &ResolvedMergeSuffixes,
6116) -> Result<Option<MergedDataFrame>, JoinError> {
6117    debug_assert_eq!(left_on.len(), 1);
6118    debug_assert_eq!(right_on.len(), 1);
6119
6120    let Some(left_keys) = left_key.as_i64_slice() else {
6121        return Ok(None);
6122    };
6123    let Some(right_keys) = right_key.as_i64_slice() else {
6124        return Ok(None);
6125    };
6126
6127    if left_keys.is_empty() != right_keys.is_empty() {
6128        return Ok(None);
6129    }
6130    let dense_domain = if left_keys.is_empty() {
6131        None
6132    } else {
6133        let left_witness = left_key
6134            .int64_dense_cycle_witness()
6135            .filter(|witness| witness.len == left_keys.len());
6136        let right_witness = right_key
6137            .int64_dense_cycle_witness()
6138            .filter(|witness| witness.len == right_keys.len());
6139        match (
6140            left_witness.and_then(dense_cycle_domain),
6141            right_witness.and_then(dense_cycle_domain),
6142        ) {
6143            (Some(left_domain), Some(right_domain)) => {
6144                if left_domain != right_domain {
6145                    return Ok(None);
6146                }
6147                Some(left_domain)
6148            }
6149            _ => {
6150                let min_max = |keys: &[i64]| {
6151                    let mut min_key = keys[0];
6152                    let mut max_key = keys[0];
6153                    for &key in &keys[1..] {
6154                        min_key = min_key.min(key);
6155                        max_key = max_key.max(key);
6156                    }
6157                    (min_key, max_key)
6158                };
6159                let (left_min_key, left_max_key) = min_max(left_keys);
6160                let (right_min_key, right_max_key) = min_max(right_keys);
6161                if left_min_key != right_min_key || left_max_key != right_max_key {
6162                    return Ok(None);
6163                }
6164                Some((left_min_key, left_max_key))
6165            }
6166        }
6167    };
6168
6169    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6170    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6171    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6172    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6173    let shared_key_names = if left_on[0] == right_on[0] {
6174        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6175    } else {
6176        HashSet::new()
6177    };
6178    let overlapping_names =
6179        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6180
6181    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
6182    for name in left.column_names() {
6183        let col = left
6184            .columns()
6185            .get(name)
6186            .expect("left column listed in column_names must exist");
6187        let Some(values) = col.as_i64_slice() else {
6188            return Ok(None);
6189        };
6190        let out_name = if left_key_name_set.contains(name.as_str()) {
6191            name.clone()
6192        } else if right_col_names.contains(name) {
6193            apply_merge_suffix(name, suffixes.left.as_deref())
6194        } else {
6195            name.clone()
6196        };
6197        specs.push(FusedInt64OutputColumn {
6198            name: out_name,
6199            side: FusedInt64Side::Left,
6200            values,
6201        });
6202    }
6203
6204    for name in right.column_names() {
6205        let col = right
6206            .columns()
6207            .get(name)
6208            .expect("right column listed in column_names must exist");
6209        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6210            continue;
6211        }
6212        let Some(values) = col.as_i64_slice() else {
6213            return Ok(None);
6214        };
6215        let out_name = if left_col_names.contains(name) {
6216            apply_merge_suffix(name, suffixes.right.as_deref())
6217        } else {
6218            name.clone()
6219        };
6220        specs.push(FusedInt64OutputColumn {
6221            name: out_name,
6222            side: FusedInt64Side::Right,
6223            values,
6224        });
6225    }
6226
6227    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6228
6229    if left_keys.is_empty() || right_keys.is_empty() {
6230        if !left_keys.is_empty() || !right_keys.is_empty() {
6231            return Ok(None);
6232        }
6233        let mut columns = ColumnStore::new();
6234        let mut column_order = Vec::with_capacity(specs.len());
6235        for spec in specs {
6236            insert_merged_output_column(
6237                &mut columns,
6238                &mut column_order,
6239                spec.name,
6240                Column::from_i64_values(Vec::new()),
6241            )?;
6242        }
6243        return Ok(Some(MergedDataFrame {
6244            index: Index::new(Vec::new()),
6245            columns,
6246            column_order,
6247        }));
6248    }
6249
6250    let (min_key, max_key) = dense_domain.expect("empty dense outer case returned above");
6251
6252    let span = i128::from(max_key)
6253        .checked_sub(i128::from(min_key))
6254        .and_then(|span| span.checked_add(1));
6255    let Some(span) = span else {
6256        return Ok(None);
6257    };
6258    let row_count = left_keys.len().saturating_add(right_keys.len());
6259    let max_dense_span = row_count.saturating_mul(4).max(1024);
6260    if span > max_dense_span as i128 {
6261        return Ok(None);
6262    }
6263    let Ok(span) = usize::try_from(span) else {
6264        return Ok(None);
6265    };
6266
6267    let mut left_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
6268    let mut right_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
6269    for (pos, &key) in left_keys.iter().enumerate() {
6270        let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
6271            return Ok(None);
6272        };
6273        left_buckets[bucket].push(pos);
6274    }
6275    for (pos, &key) in right_keys.iter().enumerate() {
6276        let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
6277            return Ok(None);
6278        };
6279        right_buckets[bucket].push(pos);
6280    }
6281
6282    let mut output_len = 0usize;
6283    for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6284        match (left_bucket.is_empty(), right_bucket.is_empty()) {
6285            (false, false) => {
6286                let Some(bucket_rows) = left_bucket.len().checked_mul(right_bucket.len()) else {
6287                    return Ok(None);
6288                };
6289                let Some(new_output_len) = output_len.checked_add(bucket_rows) else {
6290                    return Ok(None);
6291                };
6292                output_len = new_output_len;
6293            }
6294            (false, true) | (true, false) => return Ok(None),
6295            (true, true) => {}
6296        }
6297    }
6298
6299    // Lazy unit-range output index: identical labels (0..output_len as
6300    // IndexLabel::Int64, materialized on demand), pre-proven unique and
6301    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
6302    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6303    let mut columns = ColumnStore::new();
6304    let mut column_order = Vec::with_capacity(specs.len());
6305    for spec in specs {
6306        let FusedInt64OutputColumn { name, side, values } = spec;
6307        let mut data = Vec::<i64>::with_capacity(output_len);
6308        match side {
6309            FusedInt64Side::Left => {
6310                for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6311                    if left_bucket.is_empty() {
6312                        continue;
6313                    }
6314                    let repeat_count = right_bucket.len();
6315                    for &left_pos in left_bucket {
6316                        let value = values[left_pos];
6317                        for _ in 0..repeat_count {
6318                            data.push(value);
6319                        }
6320                    }
6321                }
6322            }
6323            FusedInt64Side::Right => {
6324                for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6325                    if left_bucket.is_empty() {
6326                        continue;
6327                    }
6328                    for _ in left_bucket {
6329                        for &right_pos in right_bucket {
6330                            data.push(values[right_pos]);
6331                        }
6332                    }
6333                }
6334            }
6335        }
6336        debug_assert_eq!(data.len(), output_len);
6337        insert_merged_output_column(
6338            &mut columns,
6339            &mut column_order,
6340            name,
6341            Column::from_i64_values(data),
6342        )?;
6343    }
6344
6345    Ok(Some(MergedDataFrame {
6346        index,
6347        columns,
6348        column_order,
6349    }))
6350}
6351
6352struct FixedDecimalUtf8Domain {
6353    prefix: Vec<u8>,
6354    decimal_width: usize,
6355    start: u64,
6356    len: usize,
6357}
6358
6359impl FixedDecimalUtf8Domain {
6360    fn row_width(&self) -> usize {
6361        self.prefix.len() + self.decimal_width
6362    }
6363}
6364
6365fn trailing_decimal_width(bytes: &[u8]) -> Option<usize> {
6366    let width = bytes
6367        .iter()
6368        .rev()
6369        .take_while(|byte| byte.is_ascii_digit())
6370        .count();
6371    (width > 0).then_some(width)
6372}
6373
6374fn parse_decimal_u64(bytes: &[u8]) -> Option<u64> {
6375    let mut out = 0u64;
6376    for &byte in bytes {
6377        if !byte.is_ascii_digit() {
6378            return None;
6379        }
6380        out = out.checked_mul(10)?.checked_add(u64::from(byte - b'0'))?;
6381    }
6382    Some(out)
6383}
6384
6385fn fixed_decimal_utf8_domain(bytes: &[u8], offsets: &[usize]) -> Option<FixedDecimalUtf8Domain> {
6386    let len = offsets.len().checked_sub(1)?;
6387    if len == 0 {
6388        return None;
6389    }
6390
6391    let first = utf8_span(bytes, offsets, 0);
6392    let decimal_width = trailing_decimal_width(first)?;
6393    let prefix_len = first.len().checked_sub(decimal_width)?;
6394    let prefix = first[..prefix_len].to_vec();
6395    let start = parse_decimal_u64(&first[prefix_len..])?;
6396    let row_width = first.len();
6397
6398    for row in 0..len {
6399        let span = utf8_span(bytes, offsets, row);
6400        if span.len() != row_width || !span.starts_with(&prefix) {
6401            return None;
6402        }
6403        let value = parse_decimal_u64(&span[prefix_len..])?;
6404        if value != start.checked_add(row as u64)? {
6405            return None;
6406        }
6407    }
6408
6409    Some(FixedDecimalUtf8Domain {
6410        prefix,
6411        decimal_width,
6412        start,
6413        len,
6414    })
6415}
6416
6417fn fixed_decimal_utf8_bucket(span: &[u8], domain: &FixedDecimalUtf8Domain) -> Option<usize> {
6418    if span.len() != domain.row_width() || !span.starts_with(&domain.prefix) {
6419        return None;
6420    }
6421    let value = parse_decimal_u64(&span[domain.prefix.len()..])?;
6422    let relative = value.checked_sub(domain.start)?;
6423    let bucket = usize::try_from(relative).ok()?;
6424    (bucket < domain.len).then_some(bucket)
6425}
6426
6427enum FixedDecimalUtf8OuterLane<'a> {
6428    SharedKey,
6429    LeftF64(&'a [f64]),
6430    RightF64(&'a [f64]),
6431    LeftI64(&'a [i64]),
6432    RightI64(&'a [i64]),
6433}
6434
6435fn build_single_key_fixed_decimal_utf8_outer_all_matched_merge_output(
6436    left: &fp_frame::DataFrame,
6437    right: &fp_frame::DataFrame,
6438    left_on: &[&str],
6439    right_on: &[&str],
6440    left_key: &Column,
6441    right_key: &Column,
6442    suffixes: &ResolvedMergeSuffixes,
6443) -> Result<Option<MergedDataFrame>, JoinError> {
6444    debug_assert_eq!(left_on.len(), 1);
6445    debug_assert_eq!(right_on.len(), 1);
6446
6447    if left_on[0] != right_on[0] {
6448        return Ok(None);
6449    }
6450
6451    let Some((left_bytes, left_offsets)) = left_key.as_utf8_contiguous() else {
6452        return Ok(None);
6453    };
6454    let Some((right_bytes, right_offsets)) = right_key.as_utf8_contiguous() else {
6455        return Ok(None);
6456    };
6457    let left_len = left_offsets.len().saturating_sub(1);
6458    let right_len = right_offsets.len().saturating_sub(1);
6459    if left_len == 0 || right_len == 0 {
6460        return Ok(None);
6461    }
6462
6463    let Some(domain) = fixed_decimal_utf8_domain(right_bytes, right_offsets) else {
6464        return Ok(None);
6465    };
6466
6467    let mut counts = vec![0usize; right_len];
6468    let mut left_buckets = Vec::<usize>::with_capacity(left_len);
6469    for left_pos in 0..left_len {
6470        let span = utf8_span(left_bytes, left_offsets, left_pos);
6471        let Some(bucket) = fixed_decimal_utf8_bucket(span, &domain) else {
6472            return Ok(None);
6473        };
6474        counts[bucket] = counts[bucket].checked_add(1).ok_or_else(|| {
6475            JoinError::Frame(FrameError::CompatibilityRejected(
6476                "merge output row count overflowed".to_owned(),
6477            ))
6478        })?;
6479        left_buckets.push(bucket);
6480    }
6481    if counts.contains(&0) {
6482        return Ok(None);
6483    }
6484
6485    let mut offsets = Vec::with_capacity(right_len + 1);
6486    offsets.push(0usize);
6487    for &count in &counts {
6488        offsets.push(offsets.last().copied().unwrap_or(0) + count);
6489    }
6490    let output_len = offsets[right_len];
6491    let mut left_positions = vec![0usize; output_len];
6492    let mut cursor = offsets[..right_len].to_vec();
6493    for (left_pos, &bucket) in left_buckets.iter().enumerate() {
6494        let out = cursor[bucket];
6495        left_positions[out] = left_pos;
6496        cursor[bucket] += 1;
6497    }
6498
6499    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6500    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6501    let shared_key_names = [left_on[0]].into_iter().collect::<HashSet<&str>>();
6502    let overlapping_names =
6503        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6504    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6505
6506    let mut specs = Vec::<(String, FixedDecimalUtf8OuterLane<'_>)>::new();
6507    for name in left.column_names() {
6508        let col = left
6509            .columns()
6510            .get(name)
6511            .expect("left column listed in column_names must exist");
6512        let lane = if name.as_str() == left_on[0] {
6513            FixedDecimalUtf8OuterLane::SharedKey
6514        } else if let Some(values) = col.as_f64_slice() {
6515            FixedDecimalUtf8OuterLane::LeftF64(values)
6516        } else if let Some(values) = col.as_i64_slice() {
6517            FixedDecimalUtf8OuterLane::LeftI64(values)
6518        } else {
6519            return Ok(None);
6520        };
6521        let out_name = if name.as_str() == left_on[0] {
6522            name.clone()
6523        } else if right_col_names.contains(name) {
6524            apply_merge_suffix(name, suffixes.left.as_deref())
6525        } else {
6526            name.clone()
6527        };
6528        specs.push((out_name, lane));
6529    }
6530    for name in right.column_names() {
6531        if name.as_str() == right_on[0] {
6532            continue;
6533        }
6534        let col = right
6535            .columns()
6536            .get(name)
6537            .expect("right column listed in column_names must exist");
6538        let lane = if let Some(values) = col.as_f64_slice() {
6539            FixedDecimalUtf8OuterLane::RightF64(values)
6540        } else if let Some(values) = col.as_i64_slice() {
6541            FixedDecimalUtf8OuterLane::RightI64(values)
6542        } else {
6543            return Ok(None);
6544        };
6545        let out_name = if left_col_names.contains(name) {
6546            apply_merge_suffix(name, suffixes.right.as_deref())
6547        } else {
6548            name.clone()
6549        };
6550        specs.push((out_name, lane));
6551    }
6552
6553    let run_lens: Arc<[usize]> = Arc::from(counts.clone());
6554    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6555    let mut columns = ColumnStore::new();
6556    let mut column_order = Vec::with_capacity(specs.len());
6557    for (name, lane) in specs {
6558        let column = match lane {
6559            FixedDecimalUtf8OuterLane::SharedKey => {
6560                let row_width = domain.row_width();
6561                let mut bytes = Vec::with_capacity(output_len.saturating_mul(row_width));
6562                let mut out_offsets = Vec::with_capacity(output_len + 1);
6563                out_offsets.push(0);
6564                for (bucket, &count) in counts.iter().enumerate() {
6565                    let span = utf8_span(right_bytes, right_offsets, bucket);
6566                    for _ in 0..count {
6567                        bytes.extend_from_slice(span);
6568                        out_offsets.push(bytes.len());
6569                    }
6570                }
6571                Column::from_utf8_contiguous(bytes, out_offsets)
6572            }
6573            FixedDecimalUtf8OuterLane::LeftF64(values) => {
6574                let data = left_positions.iter().map(|&pos| values[pos]).collect();
6575                Column::from_f64_values_all_valid_unchecked(data)
6576            }
6577            FixedDecimalUtf8OuterLane::RightF64(values) => {
6578                let run_values = (0..right_len).map(|bucket| values[bucket]).collect();
6579                Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(&run_lens))
6580            }
6581            FixedDecimalUtf8OuterLane::LeftI64(values) => {
6582                let data = left_positions.iter().map(|&pos| values[pos]).collect();
6583                Column::from_i64_values(data)
6584            }
6585            FixedDecimalUtf8OuterLane::RightI64(values) => {
6586                let run_values = (0..right_len).map(|bucket| values[bucket]).collect();
6587                Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(&run_lens))
6588            }
6589        };
6590        debug_assert_eq!(column.len(), output_len);
6591        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
6592    }
6593
6594    Ok(Some(MergedDataFrame {
6595        index,
6596        columns,
6597        column_order,
6598    }))
6599}
6600
6601fn build_single_key_inner_merge_output(
6602    left: &fp_frame::DataFrame,
6603    right: &fp_frame::DataFrame,
6604    left_on: &[&str],
6605    right_on: &[&str],
6606    left_positions: &[usize],
6607    right_positions: &[usize],
6608    suffixes: &ResolvedMergeSuffixes,
6609) -> Result<MergedDataFrame, JoinError> {
6610    build_single_key_inner_merge_output_with_selections(
6611        left,
6612        right,
6613        left_on,
6614        right_on,
6615        PositionSelection::Positions(left_positions),
6616        PositionSelection::Positions(right_positions),
6617        suffixes,
6618    )
6619}
6620
6621fn build_single_key_inner_contiguous_no_overlap_output(
6622    left: &fp_frame::DataFrame,
6623    right: &fp_frame::DataFrame,
6624    left_on: &[&str],
6625    right_on: &[&str],
6626    left_positions: PositionSelection<'_>,
6627    right_positions: PositionSelection<'_>,
6628) -> Option<MergedDataFrame> {
6629    let (
6630        PositionSelection::ContiguousRange {
6631            start: left_start,
6632            len,
6633        },
6634        PositionSelection::ContiguousRange {
6635            start: right_start,
6636            len: right_len,
6637        },
6638    ) = (left_positions, right_positions)
6639    else {
6640        return None;
6641    };
6642    if left_on[0] != right_on[0] || len != right_len {
6643        return None;
6644    }
6645
6646    let left_col_names = left.column_names();
6647    let right_col_names = right.column_names();
6648    if left_col_names.iter().any(|left_name| {
6649        left_name.as_str() != left_on[0]
6650            && right_col_names
6651                .iter()
6652                .any(|right_name| right_name.as_str() == left_name.as_str())
6653    }) {
6654        return None;
6655    }
6656
6657    let mut columns = ColumnStore::new();
6658    let mut column_order =
6659        Vec::with_capacity(left_col_names.len() + right_col_names.len().saturating_sub(1));
6660    let left_selection = PositionSelection::ContiguousRange {
6661        start: left_start,
6662        len,
6663    };
6664    let right_selection = PositionSelection::ContiguousRange {
6665        start: right_start,
6666        len,
6667    };
6668
6669    for name in left_col_names.iter().copied() {
6670        let column = left
6671            .columns()
6672            .get(name)
6673            .expect("left column listed in column_names must exist");
6674        let output_column = if name.as_str() == left_on[0] {
6675            take_lower_hex_sequence_range(column, left_start, len)
6676                .unwrap_or_else(|| take_position_selection_typed(column, left_selection))
6677        } else {
6678            take_position_selection_typed(column, left_selection)
6679        };
6680        column_order.push(name.clone());
6681        let previous = columns.insert(name.clone(), output_column);
6682        debug_assert!(previous.is_none());
6683    }
6684    for name in right_col_names.iter().copied() {
6685        if name.as_str() == right_on[0] {
6686            continue;
6687        }
6688        let column = right
6689            .columns()
6690            .get(name)
6691            .expect("right column listed in column_names must exist");
6692        column_order.push(name.clone());
6693        let previous = columns.insert(
6694            name.clone(),
6695            take_position_selection_typed(column, right_selection),
6696        );
6697        debug_assert!(previous.is_none());
6698    }
6699
6700    Some(MergedDataFrame {
6701        index: Index::new_known_unique_int64_unit_range(0, len),
6702        columns,
6703        column_order,
6704    })
6705}
6706
6707fn build_single_key_inner_merge_output_with_selections(
6708    left: &fp_frame::DataFrame,
6709    right: &fp_frame::DataFrame,
6710    left_on: &[&str],
6711    right_on: &[&str],
6712    left_positions: PositionSelection<'_>,
6713    right_positions: PositionSelection<'_>,
6714    suffixes: &ResolvedMergeSuffixes,
6715) -> Result<MergedDataFrame, JoinError> {
6716    debug_assert_eq!(left_on.len(), 1);
6717    debug_assert_eq!(right_on.len(), 1);
6718    debug_assert_eq!(left_positions.len(), right_positions.len());
6719
6720    if let Some(merged) = build_single_key_inner_contiguous_no_overlap_output(
6721        left,
6722        right,
6723        left_on,
6724        right_on,
6725        left_positions,
6726        right_positions,
6727    ) {
6728        return Ok(merged);
6729    }
6730
6731    let n = left_positions.len();
6732    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6733    let index = Index::new_known_unique_int64_unit_range(0, n);
6734
6735    let left_col_names = left.column_names();
6736    let right_col_names = right.column_names();
6737    let use_linear_name_lookup =
6738        left_col_names.len() + right_col_names.len() <= SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT;
6739    let left_hashed_col_names = (!use_linear_name_lookup).then(|| {
6740        left_col_names
6741            .iter()
6742            .map(|name| name.as_str())
6743            .collect::<HashSet<_>>()
6744    });
6745    let right_hashed_col_names = (!use_linear_name_lookup).then(|| {
6746        right_col_names
6747            .iter()
6748            .map(|name| name.as_str())
6749            .collect::<HashSet<_>>()
6750    });
6751    let shared_key_name = (left_on[0] == right_on[0]).then_some(left_on[0]);
6752    let mut overlapping_names = left_col_names
6753        .iter()
6754        .filter_map(|name| {
6755            let name = name.as_str();
6756            (Some(name) != shared_key_name
6757                && column_name_lookup_contains(
6758                    &right_col_names,
6759                    right_hashed_col_names.as_ref(),
6760                    name,
6761                ))
6762            .then(|| name.to_owned())
6763        })
6764        .collect::<Vec<_>>();
6765    overlapping_names.sort();
6766    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6767
6768    // Resolve output column specs in order (name/suffix resolution is cheap),
6769    // then gather them. Each output column is an independent typed gather over
6770    // the position vector, so wide/large outputs build every column in parallel
6771    // (one column per worker) — the same disjoint-fill pattern as the dense-i64
6772    // fused builder (br-frankenpandas-j3jnd). Bit-identical to the serial loop:
6773    // identical per-column take_positions_typed result, inserted in spec order.
6774    let mut specs: Vec<(String, &Column, PositionSelection<'_>)> = Vec::new();
6775    for name in left_col_names.iter().copied() {
6776        let col = left
6777            .columns()
6778            .get(name)
6779            .expect("left column listed in column_names must exist");
6780        let out_name = if name.as_str() == left_on[0] {
6781            name.clone()
6782        } else if column_name_lookup_contains(
6783            &right_col_names,
6784            right_hashed_col_names.as_ref(),
6785            name.as_str(),
6786        ) {
6787            apply_merge_suffix(name, suffixes.left.as_deref())
6788        } else {
6789            name.clone()
6790        };
6791        specs.push((out_name, col, left_positions));
6792    }
6793    for name in right_col_names.iter().copied() {
6794        if name.as_str() == right_on[0] && shared_key_name == Some(name.as_str()) {
6795            continue;
6796        }
6797        let col = right
6798            .columns()
6799            .get(name)
6800            .expect("right column listed in column_names must exist");
6801        let out_name = if column_name_lookup_contains(
6802            &left_col_names,
6803            left_hashed_col_names.as_ref(),
6804            name.as_str(),
6805        ) {
6806            apply_merge_suffix(name, suffixes.right.as_deref())
6807        } else {
6808            name.clone()
6809        };
6810        specs.push((out_name, col, right_positions));
6811    }
6812
6813    let built: Vec<Column> = {
6814        let thread_count = join_parallel_thread_count();
6815        if specs.len() > 1 && n >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
6816            let mut slots: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
6817            let chunk = specs.len().div_ceil(thread_count).max(1);
6818            std::thread::scope(|scope| {
6819                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
6820                    scope.spawn(move || {
6821                        for ((_, col, positions), slot) in spec_chunk.iter().zip(slot_chunk) {
6822                            *slot = Some(take_position_selection_typed(col, *positions));
6823                        }
6824                    });
6825                }
6826            });
6827            slots
6828                .into_iter()
6829                .map(|c| c.expect("every spec column must be built"))
6830                .collect()
6831        } else {
6832            specs
6833                .iter()
6834                .map(|(_, col, positions)| take_position_selection_typed(col, *positions))
6835                .collect()
6836        }
6837    };
6838
6839    let mut columns = ColumnStore::new();
6840    let mut column_order: Vec<String> = Vec::with_capacity(specs.len());
6841    for ((out_name, _, _), column) in specs.into_iter().zip(built) {
6842        insert_merged_output_column(&mut columns, &mut column_order, out_name, column)?;
6843    }
6844
6845    Ok(MergedDataFrame {
6846        index,
6847        columns,
6848        column_order,
6849    })
6850}
6851
6852fn build_single_key_dense_left_merge_output(
6853    left: &fp_frame::DataFrame,
6854    right: &fp_frame::DataFrame,
6855    left_on: &[&str],
6856    right_on: &[&str],
6857    left_positions: &[Option<usize>],
6858    right_positions: &[Option<usize>],
6859    suffixes: &ResolvedMergeSuffixes,
6860) -> Result<MergedDataFrame, JoinError> {
6861    debug_assert_eq!(left_on.len(), 1);
6862    debug_assert_eq!(right_on.len(), 1);
6863    debug_assert_eq!(left_positions.len(), right_positions.len());
6864
6865    let n = left_positions.len();
6866    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6867    let index = Index::new_known_unique_int64_unit_range(0, n);
6868    let mut columns = ColumnStore::new();
6869    let mut column_order: Vec<String> = Vec::new();
6870
6871    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6872    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6873    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6874    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6875    let shared_key_names = if left_on[0] == right_on[0] {
6876        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6877    } else {
6878        HashSet::new()
6879    };
6880    let overlapping_names =
6881        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6882    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6883    for name in left.column_names() {
6884        let col = left
6885            .columns()
6886            .get(name)
6887            .expect("left column listed in column_names must exist");
6888        let out_name = if left_key_name_set.contains(name.as_str()) {
6889            name.clone()
6890        } else if right_col_names.contains(name) {
6891            apply_merge_suffix(name, suffixes.left.as_deref())
6892        } else {
6893            name.clone()
6894        };
6895        let output = col.reindex_by_positions(left_positions)?;
6896        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6897    }
6898
6899    for name in right.column_names() {
6900        let col = right
6901            .columns()
6902            .get(name)
6903            .expect("right column listed in column_names must exist");
6904        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6905            continue;
6906        }
6907
6908        let reindexed = reindex_join_column_with_invented_gap(col, right_positions)?;
6909        let out_name = if left_col_names.contains(name) {
6910            apply_merge_suffix(name, suffixes.right.as_deref())
6911        } else {
6912            name.clone()
6913        };
6914        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6915    }
6916
6917    Ok(MergedDataFrame {
6918        index,
6919        columns,
6920        column_order,
6921    })
6922}
6923
6924fn build_single_key_ordered_unique_left_merge_output(
6925    left: &fp_frame::DataFrame,
6926    right: &fp_frame::DataFrame,
6927    left_on: &[&str],
6928    right_on: &[&str],
6929    right_positions: &[Option<usize>],
6930    suffixes: &ResolvedMergeSuffixes,
6931) -> Result<MergedDataFrame, JoinError> {
6932    debug_assert_eq!(left_on.len(), 1);
6933    debug_assert_eq!(right_on.len(), 1);
6934    debug_assert_eq!(left.len(), right_positions.len());
6935
6936    let n = left.len();
6937    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6938    let index = Index::new_known_unique_int64_unit_range(0, n);
6939    let mut columns = ColumnStore::new();
6940    let mut column_order: Vec<String> = Vec::new();
6941    let mut identity_positions = None;
6942
6943    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6944    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6945    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6946    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6947    let shared_key_names = if left_on[0] == right_on[0] {
6948        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6949    } else {
6950        HashSet::new()
6951    };
6952    let overlapping_names =
6953        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6954    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6955    // Building the shared Utf8 gather plan is O(output_rows): it scans every
6956    // optional position and, for a non-contiguous match pattern, allocates an
6957    // additional position tape plus validity bitmap. Most ordered Int64 joins
6958    // have only numeric payloads, where every column ignores that plan and uses
6959    // its typed reindexer. Defer the work until the first Utf8 payload actually
6960    // asks for it; subsequent Utf8 columns still share the single immutable
6961    // plan exactly as before.
6962    let right_utf8_plan: OnceLock<Option<SharedOptionalUtf8GatherPlan>> = OnceLock::new();
6963
6964    for name in left.column_names() {
6965        let col = left
6966            .columns()
6967            .get(name)
6968            .expect("left column listed in column_names must exist");
6969        let out_name = if left_key_name_set.contains(name.as_str()) {
6970            name.clone()
6971        } else if right_col_names.contains(name) {
6972            apply_merge_suffix(name, suffixes.left.as_deref())
6973        } else {
6974            name.clone()
6975        };
6976        let output = identity_merge_column(col, n, &mut identity_positions);
6977        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6978    }
6979
6980    for name in right.column_names() {
6981        let col = right
6982            .columns()
6983            .get(name)
6984            .expect("right column listed in column_names must exist");
6985        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6986            continue;
6987        }
6988
6989        let reindexed = if col.dtype() == DType::Utf8 {
6990            let utf8_plan = right_utf8_plan
6991                .get_or_init(|| shared_optional_utf8_gather_plan(right_positions, right.len()))
6992                .as_ref();
6993            reindex_with_shared_utf8_plan(col, right_positions, utf8_plan)?
6994        } else {
6995            reindex_join_column_with_invented_gap(col, right_positions)?
6996        };
6997        let out_name = if left_col_names.contains(name) {
6998            apply_merge_suffix(name, suffixes.right.as_deref())
6999        } else {
7000            name.clone()
7001        };
7002        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7003    }
7004
7005    Ok(MergedDataFrame {
7006        index,
7007        columns,
7008        column_order,
7009    })
7010}
7011
7012fn build_single_key_ordered_unique_right_merge_output(
7013    left: &fp_frame::DataFrame,
7014    right: &fp_frame::DataFrame,
7015    left_on: &[&str],
7016    right_on: &[&str],
7017    left_positions: &[Option<usize>],
7018    suffixes: &ResolvedMergeSuffixes,
7019) -> Result<MergedDataFrame, JoinError> {
7020    debug_assert_eq!(left_on.len(), 1);
7021    debug_assert_eq!(right_on.len(), 1);
7022    debug_assert_eq!(right.len(), left_positions.len());
7023
7024    let n = right.len();
7025    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7026    let index = Index::new_known_unique_int64_unit_range(0, n);
7027    let mut columns = ColumnStore::new();
7028    let mut column_order: Vec<String> = Vec::new();
7029    let mut identity_positions = None;
7030
7031    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7032    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7033    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7034    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7035    let shared_key_names = if left_on[0] == right_on[0] {
7036        [left_on[0]].into_iter().collect::<HashSet<&str>>()
7037    } else {
7038        HashSet::new()
7039    };
7040    let overlapping_names =
7041        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7042    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7043
7044    for name in left.column_names() {
7045        let col = left
7046            .columns()
7047            .get(name)
7048            .expect("left column listed in column_names must exist");
7049        let out_name = if left_key_name_set.contains(name.as_str()) {
7050            name.clone()
7051        } else if right_col_names.contains(name) {
7052            apply_merge_suffix(name, suffixes.left.as_deref())
7053        } else {
7054            name.clone()
7055        };
7056        let output = if left_key_name_set.contains(name.as_str())
7057            && shared_key_names.contains(name.as_str())
7058        {
7059            let right_key_col = right
7060                .columns()
7061                .get(right_on[0])
7062                .expect("right key column must exist");
7063            identity_merge_column(right_key_col, n, &mut identity_positions)
7064        } else {
7065            reindex_join_column_with_invented_gap(col, left_positions)?
7066        };
7067        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7068    }
7069
7070    for name in right.column_names() {
7071        let col = right
7072            .columns()
7073            .get(name)
7074            .expect("right column listed in column_names must exist");
7075        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
7076            continue;
7077        }
7078
7079        let reindexed = identity_merge_column(col, n, &mut identity_positions);
7080        let out_name = if left_col_names.contains(name) {
7081            apply_merge_suffix(name, suffixes.right.as_deref())
7082        } else {
7083            name.clone()
7084        };
7085        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7086    }
7087
7088    Ok(MergedDataFrame {
7089        index,
7090        columns,
7091        column_order,
7092    })
7093}
7094
7095fn build_single_key_dense_right_merge_output(
7096    left: &fp_frame::DataFrame,
7097    right: &fp_frame::DataFrame,
7098    left_on: &[&str],
7099    right_on: &[&str],
7100    left_positions: &[Option<usize>],
7101    right_positions: &[Option<usize>],
7102    suffixes: &ResolvedMergeSuffixes,
7103) -> Result<MergedDataFrame, JoinError> {
7104    debug_assert_eq!(left_on.len(), 1);
7105    debug_assert_eq!(right_on.len(), 1);
7106    debug_assert_eq!(left_positions.len(), right_positions.len());
7107
7108    let n = left_positions.len();
7109    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7110    let index = Index::new_known_unique_int64_unit_range(0, n);
7111    let mut columns = ColumnStore::new();
7112    let mut column_order: Vec<String> = Vec::new();
7113
7114    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7115    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7116    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7117    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7118    let shared_key_names = if left_on[0] == right_on[0] {
7119        [left_on[0]].into_iter().collect::<HashSet<&str>>()
7120    } else {
7121        HashSet::new()
7122    };
7123    let overlapping_names =
7124        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7125    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7126
7127    for name in left.column_names() {
7128        let col = left
7129            .columns()
7130            .get(name)
7131            .expect("left column listed in column_names must exist");
7132        let out_name = if left_key_name_set.contains(name.as_str()) {
7133            name.clone()
7134        } else if right_col_names.contains(name) {
7135            apply_merge_suffix(name, suffixes.left.as_deref())
7136        } else {
7137            name.clone()
7138        };
7139        let output = if left_key_name_set.contains(name.as_str())
7140            && shared_key_names.contains(name.as_str())
7141        {
7142            let right_key_col = right
7143                .columns()
7144                .get(right_on[0])
7145                .expect("right key column must exist");
7146            right_key_col.reindex_by_positions(right_positions)?
7147        } else {
7148            reindex_join_column_with_invented_gap(col, left_positions)?
7149        };
7150        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7151    }
7152
7153    for name in right.column_names() {
7154        let col = right
7155            .columns()
7156            .get(name)
7157            .expect("right column listed in column_names must exist");
7158        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
7159            continue;
7160        }
7161
7162        let reindexed = col.reindex_by_positions(right_positions)?;
7163        let out_name = if left_col_names.contains(name) {
7164            apply_merge_suffix(name, suffixes.right.as_deref())
7165        } else {
7166            name.clone()
7167        };
7168        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7169    }
7170
7171    Ok(MergedDataFrame {
7172        index,
7173        columns,
7174        column_order,
7175    })
7176}
7177
7178fn build_single_key_ordered_unique_outer_merge_output(
7179    left: &fp_frame::DataFrame,
7180    right: &fp_frame::DataFrame,
7181    left_on: &[&str],
7182    right_on: &[&str],
7183    left_positions: &[Option<usize>],
7184    right_positions: &[Option<usize>],
7185    suffixes: &ResolvedMergeSuffixes,
7186) -> Result<MergedDataFrame, JoinError> {
7187    debug_assert_eq!(left_on.len(), 1);
7188    debug_assert_eq!(right_on.len(), 1);
7189    debug_assert_eq!(left_positions.len(), right_positions.len());
7190
7191    let n = left_positions.len();
7192    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7193    let index = Index::new_known_unique_int64_unit_range(0, n);
7194    let mut columns = ColumnStore::new();
7195    let mut column_order: Vec<String> = Vec::new();
7196
7197    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7198    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7199    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7200    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7201
7202    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
7203    if left_on[0] == right_on[0] {
7204        shared_name_positions.insert(left_on[0], (0, 0));
7205    }
7206    let shared_key_names = shared_name_positions
7207        .keys()
7208        .copied()
7209        .collect::<HashSet<&str>>();
7210    let overlapping_names =
7211        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7212    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7213
7214    let mut left_take_positions = Vec::with_capacity(n);
7215    let mut right_take_positions = Vec::with_capacity(n);
7216    let mut all_positions_present = true;
7217    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
7218        let (Some(left_pos), Some(right_pos)) = (*left_pos, *right_pos) else {
7219            all_positions_present = false;
7220            break;
7221        };
7222        left_take_positions.push(left_pos);
7223        right_take_positions.push(right_pos);
7224    }
7225    let all_present_take_positions =
7226        all_positions_present.then_some((left_take_positions, right_take_positions));
7227    let all_present_left_positions = all_present_take_positions
7228        .as_ref()
7229        .map(|(positions, _)| positions.as_slice());
7230    let all_present_right_positions = all_present_take_positions
7231        .as_ref()
7232        .map(|(_, positions)| positions.as_slice());
7233    let left_has_utf8 = left
7234        .columns()
7235        .values()
7236        .any(|column| column.dtype() == DType::Utf8);
7237    let right_has_utf8 = right
7238        .columns()
7239        .values()
7240        .any(|column| column.dtype() == DType::Utf8);
7241    let left_utf8_plan = (left_has_utf8 && all_present_left_positions.is_none())
7242        .then(|| shared_optional_utf8_gather_plan(left_positions, left.len()))
7243        .flatten();
7244    let right_utf8_plan = (right_has_utf8 && all_present_right_positions.is_none())
7245        .then(|| shared_optional_utf8_gather_plan(right_positions, right.len()))
7246        .flatten();
7247
7248    // Per-column output build is INDEPENDENT across columns and was the serial
7249    // hot phase of the join (~10.5ms of str_outer_join's reindex assembly at
7250    // n=150000, 12 Utf8 value columns). Build an ordered list of column specs
7251    // (cheap), compute each column — the O(output) `reindex_join_column_with_invented_gap`
7252    // gather / take / key-coalesce — across workers, then insert in the SAME
7253    // first-seen order (br-frankenpandas-uza04.102). Byte-identical: each output
7254    // column is the same values in the same row order, inserted in the same
7255    // left-then-right column order, so `columns`/`column_order` are unchanged.
7256    enum ColBuild<'a> {
7257        KeyCoalesce {
7258            left_key_col: &'a Column,
7259            right_key_col: &'a Column,
7260        },
7261        Reindex {
7262            col: &'a Column,
7263            positions: &'a [Option<usize>],
7264            utf8_plan: Option<&'a SharedOptionalUtf8GatherPlan>,
7265        },
7266        Take {
7267            col: &'a Column,
7268            present: &'a [usize],
7269        },
7270    }
7271    let mut jobs: Vec<(String, ColBuild<'_>)> = Vec::new();
7272    for name in left.column_names() {
7273        let col = left
7274            .columns()
7275            .get(name)
7276            .expect("left column listed in column_names must exist");
7277        if left_key_name_set.contains(name.as_str()) {
7278            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
7279                let left_key_col = left
7280                    .columns()
7281                    .get(left_on[*left_key_idx])
7282                    .expect("left key column must exist");
7283                let spec = if let Some(positions) = all_present_left_positions {
7284                    ColBuild::Take {
7285                        col: left_key_col,
7286                        present: positions,
7287                    }
7288                } else {
7289                    let right_key_col = right
7290                        .columns()
7291                        .get(right_on[*right_key_idx])
7292                        .expect("right key column must exist");
7293                    ColBuild::KeyCoalesce {
7294                        left_key_col,
7295                        right_key_col,
7296                    }
7297                };
7298                jobs.push((name.clone(), spec));
7299            } else {
7300                let spec = if let Some(positions) = all_present_left_positions {
7301                    ColBuild::Take {
7302                        col,
7303                        present: positions,
7304                    }
7305                } else {
7306                    ColBuild::Reindex {
7307                        col,
7308                        positions: left_positions,
7309                        utf8_plan: left_utf8_plan.as_ref(),
7310                    }
7311                };
7312                jobs.push((name.clone(), spec));
7313            }
7314            continue;
7315        }
7316        let spec = if let Some(positions) = all_present_left_positions {
7317            ColBuild::Take {
7318                col,
7319                present: positions,
7320            }
7321        } else {
7322            ColBuild::Reindex {
7323                col,
7324                positions: left_positions,
7325                utf8_plan: left_utf8_plan.as_ref(),
7326            }
7327        };
7328        let out_name = if right_col_names.contains(name) {
7329            apply_merge_suffix(name, suffixes.left.as_deref())
7330        } else {
7331            name.clone()
7332        };
7333        jobs.push((out_name, spec));
7334    }
7335    for name in right.column_names() {
7336        let col = right
7337            .columns()
7338            .get(name)
7339            .expect("right column listed in column_names must exist");
7340        if right_key_name_set.contains(name.as_str())
7341            && shared_name_positions.contains_key(name.as_str())
7342        {
7343            continue;
7344        }
7345        let spec = if let Some(positions) = all_present_right_positions {
7346            ColBuild::Take {
7347                col,
7348                present: positions,
7349            }
7350        } else {
7351            ColBuild::Reindex {
7352                col,
7353                positions: right_positions,
7354                utf8_plan: right_utf8_plan.as_ref(),
7355            }
7356        };
7357        let out_name = if left_col_names.contains(name) {
7358            apply_merge_suffix(name, suffixes.right.as_deref())
7359        } else {
7360            name.clone()
7361        };
7362        jobs.push((out_name, spec));
7363    }
7364
7365    let compute = |spec: &ColBuild<'_>| -> Result<Column, JoinError> {
7366        match spec {
7367            ColBuild::KeyCoalesce {
7368                left_key_col,
7369                right_key_col,
7370            } => {
7371                if let Some(column) = coalesce_temporal_i64_key_column(
7372                    left_key_col,
7373                    right_key_col,
7374                    left_positions,
7375                    right_positions,
7376                ) {
7377                    return Ok(column);
7378                }
7379                if let (Some(left_keys), Some(right_keys)) =
7380                    (left_key_col.as_i64_slice(), right_key_col.as_i64_slice())
7381                {
7382                    let mut data = Vec::with_capacity(left_positions.len());
7383                    let mut all_positions_valid = true;
7384                    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
7385                        match (*left_pos, *right_pos) {
7386                            (Some(pos), _) if pos < left_keys.len() => data.push(left_keys[pos]),
7387                            (None, Some(pos)) if pos < right_keys.len() => {
7388                                data.push(right_keys[pos])
7389                            }
7390                            _ => {
7391                                all_positions_valid = false;
7392                                break;
7393                            }
7394                        }
7395                    }
7396                    if all_positions_valid {
7397                        return Ok(Column::from_i64_values(data));
7398                    }
7399                }
7400
7401                let values = left_positions
7402                    .iter()
7403                    .zip(right_positions.iter())
7404                    .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
7405                        (Some(pos), _) => left_key_col.values()[*pos].clone(),
7406                        (None, Some(pos)) => right_key_col.values()[*pos].clone(),
7407                        (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
7408                    })
7409                    .collect::<Vec<_>>();
7410                Ok(Column::from_values(values)?)
7411            }
7412            ColBuild::Reindex {
7413                col,
7414                positions,
7415                utf8_plan,
7416            } => reindex_outer_with_shared_utf8_plan(col, positions, *utf8_plan),
7417            ColBuild::Take { col, present } => Ok(take_positions_typed(col, present)),
7418        }
7419    };
7420
7421    let worker_count = fp_columnar::cached_available_parallelism()
7422        .min(64)
7423        .min(jobs.len().max(1));
7424    let computed: Vec<Result<Column, JoinError>> = if worker_count >= 2 && jobs.len() >= 2 {
7425        let next = std::sync::atomic::AtomicUsize::new(0);
7426        let jobs_ref = &jobs;
7427        let compute_ref = &compute;
7428        let mut slots: Vec<Option<Result<Column, JoinError>>> =
7429            (0..jobs.len()).map(|_| None).collect();
7430        let parts = std::thread::scope(|scope| {
7431            let mut handles = Vec::with_capacity(worker_count);
7432            for _ in 0..worker_count {
7433                let next = &next;
7434                handles.push(scope.spawn(move || {
7435                    let mut out: Vec<(usize, Result<Column, JoinError>)> = Vec::new();
7436                    loop {
7437                        let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7438                        if i >= jobs_ref.len() {
7439                            break;
7440                        }
7441                        out.push((i, compute_ref(&jobs_ref[i].1)));
7442                    }
7443                    out
7444                }));
7445            }
7446            handles
7447                .into_iter()
7448                .map(|h| h.join().expect("join assembly worker panicked"))
7449                .collect::<Vec<_>>()
7450        });
7451        for part in parts {
7452            for (i, r) in part {
7453                slots[i] = Some(r);
7454            }
7455        }
7456        slots
7457            .into_iter()
7458            .map(|s| s.expect("every output column computed"))
7459            .collect()
7460    } else {
7461        jobs.iter().map(|(_, spec)| compute(spec)).collect()
7462    };
7463
7464    for ((out_name, _), col_res) in jobs.into_iter().zip(computed) {
7465        insert_merged_output_column(&mut columns, &mut column_order, out_name, col_res?)?;
7466    }
7467
7468    Ok(MergedDataFrame {
7469        index,
7470        columns,
7471        column_order,
7472    })
7473}
7474
7475fn build_single_key_ordered_identity_inner_merge_output(
7476    left: &fp_frame::DataFrame,
7477    right: &fp_frame::DataFrame,
7478    left_on: &[&str],
7479    right_on: &[&str],
7480    suffixes: &ResolvedMergeSuffixes,
7481) -> Result<MergedDataFrame, JoinError> {
7482    debug_assert_eq!(left_on.len(), 1);
7483    debug_assert_eq!(right_on.len(), 1);
7484    debug_assert_eq!(left_on[0], right_on[0]);
7485
7486    let n = left.len();
7487    debug_assert_eq!(n, right.len());
7488    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7489    let index = Index::new_known_unique_int64_unit_range(0, n);
7490    let mut columns = ColumnStore::new();
7491    let mut column_order: Vec<String> = Vec::new();
7492    let mut identity_positions = None;
7493
7494    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7495    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7496    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7497    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7498    let shared_key_names = left_on.iter().copied().collect::<HashSet<&str>>();
7499    let overlapping_names =
7500        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7501    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7502
7503    for name in left.column_names() {
7504        let col = left
7505            .columns()
7506            .get(name)
7507            .expect("left column listed in column_names must exist");
7508        let out_name = if left_key_name_set.contains(name.as_str()) {
7509            name.clone()
7510        } else if right_col_names.contains(name) {
7511            apply_merge_suffix(name, suffixes.left.as_deref())
7512        } else {
7513            name.clone()
7514        };
7515        let output = identity_merge_column(col, n, &mut identity_positions);
7516        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7517    }
7518
7519    for name in right.column_names() {
7520        if right_key_name_set.contains(name.as_str()) {
7521            continue;
7522        }
7523
7524        let col = right
7525            .columns()
7526            .get(name)
7527            .expect("right column listed in column_names must exist");
7528        let out_name = if left_col_names.contains(name) {
7529            apply_merge_suffix(name, suffixes.right.as_deref())
7530        } else {
7531            name.clone()
7532        };
7533        let output = identity_merge_column(col, n, &mut identity_positions);
7534        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7535    }
7536
7537    Ok(MergedDataFrame {
7538        index,
7539        columns,
7540        column_order,
7541    })
7542}
7543
7544/// Hash-free inner-join position build for two all-valid, bounded-range Int64
7545/// key columns. Replaces the `FxHashMap<&JoinKeyComponent, _>` build+probe with
7546/// a counting-sort / CSR direct-address table indexed by `key - min`.
7547///
7548/// Bit-identical to the hash path's emitted `(left_pos, right_pos)` pairs: the
7549/// hash path buckets right positions in *insertion* order (ascending position),
7550/// and this CSR fill also writes right positions in ascending-position order,
7551/// so for every left row the matched right rows are emitted in the same order;
7552/// left rows are still probed in ascending order. All-valid Int64 keys map to
7553/// `Present(IndexLabel::Int64(v))` in the hash path, whose equality is plain
7554/// `i64 ==`, so membership/equality semantics are identical. A left key outside
7555/// the right key span matches nothing in either path. Returns `None` (caller
7556/// falls back to the hash path) for non-Int64, any-missing, or wide-span keys.
7557fn dense_int64_inner_positions(
7558    left_key: &Column,
7559    right_key: &Column,
7560) -> Option<(Vec<usize>, Vec<usize>)> {
7561    let left = left_key.as_i64_slice()?;
7562    let right = right_key.as_i64_slice()?;
7563    dense_i64_inner_positions_slices(left, right)
7564}
7565
7566/// Typed single-key INNER positions for all-valid temporal columns. Datetime64
7567/// and Timedelta64 both store exact nanoseconds in `i64`; matching those raw
7568/// values is identical to matching their same-variant `IndexLabel` wrappers.
7569///
7570/// The fast path requires equal temporal dtypes and rejects NaT explicitly.
7571/// Ordered inputs validate each newly reached value while intersecting, instead
7572/// of pre-scanning both slices for NaT and strict ordering. Nullable keys
7573/// therefore fall through to the Scalar oracle, preserving its Missing-to-
7574/// Missing join behavior. Output construction still gathers the original
7575/// temporal key column, so dtype and value representation are kept.
7576fn temporal_i64_inner_positions(
7577    left_key: &Column,
7578    right_key: &Column,
7579) -> Option<(Vec<usize>, Vec<usize>)> {
7580    if !left_key.validity().all() || !right_key.validity().all() {
7581        return None;
7582    }
7583
7584    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7585        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7586            if left_tz == right_tz =>
7587        {
7588            (
7589                left_key.as_datetime64_slice()?,
7590                right_key.as_datetime64_slice()?,
7591                fp_types::Timestamp::NAT,
7592            )
7593        }
7594        (DType::Timedelta64, DType::Timedelta64) => (
7595            left_key.as_timedelta64_slice()?,
7596            right_key.as_timedelta64_slice()?,
7597            fp_types::Timedelta::NAT,
7598        ),
7599        _ => return None,
7600    };
7601    let mut left_positions = Vec::with_capacity(left.len().min(right.len()));
7602    let mut right_positions = Vec::with_capacity(left_positions.capacity());
7603    let (mut left_idx, mut right_idx) = (0usize, 0usize);
7604    let mut ordered = newly_reached_temporal_i64_value_is_strict(left, 0, nat)
7605        && newly_reached_temporal_i64_value_is_strict(right, 0, nat);
7606    while ordered && left_idx < left.len() && right_idx < right.len() {
7607        match left[left_idx].cmp(&right[right_idx]) {
7608            Ordering::Equal => {
7609                left_positions.push(left_idx);
7610                right_positions.push(right_idx);
7611                left_idx += 1;
7612                right_idx += 1;
7613                ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat)
7614                    && newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7615            }
7616            Ordering::Less => {
7617                left_idx += 1;
7618                ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat);
7619            }
7620            Ordering::Greater => {
7621                right_idx += 1;
7622                ordered = newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7623            }
7624        }
7625    }
7626    while ordered && left_idx < left.len() {
7627        left_idx += 1;
7628        ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat);
7629    }
7630    while ordered && right_idx < right.len() {
7631        right_idx += 1;
7632        ordered = newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7633    }
7634    if ordered {
7635        return Some((left_positions, right_positions));
7636    }
7637
7638    if left.contains(&nat) || right.contains(&nat) {
7639        return None;
7640    }
7641
7642    dense_i64_inner_positions_slices(left, right)
7643        .or_else(|| Some(hash_i64_inner_positions_slices(left, right)))
7644}
7645
7646/// Typed single-key LEFT positions for all-valid temporal columns. The ordered
7647/// unique case uses a two-pointer match scan; remaining shapes hash the raw
7648/// nanoseconds. Both emit left-major rows and ascending right positions per
7649/// key, exactly matching the generic Scalar planner. Nullable keys and NaT
7650/// retain that planner's Missing-key behavior by declining this path.
7651fn temporal_i64_left_positions(
7652    left_key: &Column,
7653    right_key: &Column,
7654) -> Option<OptionalJoinPositions> {
7655    if !left_key.validity().all() || !right_key.validity().all() {
7656        return None;
7657    }
7658
7659    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7660        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7661            if left_tz == right_tz =>
7662        {
7663            (
7664                left_key.as_datetime64_slice()?,
7665                right_key.as_datetime64_slice()?,
7666                fp_types::Timestamp::NAT,
7667            )
7668        }
7669        (DType::Timedelta64, DType::Timedelta64) => (
7670            left_key.as_timedelta64_slice()?,
7671            right_key.as_timedelta64_slice()?,
7672            fp_types::Timedelta::NAT,
7673        ),
7674        _ => return None,
7675    };
7676    if left.contains(&nat) || right.contains(&nat) {
7677        return None;
7678    }
7679
7680    if left.windows(2).all(|pair| pair[0] < pair[1])
7681        && right.windows(2).all(|pair| pair[0] < pair[1])
7682    {
7683        let left_positions = (0..left.len()).map(Some).collect::<Vec<_>>();
7684        let mut right_positions = Vec::with_capacity(left.len());
7685        let mut right_idx = 0usize;
7686        for &left_value in left {
7687            while right_idx < right.len() && right[right_idx] < left_value {
7688                right_idx += 1;
7689            }
7690            right_positions.push(
7691                (right_idx < right.len()
7692                    && matches!(right[right_idx].cmp(&left_value), Ordering::Equal))
7693                .then_some(right_idx),
7694            );
7695        }
7696        return Some((left_positions, right_positions));
7697    }
7698
7699    if right.is_empty() {
7700        return Some(((0..left.len()).map(Some).collect(), vec![None; left.len()]));
7701    }
7702    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
7703        right.len(),
7704        Default::default(),
7705    );
7706    for (pos, &key) in right.iter().enumerate() {
7707        right_map.entry(key).or_default().push(pos);
7708    }
7709    let mut left_positions = Vec::<Option<usize>>::with_capacity(left.len());
7710    let mut right_positions = Vec::<Option<usize>>::with_capacity(left.len());
7711    for (left_pos, &key) in left.iter().enumerate() {
7712        if let Some(matches) = right_map.get(&key) {
7713            for &right_pos in matches {
7714                left_positions.push(Some(left_pos));
7715                right_positions.push(Some(right_pos));
7716            }
7717        } else {
7718            left_positions.push(Some(left_pos));
7719            right_positions.push(None);
7720        }
7721    }
7722    Some((left_positions, right_positions))
7723}
7724
7725#[inline]
7726fn newly_reached_temporal_i64_value_is_strict(values: &[i64], idx: usize, nat: i64) -> bool {
7727    let Some(&value) = values.get(idx) else {
7728        return true;
7729    };
7730    value != nat && (idx == 0 || values[idx - 1] < value)
7731}
7732
7733/// Ordered-unique single-key RIGHT matches for all-valid temporal columns.
7734/// Datetime64 and Timedelta64 both store exact nanoseconds in `i64`, so a
7735/// monotone two-pointer scan produces the same optional left position per
7736/// right row as the generic Scalar planner without materializing either key.
7737/// Each newly reached value is validated for NaT and strict ordering during
7738/// that scan, avoiding separate input pre-scans. Nullable, NaT-bearing,
7739/// duplicate, unsorted, or mixed-dtype keys decline.
7740fn ordered_unique_temporal_i64_right_match_positions(
7741    left_key: &Column,
7742    right_key: &Column,
7743) -> Option<Vec<Option<usize>>> {
7744    if !left_key.validity().all() || !right_key.validity().all() {
7745        return None;
7746    }
7747
7748    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7749        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7750            if left_tz == right_tz =>
7751        {
7752            (
7753                left_key.as_datetime64_slice()?,
7754                right_key.as_datetime64_slice()?,
7755                fp_types::Timestamp::NAT,
7756            )
7757        }
7758        (DType::Timedelta64, DType::Timedelta64) => (
7759            left_key.as_timedelta64_slice()?,
7760            right_key.as_timedelta64_slice()?,
7761            fp_types::Timedelta::NAT,
7762        ),
7763        _ => return None,
7764    };
7765    if !newly_reached_temporal_i64_value_is_strict(left, 0, nat) {
7766        return None;
7767    }
7768
7769    let mut left_positions = Vec::with_capacity(right.len());
7770    let mut left_idx = 0usize;
7771    for (right_idx, &right_value) in right.iter().enumerate() {
7772        if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
7773            return None;
7774        }
7775        while left_idx < left.len() && left[left_idx] < right_value {
7776            left_idx += 1;
7777            if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7778                return None;
7779            }
7780        }
7781        left_positions.push(
7782            (left_idx < left.len() && matches!(left[left_idx].cmp(&right_value), Ordering::Equal))
7783                .then_some(left_idx),
7784        );
7785    }
7786    while left_idx < left.len() {
7787        left_idx += 1;
7788        if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7789            return None;
7790        }
7791    }
7792    Some(left_positions)
7793}
7794
7795/// Ordered-unique single-key OUTER union for all-valid temporal columns.
7796/// Datetime64 and Timedelta64 ordering is their raw nanosecond ordering, so a
7797/// three-way merge produces the same key-sorted optional position tapes as the
7798/// generic Scalar planner without materializing either input key for position
7799/// planning. Each newly reached value is validated for NaT and strict ordering
7800/// inside that merge, avoiding separate input pre-scans. Nullable, NaT-bearing,
7801/// duplicate, unsorted, or mixed-dtype keys decline.
7802fn ordered_unique_temporal_i64_outer_positions(
7803    left_key: &Column,
7804    right_key: &Column,
7805) -> Option<OptionalJoinPositions> {
7806    if !left_key.validity().all() || !right_key.validity().all() {
7807        return None;
7808    }
7809
7810    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7811        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7812            if left_tz == right_tz =>
7813        {
7814            (
7815                left_key.as_datetime64_slice()?,
7816                right_key.as_datetime64_slice()?,
7817                fp_types::Timestamp::NAT,
7818            )
7819        }
7820        (DType::Timedelta64, DType::Timedelta64) => (
7821            left_key.as_timedelta64_slice()?,
7822            right_key.as_timedelta64_slice()?,
7823            fp_types::Timedelta::NAT,
7824        ),
7825        _ => return None,
7826    };
7827    if !newly_reached_temporal_i64_value_is_strict(left, 0, nat)
7828        || !newly_reached_temporal_i64_value_is_strict(right, 0, nat)
7829    {
7830        return None;
7831    }
7832
7833    let capacity = left.len().saturating_add(right.len());
7834    let mut left_positions = Vec::<Option<usize>>::with_capacity(capacity);
7835    let mut right_positions = Vec::<Option<usize>>::with_capacity(capacity);
7836    let (mut left_idx, mut right_idx) = (0usize, 0usize);
7837    while left_idx < left.len() && right_idx < right.len() {
7838        match left[left_idx].cmp(&right[right_idx]) {
7839            Ordering::Equal => {
7840                left_positions.push(Some(left_idx));
7841                right_positions.push(Some(right_idx));
7842                left_idx += 1;
7843                right_idx += 1;
7844                if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat)
7845                    || !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat)
7846                {
7847                    return None;
7848                }
7849            }
7850            Ordering::Less => {
7851                left_positions.push(Some(left_idx));
7852                right_positions.push(None);
7853                left_idx += 1;
7854                if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7855                    return None;
7856                }
7857            }
7858            Ordering::Greater => {
7859                left_positions.push(None);
7860                right_positions.push(Some(right_idx));
7861                right_idx += 1;
7862                if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
7863                    return None;
7864                }
7865            }
7866        }
7867    }
7868    while left_idx < left.len() {
7869        left_positions.push(Some(left_idx));
7870        right_positions.push(None);
7871        left_idx += 1;
7872        if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7873            return None;
7874        }
7875    }
7876    while right_idx < right.len() {
7877        left_positions.push(None);
7878        right_positions.push(Some(right_idx));
7879        right_idx += 1;
7880        if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
7881            return None;
7882        }
7883    }
7884    Some((left_positions, right_positions))
7885}
7886
7887/// Core counting-sort/CSR inner-join over two `i64` key slices (see
7888/// [`dense_int64_inner_positions`]). Emits `(left_pos, right_pos)` pairs with
7889/// right positions ascending per left key, left probed ascending — matching the
7890/// hash path's bucket-insertion order. Returns `None` for a span wider than the
7891/// bounded direct-address gate so the caller falls back to hashing.
7892fn dense_i64_inner_positions_slices(
7893    left: &[i64],
7894    right: &[i64],
7895) -> Option<(Vec<usize>, Vec<usize>)> {
7896    if right.is_empty() || left.is_empty() {
7897        return Some((Vec::new(), Vec::new()));
7898    }
7899
7900    let mut min = right[0];
7901    let mut max = right[0];
7902    for &v in right {
7903        if v < min {
7904            min = v;
7905        }
7906        if v > max {
7907            max = v;
7908        }
7909    }
7910    // Bounded-span gate (mirrors the fp-columnar direct-address tally gates):
7911    // the dense table costs O(span) memory, so only take it when the span is
7912    // small in absolute terms AND relative to the build (right) side.
7913    let span = (max as i128) - (min as i128) + 1;
7914    if span > (1i128 << 24) || span > 16 * (right.len() as i128) {
7915        return None;
7916    }
7917    let range = span as usize;
7918
7919    // CSR build over the right side: counts -> exclusive-prefix offsets ->
7920    // positions filled in ascending right-position order.
7921    let mut offsets = vec![0usize; range + 1];
7922    for &v in right {
7923        offsets[(v - min) as usize + 1] += 1;
7924    }
7925    for i in 0..range {
7926        offsets[i + 1] += offsets[i];
7927    }
7928    let mut positions = vec![0usize; right.len()];
7929    let mut cursor = offsets.clone();
7930    for (pos, &v) in right.iter().enumerate() {
7931        let bucket = (v - min) as usize;
7932        positions[cursor[bucket]] = pos;
7933        cursor[bucket] += 1;
7934    }
7935
7936    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
7937    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
7938    for (left_pos, &v) in left.iter().enumerate() {
7939        if v < min || v > max {
7940            continue;
7941        }
7942        let bucket = (v - min) as usize;
7943        for &right_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
7944            left_positions.push(left_pos);
7945            right_positions.push(right_pos);
7946        }
7947    }
7948    Some((left_positions, right_positions))
7949}
7950
7951/// Hash inner-join position build for the remaining all-valid Int64 single-key
7952/// shape after ordered/dense witnesses reject. This keeps the generic hash
7953/// path's left-major probe order and right-bucket insertion order, but hashes
7954/// raw `i64` keys instead of materializing `JoinKeyComponent::Present` wrappers.
7955fn hash_int64_inner_positions(
7956    left_key: &Column,
7957    right_key: &Column,
7958) -> Option<(Vec<usize>, Vec<usize>)> {
7959    let left = left_key.as_i64_slice()?;
7960    let right = right_key.as_i64_slice()?;
7961    Some(hash_i64_inner_positions_slices(left, right))
7962}
7963
7964/// LEFT-join positions via a typed `FxHashMap<i64>` build+probe for all-valid
7965/// Int64 keys — the wide/sparse sibling of `dense_int64_left_positions` (whose
7966/// direct-address table bails on a wide key span, dropping the join to the
7967/// generic `JoinKeyComponent` Scalar-materialization path: left merge on a
7968/// wide-i64 key was 0.65x pandas). Build the right key -> ascending-position
7969/// buckets, then emit one output row per (left row, matching right row) in left
7970/// order, or a single (left, None) for an unmatched left row (null-fill).
7971/// Bit-identical to the dense/generic left path: same left iteration order, same
7972/// ascending right positions per key bucket. `None` (falls back) unless BOTH keys
7973/// are all-valid Int64 (a null-bearing key keeps the generic null-matching path).
7974fn hash_int64_left_positions(
7975    left_key: &Column,
7976    right_key: &Column,
7977) -> Option<OptionalJoinPositions> {
7978    let left = left_key.as_i64_slice()?;
7979    let right = right_key.as_i64_slice()?;
7980    if right.is_empty() {
7981        let left_positions = (0..left.len()).map(Some).collect::<Vec<_>>();
7982        let right_positions = vec![None; left.len()];
7983        return Some((left_positions, right_positions));
7984    }
7985    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
7986        right.len(),
7987        Default::default(),
7988    );
7989    for (pos, &key) in right.iter().enumerate() {
7990        right_map.entry(key).or_default().push(pos);
7991    }
7992    let mut left_positions = Vec::<Option<usize>>::with_capacity(left.len());
7993    let mut right_positions = Vec::<Option<usize>>::with_capacity(left.len());
7994    for (left_pos, &key) in left.iter().enumerate() {
7995        if let Some(matches) = right_map.get(&key) {
7996            for &right_pos in matches {
7997                left_positions.push(Some(left_pos));
7998                right_positions.push(Some(right_pos));
7999            }
8000        } else {
8001            left_positions.push(Some(left_pos));
8002            right_positions.push(None);
8003        }
8004    }
8005    Some((left_positions, right_positions))
8006}
8007
8008/// OUTER positions for wide/sparse Int64 keys. Uses a LIGHT `FxHashMap<i64,u32>`
8009/// key -> gid (first-seen) plus CSR position lists per gid — far cheaper than a
8010/// `FxHashMap<i64,(SmallVec,SmallVec)>` (whose 40-byte value dominated the build
8011/// at ~270ms). Emits per key ASCENDING (gids argsorted by key), left×right cross
8012/// product per key, else unmatched-left/right — bit-identical to
8013/// `dense_int64_outer_positions` (its key-min buckets walk keys ascending with
8014/// the same per-bucket order; the CSR scatter preserves ascending row order per
8015/// key, matching the dense per-bucket push order).
8016fn hash_int64_outer_positions(
8017    left_key: &Column,
8018    right_key: &Column,
8019) -> Option<OptionalJoinPositions> {
8020    let left = left_key.as_i64_slice()?;
8021    let right = right_key.as_i64_slice()?;
8022    let mut gid_of: FxHashMap<i64, u32> = FxHashMap::with_capacity_and_hasher(
8023        left.len().saturating_add(right.len()),
8024        Default::default(),
8025    );
8026    let mut gid_keys: Vec<i64> = Vec::new();
8027    let mut left_gid: Vec<u32> = Vec::with_capacity(left.len());
8028    for &key in left {
8029        let g = *gid_of.entry(key).or_insert_with(|| {
8030            let x = gid_keys.len() as u32;
8031            gid_keys.push(key);
8032            x
8033        });
8034        left_gid.push(g);
8035    }
8036    let mut right_gid: Vec<u32> = Vec::with_capacity(right.len());
8037    for &key in right {
8038        let g = *gid_of.entry(key).or_insert_with(|| {
8039            let x = gid_keys.len() as u32;
8040            gid_keys.push(key);
8041            x
8042        });
8043        right_gid.push(g);
8044    }
8045    let ng = gid_keys.len();
8046    // CSR offsets from per-gid counts.
8047    let mut loff = vec![0u32; ng + 1];
8048    for &g in &left_gid {
8049        loff[g as usize + 1] += 1;
8050    }
8051    let mut roff = vec![0u32; ng + 1];
8052    for &g in &right_gid {
8053        roff[g as usize + 1] += 1;
8054    }
8055    for g in 0..ng {
8056        loff[g + 1] += loff[g];
8057        roff[g + 1] += roff[g];
8058    }
8059    let mut lpos = vec![0u32; left.len()];
8060    let mut lw = loff[..ng].to_vec();
8061    for (i, &g) in left_gid.iter().enumerate() {
8062        let g = g as usize;
8063        lpos[lw[g] as usize] = i as u32;
8064        lw[g] += 1;
8065    }
8066    let mut rpos = vec![0u32; right.len()];
8067    let mut rw = roff[..ng].to_vec();
8068    for (i, &g) in right_gid.iter().enumerate() {
8069        let g = g as usize;
8070        rpos[rw[g] as usize] = i as u32;
8071        rw[g] += 1;
8072    }
8073    let mut order: Vec<u32> = (0..ng as u32).collect();
8074    order.sort_unstable_by_key(|&g| gid_keys[g as usize]);
8075    let mut left_positions = Vec::<Option<usize>>::new();
8076    let mut right_positions = Vec::<Option<usize>>::new();
8077    for &g in &order {
8078        let g = g as usize;
8079        let ls = &lpos[loff[g] as usize..loff[g + 1] as usize];
8080        let rs = &rpos[roff[g] as usize..roff[g + 1] as usize];
8081        match (ls.is_empty(), rs.is_empty()) {
8082            (false, false) => {
8083                for &l in ls {
8084                    for &r in rs {
8085                        left_positions.push(Some(l as usize));
8086                        right_positions.push(Some(r as usize));
8087                    }
8088                }
8089            }
8090            (false, true) => {
8091                for &l in ls {
8092                    left_positions.push(Some(l as usize));
8093                    right_positions.push(None);
8094                }
8095            }
8096            (true, false) => {
8097                for &r in rs {
8098                    left_positions.push(None);
8099                    right_positions.push(Some(r as usize));
8100                }
8101            }
8102            (true, true) => {}
8103        }
8104    }
8105    Some((left_positions, right_positions))
8106}
8107
8108/// Hash build+probe over raw UTF-8 byte spans for all-valid contiguous-Utf8
8109/// keys (br-frankenpandas-i388q). Mirrors the generic `JoinKeyComponent` inner
8110/// path exactly — right positions pushed ascending per key bucket, left probed
8111/// in order — but hashes `&[u8]` spans directly instead of materializing each
8112/// key column to `Vec<Scalar>` and cloning every string into a
8113/// `JoinKeyComponent::Present(IndexLabel::Utf8)` wrapper. Returns `None` unless
8114/// BOTH keys are all-valid contiguous Utf8; null-bearing keys keep the generic
8115/// path (which matches null-to-null — a case `as_utf8_contiguous` excludes).
8116fn contiguous_utf8_inner_positions(
8117    left_key: &Column,
8118    right_key: &Column,
8119) -> Option<(Vec<usize>, Vec<usize>)> {
8120    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
8121    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
8122    let left_n = left_offsets.len() - 1;
8123    let right_n = right_offsets.len() - 1;
8124    if left_n == 0 || right_n == 0 {
8125        return Some((Vec::new(), Vec::new()));
8126    }
8127
8128    if let Some(positions) =
8129        sorted_contiguous_utf8_inner_positions(left_bytes, left_offsets, right_bytes, right_offsets)
8130    {
8131        return Some(positions);
8132    }
8133
8134    let mut right_map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
8135        right_n,
8136        Default::default(),
8137    );
8138    for pos in 0..right_n {
8139        let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
8140        right_map.entry(span).or_default().push(pos);
8141    }
8142
8143    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
8144    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8145    for left_pos in 0..left_n {
8146        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8147        if let Some(matches) = right_map.get(span) {
8148            for &right_pos in matches {
8149                left_positions.push(left_pos);
8150                right_positions.push(right_pos);
8151            }
8152        }
8153    }
8154    Some((left_positions, right_positions))
8155}
8156
8157fn collect_contiguous_utf8_position_map<'a>(
8158    bytes: &'a [u8],
8159    offsets: &[usize],
8160) -> FxHashMap<&'a [u8], JoinPositionBucket> {
8161    let n = offsets.len() - 1;
8162    let mut map =
8163        FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(n, Default::default());
8164    for pos in 0..n {
8165        let span = &bytes[offsets[pos]..offsets[pos + 1]];
8166        map.entry(span).or_default().push(pos);
8167    }
8168    map
8169}
8170
8171fn contiguous_utf8_left_positions(
8172    left_key: &Column,
8173    right_key: &Column,
8174) -> Option<OptionalJoinPositions> {
8175    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
8176    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
8177    let left_n = left_offsets.len() - 1;
8178    let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
8179
8180    let mut out_len = 0usize;
8181    for left_pos in 0..left_n {
8182        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8183        out_len += right_map.get(span).map_or(1, JoinPositionBucket::len);
8184    }
8185
8186    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8187    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8188    for left_pos in 0..left_n {
8189        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8190        if let Some(matches) = right_map.get(span) {
8191            for &right_pos in matches {
8192                left_positions.push(Some(left_pos));
8193                right_positions.push(Some(right_pos));
8194            }
8195        } else {
8196            left_positions.push(Some(left_pos));
8197            right_positions.push(None);
8198        }
8199    }
8200    Some((left_positions, right_positions))
8201}
8202
8203fn contiguous_utf8_outer_positions(
8204    left_key: &Column,
8205    right_key: &Column,
8206) -> Option<OptionalJoinPositions> {
8207    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
8208    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
8209    let left_n = left_offsets.len() - 1;
8210    let right_n = right_offsets.len() - 1;
8211
8212    let left_map = collect_contiguous_utf8_position_map(left_bytes, left_offsets);
8213    let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
8214    let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
8215        left_map.len() + right_map.len(),
8216        Default::default(),
8217    );
8218    let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
8219    for pos in 0..left_n {
8220        let span = &left_bytes[left_offsets[pos]..left_offsets[pos + 1]];
8221        if seen.insert(span) {
8222            keys.push(span);
8223        }
8224    }
8225    for pos in 0..right_n {
8226        let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
8227        if seen.insert(span) {
8228            keys.push(span);
8229        }
8230    }
8231    keys.sort_unstable();
8232
8233    let mut out_len = 0usize;
8234    for &key in &keys {
8235        out_len += match (left_map.get(key), right_map.get(key)) {
8236            (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
8237            (Some(lefts), None) => lefts.len(),
8238            (None, Some(rights)) => rights.len(),
8239            (None, None) => 0,
8240        };
8241    }
8242
8243    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8244    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8245    for key in keys {
8246        match (left_map.get(key), right_map.get(key)) {
8247            (Some(lefts), Some(rights)) => {
8248                for &left_pos in lefts {
8249                    for &right_pos in rights {
8250                        left_positions.push(Some(left_pos));
8251                        right_positions.push(Some(right_pos));
8252                    }
8253                }
8254            }
8255            (Some(lefts), None) => {
8256                for &left_pos in lefts {
8257                    left_positions.push(Some(left_pos));
8258                    right_positions.push(None);
8259                }
8260            }
8261            (None, Some(rights)) => {
8262                for &right_pos in rights {
8263                    left_positions.push(None);
8264                    right_positions.push(Some(right_pos));
8265                }
8266            }
8267            (None, None) => {}
8268        }
8269    }
8270    Some((left_positions, right_positions))
8271}
8272
8273fn scalar_utf8_values(column: &Column) -> Option<&[Scalar]> {
8274    if column.dtype() != DType::Utf8 || !column.validity().all() {
8275        return None;
8276    }
8277    let values = column.values();
8278    values
8279        .iter()
8280        .all(|value| matches!(value, Scalar::Utf8(_)))
8281        .then_some(values)
8282}
8283
8284fn scalar_utf8_span(value: &Scalar) -> Option<&[u8]> {
8285    match value {
8286        Scalar::Utf8(value) => Some(value.as_bytes()),
8287        _ => None,
8288    }
8289}
8290
8291fn collect_scalar_utf8_position_map(
8292    values: &[Scalar],
8293) -> Option<FxHashMap<&[u8], JoinPositionBucket>> {
8294    let mut map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
8295        values.len(),
8296        Default::default(),
8297    );
8298    for (pos, value) in values.iter().enumerate() {
8299        map.entry(scalar_utf8_span(value)?).or_default().push(pos);
8300    }
8301    Some(map)
8302}
8303
8304fn scalar_utf8_inner_positions(
8305    left_key: &Column,
8306    right_key: &Column,
8307) -> Option<(Vec<usize>, Vec<usize>)> {
8308    let left = scalar_utf8_values(left_key)?;
8309    let right = scalar_utf8_values(right_key)?;
8310    if left.is_empty() || right.is_empty() {
8311        return Some((Vec::new(), Vec::new()));
8312    }
8313
8314    let right_map = collect_scalar_utf8_position_map(right)?;
8315    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
8316    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8317    for (left_pos, value) in left.iter().enumerate() {
8318        if let Some(matches) = right_map.get(scalar_utf8_span(value)?) {
8319            for &right_pos in matches {
8320                left_positions.push(left_pos);
8321                right_positions.push(right_pos);
8322            }
8323        }
8324    }
8325    Some((left_positions, right_positions))
8326}
8327
8328fn scalar_utf8_left_positions(
8329    left_key: &Column,
8330    right_key: &Column,
8331) -> Option<OptionalJoinPositions> {
8332    let left = scalar_utf8_values(left_key)?;
8333    let right = scalar_utf8_values(right_key)?;
8334    let right_map = collect_scalar_utf8_position_map(right)?;
8335
8336    let mut out_len = 0usize;
8337    for value in left {
8338        out_len += right_map
8339            .get(scalar_utf8_span(value)?)
8340            .map_or(1, JoinPositionBucket::len);
8341    }
8342
8343    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8344    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8345    for (left_pos, value) in left.iter().enumerate() {
8346        if let Some(matches) = right_map.get(scalar_utf8_span(value)?) {
8347            for &right_pos in matches {
8348                left_positions.push(Some(left_pos));
8349                right_positions.push(Some(right_pos));
8350            }
8351        } else {
8352            left_positions.push(Some(left_pos));
8353            right_positions.push(None);
8354        }
8355    }
8356    Some((left_positions, right_positions))
8357}
8358
8359fn scalar_utf8_outer_positions(
8360    left_key: &Column,
8361    right_key: &Column,
8362) -> Option<OptionalJoinPositions> {
8363    let left = scalar_utf8_values(left_key)?;
8364    let right = scalar_utf8_values(right_key)?;
8365    let left_map = collect_scalar_utf8_position_map(left)?;
8366    let right_map = collect_scalar_utf8_position_map(right)?;
8367
8368    let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
8369        left_map.len() + right_map.len(),
8370        Default::default(),
8371    );
8372    let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
8373    for value in left {
8374        let span = scalar_utf8_span(value)?;
8375        if seen.insert(span) {
8376            keys.push(span);
8377        }
8378    }
8379    for value in right {
8380        let span = scalar_utf8_span(value)?;
8381        if seen.insert(span) {
8382            keys.push(span);
8383        }
8384    }
8385    keys.sort_unstable();
8386
8387    let mut out_len = 0usize;
8388    for &key in &keys {
8389        out_len += match (left_map.get(key), right_map.get(key)) {
8390            (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
8391            (Some(lefts), None) => lefts.len(),
8392            (None, Some(rights)) => rights.len(),
8393            (None, None) => 0,
8394        };
8395    }
8396
8397    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8398    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8399    for key in keys {
8400        match (left_map.get(key), right_map.get(key)) {
8401            (Some(lefts), Some(rights)) => {
8402                for &left_pos in lefts {
8403                    for &right_pos in rights {
8404                        left_positions.push(Some(left_pos));
8405                        right_positions.push(Some(right_pos));
8406                    }
8407                }
8408            }
8409            (Some(lefts), None) => {
8410                for &left_pos in lefts {
8411                    left_positions.push(Some(left_pos));
8412                    right_positions.push(None);
8413                }
8414            }
8415            (None, Some(rights)) => {
8416                for &right_pos in rights {
8417                    left_positions.push(None);
8418                    right_positions.push(Some(right_pos));
8419                }
8420            }
8421            (None, None) => {}
8422        }
8423    }
8424    Some((left_positions, right_positions))
8425}
8426
8427fn hash_i64_inner_positions_slices(left: &[i64], right: &[i64]) -> (Vec<usize>, Vec<usize>) {
8428    if right.is_empty() || left.is_empty() {
8429        return (Vec::new(), Vec::new());
8430    }
8431
8432    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
8433        right.len(),
8434        Default::default(),
8435    );
8436    for (pos, &key) in right.iter().enumerate() {
8437        right_map.entry(key).or_default().push(pos);
8438    }
8439
8440    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
8441    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8442    for (left_pos, &key) in left.iter().enumerate() {
8443        if let Some(matches) = right_map.get(&key) {
8444            for &right_pos in matches {
8445                left_positions.push(left_pos);
8446                right_positions.push(right_pos);
8447            }
8448        }
8449    }
8450    (left_positions, right_positions)
8451}
8452
8453/// Hash-free inner-join positions for a MULTI-column key whose every component
8454/// is an all-valid, bounded-range Int64 column. Packs each row's composite key
8455/// into a single `i64` via a mixed-radix code over the per-column spans
8456/// (`packed = Σ_c (val_c - min_c) · stride_c`, `stride_0 = 1`, `stride_c =
8457/// stride_{c-1}·range_{c-1}`), then runs the dense CSR core on the packed keys.
8458///
8459/// The packing is a bijection on the joint key box (mins/ranges computed over
8460/// BOTH sides so left- and right-side codes are comparable), so two composite
8461/// keys collide under packing IFF every component is equal — identical to the
8462/// `CompositeJoinKey` equality the FxHashMap path uses. Pair order is therefore
8463/// byte-for-byte the same as the hash path. Returns `None` (caller falls back to
8464/// the composite-hash path) for any non-Int64 / any-missing component or when
8465/// the packed span exceeds the bounded direct-address gate.
8466/// Typed INNER/LEFT positions for a 2-column all-valid Int64 composite key that's
8467/// too WIDE for `dense_packed_int64_inner_positions` (its packed mixed-radix span
8468/// exceeds the bounded gate on a high-cardinality component), which otherwise
8469/// dropped multi-key merge to the generic `collect_composite_keys` Scalar path
8470/// (2-i64-key merge was 0.65x inner / 0.69x left pandas). Packs each row's
8471/// `(k0, k1)` into a `u128` — a bijection, so key equality is exact — builds the
8472/// right key -> ascending-position map, and probes left in order: one row per
8473/// (left, matching right), or (for Left) a single `(Some, None)` null-fill for an
8474/// unmatched left row. Bit-identical to the generic `CompositeJoinKey` path (same
8475/// left iteration + ascending-right-per-key emit). Returns `None` for non-Inner/
8476/// Left, non-2-key, or any non-all-valid-Int64 component.
8477/// Each string of an all-valid text key column (a contiguous buffer or
8478/// `Scalar::Utf8` cells) in row order; `None` for any other column.
8479fn for_each_utf8_key<'a>(column: &'a Column, mut visit: impl FnMut(&'a [u8])) -> Option<()> {
8480    if let Some((bytes, offsets)) = column.as_utf8_contiguous() {
8481        for bounds in offsets.windows(2) {
8482            visit(&bytes[bounds[0]..bounds[1]]);
8483        }
8484        return Some(());
8485    }
8486    for value in scalar_utf8_values(column)? {
8487        visit(scalar_utf8_span(value)?);
8488    }
8489    Some(())
8490}
8491
8492/// A text key pair of a merge as int64 codes over one dictionary of both
8493/// sides' strings, a string numbered as its first row is met (the left's
8494/// rows first): two rows' strings are equal exactly when their codes are.
8495/// `None` unless both sides are all-valid text.
8496fn utf8_key_pair_codes<'a>(left: &'a Column, right: &'a Column) -> Option<(Column, Column)> {
8497    if left.dtype() != DType::Utf8 || right.dtype() != DType::Utf8 {
8498        return None;
8499    }
8500    let mut codes: FxHashMap<&'a [u8], i64> = FxHashMap::default();
8501    let mut code = |span: &'a [u8]| {
8502        let next = codes.len() as i64;
8503        *codes.entry(span).or_insert(next)
8504    };
8505    let mut left_codes = Vec::with_capacity(left.len());
8506    for_each_utf8_key(left, |span| left_codes.push(code(span)))?;
8507    let mut right_codes = Vec::with_capacity(right.len());
8508    for_each_utf8_key(right, |span| right_codes.push(code(span)))?;
8509    Some((
8510        Column::from_i64_values_owned(left_codes),
8511        Column::from_i64_values_owned(right_codes),
8512    ))
8513}
8514
8515fn typed_wide_two_i64_key_positions(
8516    join_type: JoinType,
8517    left_cols: &[&Column],
8518    right_cols: &[&Column],
8519) -> Option<MergeRowPositions> {
8520    if !matches!(
8521        join_type,
8522        JoinType::Inner | JoinType::Left | JoinType::Outer
8523    ) {
8524        return None;
8525    }
8526    if left_cols.len() != 2 || right_cols.len() != 2 {
8527        return None;
8528    }
8529    let l0 = left_cols[0].as_i64_slice()?;
8530    let l1 = left_cols[1].as_i64_slice()?;
8531    let r0 = right_cols[0].as_i64_slice()?;
8532    let r1 = right_cols[1].as_i64_slice()?;
8533    let pack = |a: i64, b: i64| -> u128 { (u128::from(a as u64) << 64) | u128::from(b as u64) };
8534
8535    if matches!(join_type, JoinType::Outer) {
8536        // OUTER: gid-factorize the u128 composite, CSR the per-gid positions, then
8537        // emit key-ASCENDING by the SEMANTIC (i64, i64) tuple (decoded from the
8538        // packed key — u128 order would mis-sort negatives). The typed branch
8539        // returns positions directly (the generic in-block sort is bypassed), so
8540        // they must arrive pre-sorted, matching sort_merge_rows_by_join_keys.
8541        let mut gid_of: FxHashMap<u128, u32> = FxHashMap::with_capacity_and_hasher(
8542            l0.len().saturating_add(r0.len()),
8543            Default::default(),
8544        );
8545        let mut gid_keys: Vec<u128> = Vec::new();
8546        let mut left_gid: Vec<u32> = Vec::with_capacity(l0.len());
8547        for pos in 0..l0.len() {
8548            let key = pack(l0[pos], l1[pos]);
8549            let g = *gid_of.entry(key).or_insert_with(|| {
8550                let x = gid_keys.len() as u32;
8551                gid_keys.push(key);
8552                x
8553            });
8554            left_gid.push(g);
8555        }
8556        let mut right_gid: Vec<u32> = Vec::with_capacity(r0.len());
8557        for pos in 0..r0.len() {
8558            let key = pack(r0[pos], r1[pos]);
8559            let g = *gid_of.entry(key).or_insert_with(|| {
8560                let x = gid_keys.len() as u32;
8561                gid_keys.push(key);
8562                x
8563            });
8564            right_gid.push(g);
8565        }
8566        let ng = gid_keys.len();
8567        let mut loff = vec![0u32; ng + 1];
8568        for &g in &left_gid {
8569            loff[g as usize + 1] += 1;
8570        }
8571        let mut roff = vec![0u32; ng + 1];
8572        for &g in &right_gid {
8573            roff[g as usize + 1] += 1;
8574        }
8575        for g in 0..ng {
8576            loff[g + 1] += loff[g];
8577            roff[g + 1] += roff[g];
8578        }
8579        let mut lpos = vec![0u32; l0.len()];
8580        let mut lw = loff[..ng].to_vec();
8581        for (i, &g) in left_gid.iter().enumerate() {
8582            let g = g as usize;
8583            lpos[lw[g] as usize] = i as u32;
8584            lw[g] += 1;
8585        }
8586        let mut rpos = vec![0u32; r0.len()];
8587        let mut rw = roff[..ng].to_vec();
8588        for (i, &g) in right_gid.iter().enumerate() {
8589            let g = g as usize;
8590            rpos[rw[g] as usize] = i as u32;
8591            rw[g] += 1;
8592        }
8593        // Argsort gids by the SEMANTIC (i64, i64) key (hi = k0, lo = k1).
8594        let decode = |packed: u128| -> (i64, i64) {
8595            (((packed >> 64) as u64) as i64, (packed as u64) as i64)
8596        };
8597        let mut order: Vec<u32> = (0..ng as u32).collect();
8598        order.sort_unstable_by_key(|&g| decode(gid_keys[g as usize]));
8599        let mut left_positions = Vec::<Option<usize>>::new();
8600        let mut right_positions = Vec::<Option<usize>>::new();
8601        for &g in &order {
8602            let g = g as usize;
8603            let ls = &lpos[loff[g] as usize..loff[g + 1] as usize];
8604            let rs = &rpos[roff[g] as usize..roff[g + 1] as usize];
8605            match (ls.is_empty(), rs.is_empty()) {
8606                (false, false) => {
8607                    for &l in ls {
8608                        for &r in rs {
8609                            left_positions.push(Some(l as usize));
8610                            right_positions.push(Some(r as usize));
8611                        }
8612                    }
8613                }
8614                (false, true) => {
8615                    for &l in ls {
8616                        left_positions.push(Some(l as usize));
8617                        right_positions.push(None);
8618                    }
8619                }
8620                (true, false) => {
8621                    for &r in rs {
8622                        left_positions.push(None);
8623                        right_positions.push(Some(r as usize));
8624                    }
8625                }
8626                (true, true) => {}
8627            }
8628        }
8629        return Some((left_positions, right_positions, None));
8630    }
8631
8632    // Inner / Left: right key -> ascending-position map, probe left in order.
8633    let mut right_map = FxHashMap::<u128, JoinPositionBucket>::with_capacity_and_hasher(
8634        r0.len(),
8635        Default::default(),
8636    );
8637    for pos in 0..r0.len() {
8638        right_map
8639            .entry(pack(r0[pos], r1[pos]))
8640            .or_default()
8641            .push(pos);
8642    }
8643    let is_left = matches!(join_type, JoinType::Left);
8644    let mut left_positions = Vec::<Option<usize>>::new();
8645    let mut right_positions = Vec::<Option<usize>>::new();
8646    for left_pos in 0..l0.len() {
8647        let key = pack(l0[left_pos], l1[left_pos]);
8648        if let Some(matches) = right_map.get(&key) {
8649            for &right_pos in matches {
8650                left_positions.push(Some(left_pos));
8651                right_positions.push(Some(right_pos));
8652            }
8653        } else if is_left {
8654            left_positions.push(Some(left_pos));
8655            right_positions.push(None);
8656        }
8657    }
8658    Some((left_positions, right_positions, None))
8659}
8660
8661/// General K-key (K >= 3) sibling of `typed_wide_two_i64_key_positions` for wide
8662/// Int64 key columns that overflow `dense_packed_int64_inner_positions` and exceed
8663/// the 2-key u128 packer. Factorizes each key column over left ∪ right into dense
8664/// gids (first-seen), then packs each row's per-column gids into a single u128
8665/// (column 0 most-significant) — a bijection whenever the summed gid bit-widths
8666/// fit 127 bits (else `None` → generic Scalar composite path). With the composite
8667/// as one integer, this reuses the exact same inner/left/outer emit as the 2-key
8668/// path. OUTER argsorts groups by the SEMANTIC original (i64,..,i64) tuple captured
8669/// at gid creation (packed-gid order is first-seen, not sorted). Bit-identical to
8670/// the `CompositeJoinKey` path (same left-order probe + ascending-right-per-key emit
8671/// for inner/left; same key-ascending group emit for outer). Returns `None` for
8672/// non-Inner/Left/Outer, K < 3, unequal K, any non-all-valid-Int64 component, or a
8673/// composite too wide for u128.
8674fn typed_wide_multi_i64_key_positions(
8675    join_type: JoinType,
8676    left_cols: &[&Column],
8677    right_cols: &[&Column],
8678) -> Option<MergeRowPositions> {
8679    if !matches!(
8680        join_type,
8681        JoinType::Inner | JoinType::Left | JoinType::Outer
8682    ) {
8683        return None;
8684    }
8685    let k = left_cols.len();
8686    if k < 3 || right_cols.len() != k {
8687        return None;
8688    }
8689    let mut ls: Vec<&[i64]> = Vec::with_capacity(k);
8690    let mut rs: Vec<&[i64]> = Vec::with_capacity(k);
8691    for c in 0..k {
8692        ls.push(left_cols[c].as_i64_slice()?);
8693        rs.push(right_cols[c].as_i64_slice()?);
8694    }
8695    let nl = ls[0].len();
8696    let nr = rs[0].len();
8697    if ls.iter().any(|s| s.len() != nl) || rs.iter().any(|s| s.len() != nr) {
8698        return None;
8699    }
8700
8701    // Factorize each key column over left ∪ right into dense first-seen gids.
8702    let mut lgid: Vec<Vec<u32>> = Vec::with_capacity(k);
8703    let mut rgid: Vec<Vec<u32>> = Vec::with_capacity(k);
8704    let mut cards: Vec<u64> = Vec::with_capacity(k);
8705    for c in 0..k {
8706        let mut m: FxHashMap<i64, u32> =
8707            FxHashMap::with_capacity_and_hasher(nl + nr, Default::default());
8708        let mut next: u32 = 0;
8709        let mut lg = Vec::with_capacity(nl);
8710        for &v in ls[c] {
8711            let g = *m.entry(v).or_insert_with(|| {
8712                let x = next;
8713                next += 1;
8714                x
8715            });
8716            lg.push(g);
8717        }
8718        let mut rg = Vec::with_capacity(nr);
8719        for &v in rs[c] {
8720            let g = *m.entry(v).or_insert_with(|| {
8721                let x = next;
8722                next += 1;
8723                x
8724            });
8725            rg.push(g);
8726        }
8727        cards.push(next as u64);
8728        lgid.push(lg);
8729        rgid.push(rg);
8730    }
8731
8732    // Per-column bit widths; bail if the packed composite exceeds u128.
8733    let mut bits: Vec<u32> = Vec::with_capacity(k);
8734    let mut total: u32 = 0;
8735    for &card in &cards {
8736        let b = if card <= 1 {
8737            0
8738        } else {
8739            64 - (card - 1).leading_zeros()
8740        };
8741        bits.push(b);
8742        total += b;
8743    }
8744    if total > 127 {
8745        return None;
8746    }
8747
8748    let pack = |gids: &[Vec<u32>], row: usize| -> u128 {
8749        let mut p: u128 = 0;
8750        for c in 0..k {
8751            p = (p << bits[c]) | u128::from(gids[c][row]);
8752        }
8753        p
8754    };
8755
8756    if matches!(join_type, JoinType::Outer) {
8757        let mut gid_of: FxHashMap<u128, u32> =
8758            FxHashMap::with_capacity_and_hasher(nl.saturating_add(nr), Default::default());
8759        // Semantic original tuple per composite gid (for the key-ascending sort).
8760        let mut gid_tuple: Vec<Vec<i64>> = Vec::new();
8761        let mut left_g: Vec<u32> = Vec::with_capacity(nl);
8762        for (row, _) in ls[0].iter().enumerate().take(nl) {
8763            let key = pack(&lgid, row);
8764            let g = *gid_of.entry(key).or_insert_with(|| {
8765                let x = gid_tuple.len() as u32;
8766                gid_tuple.push((0..k).map(|c| ls[c][row]).collect());
8767                x
8768            });
8769            left_g.push(g);
8770        }
8771        let mut right_g: Vec<u32> = Vec::with_capacity(nr);
8772        for (row, _) in rs[0].iter().enumerate().take(nr) {
8773            let key = pack(&rgid, row);
8774            let g = *gid_of.entry(key).or_insert_with(|| {
8775                let x = gid_tuple.len() as u32;
8776                gid_tuple.push((0..k).map(|c| rs[c][row]).collect());
8777                x
8778            });
8779            right_g.push(g);
8780        }
8781        let ng = gid_tuple.len();
8782        let mut loff = vec![0u32; ng + 1];
8783        for &g in &left_g {
8784            loff[g as usize + 1] += 1;
8785        }
8786        let mut roff = vec![0u32; ng + 1];
8787        for &g in &right_g {
8788            roff[g as usize + 1] += 1;
8789        }
8790        for g in 0..ng {
8791            loff[g + 1] += loff[g];
8792            roff[g + 1] += roff[g];
8793        }
8794        let mut lpos = vec![0u32; nl];
8795        let mut lw = loff[..ng].to_vec();
8796        for (i, &g) in left_g.iter().enumerate() {
8797            let g = g as usize;
8798            lpos[lw[g] as usize] = i as u32;
8799            lw[g] += 1;
8800        }
8801        let mut rpos = vec![0u32; nr];
8802        let mut rw = roff[..ng].to_vec();
8803        for (i, &g) in right_g.iter().enumerate() {
8804            let g = g as usize;
8805            rpos[rw[g] as usize] = i as u32;
8806            rw[g] += 1;
8807        }
8808        let mut order: Vec<u32> = (0..ng as u32).collect();
8809        order.sort_unstable_by(|&a, &b| gid_tuple[a as usize].cmp(&gid_tuple[b as usize]));
8810        let mut left_positions = Vec::<Option<usize>>::new();
8811        let mut right_positions = Vec::<Option<usize>>::new();
8812        for &g in &order {
8813            let g = g as usize;
8814            let lsl = &lpos[loff[g] as usize..loff[g + 1] as usize];
8815            let rsl = &rpos[roff[g] as usize..roff[g + 1] as usize];
8816            match (lsl.is_empty(), rsl.is_empty()) {
8817                (false, false) => {
8818                    for &l in lsl {
8819                        for &r in rsl {
8820                            left_positions.push(Some(l as usize));
8821                            right_positions.push(Some(r as usize));
8822                        }
8823                    }
8824                }
8825                (false, true) => {
8826                    for &l in lsl {
8827                        left_positions.push(Some(l as usize));
8828                        right_positions.push(None);
8829                    }
8830                }
8831                (true, false) => {
8832                    for &r in rsl {
8833                        left_positions.push(None);
8834                        right_positions.push(Some(r as usize));
8835                    }
8836                }
8837                (true, true) => {}
8838            }
8839        }
8840        return Some((left_positions, right_positions, None));
8841    }
8842
8843    // Inner / Left: right composite -> ascending-position map, probe left in order.
8844    let mut right_map =
8845        FxHashMap::<u128, JoinPositionBucket>::with_capacity_and_hasher(nr, Default::default());
8846    for pos in 0..nr {
8847        right_map.entry(pack(&rgid, pos)).or_default().push(pos);
8848    }
8849    let is_left = matches!(join_type, JoinType::Left);
8850    let mut left_positions = Vec::<Option<usize>>::new();
8851    let mut right_positions = Vec::<Option<usize>>::new();
8852    for left_pos in 0..nl {
8853        let key = pack(&lgid, left_pos);
8854        if let Some(matches) = right_map.get(&key) {
8855            for &right_pos in matches {
8856                left_positions.push(Some(left_pos));
8857                right_positions.push(Some(right_pos));
8858            }
8859        } else if is_left {
8860            left_positions.push(Some(left_pos));
8861            right_positions.push(None);
8862        }
8863    }
8864    Some((left_positions, right_positions, None))
8865}
8866
8867/// K-key (K >= 3) INNER/LEFT positions for all-valid BOUNDED-range Int64 keys
8868/// whose joint mixed-radix span fits an `i64` — even when that span exceeds the
8869/// direct-address gate of `dense_packed_int64_inner_positions` (2^24). Packs each
8870/// row's composite into one `i64` (`Σ_c (val_c - min_c)·stride_c`, `stride_0 = 1`,
8871/// `stride_c = stride_{c-1}·range_{c-1}`; a bijection on the joint key box, so
8872/// composite equality IFF every component equal) and runs the SINGLE-key i64 hash
8873/// merge on it — skipping the K per-column factorization `FxHashMap`s that
8874/// `typed_wide_multi_i64_key_positions` builds (the khash-floor cost that left
8875/// 3-key merge at 0.43-0.57x pandas). Bit-identical to that path / the generic
8876/// Scalar composite path: same left iteration order, same ascending right position
8877/// per composite bucket, same unmatched-left null-fill. Returns `None` (caller
8878/// falls back to the factorize path) unless every key is an all-valid Int64 slice
8879/// and the joint span fits `i64` — Outer bails (its key-ascending emit is handled
8880/// by the factorize path's semantic gid sort).
8881fn bounded_composite_multi_i64_key_positions(
8882    join_type: JoinType,
8883    left_cols: &[&Column],
8884    right_cols: &[&Column],
8885) -> Option<MergeRowPositions> {
8886    if !matches!(join_type, JoinType::Inner | JoinType::Left) {
8887        return None;
8888    }
8889    let k = left_cols.len();
8890    if k < 3 || right_cols.len() != k {
8891        return None;
8892    }
8893    let mut ls: Vec<&[i64]> = Vec::with_capacity(k);
8894    let mut rs: Vec<&[i64]> = Vec::with_capacity(k);
8895    for c in 0..k {
8896        ls.push(left_cols[c].as_i64_slice()?);
8897        rs.push(right_cols[c].as_i64_slice()?);
8898    }
8899    let nl = ls[0].len();
8900    let nr = rs[0].len();
8901    if ls.iter().any(|s| s.len() != nl) || rs.iter().any(|s| s.len() != nr) {
8902        return None;
8903    }
8904    if nl == 0 || nr == 0 {
8905        // Let the generic/factorize path handle degenerate empties (its
8906        // left-null-fill / empty-output shape is already validated there).
8907        return None;
8908    }
8909
8910    // Per-column min + span over left ∪ right; bail if the joint mixed-radix
8911    // product overflows i64 (a truly wide key keeps the factorize path).
8912    let mut mins = vec![0i64; k];
8913    let mut ranges = vec![0u128; k];
8914    for c in 0..k {
8915        let mut mn = i64::MAX;
8916        let mut mx = i64::MIN;
8917        for &v in ls[c] {
8918            if v < mn {
8919                mn = v;
8920            }
8921            if v > mx {
8922                mx = v;
8923            }
8924        }
8925        for &v in rs[c] {
8926            if v < mn {
8927                mn = v;
8928            }
8929            if v > mx {
8930                mx = v;
8931            }
8932        }
8933        mins[c] = mn;
8934        ranges[c] = (mx as i128 - mn as i128 + 1) as u128;
8935    }
8936    // strides[0] = 1, strides[c] = strides[c-1] * ranges[c-1]; bail on overflow.
8937    let mut strides = vec![1i64; k];
8938    let mut acc: u128 = 1;
8939    for c in 0..k {
8940        strides[c] = acc as i64;
8941        acc = acc.checked_mul(ranges[c])?;
8942        if acc > i64::MAX as u128 {
8943            return None;
8944        }
8945    }
8946    let comp = |s: &[&[i64]], row: usize| -> i64 {
8947        let mut p: i64 = 0;
8948        for c in 0..k {
8949            // (val - min) < range_c and range product fits i64 ⇒ no overflow.
8950            p += (s[c][row] - mins[c]) * strides[c];
8951        }
8952        p
8953    };
8954    let lcomp: Vec<i64> = (0..nl).map(|r| comp(&ls, r)).collect();
8955    let rcomp: Vec<i64> = (0..nr).map(|r| comp(&rs, r)).collect();
8956
8957    if matches!(join_type, JoinType::Inner) {
8958        let (lp, rp) = hash_i64_inner_positions_slices(&lcomp, &rcomp);
8959        return Some((
8960            lp.into_iter().map(Some).collect(),
8961            rp.into_iter().map(Some).collect(),
8962            None,
8963        ));
8964    }
8965
8966    // LEFT: right composite -> ascending-position buckets, probe left in order
8967    // (mirror of hash_int64_left_positions on the composite slices).
8968    let mut right_map =
8969        FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(nr, Default::default());
8970    for (pos, &key) in rcomp.iter().enumerate() {
8971        right_map.entry(key).or_default().push(pos);
8972    }
8973    let mut left_positions = Vec::<Option<usize>>::with_capacity(nl);
8974    let mut right_positions = Vec::<Option<usize>>::with_capacity(nl);
8975    for (left_pos, &key) in lcomp.iter().enumerate() {
8976        if let Some(matches) = right_map.get(&key) {
8977            for &right_pos in matches {
8978                left_positions.push(Some(left_pos));
8979                right_positions.push(Some(right_pos));
8980            }
8981        } else {
8982            left_positions.push(Some(left_pos));
8983            right_positions.push(None);
8984        }
8985    }
8986    Some((left_positions, right_positions, None))
8987}
8988
8989fn dense_packed_int64_inner_positions(
8990    left_cols: &[&Column],
8991    right_cols: &[&Column],
8992) -> Option<(Vec<usize>, Vec<usize>)> {
8993    let k = left_cols.len();
8994    if k == 0 || k != right_cols.len() {
8995        return None;
8996    }
8997
8998    let left_slices: Vec<&[i64]> = left_cols
8999        .iter()
9000        .map(|c| c.as_i64_slice())
9001        .collect::<Option<Vec<_>>>()?;
9002    let right_slices: Vec<&[i64]> = right_cols
9003        .iter()
9004        .map(|c| c.as_i64_slice())
9005        .collect::<Option<Vec<_>>>()?;
9006
9007    let n_left = left_slices[0].len();
9008    let n_right = right_slices[0].len();
9009    if n_left == 0 || n_right == 0 {
9010        return Some((Vec::new(), Vec::new()));
9011    }
9012
9013    // Per-column min and span over BOTH sides; product = joint packed span.
9014    let mut mins = vec![0i64; k];
9015    let mut strides = vec![1i128; k];
9016    let mut total: i128 = 1;
9017    for c in 0..k {
9018        let mut mn = right_slices[c][0];
9019        let mut mx = right_slices[c][0];
9020        for &v in left_slices[c].iter().chain(right_slices[c].iter()) {
9021            if v < mn {
9022                mn = v;
9023            }
9024            if v > mx {
9025                mx = v;
9026            }
9027        }
9028        mins[c] = mn;
9029        let range = (mx as i128) - (mn as i128) + 1;
9030        strides[c] = total;
9031        total = total.checked_mul(range)?;
9032        // Gate the packed span the same way the single-key core does, up front
9033        // (the product can overflow the bounded table for wide multi-keys).
9034        if total > (1i128 << 24) {
9035            return None;
9036        }
9037    }
9038    if total > 16 * ((n_left + n_right) as i128) {
9039        return None;
9040    }
9041
9042    let pack = |slices: &[&[i64]], n: usize| -> Vec<i64> {
9043        (0..n)
9044            .map(|row| {
9045                let mut acc: i128 = 0;
9046                for c in 0..k {
9047                    acc += ((slices[c][row] as i128) - (mins[c] as i128)) * strides[c];
9048                }
9049                acc as i64
9050            })
9051            .collect()
9052    };
9053    let packed_left = pack(&left_slices, n_left);
9054    let packed_right = pack(&right_slices, n_right);
9055
9056    dense_i64_inner_positions_slices(&packed_left, &packed_right)
9057}
9058
9059fn merge_single_key_inner_unsorted(
9060    left: &fp_frame::DataFrame,
9061    right: &fp_frame::DataFrame,
9062    left_on: &[&str],
9063    right_on: &[&str],
9064    left_key_columns: &[&Column],
9065    right_key_columns: &[&Column],
9066    suffixes: &ResolvedMergeSuffixes,
9067) -> Result<MergedDataFrame, JoinError> {
9068    debug_assert_eq!(left_key_columns.len(), 1);
9069    debug_assert_eq!(right_key_columns.len(), 1);
9070
9071    if left_on[0] == right_on[0]
9072        && ordered_identity_int64_keys_match(left_key_columns[0], right_key_columns[0])
9073    {
9074        return build_single_key_ordered_identity_inner_merge_output(
9075            left, right, left_on, right_on, suffixes,
9076        );
9077    }
9078    if let Some(merged) = build_single_key_affine_i64_inner_merge_output(
9079        left,
9080        right,
9081        left_on,
9082        right_on,
9083        left_key_columns[0],
9084        right_key_columns[0],
9085        suffixes,
9086    )? {
9087        return Ok(merged);
9088    }
9089    if let Some((left_positions, right_positions)) =
9090        ordered_unique_int64_inner_positions(left_key_columns[0], right_key_columns[0])
9091    {
9092        return build_single_key_inner_merge_output(
9093            left,
9094            right,
9095            left_on,
9096            right_on,
9097            &left_positions,
9098            &right_positions,
9099            suffixes,
9100        );
9101    }
9102
9103    if let Some(merged) = build_single_key_dense_i64_inner_merge_output(
9104        left,
9105        right,
9106        left_on,
9107        right_on,
9108        left_key_columns[0],
9109        right_key_columns[0],
9110        FusedInt64MergeOptions {
9111            suffixes,
9112            require_all_left_keys_matched: false,
9113        },
9114    )? {
9115        return Ok(merged);
9116    }
9117
9118    // Datetime64/Timedelta64 keys are physically i64 nanoseconds. For the
9119    // all-valid, same-dtype case, plan positions directly over that backing
9120    // instead of materializing one Scalar + JoinKeyComponent per row. Nullable
9121    // temporal keys deliberately keep the generic path below, where NaT joins
9122    // use the existing Missing-key semantics.
9123    if let Some((left_positions, right_positions)) =
9124        temporal_i64_inner_positions(left_key_columns[0], right_key_columns[0])
9125    {
9126        return build_single_key_inner_merge_output(
9127            left,
9128            right,
9129            left_on,
9130            right_on,
9131            &left_positions,
9132            &right_positions,
9133            suffixes,
9134        );
9135    }
9136
9137    // Hash-free dense direct-address build+probe for bounded all-valid Int64
9138    // keys (the common low-cardinality join-key shape). Bit-identical pairs.
9139    if let Some((left_positions, right_positions)) =
9140        dense_int64_inner_positions(left_key_columns[0], right_key_columns[0])
9141    {
9142        return build_single_key_inner_merge_output(
9143            left,
9144            right,
9145            left_on,
9146            right_on,
9147            &left_positions,
9148            &right_positions,
9149            suffixes,
9150        );
9151    }
9152    if let Some((left_positions, right_positions)) =
9153        hash_int64_inner_positions(left_key_columns[0], right_key_columns[0])
9154    {
9155        return build_single_key_inner_merge_output(
9156            left,
9157            right,
9158            left_on,
9159            right_on,
9160            &left_positions,
9161            &right_positions,
9162            suffixes,
9163        );
9164    }
9165
9166    if let Some(position_plan) =
9167        ordered_unique_utf8_inner_position_plan(left_key_columns[0], right_key_columns[0])
9168    {
9169        return match position_plan {
9170            InnerPositionPlan::Gather {
9171                left_positions,
9172                right_positions,
9173            } => build_single_key_inner_merge_output(
9174                left,
9175                right,
9176                left_on,
9177                right_on,
9178                &left_positions,
9179                &right_positions,
9180                suffixes,
9181            ),
9182            InnerPositionPlan::ContiguousRanges {
9183                left_start,
9184                right_start,
9185                len,
9186            } => build_single_key_inner_merge_output_with_selections(
9187                left,
9188                right,
9189                left_on,
9190                right_on,
9191                PositionSelection::ContiguousRange {
9192                    start: left_start,
9193                    len,
9194                },
9195                PositionSelection::ContiguousRange {
9196                    start: right_start,
9197                    len,
9198                },
9199                suffixes,
9200            ),
9201        };
9202    }
9203
9204    // Byte-span build+probe for all-valid contiguous-Utf8 string keys
9205    // (br-frankenpandas-i388q): skips the per-row String clone + Scalar
9206    // materialization of the JoinKeyComponent path. Same pairing -> same output.
9207    if let Some((left_positions, right_positions)) =
9208        contiguous_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
9209    {
9210        return build_single_key_inner_merge_output(
9211            left,
9212            right,
9213            left_on,
9214            right_on,
9215            &left_positions,
9216            &right_positions,
9217            suffixes,
9218        );
9219    }
9220    if let Some((left_positions, right_positions)) =
9221        scalar_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
9222    {
9223        return build_single_key_inner_merge_output(
9224            left,
9225            right,
9226            left_on,
9227            right_on,
9228            &left_positions,
9229            &right_positions,
9230            suffixes,
9231        );
9232    }
9233
9234    let left_keys = collect_single_join_keys(left_key_columns[0]);
9235    let right_keys = collect_single_join_keys(right_key_columns[0]);
9236    let mut right_map =
9237        FxHashMap::<&JoinKeyComponent, JoinPositionBucket>::with_capacity_and_hasher(
9238            right_keys.len(),
9239            Default::default(),
9240        );
9241    for (pos, key) in right_keys.iter().enumerate() {
9242        right_map.entry(key).or_default().push(pos);
9243    }
9244
9245    let mut left_positions = Vec::<usize>::with_capacity(left_keys.len().min(right_keys.len()));
9246    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
9247    for (left_pos, key) in left_keys.iter().enumerate() {
9248        if let Some(matches) = right_map.get(key) {
9249            for &right_pos in matches {
9250                left_positions.push(left_pos);
9251                right_positions.push(right_pos);
9252            }
9253        }
9254    }
9255
9256    build_single_key_inner_merge_output(
9257        left,
9258        right,
9259        left_on,
9260        right_on,
9261        &left_positions,
9262        &right_positions,
9263        suffixes,
9264    )
9265}
9266
9267/// Merge two DataFrames on one or more key columns.
9268///
9269/// Matches `pd.merge(left, right, left_on=left_keys, right_on=right_keys, how=join_type)`.
9270/// - Key columns are used for matching rows (hash join).
9271/// - Non-key columns are carried through and reindexed.
9272/// - Column name conflicts use configurable suffixes (default `_x`/`_y`).
9273/// - The output index is auto-generated (0..n RangeIndex-style).
9274pub fn merge_dataframes_on_with(
9275    left: &fp_frame::DataFrame,
9276    right: &fp_frame::DataFrame,
9277    left_on: &[&str],
9278    right_on: &[&str],
9279    join_type: JoinType,
9280) -> Result<MergedDataFrame, JoinError> {
9281    merge_dataframes_on_with_options(
9282        left,
9283        right,
9284        left_on,
9285        right_on,
9286        join_type,
9287        MergeExecutionOptions::default(),
9288    )
9289}
9290
9291/// Merge two DataFrames on one or more key columns with execution options.
9292pub fn merge_dataframes_on_with_options(
9293    left: &fp_frame::DataFrame,
9294    right: &fp_frame::DataFrame,
9295    left_on: &[&str],
9296    right_on: &[&str],
9297    join_type: JoinType,
9298    options: MergeExecutionOptions,
9299) -> Result<MergedDataFrame, JoinError> {
9300    let suffixes = resolve_merge_suffixes(options.suffixes.clone());
9301    let indicator_name = resolve_merge_indicator_name(options.indicator_name.as_deref())?;
9302    // A column key a side repeats (['a', 'a']; not a join key) rides through
9303    // the merge under stand-in keys and comes back under its own name, each
9304    // column its own - by name every copy read the first column (i17d4). A
9305    // name the other side also has takes each side's suffix, as pandas'
9306    // (a_x, a_x beside a_y).
9307    let left_stand_in = stand_in_repeated_keys(left, left_on, 'l')?;
9308    let right_stand_in = stand_in_repeated_keys(right, right_on, 'r')?;
9309    let merged = merge_dataframes_on_with_options_storage(
9310        left_stand_in.as_ref().map_or(left, |(frame, _)| frame),
9311        right_stand_in.as_ref().map_or(right, |(frame, _)| frame),
9312        left_on,
9313        right_on,
9314        join_type,
9315        options,
9316    )?;
9317    let merged = keeping_source_widths(
9318        merged,
9319        left,
9320        right,
9321        left_on,
9322        right_on,
9323        join_type,
9324        indicator_name.as_deref(),
9325    )?;
9326    let suffixed = |name: &str, suffix: Option<&String>| {
9327        format!("{name}{}", suffix.map_or("", String::as_str))
9328    };
9329    let mut restored: FxHashMap<String, String> = FxHashMap::default();
9330    for (stand_in, own_suffix, other, other_on, other_suffix) in [
9331        (
9332            &left_stand_in,
9333            suffixes.left.as_ref(),
9334            right,
9335            right_on,
9336            suffixes.right.as_ref(),
9337        ),
9338        (
9339            &right_stand_in,
9340            suffixes.right.as_ref(),
9341            left,
9342            left_on,
9343            suffixes.left.as_ref(),
9344        ),
9345    ] {
9346        for (key, name) in stand_in.iter().flat_map(|(_, names)| names) {
9347            if other.column_occurrences(name) == 0 || other_on.contains(&name.as_str()) {
9348                restored.insert(key.clone(), name.clone());
9349                continue;
9350            }
9351            restored.insert(key.clone(), suffixed(name, own_suffix));
9352            // The other side's own (not stood-in) copy keeps its name in the
9353            // merge: it takes that side's suffix.
9354            restored
9355                .entry(name.clone())
9356                .or_insert_with(|| suffixed(name, other_suffix));
9357        }
9358    }
9359    let merged = if restored.is_empty() {
9360        merged
9361    } else {
9362        let restore = |name: &str| {
9363            restored
9364                .get(name)
9365                .map_or_else(|| name.to_owned(), Clone::clone)
9366        };
9367        MergedDataFrame {
9368            index: merged.index,
9369            columns: ColumnStore::from_pairs(
9370                merged
9371                    .columns
9372                    .iter_positional()
9373                    .map(|(name, column)| (restore(name), column.clone())),
9374            ),
9375            column_order: merged
9376                .column_order
9377                .iter()
9378                .map(|name| restore(name))
9379                .collect(),
9380        }
9381    };
9382    Ok(merged)
9383}
9384
9385/// A frame keyed by stand-ins and each stand-in with the name it stands for.
9386type StoodIn = (fp_frame::DataFrame, Vec<(String, String)>);
9387
9388/// `frame` with each column under a repeated key (not one of `on`) keyed by
9389/// a stand-in, and the stand-ins with their names; None when no key repeats
9390/// so.
9391fn stand_in_repeated_keys(
9392    frame: &fp_frame::DataFrame,
9393    on: &[&str],
9394    side: char,
9395) -> Result<Option<StoodIn>, JoinError> {
9396    let names = frame.column_names();
9397    let repeated = |name: &str| frame.column_occurrences(name) > 1 && !on.contains(&name);
9398    if !names.iter().any(|name| repeated(name)) {
9399        return Ok(None);
9400    }
9401    let mut stand_ins = Vec::new();
9402    let keys = names
9403        .iter()
9404        .enumerate()
9405        .map(|(position, name)| {
9406            if repeated(name) {
9407                let key = format!("\u{1}i17d4-{side}{position}");
9408                stand_ins.push((key.clone(), (*name).clone()));
9409                key
9410            } else {
9411                (*name).clone()
9412            }
9413        })
9414        .collect();
9415    Ok(Some((frame.with_column_keys(keys)?, stand_ins)))
9416}
9417
9418/// Restore widths by the output projection: all left positions followed by
9419/// right positions, excluding shared keys. Display names can repeat or
9420/// collide across suffixes and therefore cannot identify a source column.
9421/// Shared numeric keys retain the width of the rows supplying their values.
9422/// Only mixed-width right/outer keys need a complete-tuple origin scan.
9423fn keeping_source_widths(
9424    mut merged: MergedDataFrame,
9425    left: &fp_frame::DataFrame,
9426    right: &fp_frame::DataFrame,
9427    left_on: &[&str],
9428    right_on: &[&str],
9429    join_type: JoinType,
9430    indicator_name: Option<&str>,
9431) -> Result<MergedDataFrame, JoinError> {
9432    let shared = |name: &str| {
9433        !matches!(join_type, JoinType::Cross)
9434            && left_on
9435                .iter()
9436                .zip(right_on)
9437                .any(|(l, r)| l == r && *l == name)
9438    };
9439    let mut sources = Vec::with_capacity(left.num_columns() + right.num_columns());
9440    let fail = || {
9441        JoinError::Frame(FrameError::CompatibilityRejected(
9442            "merge output projection does not match source positions".to_owned(),
9443        ))
9444    };
9445    for position in 0..left.num_columns() {
9446        let name = left.column_name_at(position).ok_or_else(fail)?;
9447        let source = left.column_at(position).ok_or_else(fail)?;
9448        let partner = if shared(&name) {
9449            Some(right.column(&name).ok_or_else(fail)?)
9450        } else {
9451            None
9452        };
9453        sources.push((source, partner));
9454    }
9455    for position in 0..right.num_columns() {
9456        let name = right.column_name_at(position).ok_or_else(fail)?;
9457        if !shared(&name) {
9458            sources.push((right.column_at(position).ok_or_else(fail)?, None));
9459        }
9460    }
9461    if merged.columns.len() != sources.len() + usize::from(indicator_name.is_some()) {
9462        return Err(fail());
9463    }
9464    if let Some(indicator) = indicator_name
9465        && merged.columns.name_at(sources.len()) != Some(indicator)
9466    {
9467        return Err(fail());
9468    }
9469    let needs_origins = matches!(join_type, JoinType::Right | JoinType::Outer)
9470        && sources.iter().any(|(source, partner)| {
9471            partner.is_some_and(|partner| {
9472                source.width() != partner.width()
9473                    && fp_types::NumpyNumeric::of(&source.dtype(), source.width()).is_some()
9474                    && fp_types::NumpyNumeric::of(&partner.dtype(), partner.width()).is_some()
9475            })
9476        });
9477    let origins = if needs_origins {
9478        let left_keys = collect_composite_keys(&collect_join_key_columns(left, left_on, "left")?);
9479        let left_keys: FxHashSet<_> = left_keys.into_iter().collect();
9480        let right_keys =
9481            collect_composite_keys(&collect_join_key_columns(right, right_on, "right")?);
9482        let mut has_match = false;
9483        let mut has_right_only = false;
9484        for key in right_keys {
9485            if left_keys.contains(&key) {
9486                has_match = true;
9487            } else {
9488                has_right_only = true;
9489            }
9490        }
9491        let has_left = if matches!(join_type, JoinType::Outer) {
9492            !left.is_empty()
9493        } else {
9494            has_match
9495        };
9496        Some((has_left, has_right_only))
9497    } else {
9498        None
9499    };
9500    for (position, (source, partner)) in sources.into_iter().enumerate() {
9501        let column = merged.columns.column_at_mut(position).ok_or_else(fail)?;
9502        if let Some(partner) = partner {
9503            let numeric = fp_types::NumpyNumeric::of(&source.dtype(), source.width()).zip(
9504                fp_types::NumpyNumeric::of(&partner.dtype(), partner.width()),
9505            );
9506            let Some((left_numeric, right_numeric)) = numeric else {
9507                continue;
9508            };
9509            // Every inner/left shared key comes from a present left row.
9510            // Its width must not depend on an unmatched right payload row.
9511            if matches!(join_type, JoinType::Inner | JoinType::Left) {
9512                *column = column.clone().keeping_dtype_of(source);
9513                continue;
9514            }
9515            if let Some((has_left, has_right_only)) = origins {
9516                // No right-only tuples includes empty output: pandas keeps
9517                // the left dtype. Right-only output keeps the right dtype.
9518                if !has_right_only {
9519                    *column = column.clone().keeping_dtype_of(source);
9520                    continue;
9521                }
9522                if !has_left {
9523                    *column = column.clone().keeping_dtype_of(partner);
9524                    continue;
9525                }
9526            } else if column.width().is_some() {
9527                continue;
9528            }
9529            // Both origins require the common width, including clearing a
9530            // stale narrow tag on an already typed builder's output.
9531            if let Some(width) = left_numeric.result_type(right_numeric).width() {
9532                let nullable = column.dtype().is_nullable();
9533                if width.fits_storage(&column.dtype())
9534                    && (width.is_float() || nullable || !column.has_nulls())
9535                    && column.width() != Some(width)
9536                {
9537                    *column = column.cast_to_width(width, nullable)?;
9538                }
9539            } else if column.width().is_some() {
9540                *column = column.astype(column.dtype())?;
9541            }
9542        } else if source.width().is_some() {
9543            *column = column.clone().narrowed_like(source);
9544        }
9545    }
9546    Ok(merged)
9547}
9548
9549fn merge_dataframes_on_with_options_storage(
9550    left: &fp_frame::DataFrame,
9551    right: &fp_frame::DataFrame,
9552    left_on: &[&str],
9553    right_on: &[&str],
9554    join_type: JoinType,
9555    options: MergeExecutionOptions,
9556) -> Result<MergedDataFrame, JoinError> {
9557    let MergeExecutionOptions {
9558        indicator_name,
9559        validate_mode,
9560        suffixes,
9561        sort,
9562    } = options;
9563    let indicator_name = resolve_merge_indicator_name(indicator_name.as_deref())?;
9564    let suffixes = resolve_merge_suffixes(suffixes);
9565
9566    if matches!(join_type, JoinType::Cross) {
9567        if let Some(validate_mode) = validate_mode
9568            && !matches!(validate_mode, MergeValidateMode::ManyToMany)
9569        {
9570            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9571                format!(
9572                    "merge validate='{}' is not supported for cross join",
9573                    validate_mode.as_str()
9574                ),
9575            )));
9576        }
9577        validate_merge_suffixes_intra_frame(
9578            &left.column_names(),
9579            &right.column_names(),
9580            &HashSet::new(),
9581            &suffixes,
9582        )?;
9583        return merge_dataframes_cross(left, right, indicator_name.as_deref(), &suffixes);
9584    }
9585
9586    if left_on.is_empty() || right_on.is_empty() {
9587        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9588            "merge requires at least one key column".to_owned(),
9589        )));
9590    }
9591    if left_on.len() != right_on.len() {
9592        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9593            "merge requires left_on and right_on key lists with equal length".to_owned(),
9594        )));
9595    }
9596
9597    let mut seen_left_keys = HashSet::new();
9598    for key_name in left_on {
9599        if !seen_left_keys.insert(*key_name) {
9600            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9601                format!("merge left key column '{key_name}' is duplicated"),
9602            )));
9603        }
9604    }
9605    let mut seen_right_keys = HashSet::new();
9606    for key_name in right_on {
9607        if !seen_right_keys.insert(*key_name) {
9608            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9609                format!("merge right key column '{key_name}' is duplicated"),
9610            )));
9611        }
9612    }
9613
9614    let left_key_columns = collect_join_key_columns(left, left_on, "left")?;
9615    let right_key_columns = collect_join_key_columns(right, right_on, "right")?;
9616
9617    let shared_key_names = if left_on == right_on {
9618        left_on.iter().copied().collect::<HashSet<&str>>()
9619    } else {
9620        HashSet::new()
9621    };
9622    validate_merge_suffixes_intra_frame(
9623        &left.column_names(),
9624        &right.column_names(),
9625        &shared_key_names,
9626        &suffixes,
9627    )?;
9628
9629    // br-frankenpandas-uza04: settle `validate=` HERE, off the raw typed key
9630    // buffer, instead of letting it drag the whole merge onto the generic
9631    // Scalar path.
9632    //
9633    // `validate_merge_cardinality` is called in exactly ONE place — the generic
9634    // `collect_composite_keys` branch at the bottom of this function — so
9635    // `validate_mode_allows_fast_positions` had to return false for every
9636    // enforcing mode purely to *route execution there*. The cost of asking for
9637    // a cardinality guarantee was therefore the entire fast-path family:
9638    // `dense_packed_int64_inner_positions`, `typed_wide_two_i64_key_positions`,
9639    // `bounded_composite_multi_i64_key_positions`,
9640    // `typed_wide_multi_i64_key_positions` and the single-key inner/left
9641    // shortcuts, all disabled, plus a `Vec<CompositeJoinKey>` built by reading
9642    // `column.values()[row]` — 32 B/elem of `Scalar` spine and a `SmallVec` per
9643    // row — on both sides.
9644    //
9645    // A single all-valid Int64 key needs none of that: duplicate detection is
9646    // an `FxHashSet<i64>` over `as_i64_slice`. When that check applies AND
9647    // passes, the merge is free to take exactly the path it would have taken
9648    // with no `validate=` at all, because a passing validation adds nothing to
9649    // the output — it only decides whether the merge is allowed to happen.
9650    //
9651    // Semantics preserved exactly: same messages, same left-before-right
9652    // precedence, same modes checked on the same sides. Moving the check
9653    // earlier is unobservable because nothing between this point and the old
9654    // call site can fail — every fast-path helper in between returns `Option`,
9655    // never `Err`.
9656    let typed_validation_settled = match validate_mode {
9657        Some(mode) => {
9658            typed_validate_merge_cardinality(mode, &left_key_columns, &right_key_columns)?
9659        }
9660        None => false,
9661    };
9662    let validate_allows_fast_positions =
9663        validate_mode_allows_fast_positions(validate_mode) || typed_validation_settled;
9664
9665    if matches!(join_type, JoinType::Inner)
9666        && left_on.len() == 1
9667        && right_on.len() == 1
9668        && !sort
9669        && indicator_name.is_none()
9670        && validate_allows_fast_positions
9671    {
9672        return merge_single_key_inner_unsorted(
9673            left,
9674            right,
9675            left_on,
9676            right_on,
9677            &left_key_columns,
9678            &right_key_columns,
9679            &suffixes,
9680        );
9681    }
9682    if matches!(join_type, JoinType::Left)
9683        && left_on.len() == 1
9684        && right_on.len() == 1
9685        && !sort
9686        && indicator_name.is_none()
9687        && validate_allows_fast_positions
9688        && let Some(right_positions) =
9689            ordered_unique_int64_left_match_positions(left_key_columns[0], right_key_columns[0])
9690    {
9691        return build_single_key_ordered_unique_left_merge_output(
9692            left,
9693            right,
9694            left_on,
9695            right_on,
9696            &right_positions,
9697            &suffixes,
9698        );
9699    }
9700    if matches!(join_type, JoinType::Left)
9701        && left_on.len() == 1
9702        && right_on.len() == 1
9703        && !sort
9704        && indicator_name.is_none()
9705        && validate_allows_fast_positions
9706        && let Some((left_positions, right_positions)) =
9707            temporal_i64_left_positions(left_key_columns[0], right_key_columns[0])
9708    {
9709        return build_single_key_dense_left_merge_output(
9710            left,
9711            right,
9712            left_on,
9713            right_on,
9714            &left_positions,
9715            &right_positions,
9716            &suffixes,
9717        );
9718    }
9719    if matches!(join_type, JoinType::Left)
9720        && left_on.len() == 1
9721        && right_on.len() == 1
9722        && !sort
9723        && indicator_name.is_none()
9724        && validate_allows_fast_positions
9725        && let Some(merged) = build_single_key_dense_cycle_i64_left_merge_output(
9726            left,
9727            right,
9728            left_on,
9729            right_on,
9730            left_key_columns[0],
9731            right_key_columns[0],
9732            &suffixes,
9733        )?
9734    {
9735        return Ok(merged);
9736    }
9737    if matches!(join_type, JoinType::Left)
9738        && left_on.len() == 1
9739        && right_on.len() == 1
9740        && !sort
9741        && indicator_name.is_none()
9742        && validate_allows_fast_positions
9743        && let Some(merged) = build_single_key_dense_i64_inner_merge_output(
9744            left,
9745            right,
9746            left_on,
9747            right_on,
9748            left_key_columns[0],
9749            right_key_columns[0],
9750            FusedInt64MergeOptions {
9751                suffixes: &suffixes,
9752                require_all_left_keys_matched: true,
9753            },
9754        )?
9755    {
9756        return Ok(merged);
9757    }
9758    if matches!(join_type, JoinType::Left)
9759        && left_on.len() == 1
9760        && right_on.len() == 1
9761        && !sort
9762        && indicator_name.is_none()
9763        && validate_allows_fast_positions
9764        && let Some(merged) = build_single_key_dense_i64_left_merge_output(
9765            left,
9766            right,
9767            left_on,
9768            right_on,
9769            left_key_columns[0],
9770            right_key_columns[0],
9771            &suffixes,
9772        )?
9773    {
9774        return Ok(merged);
9775    }
9776    if matches!(join_type, JoinType::Left)
9777        && left_on.len() == 1
9778        && right_on.len() == 1
9779        && !sort
9780        && indicator_name.is_none()
9781        && validate_allows_fast_positions
9782        && let Some((left_positions, right_positions)) =
9783            dense_int64_left_positions(left_key_columns[0], right_key_columns[0])
9784    {
9785        return build_single_key_dense_left_merge_output(
9786            left,
9787            right,
9788            left_on,
9789            right_on,
9790            &left_positions,
9791            &right_positions,
9792            &suffixes,
9793        );
9794    }
9795    if matches!(join_type, JoinType::Left)
9796        && left_on.len() == 1
9797        && right_on.len() == 1
9798        && !sort
9799        && indicator_name.is_none()
9800        && validate_allows_fast_positions
9801        && let Some((left_positions, right_positions)) =
9802            hash_int64_left_positions(left_key_columns[0], right_key_columns[0])
9803    {
9804        return build_single_key_dense_left_merge_output(
9805            left,
9806            right,
9807            left_on,
9808            right_on,
9809            &left_positions,
9810            &right_positions,
9811            &suffixes,
9812        );
9813    }
9814    if matches!(join_type, JoinType::Left)
9815        && left_on.len() == 1
9816        && right_on.len() == 1
9817        && !sort
9818        && indicator_name.is_none()
9819        && validate_allows_fast_positions
9820        && let Some((left_positions, right_positions)) =
9821            contiguous_utf8_left_positions(left_key_columns[0], right_key_columns[0])
9822    {
9823        return build_single_key_dense_left_merge_output(
9824            left,
9825            right,
9826            left_on,
9827            right_on,
9828            &left_positions,
9829            &right_positions,
9830            &suffixes,
9831        );
9832    }
9833    if matches!(join_type, JoinType::Left)
9834        && left_on.len() == 1
9835        && right_on.len() == 1
9836        && !sort
9837        && indicator_name.is_none()
9838        && validate_allows_fast_positions
9839        && let Some((left_positions, right_positions)) =
9840            scalar_utf8_left_positions(left_key_columns[0], right_key_columns[0])
9841    {
9842        return build_single_key_dense_left_merge_output(
9843            left,
9844            right,
9845            left_on,
9846            right_on,
9847            &left_positions,
9848            &right_positions,
9849            &suffixes,
9850        );
9851    }
9852    if matches!(join_type, JoinType::Right)
9853        && left_on.len() == 1
9854        && right_on.len() == 1
9855        && !sort
9856        && indicator_name.is_none()
9857        && validate_allows_fast_positions
9858        && let Some(left_positions) =
9859            ordered_unique_int64_right_match_positions(left_key_columns[0], right_key_columns[0])
9860    {
9861        return build_single_key_ordered_unique_right_merge_output(
9862            left,
9863            right,
9864            left_on,
9865            right_on,
9866            &left_positions,
9867            &suffixes,
9868        );
9869    }
9870    if matches!(join_type, JoinType::Right)
9871        && left_on.len() == 1
9872        && right_on.len() == 1
9873        && !sort
9874        && indicator_name.is_none()
9875        && validate_allows_fast_positions
9876        && let Some(left_positions) = ordered_unique_temporal_i64_right_match_positions(
9877            left_key_columns[0],
9878            right_key_columns[0],
9879        )
9880    {
9881        return build_single_key_ordered_unique_right_merge_output(
9882            left,
9883            right,
9884            left_on,
9885            right_on,
9886            &left_positions,
9887            &suffixes,
9888        );
9889    }
9890    if matches!(join_type, JoinType::Right)
9891        && left_on.len() == 1
9892        && right_on.len() == 1
9893        && !sort
9894        && indicator_name.is_none()
9895        && validate_allows_fast_positions
9896        && let Some(merged) = build_single_key_dense_i64_right_all_matched_merge_output(
9897            left,
9898            right,
9899            left_on,
9900            right_on,
9901            left_key_columns[0],
9902            right_key_columns[0],
9903            &suffixes,
9904        )?
9905    {
9906        return Ok(merged);
9907    }
9908    if matches!(join_type, JoinType::Right)
9909        && left_on.len() == 1
9910        && right_on.len() == 1
9911        && !sort
9912        && indicator_name.is_none()
9913        && validate_allows_fast_positions
9914        && let Some(merged) = build_single_key_dense_i64_right_merge_output(
9915            left,
9916            right,
9917            left_on,
9918            right_on,
9919            left_key_columns[0],
9920            right_key_columns[0],
9921            &suffixes,
9922        )?
9923    {
9924        return Ok(merged);
9925    }
9926    if matches!(join_type, JoinType::Right)
9927        && left_on.len() == 1
9928        && right_on.len() == 1
9929        && !sort
9930        && indicator_name.is_none()
9931        && validate_allows_fast_positions
9932        && let Some((left_positions, right_positions)) =
9933            dense_int64_right_positions(left_key_columns[0], right_key_columns[0])
9934    {
9935        return build_single_key_dense_right_merge_output(
9936            left,
9937            right,
9938            left_on,
9939            right_on,
9940            &left_positions,
9941            &right_positions,
9942            &suffixes,
9943        );
9944    }
9945    if matches!(join_type, JoinType::Outer)
9946        && left_on.len() == 1
9947        && right_on.len() == 1
9948        && !sort
9949        && indicator_name.is_none()
9950        && validate_allows_fast_positions
9951        && let Some((left_positions, right_positions)) =
9952            ordered_unique_temporal_i64_outer_positions(left_key_columns[0], right_key_columns[0])
9953    {
9954        return build_single_key_ordered_unique_outer_merge_output(
9955            left,
9956            right,
9957            left_on,
9958            right_on,
9959            &left_positions,
9960            &right_positions,
9961            &suffixes,
9962        );
9963    }
9964    if matches!(join_type, JoinType::Outer)
9965        && left_on.len() == 1
9966        && right_on.len() == 1
9967        && !sort
9968        && indicator_name.is_none()
9969        && validate_allows_fast_positions
9970        && let Some((left_positions, right_positions)) =
9971            ordered_unique_int64_outer_positions(left_key_columns[0], right_key_columns[0])
9972    {
9973        return build_single_key_ordered_unique_outer_merge_output(
9974            left,
9975            right,
9976            left_on,
9977            right_on,
9978            &left_positions,
9979            &right_positions,
9980            &suffixes,
9981        );
9982    }
9983    if matches!(join_type, JoinType::Outer)
9984        && left_on.len() == 1
9985        && right_on.len() == 1
9986        && !sort
9987        && indicator_name.is_none()
9988        && validate_allows_fast_positions
9989        && let Some(merged) = build_single_key_dense_i64_outer_all_matched_merge_output(
9990            left,
9991            right,
9992            left_on,
9993            right_on,
9994            left_key_columns[0],
9995            right_key_columns[0],
9996            &suffixes,
9997        )?
9998    {
9999        return Ok(merged);
10000    }
10001    if matches!(join_type, JoinType::Outer)
10002        && left_on.len() == 1
10003        && right_on.len() == 1
10004        && !sort
10005        && indicator_name.is_none()
10006        && validate_allows_fast_positions
10007        && let Some(merged) = build_single_key_dense_i64_outer_merge_output(
10008            left,
10009            right,
10010            left_on,
10011            right_on,
10012            left_key_columns[0],
10013            right_key_columns[0],
10014            &suffixes,
10015        )?
10016    {
10017        return Ok(merged);
10018    }
10019    if matches!(join_type, JoinType::Outer)
10020        && left_on.len() == 1
10021        && right_on.len() == 1
10022        && !sort
10023        && indicator_name.is_none()
10024        && validate_allows_fast_positions
10025        && let Some((left_positions, right_positions)) =
10026            dense_int64_outer_positions(left_key_columns[0], right_key_columns[0])
10027    {
10028        return build_single_key_ordered_unique_outer_merge_output(
10029            left,
10030            right,
10031            left_on,
10032            right_on,
10033            &left_positions,
10034            &right_positions,
10035            &suffixes,
10036        );
10037    }
10038    if matches!(join_type, JoinType::Outer)
10039        && left_on.len() == 1
10040        && right_on.len() == 1
10041        && !sort
10042        && indicator_name.is_none()
10043        && validate_allows_fast_positions
10044        && let Some((left_positions, right_positions)) =
10045            hash_int64_outer_positions(left_key_columns[0], right_key_columns[0])
10046    {
10047        return build_single_key_ordered_unique_outer_merge_output(
10048            left,
10049            right,
10050            left_on,
10051            right_on,
10052            &left_positions,
10053            &right_positions,
10054            &suffixes,
10055        );
10056    }
10057    if matches!(join_type, JoinType::Outer)
10058        && left_on.len() == 1
10059        && right_on.len() == 1
10060        && !sort
10061        && indicator_name.is_none()
10062        && validate_allows_fast_positions
10063        && let Some(merged) = build_single_key_fixed_decimal_utf8_outer_all_matched_merge_output(
10064            left,
10065            right,
10066            left_on,
10067            right_on,
10068            left_key_columns[0],
10069            right_key_columns[0],
10070            &suffixes,
10071        )?
10072    {
10073        return Ok(merged);
10074    }
10075    if matches!(join_type, JoinType::Outer)
10076        && left_on.len() == 1
10077        && right_on.len() == 1
10078        && !sort
10079        && indicator_name.is_none()
10080        && validate_allows_fast_positions
10081        && let Some((left_positions, right_positions)) =
10082            contiguous_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
10083    {
10084        return build_single_key_ordered_unique_outer_merge_output(
10085            left,
10086            right,
10087            left_on,
10088            right_on,
10089            &left_positions,
10090            &right_positions,
10091            &suffixes,
10092        );
10093    }
10094    if matches!(join_type, JoinType::Outer)
10095        && left_on.len() == 1
10096        && right_on.len() == 1
10097        && !sort
10098        && indicator_name.is_none()
10099        && validate_allows_fast_positions
10100        && let Some((left_positions, right_positions)) =
10101            scalar_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
10102    {
10103        return build_single_key_ordered_unique_outer_merge_output(
10104            left,
10105            right,
10106            left_on,
10107            right_on,
10108            &left_positions,
10109            &right_positions,
10110            &suffixes,
10111        );
10112    }
10113
10114    let needs_key_order = sort || matches!(join_type, JoinType::Outer);
10115
10116    // A text key of a multi-key INNER / LEFT merge whose other keys are
10117    // int64 joins as int64 codes over one dictionary of both sides' strings
10118    // (see [`utf8_key_pair_codes`]), so the typed int-key paths below take
10119    // it: their pairs follow equality and row order alone, never the keys'
10120    // order, which codes do not keep (an outer join's or sort's do). A (str,
10121    // int) key built a SmallVec of cloned labels a row and hashed it (merge
10122    // on ['g', 'z'] of 200k rows 22.5 ms, pandas 19.0;
10123    // br-frankenpandas-j4657). The key columns stay the output's.
10124    let coded_keys: Vec<Option<(Column, Column)>> = if left_key_columns.len() >= 2
10125        && matches!(join_type, JoinType::Inner | JoinType::Left)
10126        && !sort
10127        && indicator_name.is_none()
10128        && validate_allows_fast_positions
10129        && left_key_columns
10130            .iter()
10131            .any(|column| column.dtype() == DType::Utf8)
10132        && left_key_columns
10133            .iter()
10134            .zip(&right_key_columns)
10135            .all(|(left, right)| {
10136                (left.dtype() == DType::Utf8 && right.dtype() == DType::Utf8)
10137                    || (left.as_i64_slice().is_some() && right.as_i64_slice().is_some())
10138            }) {
10139        left_key_columns
10140            .iter()
10141            .zip(&right_key_columns)
10142            .map(|(left, right)| utf8_key_pair_codes(left, right))
10143            .collect()
10144    } else {
10145        Vec::new()
10146    };
10147    // Each key's column to match on: its codes, else itself.
10148    let match_left: Vec<&Column> = left_key_columns
10149        .iter()
10150        .enumerate()
10151        .map(|(key, &column)| {
10152            coded_keys
10153                .get(key)
10154                .and_then(Option::as_ref)
10155                .map_or(column, |(codes, _)| codes)
10156        })
10157        .collect();
10158    let match_right: Vec<&Column> = right_key_columns
10159        .iter()
10160        .enumerate()
10161        .map(|(key, &column)| {
10162            coded_keys
10163                .get(key)
10164                .and_then(Option::as_ref)
10165                .map_or(column, |(_, codes)| codes)
10166        })
10167        .collect();
10168
10169    // Hash-free fast path: a plain inner join on all-valid bounded-Int64 key
10170    // column(s) packs the composite key into one i64 and runs the dense CSR
10171    // core, skipping CompositeJoinKey materialization + FxHashMap build/probe.
10172    // Gated to inner joins with no sort/indicator/enforcing validate, where the
10173    // emitted (left,right) pairs are byte-for-byte identical to the hash path.
10174    let packed_inner = if matches!(join_type, JoinType::Inner)
10175        && !sort
10176        && validate_allows_fast_positions
10177        && indicator_name.is_none()
10178    {
10179        dense_packed_int64_inner_positions(&match_left, &match_right)
10180    } else {
10181        None
10182    };
10183
10184    // Typed wide 2-i64-key INNER/LEFT positions (bypasses the Scalar composite
10185    // path when a component is too wide for the packed dense gate). Same fast-path
10186    // gates as packed_inner (no sort/indicator, validate allows fast positions).
10187    let typed_two_key = if !sort
10188        && indicator_name.is_none()
10189        && validate_allows_fast_positions
10190        && packed_inner.is_none()
10191    {
10192        typed_wide_two_i64_key_positions(join_type, &match_left, &match_right)
10193    } else {
10194        None
10195    };
10196
10197    // Typed K-key (K >= 3) BOUNDED-Int64 INNER/LEFT positions: pack the composite
10198    // into one i64 + single-key i64 hash merge, skipping the K per-column
10199    // factorization maps the factorize path below builds (3-key merge was
10200    // 0.43-0.57x pandas — the khash floor of those maps). Same fast-path gates.
10201    let composite_multi_key = if !sort
10202        && indicator_name.is_none()
10203        && validate_allows_fast_positions
10204        && packed_inner.is_none()
10205        && typed_two_key.is_none()
10206    {
10207        bounded_composite_multi_i64_key_positions(join_type, &match_left, &match_right)
10208    } else {
10209        None
10210    };
10211
10212    // Typed general K-key (K >= 3) wide-Int64 positions: factorize-to-gid + u128
10213    // pack, bypassing the Scalar collect_composite_keys path. Same fast-path gates.
10214    let typed_multi_key = if !sort
10215        && indicator_name.is_none()
10216        && validate_allows_fast_positions
10217        && packed_inner.is_none()
10218        && typed_two_key.is_none()
10219        && composite_multi_key.is_none()
10220    {
10221        typed_wide_multi_i64_key_positions(join_type, &match_left, &match_right)
10222    } else {
10223        None
10224    };
10225
10226    let (left_positions, right_positions, _out_row_keys): MergeRowPositions =
10227        if let Some((lp, rp)) = packed_inner {
10228            (
10229                lp.into_iter().map(Some).collect(),
10230                rp.into_iter().map(Some).collect(),
10231                None,
10232            )
10233        } else if let Some(typed) = typed_two_key {
10234            typed
10235        } else if let Some(typed) = composite_multi_key {
10236            typed
10237        } else if let Some(typed) = typed_multi_key {
10238            typed
10239        } else {
10240            // Convert key columns to hashable composite keys.
10241            let left_keys = collect_composite_keys(&left_key_columns);
10242            let right_keys = collect_composite_keys(&right_key_columns);
10243            // Skip when the typed checker above already enforced this mode
10244            // (br-frankenpandas-uza04) — re-running it here would be a second
10245            // full pass over both key sides for an answer already known. A
10246            // shape the typed checker declined still lands here and is checked
10247            // exactly as before.
10248            if let Some(validate_mode) = validate_mode
10249                && !typed_validation_settled
10250            {
10251                validate_merge_cardinality(validate_mode, &left_keys, &right_keys)?;
10252            }
10253
10254            // Build only the probe maps required by the selected join direction.
10255            let right_map = if matches!(
10256                join_type,
10257                JoinType::Inner | JoinType::Left | JoinType::Outer | JoinType::Right
10258            ) {
10259                let mut m =
10260                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
10261                        right_keys.len(),
10262                        Default::default(),
10263                    );
10264                for (pos, key) in right_keys.iter().enumerate() {
10265                    m.entry(key).or_default().push(pos);
10266                }
10267                Some(m)
10268            } else {
10269                None
10270            };
10271
10272            // Right no longer needs a left_map: its branch below probes the small
10273            // right_map with a single left pass (O(right) build, not O(left)).
10274            let left_map = if matches!(join_type, JoinType::Outer) {
10275                let mut m =
10276                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
10277                        left_keys.len(),
10278                        Default::default(),
10279                    );
10280                for (pos, key) in left_keys.iter().enumerate() {
10281                    m.entry(key).or_default().push(pos);
10282                }
10283                Some(m)
10284            } else {
10285                None
10286            };
10287
10288            // Compute row position mappings.
10289            let row_capacity = match join_type {
10290                JoinType::Inner => left_keys.len().min(right_keys.len()),
10291                JoinType::Left => left_keys.len(),
10292                JoinType::Right => right_keys.len(),
10293                JoinType::Outer => left_keys.len().saturating_add(right_keys.len()),
10294                JoinType::Cross => left_keys.len().saturating_mul(right_keys.len()),
10295            };
10296            let mut left_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
10297            let mut right_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
10298            // No longer materialized: the post-position sort reads each row's key by
10299            // reference from left_keys/right_keys via its position, so the per-row
10300            // push_merge_row_key calls below no-op (no String-owning key clones).
10301            let mut out_row_keys: Option<Vec<CompositeJoinKey>> = None;
10302
10303            match join_type {
10304                JoinType::Inner | JoinType::Left | JoinType::Outer => {
10305                    let right_map = right_map
10306                        .as_ref()
10307                        .expect("right_map required for Inner, Left, and Outer joins");
10308                    for (left_pos, key) in left_keys.iter().enumerate() {
10309                        if let Some(matches) = right_map.get(key) {
10310                            for &right_pos in matches {
10311                                push_merge_row_key(&mut out_row_keys, key);
10312                                left_positions.push(Some(left_pos));
10313                                right_positions.push(Some(right_pos));
10314                            }
10315                            continue;
10316                        }
10317
10318                        if matches!(join_type, JoinType::Left | JoinType::Outer) {
10319                            push_merge_row_key(&mut out_row_keys, key);
10320                            left_positions.push(Some(left_pos));
10321                            right_positions.push(None);
10322                        }
10323                    }
10324
10325                    if matches!(join_type, JoinType::Outer) {
10326                        let left_map = left_map.as_ref().expect("left_map required for Outer join");
10327                        for (right_pos, key) in right_keys.iter().enumerate() {
10328                            if !left_map.contains_key(key) {
10329                                push_merge_row_key(&mut out_row_keys, key);
10330                                left_positions.push(None);
10331                                right_positions.push(Some(right_pos));
10332                            }
10333                        }
10334                    }
10335                }
10336                JoinType::Right => {
10337                    // Probe the SMALL right_map with a single left pass instead of
10338                    // building a left_map over every left row (the prior path —
10339                    // O(left) hash build; for a 1M⋈10k merge that was ~2.4x slower
10340                    // than the symmetric Left join). Bucket each matching left
10341                    // position under its right row; `left_by_right[r]` collects in
10342                    // left-iteration order, and we then emit right rows in order —
10343                    // byte-for-byte identical (left,right) pairs to the left_map
10344                    // path (right-row order outer, left-position order inner),
10345                    // including duplicate right keys and unmatched right rows.
10346                    let right_map = right_map
10347                        .as_ref()
10348                        .expect("right_map required for Right join");
10349                    let mut left_by_right: Vec<Vec<usize>> = vec![Vec::new(); right_keys.len()];
10350                    for (left_pos, key) in left_keys.iter().enumerate() {
10351                        if let Some(right_rows) = right_map.get(key) {
10352                            for &right_pos in right_rows {
10353                                left_by_right[right_pos].push(left_pos);
10354                            }
10355                        }
10356                    }
10357                    for (right_pos, key) in right_keys.iter().enumerate() {
10358                        let lefts = &left_by_right[right_pos];
10359                        if lefts.is_empty() {
10360                            push_merge_row_key(&mut out_row_keys, key);
10361                            left_positions.push(None);
10362                            right_positions.push(Some(right_pos));
10363                        } else {
10364                            for &left_pos in lefts {
10365                                push_merge_row_key(&mut out_row_keys, key);
10366                                left_positions.push(Some(left_pos));
10367                                right_positions.push(Some(right_pos));
10368                            }
10369                        }
10370                    }
10371                }
10372                JoinType::Cross => {
10373                    return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10374                        "cross join must be handled by merge_dataframes_cross".to_owned(),
10375                    )));
10376                }
10377            }
10378
10379            // Sort the output rows by join key in-place while left_keys/right_keys
10380            // are in scope (read by reference per row — no out_row_keys clone).
10381            if needs_key_order {
10382                sort_merge_rows_by_join_keys(
10383                    &left_keys,
10384                    &right_keys,
10385                    &mut left_positions,
10386                    &mut right_positions,
10387                );
10388            }
10389            (left_positions, right_positions, out_row_keys)
10390        };
10391
10392    let all_positions_present = matches!(join_type, JoinType::Inner)
10393        || (matches!(
10394            join_type,
10395            JoinType::Left | JoinType::Right | JoinType::Outer
10396        ) && left_positions.iter().all(Option::is_some)
10397            && right_positions.iter().all(Option::is_some));
10398    let all_present_take_positions = all_positions_present.then(|| {
10399        let left = left_positions
10400            .iter()
10401            .map(|position| position.expect("all-present join emits left positions for every row"))
10402            .collect::<Vec<_>>();
10403        let right = right_positions
10404            .iter()
10405            .map(|position| position.expect("all-present join emits right positions for every row"))
10406            .collect::<Vec<_>>();
10407        (left, right)
10408    });
10409    let all_present_left_positions = all_present_take_positions
10410        .as_ref()
10411        .map(|(positions, _)| positions.as_slice());
10412    let all_present_right_positions = all_present_take_positions
10413        .as_ref()
10414        .map(|(_, positions)| positions.as_slice());
10415
10416    // Build output columns by reindexing.
10417    let n = left_positions.len();
10418    // Lazy unit-range output index (see build_single_key_dense_i64 site).
10419    let index = Index::new_known_unique_int64_unit_range(0, n);
10420    let mut columns = ColumnStore::new();
10421    let mut column_order: Vec<String> = Vec::new();
10422
10423    // Collect column names to handle conflicts.
10424    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
10425    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
10426    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
10427    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
10428
10429    // Track positional pairs where left_on[i] and right_on[i] share the same key name.
10430    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
10431    for (idx, (left_key_name, right_key_name)) in left_on.iter().zip(right_on.iter()).enumerate() {
10432        if left_key_name == right_key_name {
10433            shared_name_positions.insert(*left_key_name, (idx, idx));
10434        }
10435    }
10436    let shared_key_names = shared_name_positions
10437        .keys()
10438        .copied()
10439        .collect::<HashSet<&str>>();
10440    let overlapping_names =
10441        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
10442    ensure_merge_suffixes_for_overlaps(&overlapping_names, &suffixes)?;
10443
10444    // Add left columns (including left key columns) in the left frame's own
10445    // column order (pandas preserves it; the BTreeMap would re-sort) — br-691lh.
10446    for name in left.column_names() {
10447        let col = left
10448            .columns()
10449            .get(name)
10450            .expect("left column listed in column_names must exist");
10451        if left_key_name_set.contains(name.as_str()) {
10452            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
10453                // Shared key name: for rows emitted from right-only keys, source key values from
10454                // the right frame instead of leaving them null.
10455                let left_key_col = left_key_columns[*left_key_idx];
10456                let key_column = if let Some(positions) = all_present_left_positions {
10457                    take_positions_typed(left_key_col, positions)
10458                } else {
10459                    let right_key_col = right_key_columns[*right_key_idx];
10460                    coalesce_utf8_contiguous_key_column(
10461                        left_key_col,
10462                        right_key_col,
10463                        &left_positions,
10464                        &right_positions,
10465                    )
10466                    .map(Ok)
10467                    .unwrap_or_else(|| {
10468                        let values = left_positions
10469                            .iter()
10470                            .zip(right_positions.iter())
10471                            .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
10472                                (Some(pos), _) => left_key_col.values()[*pos].clone(),
10473                                (None, Some(pos)) => right_key_col.values()[*pos].clone(),
10474                                (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
10475                            })
10476                            .collect::<Vec<_>>();
10477                        Column::from_values(values)
10478                    })?
10479                };
10480                insert_merged_output_column(
10481                    &mut columns,
10482                    &mut column_order,
10483                    name.clone(),
10484                    key_column,
10485                )?;
10486            } else {
10487                let key_column = if let Some(positions) = all_present_left_positions {
10488                    take_positions_typed(col, positions)
10489                } else {
10490                    reindex_join_column_with_invented_gap(col, &left_positions)?
10491                };
10492                insert_merged_output_column(
10493                    &mut columns,
10494                    &mut column_order,
10495                    name.clone(),
10496                    key_column,
10497                )?;
10498            }
10499            continue;
10500        }
10501        let reindexed = if let Some(positions) = all_present_left_positions {
10502            take_positions_typed(col, positions)
10503        } else {
10504            reindex_join_column_with_invented_gap(col, &left_positions)?
10505        };
10506        let out_name = if right_col_names.contains(name) {
10507            apply_merge_suffix(name, suffixes.left.as_deref())
10508        } else {
10509            name.clone()
10510        };
10511        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10512    }
10513
10514    // Add right non-key columns in the right frame's own column order — br-691lh.
10515    for name in right.column_names() {
10516        let col = right
10517            .columns()
10518            .get(name)
10519            .expect("right column listed in column_names must exist");
10520        if right_key_name_set.contains(name.as_str())
10521            && shared_name_positions.contains_key(name.as_str())
10522        {
10523            // Shared same-name key already emitted from the left side.
10524            continue;
10525        }
10526        let reindexed = if let Some(positions) = all_present_right_positions {
10527            take_positions_typed(col, positions)
10528        } else {
10529            reindex_join_column_with_invented_gap(col, &right_positions)?
10530        };
10531        let out_name = if left_col_names.contains(name) {
10532            apply_merge_suffix(name, suffixes.right.as_deref())
10533        } else {
10534            name.clone()
10535        };
10536        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10537    }
10538
10539    if let Some(indicator_name) = indicator_name.as_deref() {
10540        ensure_indicator_name_available(
10541            indicator_name,
10542            &left_col_names,
10543            &right_col_names,
10544            &columns,
10545        )?;
10546        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions);
10547        insert_merged_output_column(
10548            &mut columns,
10549            &mut column_order,
10550            indicator_name.to_owned(),
10551            indicator_col,
10552        )?;
10553    }
10554
10555    Ok(MergedDataFrame {
10556        index,
10557        columns,
10558        column_order,
10559    })
10560}
10561
10562/// Merge two DataFrames on one or more key columns with identical key names.
10563///
10564/// Matches `pd.merge(left, right, on=keys, how=join_type)`.
10565pub fn merge_dataframes_on(
10566    left: &fp_frame::DataFrame,
10567    right: &fp_frame::DataFrame,
10568    on: &[&str],
10569    join_type: JoinType,
10570) -> Result<MergedDataFrame, JoinError> {
10571    merge_dataframes_on_with(left, right, on, on, join_type)
10572}
10573
10574/// Merge two DataFrames on a single key column.
10575pub fn merge_dataframes(
10576    left: &fp_frame::DataFrame,
10577    right: &fp_frame::DataFrame,
10578    on: &str,
10579    join_type: JoinType,
10580) -> Result<MergedDataFrame, JoinError> {
10581    if matches!(join_type, JoinType::Inner) {
10582        let left_key = left.column(on).ok_or_else(|| {
10583            JoinError::Frame(FrameError::CompatibilityRejected(format!(
10584                "left DataFrame missing key column '{on}'"
10585            )))
10586        })?;
10587        let right_key = right.column(on).ok_or_else(|| {
10588            JoinError::Frame(FrameError::CompatibilityRejected(format!(
10589                "right DataFrame missing key column '{on}'"
10590            )))
10591        })?;
10592        validate_object_join_keys(left_key)?;
10593        validate_object_join_keys(right_key)?;
10594        let suffixes = ResolvedMergeSuffixes::default();
10595        return merge_single_key_inner_unsorted(
10596            left,
10597            right,
10598            &[on],
10599            &[on],
10600            &[left_key],
10601            &[right_key],
10602            &suffixes,
10603        );
10604    }
10605    merge_dataframes_on(left, right, &[on], join_type)
10606}
10607
10608fn merge_dataframes_cross(
10609    left: &fp_frame::DataFrame,
10610    right: &fp_frame::DataFrame,
10611    indicator_name: Option<&str>,
10612    suffixes: &ResolvedMergeSuffixes,
10613) -> Result<MergedDataFrame, JoinError> {
10614    let left_rows = left.index().len();
10615    let right_rows = right.index().len();
10616    let out_rows = left_rows.saturating_mul(right_rows);
10617
10618    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_rows);
10619    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_rows);
10620    for left_pos in 0..left_rows {
10621        for right_pos in 0..right_rows {
10622            left_positions.push(Some(left_pos));
10623            right_positions.push(Some(right_pos));
10624        }
10625    }
10626
10627    let index = Index::new((0..out_rows as i64).map(IndexLabel::from).collect());
10628    let mut columns = ColumnStore::new();
10629    let mut column_order: Vec<String> = Vec::new();
10630
10631    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
10632    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
10633    let overlapping_names =
10634        collect_overlapping_column_names(&left_col_names, &right_col_names, &HashSet::new());
10635    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
10636
10637    // Each side's columns in its own order, as pandas (the store iterates
10638    // them by name, so the right side's came back sorted; buwrx).
10639    for position in 0..left.num_columns() {
10640        let (Some(name), Some(col)) = (left.column_name_at(position), left.column_at(position))
10641        else {
10642            continue;
10643        };
10644        let reindexed = col.reindex_by_positions(&left_positions)?;
10645        let out_name = if right_col_names.contains(&name) {
10646            apply_merge_suffix(&name, suffixes.left.as_deref())
10647        } else {
10648            name
10649        };
10650        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10651    }
10652
10653    for position in 0..right.num_columns() {
10654        let (Some(name), Some(col)) = (right.column_name_at(position), right.column_at(position))
10655        else {
10656            continue;
10657        };
10658        let reindexed = col.reindex_by_positions(&right_positions)?;
10659        let out_name = if left_col_names.contains(&name) {
10660            apply_merge_suffix(&name, suffixes.right.as_deref())
10661        } else {
10662            name
10663        };
10664        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10665    }
10666
10667    if let Some(indicator_name) = indicator_name {
10668        ensure_indicator_name_available(
10669            indicator_name,
10670            &left_col_names,
10671            &right_col_names,
10672            &columns,
10673        )?;
10674        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions);
10675        insert_merged_output_column(
10676            &mut columns,
10677            &mut column_order,
10678            indicator_name.to_owned(),
10679            indicator_col,
10680        )?;
10681    }
10682
10683    Ok(MergedDataFrame {
10684        index,
10685        columns,
10686        column_order,
10687    })
10688}
10689
10690/// Extension trait adding `.merge()` and `.join()` instance methods to `DataFrame`.
10691///
10692/// Import this trait to get pandas-style `df.merge(other, ...)` and `df.join(other, ...)`
10693/// as instance methods.
10694pub trait DataFrameMergeExt {
10695    /// Merge this DataFrame with another on shared key columns.
10696    ///
10697    /// Matches `pd.DataFrame.merge(other, on=keys, how=join_type)`.
10698    fn merge(
10699        &self,
10700        other: &fp_frame::DataFrame,
10701        on: &[&str],
10702        how: JoinType,
10703    ) -> Result<MergedDataFrame, JoinError>;
10704
10705    /// Merge with separate left/right key columns and execution options.
10706    ///
10707    /// Matches `pd.DataFrame.merge(other, left_on=..., right_on=..., how=...)`.
10708    fn merge_with_options(
10709        &self,
10710        other: &fp_frame::DataFrame,
10711        left_on: &[&str],
10712        right_on: &[&str],
10713        how: JoinType,
10714        options: MergeExecutionOptions,
10715    ) -> Result<MergedDataFrame, JoinError>;
10716
10717    /// Join another DataFrame on the index.
10718    ///
10719    /// Matches `pd.DataFrame.join(other, how=join_type)` (index-based join).
10720    fn join_on_index(
10721        &self,
10722        other: &fp_frame::DataFrame,
10723        how: JoinType,
10724    ) -> Result<MergedDataFrame, JoinError>;
10725
10726    /// pandas-named alias for [`Self::join_on_index`]. Matches
10727    /// `pd.DataFrame.join(other, how=...)` directly. Per br-frankenpandas-nk54a.
10728    ///
10729    /// Default impl delegates to `join_on_index`. Implementors that already
10730    /// have an optimized index-based join can leave this default.
10731    fn join(
10732        &self,
10733        other: &fp_frame::DataFrame,
10734        how: JoinType,
10735    ) -> Result<MergedDataFrame, JoinError> {
10736        self.join_on_index(other, how)
10737    }
10738
10739    /// Perform an asof merge (nearest-match join) on a sorted key column.
10740    ///
10741    /// Matches `pd.merge_asof(left, right, on=key)`. Both DataFrames must
10742    /// be sorted by the key column. For each row in `left`, finds the last
10743    /// row in `right` where `right[on] <= left[on]` (backward direction)
10744    /// or the nearest row in the specified direction.
10745    ///
10746    /// `direction`: "backward" (default), "forward", "nearest".
10747    fn merge_asof(
10748        &self,
10749        other: &fp_frame::DataFrame,
10750        on: &str,
10751        direction: &str,
10752    ) -> Result<MergedDataFrame, JoinError>;
10753
10754    /// Perform an asof merge with additional options.
10755    ///
10756    /// Matches `pd.merge_asof(left, right, on=key, direction=...,
10757    /// allow_exact_matches=..., tolerance=..., by=...)`.
10758    ///
10759    /// # Parameters
10760    /// - `other`: Right DataFrame to merge with
10761    /// - `on`: Column name to merge on (must be numeric and sorted)
10762    /// - `direction`: "backward", "forward", or "nearest"
10763    /// - `options`: Additional options (allow_exact_matches, tolerance, by)
10764    fn merge_asof_with_options(
10765        &self,
10766        other: &fp_frame::DataFrame,
10767        on: &str,
10768        direction: &str,
10769        options: MergeAsofOptions,
10770    ) -> Result<MergedDataFrame, JoinError>;
10771
10772    /// Perform an ordered merge (outer join + sort by keys).
10773    ///
10774    /// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
10775    fn merge_ordered(
10776        &self,
10777        other: &fp_frame::DataFrame,
10778        on: &[&str],
10779        fill_method: Option<&str>,
10780    ) -> Result<MergedDataFrame, JoinError>;
10781}
10782
10783/// Perform an ordered merge of two DataFrames.
10784///
10785/// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
10786/// Performs an outer join and ensures the result is sorted by the join keys.
10787pub fn merge_ordered(
10788    left: &fp_frame::DataFrame,
10789    right: &fp_frame::DataFrame,
10790    on: &[&str],
10791    fill_method: Option<&str>,
10792) -> Result<MergedDataFrame, JoinError> {
10793    let options = MergeExecutionOptions {
10794        sort: true,
10795        ..MergeExecutionOptions::default()
10796    };
10797    let merged = merge_dataframes_on_with_options(left, right, on, on, JoinType::Outer, options)?;
10798
10799    if let Some(method) = fill_method {
10800        // Convert to DataFrame to apply fill
10801        let mut df = fp_frame::DataFrame::new_with_column_order(
10802            merged.index.clone(),
10803            merged.columns.clone(),
10804            merged.column_order.clone(),
10805        )
10806        .map_err(JoinError::Frame)?;
10807
10808        df = match method {
10809            "ffill" => df.ffill(None).map_err(JoinError::Frame)?,
10810            _ => {
10811                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10812                    format!("merge_ordered: fill_method must be 'ffill' or None, got '{method}'"),
10813                )));
10814            }
10815        };
10816        // pandas forward-fills the join's row indexers, not the values: a
10817        // column the fill leaves whole keeps its side's dtype (an int
10818        // column stayed float64 after the outer join's NaN), one with a
10819        // leading gap is still float64 NaN there.
10820        let names: Vec<String> = df.column_names().into_iter().cloned().collect();
10821        for name in names {
10822            let Some(source) = source_column_dtype(left, right, &name) else {
10823                continue;
10824            };
10825            let Some(filled) = df.column(&name) else {
10826                continue;
10827            };
10828            if filled.dtype() != source
10829                && matches!(source, DType::Int64 | DType::Bool)
10830                && !filled.values().iter().any(Scalar::is_missing)
10831            {
10832                let restored = filled.astype(source).map_err(|err| {
10833                    JoinError::Frame(FrameError::CompatibilityRejected(err.to_string()))
10834                })?;
10835                df = df.with_column(name, restored).map_err(JoinError::Frame)?;
10836            }
10837        }
10838
10839        let column_order = df.column_names().into_iter().cloned().collect();
10840        Ok(MergedDataFrame {
10841            index: df.index().clone(),
10842            columns: df.columns().clone(),
10843            column_order,
10844        })
10845    } else {
10846        Ok(merged)
10847    }
10848}
10849
10850/// The dtype of the input column a merged column `name` came from: the
10851/// left's or the right's of that name, else (an overlap) the left's for a
10852/// `_x` suffix and the right's for a `_y` one.
10853fn source_column_dtype(
10854    left: &fp_frame::DataFrame,
10855    right: &fp_frame::DataFrame,
10856    name: &str,
10857) -> Option<DType> {
10858    let dtype = |frame: &fp_frame::DataFrame, name: &str| frame.column(name).map(Column::dtype);
10859    match (left.column(name), right.column(name)) {
10860        (Some(column), None) | (None, Some(column)) => Some(column.dtype()),
10861        (Some(_), Some(_)) => None,
10862        (None, None) => name
10863            .strip_suffix("_x")
10864            .and_then(|stem| dtype(left, stem))
10865            .or_else(|| name.strip_suffix("_y").and_then(|stem| dtype(right, stem))),
10866    }
10867}
10868
10869/// Direction for asof merge matching.
10870#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10871pub enum AsofDirection {
10872    Backward,
10873    Forward,
10874    Nearest,
10875}
10876
10877/// Options for asof merge operations.
10878///
10879/// Matches pandas `merge_asof` parameters:
10880/// - `allow_exact_matches`: If true (default), allow matching with same key value
10881/// - `tolerance`: Maximum distance between keys for a match
10882/// - `by`: Columns to match exactly before asof matching
10883#[derive(Debug, Clone, Default)]
10884pub struct MergeAsofOptions {
10885    /// If true (default), allow matching with the same 'on' value.
10886    /// If false, don't match rows where left key == right key exactly.
10887    pub allow_exact_matches: bool,
10888    /// Maximum distance between left and right keys for a valid match.
10889    /// None means no tolerance limit.
10890    pub tolerance: Option<f64>,
10891    /// Columns to match exactly before performing asof merge.
10892    /// Acts like an equi-join on these columns first.
10893    pub by: Option<Vec<String>>,
10894}
10895
10896impl MergeAsofOptions {
10897    /// Create options with defaults matching pandas behavior.
10898    pub fn new() -> Self {
10899        Self {
10900            allow_exact_matches: true,
10901            tolerance: None,
10902            by: None,
10903        }
10904    }
10905
10906    /// Set whether exact matches are allowed.
10907    pub fn allow_exact_matches(mut self, allow: bool) -> Self {
10908        self.allow_exact_matches = allow;
10909        self
10910    }
10911
10912    /// Set the tolerance for matching.
10913    pub fn tolerance(mut self, tol: f64) -> Self {
10914        self.tolerance = Some(tol);
10915        self
10916    }
10917
10918    /// Set the columns to match exactly before asof merge.
10919    pub fn by(mut self, cols: Vec<String>) -> Self {
10920        self.by = Some(cols);
10921        self
10922    }
10923}
10924
10925/// When BOTH `on` keys are Datetime64, extract them as f64 SHIFTED by the global
10926/// minimum ns so the values fit f64's 2^53 integer precision exactly. A raw
10927/// Datetime64->ns->f64 cast collapses ns (~1.6e18) to garbage (>2^53), so
10928/// merge_asof previously REJECTED datetime keys ("must be numeric") — the primary
10929/// time-series asof case. Shifting is order- and difference-preserving (both sides
10930/// by the same min), so the f64 asof match + tolerance stay exact whenever the ns
10931/// RANGE fits 2^53 (~104 days). Returns:
10932/// - `None`: not both Datetime64 → caller uses the f64 numeric path unchanged.
10933/// - `Some(Err)`: range too wide for exact f64 → clean rejection (better than the
10934///   silently-wrong result a lossy cast would give).
10935/// - `Some(Ok((left,right)))`: shifted f64 keys, NaT/null → NaN.
10936type ShiftedDatetimeAsofKeys = (Vec<f64>, Vec<f64>);
10937
10938fn try_asof_datetime_shift(
10939    left_key: &Column,
10940    right_key: &Column,
10941    on: &str,
10942) -> Option<Result<ShiftedDatetimeAsofKeys, JoinError>> {
10943    if !matches!(
10944        (left_key.dtype(), right_key.dtype()),
10945        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz }) if left_tz == right_tz
10946    ) {
10947        return None;
10948    }
10949    let ld = left_key.as_datetime64_slice()?;
10950    let rd = right_key.as_datetime64_slice()?;
10951    let lv = left_key.validity();
10952    let rv = right_key.validity();
10953    // All-valid fast path: when a side has no null bits, the per-element
10954    // ValidityMask::get bit-test is skipped in both the min-scan and the shift
10955    // (only the cheap NaT sentinel compare remains, which vectorizes). NaT/null
10956    // are rare in an asof `on` key, so this is the hot path.
10957    let l_all = lv.all();
10958    let r_all = rv.all();
10959    let is_valid = |data: &[i64], v: &fp_columnar::ValidityMask, all: bool, i: usize| -> bool {
10960        (all || v.get(i)) && data[i] != fp_types::Timestamp::NAT
10961    };
10962    // Global min/max over the valid (non-NaT) ns of both sides.
10963    let mut lo = i64::MAX;
10964    let mut hi = i64::MIN;
10965    let mut any = false;
10966    for i in 0..ld.len() {
10967        if is_valid(ld, lv, l_all, i) {
10968            lo = lo.min(ld[i]);
10969            hi = hi.max(ld[i]);
10970            any = true;
10971        }
10972    }
10973    for i in 0..rd.len() {
10974        if is_valid(rd, rv, r_all, i) {
10975            lo = lo.min(rd[i]);
10976            hi = hi.max(rd[i]);
10977            any = true;
10978        }
10979    }
10980    if !any {
10981        // All-NaT/empty: every shifted value is NaN; produce that directly.
10982        return Some(Ok((vec![f64::NAN; ld.len()], vec![f64::NAN; rd.len()])));
10983    }
10984    if (hi as i128 - lo as i128) >= (1i128 << 53) {
10985        return Some(Err(JoinError::Frame(FrameError::CompatibilityRejected(
10986            format!(
10987                "merge_asof: Datetime64 key '{on}' spans more than ~104 days of nanoseconds, \
10988             which exceeds f64 asof precision; not yet supported"
10989            ),
10990        ))));
10991    }
10992    let shift = |data: &[i64], v: &fp_columnar::ValidityMask, all: bool| -> Vec<f64> {
10993        (0..data.len())
10994            .map(|i| {
10995                if is_valid(data, v, all, i) {
10996                    (data[i] - lo) as f64
10997                } else {
10998                    f64::NAN
10999                }
11000            })
11001            .collect()
11002    };
11003    Some(Ok((shift(ld, lv, l_all), shift(rd, rv, r_all))))
11004}
11005
11006#[derive(Clone, Copy)]
11007struct Datetime64AsofKey<'a> {
11008    data: &'a [i64],
11009    validity: &'a ValidityMask,
11010    all_valid: bool,
11011}
11012
11013impl Datetime64AsofKey<'_> {
11014    #[inline]
11015    fn is_valid(self, i: usize) -> bool {
11016        (self.all_valid || self.validity.get(i)) && self.data[i] != fp_types::Timestamp::NAT
11017    }
11018}
11019
11020fn datetime64_key_parts(column: &Column) -> Option<Datetime64AsofKey<'_>> {
11021    let data = column.as_datetime64_slice()?;
11022    let validity = column.validity();
11023    Some(Datetime64AsofKey {
11024        data,
11025        validity,
11026        all_valid: validity.all(),
11027    })
11028}
11029
11030fn ensure_sorted_non_decreasing_datetime64(
11031    key: Datetime64AsofKey<'_>,
11032    side: &str,
11033    on: &str,
11034) -> Result<(), JoinError> {
11035    let mut prev: Option<i64> = None;
11036    for i in 0..key.data.len() {
11037        if !key.is_valid(i) {
11038            continue;
11039        }
11040        let value = key.data[i];
11041        if let Some(prev_value) = prev
11042            && value < prev_value
11043        {
11044            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11045                format!("merge_asof: {side} column '{on}' must be sorted"),
11046            )));
11047        }
11048        prev = Some(value);
11049    }
11050    Ok(())
11051}
11052
11053fn within_datetime64_tolerance(left: i64, right: i64, tolerance: Option<f64>) -> bool {
11054    match tolerance {
11055        Some(tol) => ((left as i128 - right as i128).abs() as f64) <= tol,
11056        None => true,
11057    }
11058}
11059
11060fn compute_asof_matches_datetime64(
11061    left: Datetime64AsofKey<'_>,
11062    right: Datetime64AsofKey<'_>,
11063    direction: AsofDirection,
11064    allow_exact_matches: bool,
11065    tolerance: Option<f64>,
11066) -> Vec<Option<usize>> {
11067    let mut filtered_values = Vec::new();
11068    let mut filtered_positions = Vec::new();
11069    let (right_valid_values, right_valid_positions) =
11070        if right.all_valid && !right.data.contains(&fp_types::Timestamp::NAT) {
11071            (right.data, None)
11072        } else {
11073            for i in 0..right.data.len() {
11074                if right.is_valid(i) {
11075                    filtered_values.push(right.data[i]);
11076                    filtered_positions.push(i);
11077                }
11078            }
11079            (
11080                filtered_values.as_slice(),
11081                Some(filtered_positions.as_slice()),
11082            )
11083        };
11084
11085    compute_asof_matches_datetime64_prepared(
11086        left,
11087        right_valid_values,
11088        right_valid_positions,
11089        direction,
11090        allow_exact_matches,
11091        tolerance,
11092    )
11093}
11094
11095fn compute_asof_matches_datetime64_prepared(
11096    left: Datetime64AsofKey<'_>,
11097    right_valid_values: &[i64],
11098    right_valid_positions: Option<&[usize]>,
11099    direction: AsofDirection,
11100    allow_exact_matches: bool,
11101    tolerance: Option<f64>,
11102) -> Vec<Option<usize>> {
11103    let right_source_position =
11104        |position: usize| right_valid_positions.map_or(position, |positions| positions[position]);
11105
11106    let mut right_matches = Vec::with_capacity(left.data.len());
11107
11108    match direction {
11109        AsofDirection::Backward => {
11110            let mut best: Option<usize> = None;
11111            let mut best_val: Option<i64> = None;
11112            let mut j = 0usize;
11113            for i in 0..left.data.len() {
11114                if !left.is_valid(i) {
11115                    right_matches.push(None);
11116                    continue;
11117                }
11118                let lv = left.data[i];
11119                while j < right_valid_values.len() {
11120                    let rv = right_valid_values[j];
11121                    let should_include = if allow_exact_matches {
11122                        rv <= lv
11123                    } else {
11124                        rv < lv
11125                    };
11126                    if !should_include {
11127                        break;
11128                    }
11129                    best = Some(right_source_position(j));
11130                    best_val = Some(rv);
11131                    j += 1;
11132                }
11133
11134                let matched = match (best, best_val) {
11135                    (Some(idx), Some(rv)) if within_datetime64_tolerance(lv, rv, tolerance) => {
11136                        Some(idx)
11137                    }
11138                    _ => None,
11139                };
11140                right_matches.push(matched);
11141            }
11142        }
11143        AsofDirection::Forward => {
11144            let mut j = 0usize;
11145            for i in 0..left.data.len() {
11146                if !left.is_valid(i) {
11147                    right_matches.push(None);
11148                    continue;
11149                }
11150                let lv = left.data[i];
11151                while j < right_valid_values.len() {
11152                    let rv = right_valid_values[j];
11153                    let should_skip = if allow_exact_matches {
11154                        rv < lv
11155                    } else {
11156                        rv <= lv
11157                    };
11158                    if !should_skip {
11159                        break;
11160                    }
11161                    j += 1;
11162                }
11163
11164                if j < right_valid_values.len() {
11165                    let rv = right_valid_values[j];
11166                    if within_datetime64_tolerance(lv, rv, tolerance) {
11167                        right_matches.push(Some(right_source_position(j)));
11168                    } else {
11169                        right_matches.push(None);
11170                    }
11171                } else {
11172                    right_matches.push(None);
11173                }
11174            }
11175        }
11176        AsofDirection::Nearest => {
11177            for i in 0..left.data.len() {
11178                if !left.is_valid(i) {
11179                    right_matches.push(None);
11180                    continue;
11181                }
11182                if right_valid_values.is_empty() {
11183                    right_matches.push(None);
11184                    continue;
11185                }
11186
11187                let lv = left.data[i];
11188                let (lower, upper) = if allow_exact_matches {
11189                    let lo = right_valid_values.partition_point(|rv| *rv <= lv);
11190                    let up = right_valid_values.partition_point(|rv| *rv < lv);
11191                    (
11192                        if lo > 0 { Some(lo - 1) } else { None },
11193                        if up < right_valid_values.len() {
11194                            Some(up)
11195                        } else {
11196                            None
11197                        },
11198                    )
11199                } else {
11200                    let lo = right_valid_values.partition_point(|rv| *rv < lv);
11201                    let up = right_valid_values.partition_point(|rv| *rv <= lv);
11202                    (
11203                        if lo > 0 { Some(lo - 1) } else { None },
11204                        if up < right_valid_values.len() {
11205                            Some(up)
11206                        } else {
11207                            None
11208                        },
11209                    )
11210                };
11211
11212                let chosen = match (lower, upper) {
11213                    (Some(l), Some(u)) => {
11214                        let lower_dist = (right_valid_values[l] as i128 - lv as i128).abs();
11215                        let upper_dist = (right_valid_values[u] as i128 - lv as i128).abs();
11216                        if upper_dist < lower_dist {
11217                            Some(u)
11218                        } else {
11219                            Some(l)
11220                        }
11221                    }
11222                    (Some(l), None) => Some(l),
11223                    (None, Some(u)) => Some(u),
11224                    (None, None) => None,
11225                };
11226
11227                let matched = match chosen {
11228                    Some(idx)
11229                        if within_datetime64_tolerance(lv, right_valid_values[idx], tolerance) =>
11230                    {
11231                        Some(right_source_position(idx))
11232                    }
11233                    _ => None,
11234                };
11235                right_matches.push(matched);
11236            }
11237        }
11238    }
11239
11240    right_matches
11241}
11242
11243fn try_asof_datetime_matches(
11244    left_key: &Column,
11245    right_key: &Column,
11246    on: &str,
11247    direction: AsofDirection,
11248    allow_exact_matches: bool,
11249    tolerance: Option<f64>,
11250) -> Option<Result<Vec<Option<usize>>, JoinError>> {
11251    if !matches!(
11252        (left_key.dtype(), right_key.dtype()),
11253        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz }) if left_tz == right_tz
11254    ) {
11255        return None;
11256    }
11257    let left = datetime64_key_parts(left_key)?;
11258    let right = datetime64_key_parts(right_key)?;
11259
11260    Some((|| {
11261        ensure_sorted_non_decreasing_datetime64(left, "left", on)?;
11262        ensure_sorted_non_decreasing_datetime64(right, "right", on)?;
11263
11264        Ok(compute_asof_matches_datetime64(
11265            left,
11266            right,
11267            direction,
11268            allow_exact_matches,
11269            tolerance,
11270        ))
11271    })())
11272}
11273
11274fn asof_numeric_values(column: &Column, side: &str, on: &str) -> Result<Vec<f64>, JoinError> {
11275    // Typed fast path: an all-valid Int64/Float64 key column reads the raw slice
11276    // directly, skipping the per-cell values() Scalar materialization + to_f64
11277    // dispatch (merge_asof key extraction was ~0.83x pandas). Bit-identical:
11278    // as_i64_slice/as_f64_slice are all-valid (no missing → no NaN-fill branch),
11279    // and Scalar::Int64(v).to_f64() == v as f64, Scalar::Float64(v).to_f64() == v.
11280    // Nullable / Timedelta64 / Datetime64 keys fall through to the Scalar loop.
11281    if let Some(data) = column.as_i64_slice() {
11282        return Ok(data.iter().map(|&v| v as f64).collect());
11283    }
11284    if let Some(data) = column.as_f64_slice() {
11285        return Ok(data.to_vec());
11286    }
11287    let mut out = Vec::with_capacity(column.len());
11288    for value in column.values() {
11289        // pandas merge_asof accepts Timedelta64 (and datetime) `on` columns
11290        // and orders them by ns count. Scalar::Timedelta64.to_f64() returns
11291        // NonNumericValue, so the default branch would reject the join.
11292        // Extract ns directly for non-NaT Timedelta values; treat NaT as NaN
11293        // (matches the ValueIsMissing arm below).
11294        if let Scalar::Timedelta64(ns) = value {
11295            if *ns == fp_types::Timedelta::NAT {
11296                out.push(f64::NAN);
11297            } else {
11298                out.push(*ns as f64);
11299            }
11300            continue;
11301        }
11302        match value.to_f64() {
11303            Ok(v) => out.push(v),
11304            Err(TypeError::ValueIsMissing { .. }) => out.push(f64::NAN),
11305            Err(_) => {
11306                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11307                    format!("merge_asof: {side} column '{on}' must be numeric"),
11308                )));
11309            }
11310        }
11311    }
11312    Ok(out)
11313}
11314
11315/// `merge_asof` compares ordering keys rather than coercing them to a common
11316/// numeric representation.  Converting both sides to `f64` before validating
11317/// their dtypes makes an `int64` key appear compatible with a `float64` key,
11318/// which pandas rejects even when every finite value is exactly representable.
11319fn ensure_matching_asof_key_dtypes(
11320    left_key: &Column,
11321    right_key: &Column,
11322    on: &str,
11323) -> Result<(), JoinError> {
11324    if left_key.dtype() != right_key.dtype() {
11325        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11326            format!(
11327                "merge_asof: incompatible merge keys [0] for '{on}': left dtype('{}'), right dtype('{}'), must be the same type",
11328                left_key.dtype().name(),
11329                right_key.dtype().name(),
11330            ),
11331        )));
11332    }
11333    Ok(())
11334}
11335
11336fn ensure_sorted_non_decreasing(values: &[f64], side: &str, on: &str) -> Result<(), JoinError> {
11337    let mut prev: Option<f64> = None;
11338    for &value in values {
11339        if value.is_nan() {
11340            continue;
11341        }
11342        if let Some(prev_value) = prev
11343            && value < prev_value
11344        {
11345            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11346                format!("merge_asof: {side} column '{on}' must be sorted"),
11347            )));
11348        }
11349        prev = Some(value);
11350    }
11351    Ok(())
11352}
11353
11354/// Perform an asof merge between two DataFrames.
11355pub fn merge_asof(
11356    left: &fp_frame::DataFrame,
11357    right: &fp_frame::DataFrame,
11358    on: &str,
11359    direction: AsofDirection,
11360) -> Result<MergedDataFrame, JoinError> {
11361    merge_asof_with_options(left, right, on, direction, MergeAsofOptions::new())
11362}
11363
11364/// Perform an asof merge between two DataFrames with additional options.
11365///
11366/// # Parameters
11367/// - `left`: Left DataFrame
11368/// - `right`: Right DataFrame
11369/// - `on`: Column name to merge on (must be numeric and sorted)
11370/// - `direction`: Match direction (Backward, Forward, Nearest)
11371/// - `options`: Additional merge options (allow_exact_matches, tolerance, by)
11372pub fn merge_asof_with_options(
11373    left: &fp_frame::DataFrame,
11374    right: &fp_frame::DataFrame,
11375    on: &str,
11376    direction: AsofDirection,
11377    options: MergeAsofOptions,
11378) -> Result<MergedDataFrame, JoinError> {
11379    // If `by` columns are specified, we need to do grouped asof merge
11380    if let Some(ref by_cols) = options.by {
11381        return merge_asof_grouped(left, right, on, direction, &options, by_cols);
11382    }
11383
11384    merge_asof_simple(left, right, on, direction, &options)
11385}
11386
11387/// Simple asof merge without grouping.
11388fn merge_asof_simple(
11389    left: &fp_frame::DataFrame,
11390    right: &fp_frame::DataFrame,
11391    on: &str,
11392    direction: AsofDirection,
11393    options: &MergeAsofOptions,
11394) -> Result<MergedDataFrame, JoinError> {
11395    let left_key = left.columns().get(on).ok_or_else(|| {
11396        JoinError::Frame(FrameError::CompatibilityRejected(format!(
11397            "merge_asof: column '{on}' not found in left"
11398        )))
11399    })?;
11400    let right_key = right.columns().get(on).ok_or_else(|| {
11401        JoinError::Frame(FrameError::CompatibilityRejected(format!(
11402            "merge_asof: column '{on}' not found in right"
11403        )))
11404    })?;
11405
11406    ensure_matching_asof_key_dtypes(left_key, right_key, on)?;
11407
11408    if let Some(datetime_matches) = try_asof_datetime_matches(
11409        left_key,
11410        right_key,
11411        on,
11412        direction,
11413        options.allow_exact_matches,
11414        options.tolerance,
11415    ) {
11416        let right_matches = datetime_matches?;
11417        return build_asof_output(left, right, on, &right_matches, None);
11418    }
11419
11420    // Non-Datetime64 keys: use the f64 numeric path. The grouped Datetime64
11421    // route below still uses the old shift-to-f64 bridge until it gets its own
11422    // i64 grouped path.
11423    let (left_vals, right_vals) = match try_asof_datetime_shift(left_key, right_key, on) {
11424        Some(shifted) => shifted?,
11425        None => (
11426            asof_numeric_values(left_key, "left", on)?,
11427            asof_numeric_values(right_key, "right", on)?,
11428        ),
11429    };
11430
11431    // With matching key dtypes, pandas accepts NaN keys: the NaN row gets a
11432    // null in the joined columns (no match). Dtype incompatibility is rejected
11433    // above before this value-level rule is reached.
11434    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
11435    ensure_sorted_non_decreasing(&right_vals, "right", on)?;
11436
11437    let right_matches = compute_asof_matches(
11438        &left_vals,
11439        &right_vals,
11440        direction,
11441        options.allow_exact_matches,
11442        options.tolerance,
11443    );
11444
11445    build_asof_output(left, right, on, &right_matches, None)
11446}
11447
11448/// Grouped asof merge: match on `by` columns first, then asof within groups.
11449fn merge_asof_grouped(
11450    left: &fp_frame::DataFrame,
11451    right: &fp_frame::DataFrame,
11452    on: &str,
11453    direction: AsofDirection,
11454    options: &MergeAsofOptions,
11455    by_cols: &[String],
11456) -> Result<MergedDataFrame, JoinError> {
11457    // Validate by columns exist
11458    for col in by_cols {
11459        let left_column = left.columns().get(col).ok_or_else(|| {
11460            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11461                "merge_asof: 'by' column '{col}' not found in left"
11462            )))
11463        })?;
11464        let right_column = right.columns().get(col).ok_or_else(|| {
11465            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11466                "merge_asof: 'by' column '{col}' not found in right"
11467            )))
11468        })?;
11469        validate_object_join_keys(left_column)?;
11470        validate_object_join_keys(right_column)?;
11471    }
11472
11473    let left_key = left.columns().get(on).ok_or_else(|| {
11474        JoinError::Frame(FrameError::CompatibilityRejected(format!(
11475            "merge_asof: column '{on}' not found in left"
11476        )))
11477    })?;
11478    let right_key = right.columns().get(on).ok_or_else(|| {
11479        JoinError::Frame(FrameError::CompatibilityRejected(format!(
11480            "merge_asof: column '{on}' not found in right"
11481        )))
11482    })?;
11483
11484    ensure_matching_asof_key_dtypes(left_key, right_key, on)?;
11485
11486    // Datetime64 keys: shift-to-f64 (exact for <~104-day ns ranges) instead of the
11487    // rejected/precision-lossy direct cast. Falls back to the f64 numeric path.
11488    let (left_vals, right_vals) = match try_asof_datetime_shift(left_key, right_key, on) {
11489        Some(shifted) => shifted?,
11490        None => (
11491            asof_numeric_values(left_key, "left", on)?,
11492            asof_numeric_values(right_key, "right", on)?,
11493        ),
11494    };
11495
11496    // With matching key dtypes, pandas accepts NaN keys: the NaN row gets a
11497    // null in the joined columns (no match). Dtype incompatibility is rejected
11498    // above before this value-level rule is reached.
11499    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
11500    ensure_sorted_non_decreasing(&right_vals, "right", on)?;
11501
11502    // Dense u32 group ids over the `by` columns (shared id space for left and
11503    // right). The single non-float `by` column case factorizes the column's
11504    // scalars with a borrowed typed key — no per-row `format!`/`Vec<String>`
11505    // allocation — and is bit-identical to the Debug-string grouping (see
11506    // `build_group_ids`). Everything else falls back to the string path.
11507    let (left_ids, right_ids) = build_group_ids(left, right, by_cols)?;
11508
11509    // Group right rows by their `by` group id for asof matching (looked up by
11510    // `.get()` per left group below). No per-group sort validation is needed:
11511    // the global `ensure_sorted_non_decreasing` checks above already require the
11512    // `on` column to be non-decreasing over the whole frame, and every
11513    // per-group subsequence of a sorted column is itself sorted — so the old
11514    // per-group checks were unreachable (the global check fires first on any
11515    // unsorted input). FxHashMap (vs std SipHash) speeds the build.
11516    let mut right_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
11517    for (idx, &id) in right_ids.iter().enumerate() {
11518        right_groups.entry(id).or_default().push(idx);
11519    }
11520
11521    // Group LEFT rows by their `by` group id (preserving the globally-sorted
11522    // order within each group), then run the monotonic two-pointer asof sweep
11523    // ONCE per group over all of the group's left values — instead of rebuilding
11524    // the group's right-value vector and re-scanning it from scratch for every
11525    // individual left row (the old O(L·R) per group). compute_asof_matches
11526    // already drives a single left array with a monotonic cursor and handles
11527    // NaN left keys (→ None, cursor unchanged); because every per-group left
11528    // subsequence is sorted (the global `on` column is non-decreasing), the
11529    // grouped sweep yields the identical match for each left row as the old
11530    // fresh-per-row scan. Results are scattered by absolute left index, so the
11531    // output order is independent of group-iteration order.
11532    let mut left_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
11533    for (left_idx, &id) in left_ids.iter().enumerate() {
11534        left_groups.entry(id).or_default().push(left_idx);
11535    }
11536
11537    let mut right_matches: Vec<Option<usize>> = vec![None; left_vals.len()];
11538    for (group_id, left_positions) in &left_groups {
11539        let Some(group_indices) = right_groups.get(group_id) else {
11540            continue; // no right rows for this group -> all matches stay None
11541        };
11542        let group_right_vals: Vec<f64> = group_indices.iter().map(|&i| right_vals[i]).collect();
11543        let group_left_vals: Vec<f64> = left_positions.iter().map(|&i| left_vals[i]).collect();
11544
11545        let group_matches = compute_asof_matches(
11546            &group_left_vals,
11547            &group_right_vals,
11548            direction,
11549            options.allow_exact_matches,
11550            options.tolerance,
11551        );
11552
11553        for (k, &left_idx) in left_positions.iter().enumerate() {
11554            if let Some(Some(group_idx)) = group_matches.get(k) {
11555                right_matches[left_idx] = Some(group_indices[*group_idx]);
11556            }
11557        }
11558    }
11559
11560    build_asof_output(left, right, on, &right_matches, Some(by_cols))
11561}
11562
11563/// Borrowed, allocation-free `by`-key for the single-column factorize fast
11564/// path. Each variant is the typed payload of a `Scalar` whose *derived*
11565/// `Debug` is injective and equality-consistent — so two scalars share a
11566/// `ByKey` iff their `format!("{val:?}")` strings (the legacy group key) are
11567/// equal. `Float64` (`-0.0` vs `0.0`, `NaN`) and `Interval` Debug strings
11568/// disagree with value equality, so `from_scalar` returns `None` for them and
11569/// the caller falls back to the string path.
11570#[derive(PartialEq, Eq, Hash)]
11571enum ByKey<'a> {
11572    Null(u8),
11573    Bool(bool),
11574    Int(i64),
11575    Str(&'a str),
11576    Timedelta(i64),
11577    Datetime(i64),
11578    Period(i64),
11579}
11580
11581impl<'a> ByKey<'a> {
11582    fn from_scalar(s: &'a Scalar) -> Option<Self> {
11583        Some(match s {
11584            Scalar::Null(NullKind::Null) => ByKey::Null(0),
11585            Scalar::Null(NullKind::NaN) => ByKey::Null(1),
11586            Scalar::Null(NullKind::NaT) => ByKey::Null(2),
11587            Scalar::Bool(b) => ByKey::Bool(*b),
11588            Scalar::Int64(v) => ByKey::Int(*v),
11589            Scalar::Utf8(s) => ByKey::Str(s.as_str()),
11590            Scalar::Timedelta64(v) => ByKey::Timedelta(*v),
11591            Scalar::Datetime64(v) => ByKey::Datetime(*v),
11592            Scalar::Period(v) => ByKey::Period(v.ordinal),
11593            Scalar::Float64(_) | Scalar::Interval(_) | Scalar::Object(_) => return None,
11594        })
11595    }
11596}
11597
11598/// Factorize a single `by` column over both frames into a shared u32 id space.
11599/// Returns `None` (caller falls back to the string path) if any value is a
11600/// `Float64`/`Interval` whose Debug string would not agree with typed equality.
11601fn try_factorize_typed<'a>(
11602    left: &'a [Scalar],
11603    right: &'a [Scalar],
11604) -> Option<(Vec<u32>, Vec<u32>)> {
11605    let mut codes: FxHashMap<ByKey<'a>, u32> = FxHashMap::default();
11606    let mut next = 0u32;
11607    let mut left_ids = Vec::with_capacity(left.len());
11608    for v in left {
11609        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
11610            let i = next;
11611            next += 1;
11612            i
11613        });
11614        left_ids.push(id);
11615    }
11616    let mut right_ids = Vec::with_capacity(right.len());
11617    for v in right {
11618        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
11619            let i = next;
11620            next += 1;
11621            i
11622        });
11623        right_ids.push(id);
11624    }
11625    Some((left_ids, right_ids))
11626}
11627
11628/// Build dense u32 group ids for the left and right frames over the `by`
11629/// columns, sharing one id space. Returns `(left_ids, right_ids)`.
11630///
11631/// Fast path (a single non-float `by` column): factorize the column's scalars
11632/// directly with the borrowed typed [`ByKey`] — zero per-row string formatting
11633/// or allocation. Bit-identical to the `format!("{val:?}")` grouping because
11634/// the typed key induces the exact same equality classes. Multi-column or
11635/// float/interval `by` keys route to the original Debug-string builder, whose
11636/// per-row composite keys are then interned to u32 (one clone per *distinct*
11637/// group, not per row).
11638fn build_group_ids(
11639    left: &fp_frame::DataFrame,
11640    right: &fp_frame::DataFrame,
11641    by_cols: &[String],
11642) -> Result<(Vec<u32>, Vec<u32>), JoinError> {
11643    if by_cols.len() == 1
11644        && let (Some(lcol), Some(rcol)) = (
11645            left.columns().get(&by_cols[0]),
11646            right.columns().get(&by_cols[0]),
11647        )
11648        && let Some(ids) = try_factorize_typed(lcol.values(), rcol.values())
11649    {
11650        return Ok(ids);
11651    }
11652
11653    let left_keys = build_group_keys(left, by_cols)?;
11654    let right_keys = build_group_keys(right, by_cols)?;
11655    let mut codes: FxHashMap<Vec<String>, u32> = FxHashMap::default();
11656    let mut next = 0u32;
11657    let mut intern = |k: &Vec<String>, codes: &mut FxHashMap<Vec<String>, u32>| -> u32 {
11658        if let Some(&id) = codes.get(k) {
11659            id
11660        } else {
11661            let id = next;
11662            next += 1;
11663            codes.insert(k.clone(), id);
11664            id
11665        }
11666    };
11667    let left_ids = left_keys.iter().map(|k| intern(k, &mut codes)).collect();
11668    let right_ids = right_keys.iter().map(|k| intern(k, &mut codes)).collect();
11669    Ok((left_ids, right_ids))
11670}
11671
11672/// Build group keys from the `by` columns.
11673fn build_group_keys(
11674    df: &fp_frame::DataFrame,
11675    by_cols: &[String],
11676) -> Result<Vec<Vec<String>>, JoinError> {
11677    let n = df.len();
11678    let mut keys = vec![Vec::with_capacity(by_cols.len()); n];
11679
11680    for col_name in by_cols {
11681        let col = df.columns().get(col_name).ok_or_else(|| {
11682            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11683                "merge_asof: column '{col_name}' not found"
11684            )))
11685        })?;
11686        for (i, val) in col.values().iter().enumerate() {
11687            keys[i].push(format!("{val:?}"));
11688        }
11689    }
11690
11691    Ok(keys)
11692}
11693
11694/// Compute asof matches for a single group or the whole dataset.
11695fn compute_asof_matches(
11696    left_vals: &[f64],
11697    right_vals: &[f64],
11698    direction: AsofDirection,
11699    allow_exact_matches: bool,
11700    tolerance: Option<f64>,
11701) -> Vec<Option<usize>> {
11702    let mut right_non_nan_values = Vec::new();
11703    let mut right_non_nan_positions = Vec::new();
11704    for (pos, &rv) in right_vals.iter().enumerate() {
11705        if !rv.is_nan() {
11706            right_non_nan_values.push(rv);
11707            right_non_nan_positions.push(pos);
11708        }
11709    }
11710
11711    let mut right_matches: Vec<Option<usize>> = Vec::with_capacity(left_vals.len());
11712
11713    match direction {
11714        AsofDirection::Backward => {
11715            let mut best: Option<usize> = None;
11716            let mut best_val: Option<f64> = None;
11717            let mut j = 0usize;
11718            for &lv in left_vals {
11719                if lv.is_nan() {
11720                    right_matches.push(None);
11721                    continue;
11722                }
11723                // Advance while right <= left (or right < left if !allow_exact_matches)
11724                while j < right_non_nan_values.len() {
11725                    let rv = right_non_nan_values[j];
11726                    let should_include = if allow_exact_matches {
11727                        rv <= lv
11728                    } else {
11729                        rv < lv
11730                    };
11731                    if !should_include {
11732                        break;
11733                    }
11734                    best = Some(right_non_nan_positions[j]);
11735                    best_val = Some(rv);
11736                    j += 1;
11737                }
11738
11739                // Check tolerance
11740                let matched = match (best, best_val, tolerance) {
11741                    (Some(idx), Some(rv), Some(tol)) if (lv - rv).abs() <= tol => Some(idx),
11742                    (Some(idx), _, None) => Some(idx),
11743                    _ => None,
11744                };
11745                right_matches.push(matched);
11746            }
11747        }
11748        AsofDirection::Forward => {
11749            let mut j = 0usize;
11750            for &lv in left_vals {
11751                if lv.is_nan() {
11752                    right_matches.push(None);
11753                    continue;
11754                }
11755                // Advance while right < left (or right <= left if !allow_exact_matches)
11756                while j < right_non_nan_values.len() {
11757                    let rv = right_non_nan_values[j];
11758                    let should_skip = if allow_exact_matches {
11759                        rv < lv
11760                    } else {
11761                        rv <= lv
11762                    };
11763                    if !should_skip {
11764                        break;
11765                    }
11766                    j += 1;
11767                }
11768
11769                if j < right_non_nan_values.len() {
11770                    let rv = right_non_nan_values[j];
11771                    // Check tolerance
11772                    let matched = match tolerance {
11773                        Some(tol) if (rv - lv).abs() <= tol => Some(right_non_nan_positions[j]),
11774                        None => Some(right_non_nan_positions[j]),
11775                        _ => None,
11776                    };
11777                    right_matches.push(matched);
11778                } else {
11779                    right_matches.push(None);
11780                }
11781            }
11782        }
11783        AsofDirection::Nearest => {
11784            for &lv in left_vals {
11785                if lv.is_nan() {
11786                    right_matches.push(None);
11787                    continue;
11788                }
11789                if right_non_nan_values.is_empty() {
11790                    right_matches.push(None);
11791                    continue;
11792                }
11793
11794                // For nearest, pick the closest neighbor on each side. The
11795                // candidate window depends on whether exact (equal) keys may
11796                // match:
11797                //   allow_exact:  lower = last value <= lv, upper = first value >= lv
11798                //   !allow_exact: lower = last value <  lv, upper = first value >  lv
11799                // Selecting the window up front (rather than excluding exact
11800                // matches after the fact) skips over runs of exact-equal keys
11801                // when they are disallowed, so a nearer non-equal key beyond
11802                // the run is still found — matching pandas merge_asof.
11803                let (lower, upper) = if allow_exact_matches {
11804                    let lo = right_non_nan_values.partition_point(|rv| *rv <= lv);
11805                    let up = right_non_nan_values.partition_point(|rv| *rv < lv);
11806                    (
11807                        if lo > 0 { Some(lo - 1) } else { None },
11808                        if up < right_non_nan_values.len() {
11809                            Some(up)
11810                        } else {
11811                            None
11812                        },
11813                    )
11814                } else {
11815                    let lo = right_non_nan_values.partition_point(|rv| *rv < lv);
11816                    let up = right_non_nan_values.partition_point(|rv| *rv <= lv);
11817                    (
11818                        if lo > 0 { Some(lo - 1) } else { None },
11819                        if up < right_non_nan_values.len() {
11820                            Some(up)
11821                        } else {
11822                            None
11823                        },
11824                    )
11825                };
11826
11827                let chosen = match (lower, upper) {
11828                    (Some(l), Some(u)) => {
11829                        let lower_dist = (right_non_nan_values[l] - lv).abs();
11830                        let upper_dist = (right_non_nan_values[u] - lv).abs();
11831                        // Ties go to the lower (backward) neighbor, like pandas.
11832                        if upper_dist < lower_dist {
11833                            Some(u)
11834                        } else {
11835                            Some(l)
11836                        }
11837                    }
11838                    (Some(l), None) => Some(l),
11839                    (None, Some(u)) => Some(u),
11840                    (None, None) => None,
11841                };
11842
11843                // Apply tolerance check
11844                let matched = match chosen {
11845                    Some(idx) => {
11846                        let rv = right_non_nan_values[idx];
11847                        match tolerance {
11848                            Some(tol) if (lv - rv).abs() <= tol => {
11849                                Some(right_non_nan_positions[idx])
11850                            }
11851                            None => Some(right_non_nan_positions[idx]),
11852                            _ => None,
11853                        }
11854                    }
11855                    None => None,
11856                };
11857                right_matches.push(matched);
11858            }
11859        }
11860    }
11861
11862    right_matches
11863}
11864
11865/// Build the output DataFrame from computed matches.
11866/// One output column of `build_asof_output`: left columns are present for every
11867/// row (clone), right columns are gathered by the asof match positions.
11868enum AsofOutputTask<'a> {
11869    LeftClone(&'a Column),
11870    RightGather(&'a Column),
11871}
11872
11873fn build_asof_output(
11874    left: &fp_frame::DataFrame,
11875    right: &fp_frame::DataFrame,
11876    on: &str,
11877    right_matches: &[Option<usize>],
11878    by_cols: Option<&[String]>,
11879) -> Result<MergedDataFrame, JoinError> {
11880    let right_n = right.len();
11881
11882    let left_col_names: Vec<String> = left.column_names().iter().map(|s| s.to_string()).collect();
11883    let right_col_names_all: Vec<String> =
11884        right.column_names().iter().map(|s| s.to_string()).collect();
11885
11886    // Exclude the `on` column and `by` columns from right output
11887    let excluded_cols: HashSet<&str> = {
11888        let mut s = HashSet::new();
11889        s.insert(on);
11890        if let Some(by) = by_cols {
11891            for c in by {
11892                s.insert(c.as_str());
11893            }
11894        }
11895        s
11896    };
11897
11898    let right_col_names: Vec<String> = right_col_names_all
11899        .iter()
11900        .filter(|c| !excluded_cols.contains(c.as_str()))
11901        .cloned()
11902        .collect();
11903
11904    let left_name_set: HashSet<&String> = left_col_names.iter().collect();
11905    let right_name_set: HashSet<&String> = right_col_names_all.iter().collect();
11906    let mut excluded_names = HashSet::new();
11907    excluded_names.insert(on);
11908    // `by` columns are equi-join keys: pandas emits them once, unsuffixed,
11909    // exactly like `on`. They were left out of this set, so a `by` column
11910    // present on both sides counted as an overlap and the LEFT copy came out
11911    // as `group_x` (the right copy is excluded above), where pandas 2.2.3
11912    // returns `group` (br-frankenpandas-fkiu9, live-oracle
11913    // merge_asof_by_group_and_no_exact_matches).
11914    if let Some(by) = by_cols {
11915        for column in by {
11916            excluded_names.insert(column.as_str());
11917        }
11918    }
11919    let overlap_names =
11920        collect_overlapping_column_names(&left_name_set, &right_name_set, &excluded_names);
11921    let overlap_set: HashSet<String> = overlap_names.iter().cloned().collect();
11922    let suffixes = ResolvedMergeSuffixes::default();
11923    ensure_merge_suffixes_for_overlaps(&overlap_names, &suffixes)?;
11924
11925    let n_out = left.len();
11926    let mut out_columns = ColumnStore::new();
11927    let mut column_order: Vec<String> = Vec::new();
11928
11929    // Resolve every output column (name + build task) in order, then build the
11930    // columns — left columns clone all rows, right columns gather matched-or-null
11931    // values. Each output column is independent, so wide/large outputs build all
11932    // columns across a worker pool (br-frankenpandas-fu8f5; same disjoint-fill
11933    // pattern as the dense-i64/inner-merge builders). Bit-identical to the serial
11934    // loops: identical per-column result (left clone; right Scalar gather with
11935    // Null(NullKind::NaN) on unmatched, then Column::new with the source dtype),
11936    // inserted in the same order.
11937    let mut specs: Vec<(String, AsofOutputTask<'_>)> = Vec::new();
11938    for col_name in &left_col_names {
11939        let col = left.columns().get(col_name).ok_or_else(|| {
11940            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11941                "merge_asof: left column '{col_name}' not found"
11942            )))
11943        })?;
11944        let output_name = if overlap_set.contains(col_name) {
11945            apply_merge_suffix(col_name, suffixes.left.as_deref())
11946        } else {
11947            col_name.clone()
11948        };
11949        specs.push((output_name, AsofOutputTask::LeftClone(col)));
11950    }
11951    for col_name in &right_col_names {
11952        let right_col = right.columns().get(col_name).ok_or_else(|| {
11953            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11954                "merge_asof: right column '{col_name}' not found"
11955            )))
11956        })?;
11957        let output_name = if overlap_set.contains(col_name) {
11958            apply_merge_suffix(col_name, suffixes.right.as_deref())
11959        } else {
11960            col_name.clone()
11961        };
11962        specs.push((output_name, AsofOutputTask::RightGather(right_col)));
11963    }
11964
11965    let build_one = |task: &AsofOutputTask<'_>| -> Result<Column, JoinError> {
11966        match task {
11967            AsofOutputTask::LeftClone(col) => Ok((*col).clone()),
11968            AsofOutputTask::RightGather(right_col) => {
11969                // Typed all-valid-Float64 gather (br-frankenpandas asof typed
11970                // output): an `as_f64_slice` source is all-valid, so it carries
11971                // NO NaN values (Float64 validity marks NaN invalid, and the
11972                // slice is gated on `validity.all()`). Gather matched data into a
11973                // contiguous f64 buffer + validity bitset instead of cloning a
11974                // 32 B Scalar per row and re-validating in Column::new. Bit-
11975                // identical to the Scalar path: a matched slot is a finite
11976                // `Float64(src[j])` (valid bit), an unmatched slot is
11977                // `Null(NullKind::NaN)` (cleared bit) — exactly what the Scalar
11978                // gather + Column::new produce, with no matched-NaN ambiguity
11979                // because the source has none.
11980                if let Some(src) = right_col.as_f64_slice() {
11981                    let mut data = Vec::with_capacity(n_out);
11982                    let mut validity = fp_columnar::ValidityMask::all_valid(n_out);
11983                    for (i, m) in right_matches.iter().enumerate() {
11984                        match m {
11985                            Some(j) if *j < right_n => data.push(src[*j]),
11986                            _ => {
11987                                // 0.0 datum + cleared bit is the gap convention:
11988                                // LazyNullableFloat64 materializes Null(NaN) only
11989                                // when the datum is NOT NaN, so an unmatched slot
11990                                // must use 0.0 (a NaN datum would materialize a
11991                                // present Float64(NaN) instead).
11992                                data.push(0.0);
11993                                validity.set(i, false);
11994                            }
11995                        }
11996                    }
11997                    return Ok(Column::from_f64_values_with_validity(data, validity));
11998                }
11999                // A right column that gains an UNMATCHED row gains a gap, and an
12000                // all-valid numpy int64 cannot hold one — pandas widens it to
12001                // float64, exactly as it does for the join family. This used to
12002                // be a hand-rolled gather ending in
12003                // `Column::new(right_col.dtype(), vals)`, which kept Int64 and
12004                // left the present values pinned as ints beside a NaN.
12005                //
12006                // MEASURED, live pandas 2.2.3:
12007                //   L = DataFrame({'time':[1,5,10], 'left_val':[10,50,100]})
12008                //   R = DataFrame({'time':[2,6],    'right_val':[20,60]})
12009                //   pd.merge_asof(L, R, on='time', direction='forward')
12010                //     right_val -> [20.0, 60.0, NaN]   dtype float64
12011                //     time and left_val stay int64 — they gain no gap
12012                //   with every left row matched, right_val stays int64
12013                //
12014                // Note the rule here is PER COLUMN, unlike Series.unstack where
12015                // a gap widens the whole frame: merge builds each output column
12016                // independently, so only the column that gains the gap moves.
12017                //
12018                // reindex_join_column_with_invented_gap is the helper the nywa8
12019                // join sweep already built for this, including the guard that a
12020                // source ALREADY carrying a missing value is nullable and keeps
12021                // its dtype. merge_asof was the sibling that sweep did not
12022                // reach; calling it rather than re-deriving the rule here.
12023                Ok(reindex_join_column_with_invented_gap(
12024                    right_col,
12025                    right_matches,
12026                )?)
12027            }
12028        }
12029    };
12030
12031    let built: Vec<Result<Column, JoinError>> = {
12032        let thread_count = join_parallel_thread_count();
12033        if specs.len() > 1 && n_out >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
12034            let mut slots: Vec<Option<Result<Column, JoinError>>> =
12035                (0..specs.len()).map(|_| None).collect();
12036            let chunk = specs.len().div_ceil(thread_count).max(1);
12037            let build_one = &build_one;
12038            std::thread::scope(|scope| {
12039                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
12040                    scope.spawn(move || {
12041                        for ((_, task), slot) in spec_chunk.iter().zip(slot_chunk) {
12042                            *slot = Some(build_one(task));
12043                        }
12044                    });
12045                }
12046            });
12047            slots
12048                .into_iter()
12049                .map(|c| c.expect("every asof output column must be built"))
12050                .collect()
12051        } else {
12052            specs.iter().map(|(_, task)| build_one(task)).collect()
12053        }
12054    };
12055
12056    for ((output_name, _), column) in specs.into_iter().zip(built) {
12057        insert_merged_output_column(&mut out_columns, &mut column_order, output_name, column?)?;
12058    }
12059
12060    Ok(MergedDataFrame {
12061        index: left.index().clone(),
12062        columns: out_columns,
12063        column_order,
12064    })
12065}
12066
12067impl DataFrameMergeExt for fp_frame::DataFrame {
12068    fn merge(
12069        &self,
12070        other: &fp_frame::DataFrame,
12071        on: &[&str],
12072        how: JoinType,
12073    ) -> Result<MergedDataFrame, JoinError> {
12074        merge_dataframes_on(self, other, on, how)
12075    }
12076
12077    fn merge_with_options(
12078        &self,
12079        other: &fp_frame::DataFrame,
12080        left_on: &[&str],
12081        right_on: &[&str],
12082        how: JoinType,
12083        options: MergeExecutionOptions,
12084    ) -> Result<MergedDataFrame, JoinError> {
12085        merge_dataframes_on_with_options(self, other, left_on, right_on, how, options)
12086    }
12087
12088    fn join_on_index(
12089        &self,
12090        other: &fp_frame::DataFrame,
12091        how: JoinType,
12092    ) -> Result<MergedDataFrame, JoinError> {
12093        let left = self.reset_index(false)?;
12094        let right = other.reset_index(false)?;
12095        merge_dataframes_on(&left, &right, &["index"], how)
12096    }
12097
12098    fn merge_asof(
12099        &self,
12100        other: &fp_frame::DataFrame,
12101        on: &str,
12102        direction: &str,
12103    ) -> Result<MergedDataFrame, JoinError> {
12104        self.merge_asof_with_options(other, on, direction, MergeAsofOptions::new())
12105    }
12106
12107    fn merge_asof_with_options(
12108        &self,
12109        other: &fp_frame::DataFrame,
12110        on: &str,
12111        direction: &str,
12112        options: MergeAsofOptions,
12113    ) -> Result<MergedDataFrame, JoinError> {
12114        let dir = match direction {
12115            "backward" => AsofDirection::Backward,
12116            "forward" => AsofDirection::Forward,
12117            "nearest" => AsofDirection::Nearest,
12118            _ => {
12119                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
12120                    format!("merge_asof: invalid direction '{direction}'"),
12121                )));
12122            }
12123        };
12124        crate::merge_asof_with_options(self, other, on, dir, options)
12125    }
12126
12127    fn merge_ordered(
12128        &self,
12129        other: &fp_frame::DataFrame,
12130        on: &[&str],
12131        fill_method: Option<&str>,
12132    ) -> Result<MergedDataFrame, JoinError> {
12133        crate::merge_ordered(self, other, on, fill_method)
12134    }
12135}
12136
12137#[cfg(test)]
12138mod tests {
12139    use fp_columnar::{Column, ValidityMask};
12140    use fp_frame::{ColumnStore, Series};
12141    use fp_index::{Index, IndexLabel};
12142    use fp_types::{DType, NullKind, Scalar};
12143
12144    use super::{
12145        DataFrameMergeExt, DenseI64InnerOutputPlan, DenseI64LaneData, FusedInt64OutputColumn,
12146        FusedInt64Side, InnerPositionPlan, JoinExecutionOptions, JoinType, PositionSelection,
12147        ResolvedMergeSuffixes, build_dense_i64_inner_output_data,
12148        build_single_key_dense_cycle_i64_left_merge_output,
12149        build_single_key_dense_i64_left_merge_output,
12150        build_single_key_dense_i64_right_merge_output,
12151        build_single_key_inner_contiguous_no_overlap_output, dense_int64_outer_positions,
12152        join_series, join_series_with_options, join_series_with_trace,
12153        lower_hex_overlap_plan_from_certificates, ordered_unique_int64_outer_positions,
12154        ordered_unique_utf8_inner_position_plan, ordered_unique_utf8_inner_positions,
12155        ordered_utf8_lower_hex_overlap_len, scalar_utf8_left_positions,
12156        scalar_utf8_outer_positions, sorted_contiguous_utf8_inner_positions,
12157        strictly_increasing_utf8_key_spans, utf8_span_lower_bound,
12158    };
12159
12160    fn contiguous_utf8_column(values: &[&str]) -> Column {
12161        let mut bytes = Vec::new();
12162        let mut offsets = Vec::with_capacity(values.len() + 1);
12163        offsets.push(0);
12164        for value in values {
12165            bytes.extend_from_slice(value.as_bytes());
12166            offsets.push(bytes.len());
12167        }
12168        Column::from_utf8_contiguous(bytes, offsets)
12169    }
12170
12171    fn utf8_key_merge_frame(keys: &[&str], value_name: &str, base: i64) -> DataFrame {
12172        let index = Index::new(
12173            (0..keys.len())
12174                .map(|row| IndexLabel::Int64(row as i64))
12175                .collect(),
12176        );
12177        let mut columns = ColumnStore::new();
12178        columns.insert("id".to_owned(), contiguous_utf8_column(keys));
12179        columns.insert(
12180            value_name.to_owned(),
12181            Column::from_i64_values((0..keys.len()).map(|row| base + row as i64).collect()),
12182        );
12183        DataFrame::new_with_column_order(
12184            index,
12185            columns,
12186            vec!["id".to_owned(), value_name.to_owned()],
12187        )
12188        .expect("utf8 key frame")
12189    }
12190
12191    fn scalar_utf8_column(values: &[&str]) -> Column {
12192        Column::from_values(
12193            values
12194                .iter()
12195                .map(|value| Scalar::Utf8((*value).to_owned()))
12196                .collect(),
12197        )
12198        .expect("scalar utf8 column")
12199    }
12200
12201    #[test]
12202    fn scalar_utf8_left_positions_preserve_duplicate_order_blackthrush() {
12203        let left = scalar_utf8_column(&["b", "a", "b", "x"]);
12204        let right = scalar_utf8_column(&["a", "b", "b"]);
12205
12206        let (left_positions, right_positions) =
12207            scalar_utf8_left_positions(&left, &right).expect("scalar utf8 left positions");
12208
12209        assert_eq!(
12210            left_positions,
12211            vec![Some(0), Some(0), Some(1), Some(2), Some(2), Some(3)]
12212        );
12213        assert_eq!(
12214            right_positions,
12215            vec![Some(1), Some(2), Some(0), Some(1), Some(2), None]
12216        );
12217    }
12218
12219    #[test]
12220    fn scalar_utf8_outer_positions_sort_keys_and_keep_unmatched_blackthrush() {
12221        let left = scalar_utf8_column(&["b", "a", "b", "x"]);
12222        let right = scalar_utf8_column(&["a", "b", "b", "z"]);
12223
12224        let (left_positions, right_positions) =
12225            scalar_utf8_outer_positions(&left, &right).expect("scalar utf8 outer positions");
12226
12227        assert_eq!(
12228            left_positions,
12229            vec![Some(1), Some(0), Some(0), Some(2), Some(2), Some(3), None,]
12230        );
12231        assert_eq!(
12232            right_positions,
12233            vec![Some(0), Some(1), Some(2), Some(1), Some(2), None, Some(3),]
12234        );
12235    }
12236
12237    #[test]
12238    fn dense_outer_positions_group_repeated_keys_e186m() {
12239        // Each side's rows grouped by key in one counting pass: keys
12240        // ascending, a key's left rows in order, each with its right rows
12241        // in order, a one-sided key with None opposite (br-frankenpandas-e186m).
12242        let left = Column::from_i64_values(vec![3, 1, 3, 2]);
12243        let right = Column::from_i64_values(vec![1, 3, 3, 5]);
12244        let (left_positions, right_positions) =
12245            dense_int64_outer_positions(&left, &right).expect("dense outer positions");
12246        assert_eq!(
12247            left_positions,
12248            vec![Some(1), Some(3), Some(0), Some(0), Some(2), Some(2), None]
12249        );
12250        assert_eq!(
12251            right_positions,
12252            vec![Some(0), None, Some(1), Some(2), Some(1), Some(2), Some(3)]
12253        );
12254        // A key holding a missing value, or keys spread past the dense table,
12255        // decline (NEGATIVE).
12256        let gappy = Column::new(
12257            DType::Int64,
12258            vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)],
12259        )
12260        .expect("int column with a gap");
12261        assert!(dense_int64_outer_positions(&gappy, &right).is_none());
12262        let sparse = Column::from_i64_values(vec![0, 1_000_000_000, 0]);
12263        assert!(dense_int64_outer_positions(&sparse, &right).is_none());
12264    }
12265
12266    #[test]
12267    fn inner_join_multiplies_cardinality_for_duplicates() {
12268        let left = Series::from_values(
12269            "left",
12270            vec!["k".into(), "k".into(), "x".into()],
12271            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12272        )
12273        .expect("left");
12274
12275        let right = Series::from_values(
12276            "right",
12277            vec!["k".into(), "k".into()],
12278            vec![Scalar::Int64(10), Scalar::Int64(20)],
12279        )
12280        .expect("right");
12281
12282        let out = join_series(&left, &right, JoinType::Inner).expect("join");
12283        assert_eq!(out.index.labels().len(), 4);
12284        assert_eq!(
12285            out.left_values.values(),
12286            &[
12287                Scalar::Int64(1),
12288                Scalar::Int64(1),
12289                Scalar::Int64(2),
12290                Scalar::Int64(2)
12291            ]
12292        );
12293    }
12294
12295    #[test]
12296    fn left_join_injects_missing_for_unmatched_right_rows() {
12297        let left = Series::from_values(
12298            "left",
12299            vec!["a".into(), "b".into()],
12300            vec![Scalar::Int64(1), Scalar::Int64(2)],
12301        )
12302        .expect("left");
12303        let right =
12304            Series::from_values("right", vec!["a".into()], vec![Scalar::Int64(10)]).expect("right");
12305
12306        let out = join_series(&left, &right, JoinType::Left).expect("join");
12307        // The right side gains a gap, so pandas widens it to float64 and the
12308        // gap is a NaN — on a LEFT join exactly as on an outer one. MEASURED,
12309        // live pandas 2.2.3, l=[10,20,30]@[1,2,3] joined with r=[200]@[2]:
12310        //   how='left'  -> l int64 [10,20,30]   r float64 [nan, 200.0, nan]
12311        //   how='outer' -> same
12312        // This assertion previously pinned Int64 + Null(Null), which was
12313        // FrankenPandas' own pre-fix answer. (br-frankenpandas-nywa8)
12314        assert_eq!(
12315            out.right_values.values(),
12316            &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
12317        );
12318    }
12319
12320    #[test]
12321    fn arena_join_matches_global_allocator_behavior() {
12322        let left = Series::from_values(
12323            "left",
12324            vec!["k".into(), "k".into(), "x".into()],
12325            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12326        )
12327        .expect("left");
12328
12329        let right = Series::from_values(
12330            "right",
12331            vec!["k".into(), "k".into()],
12332            vec![Scalar::Int64(10), Scalar::Int64(20)],
12333        )
12334        .expect("right");
12335
12336        let global = join_series_with_options(
12337            &left,
12338            &right,
12339            JoinType::Inner,
12340            JoinExecutionOptions {
12341                use_arena: false,
12342                arena_budget_bytes: 0,
12343            },
12344        )
12345        .expect("global join");
12346
12347        let arena = join_series_with_options(
12348            &left,
12349            &right,
12350            JoinType::Inner,
12351            JoinExecutionOptions::default(),
12352        )
12353        .expect("arena join");
12354
12355        assert_eq!(arena, global);
12356    }
12357
12358    #[test]
12359    fn arena_join_falls_back_when_budget_is_too_small() {
12360        let left = Series::from_values(
12361            "left",
12362            vec!["a".into(), "a".into(), "a".into()],
12363            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12364        )
12365        .expect("left");
12366        let right = Series::from_values(
12367            "right",
12368            vec!["a".into(), "a".into()],
12369            vec![Scalar::Int64(10), Scalar::Int64(20)],
12370        )
12371        .expect("right");
12372
12373        let options = JoinExecutionOptions {
12374            use_arena: true,
12375            arena_budget_bytes: 1,
12376        };
12377        let (fallback_out, trace) =
12378            join_series_with_trace(&left, &right, JoinType::Inner, options).expect("fallback join");
12379        let global_out = join_series_with_options(
12380            &left,
12381            &right,
12382            JoinType::Inner,
12383            JoinExecutionOptions {
12384                use_arena: false,
12385                arena_budget_bytes: 0,
12386            },
12387        )
12388        .expect("global join");
12389
12390        assert_eq!(fallback_out, global_out);
12391        assert!(!trace.used_arena);
12392        assert!(trace.estimated_bytes > options.arena_budget_bytes);
12393    }
12394
12395    #[test]
12396    fn arena_join_is_stable_across_many_small_operations() {
12397        let left = Series::from_values(
12398            "left",
12399            vec!["a".into(), "b".into()],
12400            vec![Scalar::Int64(1), Scalar::Int64(2)],
12401        )
12402        .expect("left");
12403        let right = Series::from_values(
12404            "right",
12405            vec!["a".into(), "b".into()],
12406            vec![Scalar::Int64(10), Scalar::Int64(20)],
12407        )
12408        .expect("right");
12409
12410        let options = JoinExecutionOptions::default();
12411        for _ in 0..1_000 {
12412            let out = join_series_with_options(&left, &right, JoinType::Inner, options)
12413                .expect("arena join");
12414            assert_eq!(out.index.labels().len(), 2);
12415            assert_eq!(
12416                out.right_values.values(),
12417                &[Scalar::Int64(10), Scalar::Int64(20)]
12418            );
12419        }
12420    }
12421
12422    /// AG-06-T test #8: 100K-row inner join with arena -> correct output, no OOM.
12423    #[test]
12424    fn arena_large_join_100k_rows() {
12425        let n = 100_000;
12426        let labels: Vec<IndexLabel> = (0..n).map(|i| IndexLabel::Int64(i as i64 % 1000)).collect();
12427        let values: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
12428
12429        let left = Series::from_values("left", labels.clone(), values.clone()).expect("left");
12430        let right = Series::from_values("right", labels, values).expect("right");
12431
12432        let out = join_series_with_options(
12433            &left,
12434            &right,
12435            JoinType::Inner,
12436            JoinExecutionOptions::default(),
12437        )
12438        .expect("100K arena join");
12439
12440        // With 1000 distinct keys, each appearing 100 times on each side,
12441        // inner join produces 100 * 100 * 1000 = 10M rows.
12442        // But that's too large; use a budget that forces fallback.
12443        let out_fallback = join_series_with_options(
12444            &left,
12445            &right,
12446            JoinType::Inner,
12447            JoinExecutionOptions {
12448                use_arena: true,
12449                arena_budget_bytes: 1,
12450            },
12451        )
12452        .expect("100K fallback join");
12453
12454        assert_eq!(out.index.labels().len(), out_fallback.index.labels().len());
12455    }
12456
12457    #[test]
12458    fn right_join_contains_all_right_labels() {
12459        let left = Series::from_values(
12460            "left",
12461            vec!["a".into(), "b".into()],
12462            vec![Scalar::Int64(1), Scalar::Int64(2)],
12463        )
12464        .expect("left");
12465        let right = Series::from_values(
12466            "right",
12467            vec!["b".into(), "c".into()],
12468            vec![Scalar::Int64(20), Scalar::Int64(30)],
12469        )
12470        .expect("right");
12471
12472        let out = join_series(&left, &right, JoinType::Right).expect("join");
12473        // Right join: all right labels preserved. "b" matches, "c" unmatched.
12474        assert_eq!(out.index.labels().len(), 2);
12475        assert_eq!(
12476            out.index.labels(),
12477            &[IndexLabel::Utf8("b".into()), IndexLabel::Utf8("c".into())]
12478        );
12479        // "b" matched -> left=2, right=20. "c" unmatched -> left is a gap, so
12480        // the LEFT lane widens to float64 with a NaN (br-frankenpandas-nywa8;
12481        // the widening follows the invented gap, not the join type).
12482        assert_eq!(
12483            out.left_values.values(),
12484            &[Scalar::Float64(2.0), Scalar::Null(NullKind::NaN)]
12485        );
12486        assert_eq!(
12487            out.right_values.values(),
12488            &[Scalar::Int64(20), Scalar::Int64(30)]
12489        );
12490    }
12491
12492    #[test]
12493    fn right_join_multiplies_cardinality_for_duplicates() {
12494        let left = Series::from_values(
12495            "left",
12496            vec!["k".into(), "k".into()],
12497            vec![Scalar::Int64(1), Scalar::Int64(2)],
12498        )
12499        .expect("left");
12500        let right = Series::from_values(
12501            "right",
12502            vec!["k".into(), "x".into()],
12503            vec![Scalar::Int64(10), Scalar::Int64(30)],
12504        )
12505        .expect("right");
12506
12507        let out = join_series(&left, &right, JoinType::Right).expect("join");
12508        // "k" in right matches 2 left rows -> 2 output rows for "k", plus 1 for "x" unmatched.
12509        assert_eq!(out.index.labels().len(), 3);
12510        assert_eq!(
12511            out.right_values.values(),
12512            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(30)]
12513        );
12514    }
12515
12516    #[test]
12517    fn outer_join_contains_all_labels_from_both_sides() {
12518        let left = Series::from_values(
12519            "left",
12520            vec!["a".into(), "b".into()],
12521            vec![Scalar::Int64(1), Scalar::Int64(2)],
12522        )
12523        .expect("left");
12524        let right = Series::from_values(
12525            "right",
12526            vec!["b".into(), "c".into()],
12527            vec![Scalar::Int64(20), Scalar::Int64(30)],
12528        )
12529        .expect("right");
12530
12531        let out = join_series(&left, &right, JoinType::Outer).expect("join");
12532        // Outer: "a" (left only), "b" (both), "c" (right only) -> 3 rows
12533        assert_eq!(out.index.labels().len(), 3);
12534        assert_eq!(
12535            out.left_values.values(),
12536            &[
12537                Scalar::Float64(1.0),
12538                Scalar::Float64(2.0),
12539                Scalar::Null(NullKind::NaN)
12540            ]
12541        );
12542        assert_eq!(
12543            out.right_values.values(),
12544            &[
12545                Scalar::Null(NullKind::NaN),
12546                Scalar::Float64(20.0),
12547                Scalar::Float64(30.0)
12548            ]
12549        );
12550    }
12551
12552    #[test]
12553    fn outer_join_sorts_union_labels_like_pandas() {
12554        let left = Series::from_values(
12555            "left",
12556            vec!["a".into(), "c".into()],
12557            vec![Scalar::Int64(1), Scalar::Int64(3)],
12558        )
12559        .expect("left");
12560        let right = Series::from_values(
12561            "right",
12562            vec!["b".into(), "c".into()],
12563            vec![Scalar::Int64(20), Scalar::Int64(30)],
12564        )
12565        .expect("right");
12566
12567        let out = join_series(&left, &right, JoinType::Outer).expect("join");
12568        assert_eq!(
12569            out.index.labels(),
12570            &[
12571                IndexLabel::Utf8("a".into()),
12572                IndexLabel::Utf8("b".into()),
12573                IndexLabel::Utf8("c".into())
12574            ]
12575        );
12576        assert_eq!(
12577            out.left_values.values(),
12578            &[
12579                Scalar::Float64(1.0),
12580                Scalar::Null(NullKind::NaN),
12581                Scalar::Float64(3.0)
12582            ]
12583        );
12584        assert_eq!(
12585            out.right_values.values(),
12586            &[
12587                Scalar::Null(NullKind::NaN),
12588                Scalar::Float64(20.0),
12589                Scalar::Float64(30.0)
12590            ]
12591        );
12592    }
12593
12594    #[test]
12595    fn outer_join_with_duplicates() {
12596        let left = Series::from_values(
12597            "left",
12598            vec!["k".into(), "k".into(), "a".into()],
12599            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12600        )
12601        .expect("left");
12602        let right = Series::from_values(
12603            "right",
12604            vec!["k".into(), "z".into()],
12605            vec![Scalar::Int64(10), Scalar::Int64(99)],
12606        )
12607        .expect("right");
12608
12609        let out = join_series(&left, &right, JoinType::Outer).expect("join");
12610        // "k" x "k": 2 matched rows. "a": left-only (1 row). "z": right-only (1 row).
12611        assert_eq!(out.index.labels().len(), 4);
12612    }
12613
12614    #[test]
12615    fn arena_right_join_matches_global() {
12616        let left = Series::from_values(
12617            "left",
12618            vec!["a".into(), "b".into()],
12619            vec![Scalar::Int64(1), Scalar::Int64(2)],
12620        )
12621        .expect("left");
12622        let right = Series::from_values(
12623            "right",
12624            vec!["b".into(), "c".into()],
12625            vec![Scalar::Int64(20), Scalar::Int64(30)],
12626        )
12627        .expect("right");
12628
12629        let global = join_series_with_options(
12630            &left,
12631            &right,
12632            JoinType::Right,
12633            JoinExecutionOptions {
12634                use_arena: false,
12635                arena_budget_bytes: 0,
12636            },
12637        )
12638        .expect("global");
12639        let arena = join_series_with_options(
12640            &left,
12641            &right,
12642            JoinType::Right,
12643            JoinExecutionOptions::default(),
12644        )
12645        .expect("arena");
12646        assert_eq!(arena, global);
12647    }
12648
12649    #[test]
12650    fn arena_outer_join_matches_global() {
12651        let left = Series::from_values(
12652            "left",
12653            vec!["a".into(), "b".into()],
12654            vec![Scalar::Int64(1), Scalar::Int64(2)],
12655        )
12656        .expect("left");
12657        let right = Series::from_values(
12658            "right",
12659            vec!["b".into(), "c".into()],
12660            vec![Scalar::Int64(20), Scalar::Int64(30)],
12661        )
12662        .expect("right");
12663
12664        let global = join_series_with_options(
12665            &left,
12666            &right,
12667            JoinType::Outer,
12668            JoinExecutionOptions {
12669                use_arena: false,
12670                arena_budget_bytes: 0,
12671            },
12672        )
12673        .expect("global");
12674        let arena = join_series_with_options(
12675            &left,
12676            &right,
12677            JoinType::Outer,
12678            JoinExecutionOptions::default(),
12679        )
12680        .expect("arena");
12681        assert_eq!(arena, global);
12682    }
12683
12684    /// AG-06-T test #6: arena is scoped per-operation. Two sequential
12685    /// operations each get their own arena (verified by both succeeding).
12686    #[test]
12687    fn arena_reset_between_operations() {
12688        let left = Series::from_values(
12689            "left",
12690            vec!["a".into(), "b".into()],
12691            vec![Scalar::Int64(1), Scalar::Int64(2)],
12692        )
12693        .expect("left");
12694        let right = Series::from_values(
12695            "right",
12696            vec!["a".into(), "c".into()],
12697            vec![Scalar::Int64(10), Scalar::Int64(30)],
12698        )
12699        .expect("right");
12700
12701        // Operation 1: inner join
12702        let out1 = join_series_with_options(
12703            &left,
12704            &right,
12705            JoinType::Inner,
12706            JoinExecutionOptions::default(),
12707        )
12708        .expect("op1");
12709        assert_eq!(out1.index.labels().len(), 1);
12710
12711        // Operation 2: left join (arena from op1 was freed)
12712        let out2 = join_series_with_options(
12713            &left,
12714            &right,
12715            JoinType::Left,
12716            JoinExecutionOptions::default(),
12717        )
12718        .expect("op2");
12719        assert_eq!(out2.index.labels().len(), 2);
12720    }
12721
12722    // ---- DataFrame merge tests (bd-2gi.17) ----
12723
12724    use fp_frame::{DataFrame, FrameError};
12725
12726    use super::{
12727        JoinError, MergeExecutionOptions, MergeValidateMode, MergedDataFrame,
12728        build_single_key_dense_right_merge_output, dense_int64_right_positions, merge_dataframes,
12729        merge_dataframes_on, merge_dataframes_on_with, merge_dataframes_on_with_options,
12730        ordered_identity_int64_keys_match, resolve_merge_suffixes,
12731    };
12732
12733    fn make_left_df() -> DataFrame {
12734        DataFrame::from_dict(
12735            &["id", "val_a"],
12736            vec![
12737                (
12738                    "id",
12739                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12740                ),
12741                (
12742                    "val_a",
12743                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
12744                ),
12745            ],
12746        )
12747        .unwrap()
12748    }
12749
12750    fn make_right_df() -> DataFrame {
12751        DataFrame::from_dict(
12752            &["id", "val_b"],
12753            vec![
12754                (
12755                    "id",
12756                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
12757                ),
12758                (
12759                    "val_b",
12760                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
12761                ),
12762            ],
12763        )
12764        .unwrap()
12765    }
12766
12767    #[test]
12768    fn merge_preserves_pandas_column_order_for_nonalphabetical_names() {
12769        // br-frankenpandas-691lh: output columns follow pandas order — key/left
12770        // columns in the LEFT frame's source order, then right non-key columns —
12771        // not alphabetical (the columns map is a BTreeMap). Verified vs pandas
12772        // 2.2.3: merge(left[k,zebra,apple], right[k,mango], on=k)
12773        //   -> [k, zebra, apple, mango].
12774        let left = DataFrame::from_dict(
12775            &["k", "zebra", "apple"],
12776            vec![
12777                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
12778                ("zebra", vec![Scalar::Int64(10), Scalar::Int64(20)]),
12779                ("apple", vec![Scalar::Int64(30), Scalar::Int64(40)]),
12780            ],
12781        )
12782        .unwrap();
12783        let right = DataFrame::from_dict(
12784            &["k", "mango"],
12785            vec![
12786                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
12787                ("mango", vec![Scalar::Int64(50), Scalar::Int64(60)]),
12788            ],
12789        )
12790        .unwrap();
12791        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
12792        let order: Vec<&str> = merged.column_order.iter().map(String::as_str).collect();
12793        assert_eq!(order, ["k", "zebra", "apple", "mango"]);
12794    }
12795
12796    #[test]
12797    fn merge_outer_gap_widens_int64_and_keeps_int64_nullable_4qg5w_11() {
12798        // DISC-011's merge row (pandas 2.2.3): the row an outer merge invents
12799        // is float64 NaN in a numpy int64 column and NA in a nullable Int64.
12800        let frame = |key: &str, keys: &[i64], name: &str, dtype: DType, values: &[i64]| {
12801            let ints = |xs: &[i64]| xs.iter().map(|x| Scalar::Int64(*x)).collect::<Vec<_>>();
12802            let labels = (0..keys.len() as i64).map(IndexLabel::Int64).collect();
12803            let columns = std::collections::BTreeMap::from([
12804                (
12805                    key.to_owned(),
12806                    Column::new(DType::Int64, ints(keys)).unwrap(),
12807                ),
12808                (name.to_owned(), Column::new(dtype, ints(values)).unwrap()),
12809            ]);
12810            DataFrame::new_with_column_order(
12811                Index::new(labels),
12812                columns,
12813                vec![key.to_owned(), name.to_owned()],
12814            )
12815            .unwrap()
12816        };
12817        for (dtype, widened) in [
12818            (DType::Int64, DType::Float64),
12819            (DType::Int64Nullable, DType::Int64Nullable),
12820        ] {
12821            let left = frame("k", &[1, 2], "v", dtype.clone(), &[7, 8]);
12822            let right = frame("k", &[2, 3], "w", dtype.clone(), &[5, 6]);
12823            let merged = merge_dataframes(&left, &right, "k", JoinType::Outer).unwrap();
12824            let v = merged.columns.get("v").unwrap();
12825            assert_eq!(v.dtype(), widened, "{dtype:?}");
12826            match widened {
12827                DType::Float64 => {
12828                    assert_eq!(v.values()[0], Scalar::Float64(7.0));
12829                    assert_eq!(v.values()[2], Scalar::Null(NullKind::NaN));
12830                }
12831                _ => {
12832                    assert_eq!(v.values()[0], Scalar::Int64(7));
12833                    assert!(v.values()[2].is_missing(), "{dtype:?}: {:?}", v.values());
12834                }
12835            }
12836        }
12837    }
12838
12839    #[test]
12840    fn join_row_count_lattice_n8npw() {
12841        // Invariant (br-frankenpandas-n8npw): inner<=left<=outer and inner<=right<=outer
12842        // by row count. Seeded LCG, no mocks.
12843        let mut s: u64 = 0x4e57_0b1c_2d3e_4f55;
12844        let mut next = || {
12845            s = s
12846                .wrapping_mul(6_364_136_223_846_793_005)
12847                .wrapping_add(1_442_695_040_888_963_407);
12848            (s >> 33) as u32
12849        };
12850        for iter in 0..300u32 {
12851            let ln = (next() % 6) as usize + 1;
12852            let rn = (next() % 6) as usize + 1;
12853            let lk: Vec<Scalar> = (0..ln)
12854                .map(|_| Scalar::Int64((next() % 4) as i64))
12855                .collect();
12856            let rk: Vec<Scalar> = (0..rn)
12857                .map(|_| Scalar::Int64((next() % 4) as i64))
12858                .collect();
12859            let left = DataFrame::from_dict(
12860                &["k", "lv"],
12861                vec![
12862                    ("k", lk),
12863                    ("lv", (0..ln).map(|i| Scalar::Int64(i as i64)).collect()),
12864                ],
12865            )
12866            .unwrap();
12867            let right = DataFrame::from_dict(
12868                &["k", "rv"],
12869                vec![
12870                    ("k", rk),
12871                    ("rv", (0..rn).map(|i| Scalar::Int64(i as i64)).collect()),
12872                ],
12873            )
12874            .unwrap();
12875            let rows = |jt| {
12876                let m = merge_dataframes(&left, &right, "k", jt).unwrap();
12877                merged_values(&m, "k").unwrap().len()
12878            };
12879            let inner = rows(JoinType::Inner);
12880            let lj = rows(JoinType::Left);
12881            let rj = rows(JoinType::Right);
12882            let outer = rows(JoinType::Outer);
12883            assert!(
12884                inner <= lj && lj <= outer,
12885                "inner<=left<=outer iter={iter}: {inner} {lj} {outer}"
12886            );
12887            assert!(
12888                inner <= rj && rj <= outer,
12889                "inner<=right<=outer iter={iter}: {inner} {rj} {outer}"
12890            );
12891        }
12892    }
12893
12894    #[test]
12895    fn right_join_null_fill_multiset_7je8m() {
12896        use std::collections::HashMap;
12897        // Differential (br-frankenpandas-7je8m): RIGHT join preserves every right row;
12898        // matched left payload cross-product else null. (key, lv-or-None, rv) multiset
12899        // vs oracle. Seeded LCG, no mocks.
12900        let mut s: u64 = 0x4e57_0b1c_2d3e_4f54;
12901        let mut next = || {
12902            s = s
12903                .wrapping_mul(6_364_136_223_846_793_005)
12904                .wrapping_add(1_442_695_040_888_963_407);
12905            (s >> 33) as u32
12906        };
12907        for iter in 0..300u32 {
12908            let ln = (next() % 6) as usize + 1;
12909            let rn = (next() % 6) as usize + 1;
12910            let lk: Vec<i64> = (0..ln).map(|_| (next() % 4) as i64).collect();
12911            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
12912            let rk: Vec<i64> = (0..rn).map(|_| (next() % 4) as i64).collect();
12913            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
12914            let left = DataFrame::from_dict(
12915                &["k", "lv"],
12916                vec![
12917                    ("k", lk.iter().map(|&x| Scalar::Int64(x)).collect()),
12918                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
12919                ],
12920            )
12921            .unwrap();
12922            let right = DataFrame::from_dict(
12923                &["k", "rv"],
12924                vec![
12925                    ("k", rk.iter().map(|&x| Scalar::Int64(x)).collect()),
12926                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
12927                ],
12928            )
12929            .unwrap();
12930            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).unwrap();
12931
12932            let ks = merged_values(&merged, "k").unwrap();
12933            let lvs = merged_values(&merged, "lv").unwrap();
12934            let rvs = merged_values(&merged, "rv").unwrap();
12935            let ki = |v: &Scalar| -> i64 {
12936                match v {
12937                    Scalar::Int64(x) => *x,
12938                    Scalar::Float64(x) => *x as i64,
12939                    _ => i64::MIN,
12940                }
12941            };
12942            let kopt =
12943                |v: &Scalar| -> Option<i64> { if v.is_missing() { None } else { Some(ki(v)) } };
12944            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
12945                .map(|i| (ki(&ks[i]), kopt(&lvs[i]), ki(&rvs[i])))
12946                .collect();
12947            // Oracle.
12948            let mut lby: HashMap<i64, Vec<i64>> = HashMap::new();
12949            for i in 0..ln {
12950                lby.entry(lk[i]).or_default().push(lv[i]);
12951            }
12952            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
12953            for i in 0..rn {
12954                match lby.get(&rk[i]) {
12955                    Some(lvals) => {
12956                        for &a in lvals {
12957                            exp.push((rk[i], Some(a), rv[i]));
12958                        }
12959                    }
12960                    None => exp.push((rk[i], None, rv[i])),
12961                }
12962            }
12963            got.sort();
12964            exp.sort();
12965            assert_eq!(got, exp, "right join multiset iter={iter}");
12966        }
12967    }
12968
12969    #[test]
12970    fn inner_join_utf8_value_multiset_fr4ns() {
12971        use std::collections::HashMap;
12972        // Differential (br-frankenpandas-fr4ns): inner join on Utf8 keys; the (key,
12973        // lv, rv) multiset == per-key cross-product (5foyp was int/dense; jlf8d a
12974        // single case). Seeded LCG, no mocks.
12975        let mut s: u64 = 0x4e57_0b1c_2d3e_4f51;
12976        let mut next = || {
12977            s = s
12978                .wrapping_mul(6_364_136_223_846_793_005)
12979                .wrapping_add(1_442_695_040_888_963_407);
12980            (s >> 33) as u32
12981        };
12982        let key = |n: u32| Scalar::Utf8(format!("{}", (b'a' + (n % 4) as u8) as char));
12983        for iter in 0..300u32 {
12984            let ln = (next() % 6) as usize + 1;
12985            let rn = (next() % 6) as usize + 1;
12986            let lk: Vec<Scalar> = (0..ln).map(|_| key(next())).collect();
12987            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
12988            let rk: Vec<Scalar> = (0..rn).map(|_| key(next())).collect();
12989            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
12990            let left = DataFrame::from_dict(
12991                &["k", "lv"],
12992                vec![
12993                    ("k", lk.clone()),
12994                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
12995                ],
12996            )
12997            .unwrap();
12998            let right = DataFrame::from_dict(
12999                &["k", "rv"],
13000                vec![
13001                    ("k", rk.clone()),
13002                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
13003                ],
13004            )
13005            .unwrap();
13006            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
13007
13008            let ks = merged_values(&merged, "k").unwrap();
13009            let lvs = merged_values(&merged, "lv").unwrap();
13010            let rvs = merged_values(&merged, "rv").unwrap();
13011            let kstr = |v: &Scalar| -> String {
13012                match v {
13013                    Scalar::Utf8(x) => x.clone(),
13014                    _ => String::new(),
13015                }
13016            };
13017            let ki = |v: &Scalar| -> i64 {
13018                match v {
13019                    Scalar::Int64(x) => *x,
13020                    _ => i64::MIN,
13021                }
13022            };
13023            let mut got: Vec<(String, i64, i64)> = (0..ks.len())
13024                .map(|i| (kstr(&ks[i]), ki(&lvs[i]), ki(&rvs[i])))
13025                .collect();
13026            // Oracle: per-key cross product.
13027            let mut lby: HashMap<String, Vec<i64>> = HashMap::new();
13028            for i in 0..ln {
13029                lby.entry(kstr(&lk[i])).or_default().push(lv[i]);
13030            }
13031            let mut rby: HashMap<String, Vec<i64>> = HashMap::new();
13032            for i in 0..rn {
13033                rby.entry(kstr(&rk[i])).or_default().push(rv[i]);
13034            }
13035            let mut exp: Vec<(String, i64, i64)> = Vec::new();
13036            for (k, lvals) in &lby {
13037                if let Some(rvals) = rby.get(k) {
13038                    for &a in lvals {
13039                        for &b in rvals {
13040                            exp.push((k.clone(), a, b));
13041                        }
13042                    }
13043                }
13044            }
13045            got.sort();
13046            exp.sort();
13047            assert_eq!(got, exp, "inner Utf8 multiset iter={iter}");
13048        }
13049    }
13050
13051    #[test]
13052    fn inner_join_utf8_keys_jlf8d() {
13053        use std::collections::HashMap;
13054        // br-frankenpandas-jlf8d: inner join on Utf8 keys (general/hash path).
13055        let s = |v: &str| Scalar::Utf8(v.to_owned());
13056        let left = DataFrame::from_dict(
13057            &["k", "lv"],
13058            vec![
13059                ("k", vec![s("a"), s("b"), s("c")]),
13060                (
13061                    "lv",
13062                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13063                ),
13064            ],
13065        )
13066        .expect("left");
13067        let right = DataFrame::from_dict(
13068            &["k", "rv"],
13069            vec![
13070                ("k", vec![s("b"), s("c"), s("d")]),
13071                (
13072                    "rv",
13073                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
13074                ),
13075            ],
13076        )
13077        .expect("right");
13078        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
13079
13080        let keys = merged_values(&merged, "k").expect("k");
13081        let lv = merged_values(&merged, "lv").expect("lv");
13082        let rv = merged_values(&merged, "rv").expect("rv");
13083        let exp_lv: HashMap<&str, i64> = [("b", 2), ("c", 3)].into_iter().collect();
13084        let exp_rv: HashMap<&str, i64> = [("b", 10), ("c", 20)].into_iter().collect();
13085        assert_eq!(keys.len(), 2, "inner keys = {{b,c}}");
13086        for i in 0..keys.len() {
13087            let k = match &keys[i] {
13088                Scalar::Utf8(x) => x.as_str(),
13089                _ => "?",
13090            };
13091            let geti = |s: &Scalar| match s {
13092                Scalar::Int64(v) => *v,
13093                _ => i64::MIN,
13094            };
13095            assert_eq!(geti(&lv[i]), exp_lv[k], "lv at {k}");
13096            assert_eq!(geti(&rv[i]), exp_rv[k], "rv at {k}");
13097        }
13098    }
13099
13100    #[test]
13101    fn merge_indicator_is_held_as_codes_fl3f0() {
13102        // br-frankenpandas-fl3f0: `_merge` is each row's code into the fixed
13103        // categories [left_only, right_only, both] (0 / 1 / 2), as pandas'
13104        // Categorical - a String a row was made into a Scalar-backed
13105        // categorical - and reads back as those categories. NEGATIVE: a row
13106        // in neither side would be missing (-1), never a category.
13107        let left_positions = [Some(0), Some(1), None, Some(2)];
13108        let right_positions = [None, Some(0), Some(1), Some(1)];
13109        let column = super::build_merge_indicator_column(&left_positions, &right_positions);
13110        assert_eq!(column.dtype(), fp_types::DType::Categorical);
13111        assert_eq!(column.categorical_codes(), Some(&[0, 2, 1, 2][..]));
13112        let categories: Vec<Scalar> = ["left_only", "right_only", "both"]
13113            .map(|category| Scalar::Utf8(category.to_owned()))
13114            .to_vec();
13115        assert_eq!(
13116            column.categorical().map(|meta| meta.categories.clone()),
13117            Some(categories)
13118        );
13119        let shown: Vec<Scalar> = ["left_only", "both", "right_only", "both"]
13120            .map(|value| Scalar::Utf8(value.to_owned()))
13121            .to_vec();
13122        assert_eq!(column.values(), shown.as_slice());
13123        let neither = super::build_merge_indicator_column(&[None], &[None]);
13124        assert_eq!(neither.categorical_codes(), Some(&[-1][..]));
13125        assert!(neither.values()[0].is_missing());
13126    }
13127
13128    #[test]
13129    fn merge_indicator_column_d3ec6() {
13130        use std::collections::BTreeSet;
13131        // br-frankenpandas-d3ec6: outer-join indicator marks left_only/both/right_only.
13132        let left = DataFrame::from_dict(
13133            &["k"],
13134            vec![(
13135                "k",
13136                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13137            )],
13138        )
13139        .expect("left");
13140        let right = DataFrame::from_dict(
13141            &["k"],
13142            vec![(
13143                "k",
13144                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
13145            )],
13146        )
13147        .expect("right");
13148        let opts = super::MergeExecutionOptions {
13149            indicator_name: Some("_merge".to_owned()),
13150            ..Default::default()
13151        };
13152        let m = super::merge_dataframes_on_with_options(
13153            &left,
13154            &right,
13155            &["k"],
13156            &["k"],
13157            JoinType::Outer,
13158            opts,
13159        )
13160        .expect("merge");
13161
13162        let keys = merged_values(&m, "k").expect("k");
13163        let ind = merged_values(&m, "_merge").expect("_merge present");
13164        let lset: BTreeSet<i64> = [1, 2, 3].into_iter().collect();
13165        let rset: BTreeSet<i64> = [2, 3, 4].into_iter().collect();
13166        assert_eq!(keys.len(), 4, "outer keys = union");
13167        for i in 0..keys.len() {
13168            let k = match &keys[i] {
13169                Scalar::Int64(v) => *v,
13170                _ => i64::MIN,
13171            };
13172            let exp = match (lset.contains(&k), rset.contains(&k)) {
13173                (true, true) => "both",
13174                (true, false) => "left_only",
13175                (false, true) => "right_only",
13176                (false, false) => "??",
13177            };
13178            assert_eq!(ind[i], Scalar::Utf8(exp.to_owned()), "indicator at key {k}");
13179        }
13180    }
13181
13182    #[test]
13183    fn merge_overlapping_columns_suffixed_vb10q() {
13184        // br-frankenpandas-vb10q: a non-key column present in both frames is
13185        // suffixed _x (left) / _y (right) on merge.
13186        let mk = |vfactor: i64| {
13187            DataFrame::from_dict(
13188                &["k", "v"],
13189                vec![
13190                    (
13191                        "k",
13192                        vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13193                    ),
13194                    (
13195                        "v",
13196                        vec![
13197                            Scalar::Int64(vfactor),
13198                            Scalar::Int64(2 * vfactor),
13199                            Scalar::Int64(3 * vfactor),
13200                        ],
13201                    ),
13202                ],
13203            )
13204            .expect("frame")
13205        };
13206        let left = mk(10); // v = k*10
13207        let right = mk(100); // v = k*100
13208        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
13209
13210        let keys = merged_values(&merged, "k").expect("k");
13211        let vx = merged_values(&merged, "v_x").expect("v_x present");
13212        let vy = merged_values(&merged, "v_y").expect("v_y present");
13213        assert_eq!(keys.len(), 3);
13214        for i in 0..keys.len() {
13215            let k = match &keys[i] {
13216                Scalar::Int64(x) => *x,
13217                _ => i64::MIN,
13218            };
13219            assert_eq!(vx[i], Scalar::Int64(k * 10), "v_x at key {k}");
13220            assert_eq!(vy[i], Scalar::Int64(k * 100), "v_y at key {k}");
13221        }
13222    }
13223
13224    #[test]
13225    fn int64_join_row_count_matches_cardinality_invariant_ya1po() {
13226        use std::collections::BTreeMap;
13227
13228        // Metamorphic harness (br-frankenpandas-ya1po): merge_dataframes row count
13229        // must equal the pandas-standard cardinality per join type — an
13230        // ordering-independent invariant guarding the dense/direct-address Int64
13231        // join fast paths. Deterministic seeded LCG — no rand crate, no mocks.
13232        let mut state: u64 = 0xa5a5_5a5a_dead_beef;
13233        let mut next = || {
13234            state = state
13235                .wrapping_mul(6_364_136_223_846_793_005)
13236                .wrapping_add(1_442_695_040_888_963_407);
13237            (state >> 33) as u32
13238        };
13239
13240        let build = |keys: &[i64], payload_name: &str| {
13241            let n = keys.len();
13242            DataFrame::from_dict(
13243                &["k", payload_name],
13244                vec![
13245                    (
13246                        "k",
13247                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13248                    ),
13249                    (
13250                        payload_name,
13251                        (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>(),
13252                    ),
13253                ],
13254            )
13255            .expect("frame")
13256        };
13257
13258        for iter in 0..1500u32 {
13259            let nl = (next() % 9) as usize + 1;
13260            let nr = (next() % 9) as usize + 1;
13261            // Small key range so many-to-many (duplicate-key) joins are common.
13262            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
13263            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
13264            let left = build(&lk, "lv");
13265            let right = build(&rk, "rv");
13266
13267            let mut lc: BTreeMap<i64, i64> = BTreeMap::new();
13268            let mut rc: BTreeMap<i64, i64> = BTreeMap::new();
13269            for &k in &lk {
13270                *lc.entry(k).or_default() += 1;
13271            }
13272            for &k in &rk {
13273                *rc.entry(k).or_default() += 1;
13274            }
13275            let mut all_keys: Vec<i64> = lc.keys().chain(rc.keys()).copied().collect();
13276            all_keys.sort_unstable();
13277            all_keys.dedup();
13278
13279            let g = |k: i64, m: &BTreeMap<i64, i64>| m.get(&k).copied().unwrap_or(0);
13280            let inner: i64 = all_keys.iter().map(|&k| g(k, &lc) * g(k, &rc)).sum();
13281            let left_exp: i64 = lc.iter().map(|(&k, &l)| l * g(k, &rc).max(1)).sum();
13282            let right_exp: i64 = rc.iter().map(|(&k, &r)| r * g(k, &lc).max(1)).sum();
13283            let outer: i64 = all_keys
13284                .iter()
13285                .map(|&k| {
13286                    let (l, r) = (g(k, &lc), g(k, &rc));
13287                    if l > 0 && r > 0 { l * r } else { l + r }
13288                })
13289                .sum();
13290
13291            let ctx = format!("iter={iter} lk={lk:?} rk={rk:?}");
13292            for (jt, exp) in [
13293                (JoinType::Inner, inner),
13294                (JoinType::Left, left_exp),
13295                (JoinType::Right, right_exp),
13296                (JoinType::Outer, outer),
13297            ] {
13298                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
13299                let rows = merged_values(&merged, "k").expect("key col").len() as i64;
13300                assert_eq!(rows, exp, "{jt:?} row count {ctx}");
13301            }
13302        }
13303    }
13304
13305    #[test]
13306    fn inner_join_value_multiset_matches_crossproduct_oracle_5foyp() {
13307        use std::collections::BTreeMap;
13308
13309        // Value-level oracle (br-frankenpandas-5foyp): an inner join must pair the
13310        // CORRECT rows, not merely produce the right count. Assert the multiset of
13311        // output (key, left_payload, right_payload) triples equals the
13312        // independently-computed per-key cross product. Ordering-independent
13313        // (sorted-vector compare). Deterministic seeded LCG — no rand, no mocks.
13314        let mut state: u64 = 0x0ddc_0ffe_e0dd_f00d;
13315        let mut next = || {
13316            state = state
13317                .wrapping_mul(6_364_136_223_846_793_005)
13318                .wrapping_add(1_442_695_040_888_963_407);
13319            (state >> 33) as u32
13320        };
13321
13322        let build = |keys: &[i64], pname: &str| {
13323            let n = keys.len();
13324            DataFrame::from_dict(
13325                &["k", pname],
13326                vec![
13327                    (
13328                        "k",
13329                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13330                    ),
13331                    // Distinct per-row payload (= row index) so mis-pairings are visible.
13332                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
13333                ],
13334            )
13335            .expect("frame")
13336        };
13337        // Extract i64; a non-Int64 maps to a sentinel that will never equal a
13338        // real row index/key, so any dtype regression still fails the multiset
13339        // assert below (no panic — keeps the helper side-effect-free).
13340        let geti = |s: &Scalar| match s {
13341            Scalar::Int64(v) => *v,
13342            _ => i64::MIN,
13343        };
13344
13345        for iter in 0..1500u32 {
13346            let nl = (next() % 9) as usize + 1;
13347            let nr = (next() % 9) as usize + 1;
13348            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
13349            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
13350            let left = build(&lk, "lv");
13351            let right = build(&rk, "rv");
13352
13353            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
13354            let ks = merged_values(&merged, "k").expect("k");
13355            let lvs = merged_values(&merged, "lv").expect("lv");
13356            let rvs = merged_values(&merged, "rv").expect("rv");
13357            let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
13358                .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
13359                .collect();
13360            got.sort_unstable();
13361
13362            // Independent oracle: per-key cross product of left/right row payloads.
13363            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13364            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13365            for (i, &k) in lk.iter().enumerate() {
13366                lg.entry(k).or_default().push(i as i64);
13367            }
13368            for (i, &k) in rk.iter().enumerate() {
13369                rg.entry(k).or_default().push(i as i64);
13370            }
13371            let mut exp: Vec<(i64, i64, i64)> = Vec::new();
13372            for (&k, lps) in &lg {
13373                if let Some(rps) = rg.get(&k) {
13374                    for &a in lps {
13375                        for &b in rps {
13376                            exp.push((k, a, b));
13377                        }
13378                    }
13379                }
13380            }
13381            exp.sort_unstable();
13382
13383            assert_eq!(
13384                got, exp,
13385                "inner join value multiset iter={iter} lk={lk:?} rk={rk:?}"
13386            );
13387        }
13388    }
13389
13390    #[test]
13391    fn left_outer_join_nullfill_value_oracle_kaj3t() {
13392        use std::collections::BTreeMap;
13393
13394        // Value oracle for LEFT/OUTER null-fill (br-frankenpandas-kaj3t): unmatched
13395        // rows get NULL-filled on the absent side — the subtlest join behavior.
13396        // NULL is represented by the i64::MIN sentinel (payloads are 0..n and keys
13397        // 0..3, so a sentinel never collides with a real value). Deterministic
13398        // seeded LCG — no rand crate, no mocks.
13399        const NUL: i64 = i64::MIN;
13400        let mut state: u64 = 0xfeed_face_cafe_b0ba;
13401        let mut next = || {
13402            state = state
13403                .wrapping_mul(6_364_136_223_846_793_005)
13404                .wrapping_add(1_442_695_040_888_963_407);
13405            (state >> 33) as u32
13406        };
13407
13408        let build = |keys: &[i64], pname: &str| {
13409            let n = keys.len();
13410            DataFrame::from_dict(
13411                &["k", pname],
13412                vec![
13413                    (
13414                        "k",
13415                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13416                    ),
13417                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
13418                ],
13419            )
13420            .expect("frame")
13421        };
13422        // Int64 -> value. Left/outer joins upcast Int64 payload columns to
13423        // Float64 when null-fill introduces missing values (pandas parity: Int64
13424        // can't hold NaN), so accept finite Float64 too. NULL / NaN -> NUL
13425        // sentinel. Payloads are small whole numbers, so f64 -> i64 is exact.
13426        let geti = |s: &Scalar| match s {
13427            Scalar::Int64(v) => *v,
13428            Scalar::Float64(v) if v.is_finite() => *v as i64,
13429            _ => NUL,
13430        };
13431
13432        for iter in 0..1500u32 {
13433            let nl = (next() % 9) as usize + 1;
13434            let nr = (next() % 9) as usize + 1;
13435            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
13436            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
13437            let left = build(&lk, "lv");
13438            let right = build(&rk, "rv");
13439
13440            // Right rows grouped by key (payload = row index).
13441            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13442            for (j, &k) in rk.iter().enumerate() {
13443                rg.entry(k).or_default().push(j as i64);
13444            }
13445            let lkeys: std::collections::BTreeSet<i64> = lk.iter().copied().collect();
13446
13447            let read = |jt: JoinType| -> Vec<(i64, i64, i64)> {
13448                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
13449                let ks = merged_values(&merged, "k").expect("k");
13450                let lvs = merged_values(&merged, "lv").expect("lv");
13451                let rvs = merged_values(&merged, "rv").expect("rv");
13452                let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
13453                    .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
13454                    .collect();
13455                got.sort_unstable();
13456                got
13457            };
13458
13459            // LEFT oracle: every left row appears; matched -> one row per right
13460            // match, unmatched -> NULL right payload (key still the left key).
13461            let mut exp_left: Vec<(i64, i64, i64)> = Vec::new();
13462            for (i, &k) in lk.iter().enumerate() {
13463                match rg.get(&k) {
13464                    Some(rps) => {
13465                        for &j in rps {
13466                            exp_left.push((k, i as i64, j));
13467                        }
13468                    }
13469                    None => exp_left.push((k, i as i64, NUL)),
13470                }
13471            }
13472            exp_left.sort_unstable();
13473            assert_eq!(
13474                read(JoinType::Left),
13475                exp_left,
13476                "left join value oracle iter={iter} lk={lk:?} rk={rk:?}"
13477            );
13478
13479            // OUTER oracle: LEFT plus right-only rows (no left match) with NULL
13480            // left payload and the coalesced key.
13481            let mut exp_outer = exp_left.clone();
13482            for (j, &k) in rk.iter().enumerate() {
13483                if !lkeys.contains(&k) {
13484                    exp_outer.push((k, NUL, j as i64));
13485                }
13486            }
13487            exp_outer.sort_unstable();
13488            assert_eq!(
13489                read(JoinType::Outer),
13490                exp_outer,
13491                "outer join value oracle iter={iter} lk={lk:?} rk={rk:?}"
13492            );
13493        }
13494    }
13495
13496    #[test]
13497    fn left_join_value_multiset_matches_unmatched_oracle_gp0ik() {
13498        use std::collections::BTreeMap;
13499
13500        // Value-level LEFT join oracle (br-frankenpandas-gp0ik): matched keys
13501        // emit the left/right cross product; unmatched left rows emit exactly one
13502        // row with a missing right payload. Ordering-independent sorted multiset.
13503        let mut state: u64 = 0x51de_cafe_2026_0618;
13504        let mut next = || {
13505            state = state
13506                .wrapping_mul(6_364_136_223_846_793_005)
13507                .wrapping_add(1_442_695_040_888_963_407);
13508            (state >> 33) as u32
13509        };
13510
13511        let build = |keys: &[i64], pname: &str| {
13512            let n = keys.len();
13513            DataFrame::from_dict(
13514                &["k", pname],
13515                vec![
13516                    (
13517                        "k",
13518                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13519                    ),
13520                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
13521                ],
13522            )
13523            .expect("frame")
13524        };
13525        let geti = |s: &Scalar| match s {
13526            Scalar::Int64(v) => *v,
13527            _ => i64::MIN,
13528        };
13529        let get_optional_i64 = |s: &Scalar| match s {
13530            Scalar::Int64(v) => Some(*v),
13531            Scalar::Float64(v) if v.is_finite() && v.fract() == 0.0 => Some(*v as i64),
13532            value if value.is_missing() => None,
13533            _ => Some(i64::MIN),
13534        };
13535
13536        for iter in 0..1500u32 {
13537            let nl = (next() % 9) as usize + 1;
13538            let nr = (next() % 9) as usize + 1;
13539            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64).collect();
13540            let rk: Vec<i64> = (0..nr).map(|_| (next() % 3) as i64).collect();
13541            let left = build(&lk, "lv");
13542            let right = build(&rk, "rv");
13543
13544            let merged = merge_dataframes(&left, &right, "k", JoinType::Left).expect("merge");
13545            let ks = merged_values(&merged, "k").expect("k");
13546            let lvs = merged_values(&merged, "lv").expect("lv");
13547            let rvs = merged_values(&merged, "rv").expect("rv");
13548            let mut got: Vec<(i64, i64, Option<i64>)> = (0..ks.len())
13549                .map(|i| (geti(&ks[i]), geti(&lvs[i]), get_optional_i64(&rvs[i])))
13550                .collect();
13551            got.sort_unstable();
13552
13553            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13554            for (i, &k) in rk.iter().enumerate() {
13555                rg.entry(k).or_default().push(i as i64);
13556            }
13557            let mut exp: Vec<(i64, i64, Option<i64>)> = Vec::new();
13558            for (left_pos, &k) in lk.iter().enumerate() {
13559                if let Some(right_positions) = rg.get(&k) {
13560                    for &right_pos in right_positions {
13561                        exp.push((k, left_pos as i64, Some(right_pos)));
13562                    }
13563                } else {
13564                    exp.push((k, left_pos as i64, None));
13565                }
13566            }
13567            exp.sort_unstable();
13568
13569            assert_eq!(
13570                got, exp,
13571                "left join value multiset iter={iter} lk={lk:?} rk={rk:?}"
13572            );
13573        }
13574    }
13575
13576    #[test]
13577    fn right_join_value_multiset_matches_unmatched_oracle_pd1h5() {
13578        use std::collections::BTreeMap;
13579
13580        // Value-level RIGHT join oracle (br-frankenpandas-pd1h5): matched keys
13581        // emit the left/right cross product; unmatched right rows emit exactly one
13582        // row with a missing left payload. Ordering-independent sorted multiset.
13583        let mut state: u64 = 0x7191_2026_0618_a015;
13584        let mut next = || {
13585            state = state
13586                .wrapping_mul(6_364_136_223_846_793_005)
13587                .wrapping_add(1_442_695_040_888_963_407);
13588            (state >> 33) as u32
13589        };
13590
13591        let build = |keys: &[i64], pname: &str| {
13592            let n = keys.len();
13593            DataFrame::from_dict(
13594                &["k", pname],
13595                vec![
13596                    (
13597                        "k",
13598                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13599                    ),
13600                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
13601                ],
13602            )
13603            .expect("frame")
13604        };
13605        let geti = |s: &Scalar| match s {
13606            Scalar::Int64(v) => *v,
13607            Scalar::Float64(v) if v.is_finite() => *v as i64,
13608            _ => i64::MIN,
13609        };
13610        let get_optional_i64 = |s: &Scalar| match s {
13611            Scalar::Int64(v) => Some(*v),
13612            Scalar::Float64(v) if v.is_finite() => Some(*v as i64),
13613            value if value.is_missing() => None,
13614            _ => Some(i64::MIN),
13615        };
13616
13617        for iter in 0..1500u32 {
13618            let nl = (next() % 9) as usize + 1;
13619            let nr = (next() % 9) as usize + 1;
13620            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
13621            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64).collect();
13622            let left = build(&lk, "lv");
13623            let right = build(&rk, "rv");
13624
13625            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).expect("merge");
13626            let ks = merged_values(&merged, "k").expect("k");
13627            let lvs = merged_values(&merged, "lv").expect("lv");
13628            let rvs = merged_values(&merged, "rv").expect("rv");
13629            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
13630                .map(|i| (geti(&ks[i]), get_optional_i64(&lvs[i]), geti(&rvs[i])))
13631                .collect();
13632            got.sort_unstable();
13633
13634            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13635            for (i, &k) in lk.iter().enumerate() {
13636                lg.entry(k).or_default().push(i as i64);
13637            }
13638            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
13639            for (right_pos, &k) in rk.iter().enumerate() {
13640                if let Some(left_positions) = lg.get(&k) {
13641                    for &left_pos in left_positions {
13642                        exp.push((k, Some(left_pos), right_pos as i64));
13643                    }
13644                } else {
13645                    exp.push((k, None, right_pos as i64));
13646                }
13647            }
13648            exp.sort_unstable();
13649
13650            assert_eq!(
13651                got, exp,
13652                "right join value multiset iter={iter} lk={lk:?} rk={rk:?}"
13653            );
13654        }
13655    }
13656
13657    fn merged_values<'a>(
13658        merged: &'a MergedDataFrame,
13659        name: &str,
13660    ) -> Result<&'a [Scalar], JoinError> {
13661        Ok(merged
13662            .columns
13663            .get(name)
13664            .ok_or_else(|| {
13665                JoinError::Frame(FrameError::CompatibilityRejected(format!(
13666                    "missing merged column '{name}'"
13667                )))
13668            })?
13669            .values())
13670    }
13671
13672    #[test]
13673    fn temporal_i64_inner_positions_match_scalar_oracle_with_duplicates_b2hwb() {
13674        let build_positions_from_scalar_oracle = |left: &Column, right: &Column| {
13675            let left_keys = super::collect_single_join_keys(left);
13676            let right_keys = super::collect_single_join_keys(right);
13677            let mut left_positions = Vec::new();
13678            let mut right_positions = Vec::new();
13679            for (left_pos, left_key) in left_keys.iter().enumerate() {
13680                for (right_pos, right_key) in right_keys.iter().enumerate() {
13681                    if left_key == right_key {
13682                        left_positions.push(left_pos);
13683                        right_positions.push(right_pos);
13684                    }
13685                }
13686            }
13687            (left_positions, right_positions)
13688        };
13689
13690        let left_ns = [30, 10, 20, 10];
13691        let right_ns = [10, 30, 10, 40];
13692        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
13693            let scalar = |ns| match &temporal {
13694                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
13695                DType::Timedelta64 => Scalar::Timedelta64(ns),
13696                _ => unreachable!("test iterates only temporal dtypes"),
13697            };
13698            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
13699                .expect("left temporal key");
13700            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
13701                .expect("right temporal key");
13702
13703            assert_eq!(
13704                super::temporal_i64_inner_positions(&left, &right),
13705                Some(build_positions_from_scalar_oracle(&left, &right)),
13706                "raw-nanosecond planner must preserve scalar-oracle pair order for {temporal:?}"
13707            );
13708        }
13709
13710        let nat = fp_types::Timestamp::NAT;
13711        let ordered = Column::from_datetime64_values(vec![1, 2, 3, 4]);
13712        let nat_middle = Column::from_datetime64_values(vec![1, 2, nat, 4]);
13713        let nat_tail = Column::from_datetime64_values(vec![1, 2, 3, nat]);
13714        let single_nat = Column::from_datetime64_values(vec![nat]);
13715        for (left, right) in [
13716            (&nat_middle, &ordered),
13717            (&ordered, &nat_tail),
13718            (&single_nat, &ordered),
13719        ] {
13720            assert!(
13721                super::temporal_i64_inner_positions(left, right).is_none(),
13722                "NaT anywhere must retain the scalar INNER fallback",
13723            );
13724        }
13725    }
13726
13727    #[test]
13728    #[ignore = "foreground performance probe"]
13729    fn bench_temporal_i64_inner_validation_fusion_71kgc() {
13730        let n = 400_000_i64;
13731        let input_len = usize::try_from(n).expect("positive benchmark length");
13732        let left = Column::from_datetime64_values_with_validity(
13733            (0..n).collect(),
13734            ValidityMask::all_valid(input_len),
13735        );
13736        let right = Column::from_datetime64_values_with_validity(
13737            (0..n).map(|value| value * 2).collect(),
13738            ValidityMask::all_valid(input_len),
13739        );
13740
13741        // Exact pre-71kgc ordered body: separate NaT and strict-order scans
13742        // followed by the same two-pointer intersection.
13743        let former = || {
13744            if !left.validity().all() || !right.validity().all() {
13745                return None;
13746            }
13747            let left_raw = left.as_datetime64_slice()?;
13748            let right_raw = right.as_datetime64_slice()?;
13749            let nat = fp_types::Timestamp::NAT;
13750            if left_raw.contains(&nat) || right_raw.contains(&nat) {
13751                return None;
13752            }
13753            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
13754                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
13755            {
13756                return None;
13757            }
13758
13759            let mut left_positions = Vec::with_capacity(left_raw.len().min(right_raw.len()));
13760            let mut right_positions = Vec::with_capacity(left_positions.capacity());
13761            let (mut left_idx, mut right_idx) = (0usize, 0usize);
13762            while left_idx < left_raw.len() && right_idx < right_raw.len() {
13763                match left_raw[left_idx].cmp(&right_raw[right_idx]) {
13764                    std::cmp::Ordering::Equal => {
13765                        left_positions.push(left_idx);
13766                        right_positions.push(right_idx);
13767                        left_idx += 1;
13768                        right_idx += 1;
13769                    }
13770                    std::cmp::Ordering::Less => left_idx += 1,
13771                    std::cmp::Ordering::Greater => right_idx += 1,
13772                }
13773            }
13774            Some((left_positions, right_positions))
13775        };
13776        let candidate = || super::temporal_i64_inner_positions(&left, &right);
13777
13778        let former_output = former().expect("former temporal INNER positions");
13779        let candidate_output = candidate().expect("temporal INNER positions");
13780        assert_eq!(candidate_output, former_output);
13781        assert_eq!(candidate_output.0.len(), input_len.div_ceil(2));
13782        drop((former_output, candidate_output));
13783        for _ in 0..2 {
13784            std::hint::black_box(former());
13785            std::hint::black_box(candidate());
13786        }
13787
13788        type InnerPositions = Option<(Vec<usize>, Vec<usize>)>;
13789        let sample = |plan: &dyn Fn() -> InnerPositions| {
13790            let start = std::time::Instant::now();
13791            let output = std::hint::black_box(plan()).expect("supported temporal INNER plan");
13792            assert_eq!(std::hint::black_box(output.0.len()), input_len.div_ceil(2));
13793            drop(output);
13794            start.elapsed().as_secs_f64() * 1_000.0
13795        };
13796        let mut former_a = Vec::with_capacity(15);
13797        let mut former_b = Vec::with_capacity(15);
13798        let mut candidate_a = Vec::with_capacity(15);
13799        let mut candidate_b = Vec::with_capacity(15);
13800        for round in 0..15 {
13801            if round % 2 == 0 {
13802                former_a.push(sample(&former));
13803                candidate_a.push(sample(&candidate));
13804                candidate_b.push(sample(&candidate));
13805                former_b.push(sample(&former));
13806            } else {
13807                former_b.push(sample(&former));
13808                candidate_b.push(sample(&candidate));
13809                candidate_a.push(sample(&candidate));
13810                former_a.push(sample(&former));
13811            }
13812        }
13813
13814        let report = |label: &str, mut samples: Vec<f64>| {
13815            samples.sort_by(f64::total_cmp);
13816            let p50 = samples[samples.len() / 2];
13817            let p95_idx = samples
13818                .len()
13819                .saturating_mul(95)
13820                .div_ceil(100)
13821                .saturating_sub(1);
13822            println!(
13823                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
13824                samples[p95_idx],
13825                samples[samples.len() - 1],
13826            );
13827        };
13828        report("inner_plan_three_pass_former_a", former_a);
13829        report("inner_plan_three_pass_former_b", former_b);
13830        report("inner_plan_fused_candidate_a", candidate_a);
13831        report("inner_plan_fused_candidate_b", candidate_b);
13832    }
13833
13834    #[test]
13835    fn merge_datetime_inner_preserves_dtype_order_and_nat_fallback_b2hwb() -> Result<(), JoinError>
13836    {
13837        let left = DataFrame::from_dict(
13838            &["key", "lv"],
13839            vec![
13840                (
13841                    "key",
13842                    vec![
13843                        Scalar::Datetime64(30),
13844                        Scalar::Datetime64(10),
13845                        Scalar::Datetime64(20),
13846                        Scalar::Datetime64(10),
13847                    ],
13848                ),
13849                (
13850                    "lv",
13851                    vec![
13852                        Scalar::Int64(0),
13853                        Scalar::Int64(1),
13854                        Scalar::Int64(2),
13855                        Scalar::Int64(3),
13856                    ],
13857                ),
13858            ],
13859        )?;
13860        let right = DataFrame::from_dict(
13861            &["key", "rv"],
13862            vec![
13863                (
13864                    "key",
13865                    vec![
13866                        Scalar::Datetime64(10),
13867                        Scalar::Datetime64(30),
13868                        Scalar::Datetime64(10),
13869                        Scalar::Datetime64(40),
13870                    ],
13871                ),
13872                (
13873                    "rv",
13874                    vec![
13875                        Scalar::Int64(100),
13876                        Scalar::Int64(101),
13877                        Scalar::Int64(102),
13878                        Scalar::Int64(103),
13879                    ],
13880                ),
13881            ],
13882        )?;
13883        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner)?;
13884        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
13885        assert_eq!(
13886            merged_values(&merged, "key")?,
13887            &[
13888                Scalar::Datetime64(30),
13889                Scalar::Datetime64(10),
13890                Scalar::Datetime64(10),
13891                Scalar::Datetime64(10),
13892                Scalar::Datetime64(10),
13893            ]
13894        );
13895        assert_eq!(
13896            merged_values(&merged, "lv")?,
13897            &[
13898                Scalar::Int64(0),
13899                Scalar::Int64(1),
13900                Scalar::Int64(1),
13901                Scalar::Int64(3),
13902                Scalar::Int64(3),
13903            ]
13904        );
13905        assert_eq!(
13906            merged_values(&merged, "rv")?,
13907            &[
13908                Scalar::Int64(101),
13909                Scalar::Int64(100),
13910                Scalar::Int64(102),
13911                Scalar::Int64(100),
13912                Scalar::Int64(102),
13913            ]
13914        );
13915
13916        let nat = fp_types::Timestamp::NAT;
13917        let nat_left = DataFrame::from_dict(
13918            &["key", "lv"],
13919            vec![
13920                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
13921                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
13922            ],
13923        )?;
13924        let nat_right = DataFrame::from_dict(
13925            &["key", "rv"],
13926            vec![
13927                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
13928                ("rv", vec![Scalar::Int64(10), Scalar::Int64(11)]),
13929            ],
13930        )?;
13931        assert!(
13932            super::temporal_i64_inner_positions(
13933                nat_left.column("key").expect("left NaT key"),
13934                nat_right.column("key").expect("right NaT key")
13935            )
13936            .is_none(),
13937            "NaT must retain the scalar Missing-key fallback"
13938        );
13939        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Inner)?;
13940        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
13941        assert_eq!(nat_merged.index.len(), 2);
13942        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
13943        assert_eq!(
13944            &merged_values(&nat_merged, "key")?[1..],
13945            &[Scalar::Datetime64(5)]
13946        );
13947
13948        Ok(())
13949    }
13950
13951    #[test]
13952    fn temporal_i64_left_positions_match_scalar_oracle_with_duplicates_lw0qg() {
13953        let build_positions_from_scalar_oracle = |left: &Column, right: &Column| {
13954            let left_keys = super::collect_single_join_keys(left);
13955            let right_keys = super::collect_single_join_keys(right);
13956            let mut left_positions = Vec::new();
13957            let mut right_positions = Vec::new();
13958            for (left_pos, left_key) in left_keys.iter().enumerate() {
13959                let mut matched = false;
13960                for (right_pos, right_key) in right_keys.iter().enumerate() {
13961                    if left_key == right_key {
13962                        left_positions.push(Some(left_pos));
13963                        right_positions.push(Some(right_pos));
13964                        matched = true;
13965                    }
13966                }
13967                if !matched {
13968                    left_positions.push(Some(left_pos));
13969                    right_positions.push(None);
13970                }
13971            }
13972            (left_positions, right_positions)
13973        };
13974
13975        let left_ns = [30, 10, 20, 10, 50];
13976        let right_ns = [10, 30, 10, 40];
13977        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
13978            let scalar = |ns| match &temporal {
13979                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
13980                DType::Timedelta64 => Scalar::Timedelta64(ns),
13981                _ => unreachable!("test iterates only temporal dtypes"),
13982            };
13983            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
13984                .expect("left temporal key");
13985            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
13986                .expect("right temporal key");
13987
13988            assert_eq!(
13989                super::temporal_i64_left_positions(&left, &right),
13990                Some(build_positions_from_scalar_oracle(&left, &right)),
13991                "raw-nanosecond LEFT planner must preserve scalar-oracle row order for {temporal:?}"
13992            );
13993        }
13994    }
13995
13996    #[test]
13997    fn merge_datetime_left_preserves_dtype_order_and_nat_fallback_lw0qg() -> Result<(), JoinError> {
13998        let left = DataFrame::from_dict(
13999            &["key", "lv"],
14000            vec![
14001                (
14002                    "key",
14003                    vec![
14004                        Scalar::Datetime64(30),
14005                        Scalar::Datetime64(10),
14006                        Scalar::Datetime64(20),
14007                        Scalar::Datetime64(10),
14008                        Scalar::Datetime64(50),
14009                    ],
14010                ),
14011                (
14012                    "lv",
14013                    vec![
14014                        Scalar::Int64(0),
14015                        Scalar::Int64(1),
14016                        Scalar::Int64(2),
14017                        Scalar::Int64(3),
14018                        Scalar::Int64(4),
14019                    ],
14020                ),
14021            ],
14022        )?;
14023        let right = DataFrame::from_dict(
14024            &["key", "rv"],
14025            vec![
14026                (
14027                    "key",
14028                    vec![
14029                        Scalar::Datetime64(10),
14030                        Scalar::Datetime64(30),
14031                        Scalar::Datetime64(10),
14032                        Scalar::Datetime64(40),
14033                    ],
14034                ),
14035                (
14036                    "rv",
14037                    vec![
14038                        Scalar::Int64(100),
14039                        Scalar::Int64(101),
14040                        Scalar::Int64(102),
14041                        Scalar::Int64(103),
14042                    ],
14043                ),
14044            ],
14045        )?;
14046        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Left)?;
14047        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
14048        assert_eq!(
14049            merged_values(&merged, "key")?,
14050            &[
14051                Scalar::Datetime64(30),
14052                Scalar::Datetime64(10),
14053                Scalar::Datetime64(10),
14054                Scalar::Datetime64(20),
14055                Scalar::Datetime64(10),
14056                Scalar::Datetime64(10),
14057                Scalar::Datetime64(50),
14058            ]
14059        );
14060        assert_eq!(
14061            merged_values(&merged, "lv")?,
14062            &[
14063                Scalar::Int64(0),
14064                Scalar::Int64(1),
14065                Scalar::Int64(1),
14066                Scalar::Int64(2),
14067                Scalar::Int64(3),
14068                Scalar::Int64(3),
14069                Scalar::Int64(4),
14070            ]
14071        );
14072        let right_values = merged_values(&merged, "rv")?;
14073        assert_eq!(right_values.len(), 7);
14074        assert_eq!(right_values[0], Scalar::Float64(101.0));
14075        assert_eq!(
14076            &right_values[1..3],
14077            &[Scalar::Float64(100.0), Scalar::Float64(102.0)]
14078        );
14079        assert!(right_values[3].is_missing());
14080        assert_eq!(
14081            &right_values[4..6],
14082            &[Scalar::Float64(100.0), Scalar::Float64(102.0)]
14083        );
14084        assert!(right_values[6].is_missing());
14085
14086        let nat = fp_types::Timestamp::NAT;
14087        let nat_left = DataFrame::from_dict(
14088            &["key", "lv"],
14089            vec![
14090                (
14091                    "key",
14092                    vec![
14093                        Scalar::Datetime64(nat),
14094                        Scalar::Datetime64(5),
14095                        Scalar::Datetime64(7),
14096                    ],
14097                ),
14098                (
14099                    "lv",
14100                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
14101                ),
14102            ],
14103        )?;
14104        let nat_right = DataFrame::from_dict(
14105            &["key", "rv"],
14106            vec![
14107                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
14108                ("rv", vec![Scalar::Int64(10), Scalar::Int64(11)]),
14109            ],
14110        )?;
14111        assert!(
14112            super::temporal_i64_left_positions(
14113                nat_left.column("key").expect("left NaT key"),
14114                nat_right.column("key").expect("right NaT key")
14115            )
14116            .is_none(),
14117            "NaT must retain the scalar Missing-key fallback"
14118        );
14119        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Left)?;
14120        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
14121        assert_eq!(nat_merged.index.len(), 3);
14122        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
14123        assert_eq!(
14124            &merged_values(&nat_merged, "key")?[1..],
14125            &[Scalar::Datetime64(5), Scalar::Datetime64(7)]
14126        );
14127        let nat_right_values = merged_values(&nat_merged, "rv")?;
14128        assert_eq!(
14129            &nat_right_values[..2],
14130            &[Scalar::Float64(10.0), Scalar::Float64(11.0)]
14131        );
14132        assert!(nat_right_values[2].is_missing());
14133
14134        Ok(())
14135    }
14136
14137    #[test]
14138    fn temporal_i64_right_positions_match_scalar_oracle_and_reject_unsupported_8tf5c() {
14139        let scalar_oracle = |left: &Column, right: &Column| {
14140            let left_keys = super::collect_single_join_keys(left);
14141            let right_keys = super::collect_single_join_keys(right);
14142            right_keys
14143                .iter()
14144                .map(|right_key| left_keys.iter().position(|left_key| left_key == right_key))
14145                .collect::<Vec<_>>()
14146        };
14147
14148        let left_ns = [-20, 10, 30, 50];
14149        let right_ns = [-30, -20, 20, 30, 60];
14150        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14151            let scalar = |ns| match &temporal {
14152                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
14153                DType::Timedelta64 => Scalar::Timedelta64(ns),
14154                _ => unreachable!("test iterates only temporal dtypes"),
14155            };
14156            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
14157                .expect("left temporal key");
14158            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
14159                .expect("right temporal key");
14160            assert_eq!(
14161                super::ordered_unique_temporal_i64_right_match_positions(&left, &right),
14162                Some(scalar_oracle(&left, &right)),
14163                "raw-nanosecond RIGHT planner must preserve right-major scalar matches for {temporal:?}",
14164            );
14165        }
14166
14167        let empty_left = Column::from_datetime64_values(Vec::new());
14168        let ordered_right = Column::from_datetime64_values(vec![1, 2, 3]);
14169        assert_eq!(
14170            super::ordered_unique_temporal_i64_right_match_positions(&empty_left, &ordered_right,),
14171            Some(vec![None; 3]),
14172        );
14173
14174        let nat = fp_types::Timestamp::NAT;
14175        let nat_left = Column::from_datetime64_values(vec![nat, 1, 2]);
14176        let nat_middle_left = Column::from_datetime64_values(vec![1, nat, 3]);
14177        let nat_tail_right = Column::from_datetime64_values(vec![1, 2, nat]);
14178        let single_nat = Column::from_datetime64_values(vec![nat]);
14179        let duplicate_left = Column::from_datetime64_values(vec![1, 1, 2]);
14180        let late_duplicate_left = Column::from_datetime64_values(vec![1, 2, 3, 3]);
14181        let unsorted_right = Column::from_datetime64_values(vec![2, 1, 3]);
14182        let late_unsorted_right = Column::from_datetime64_values(vec![1, 2, 4, 3]);
14183        let mixed_right =
14184            Column::from_values([1, 2, 3].into_iter().map(Scalar::Timedelta64).collect())
14185                .expect("mixed timedelta key");
14186        let mut validity = ValidityMask::all_valid(3);
14187        validity.set(1, false);
14188        let nullable_left = Column::from_datetime64_values_with_validity(vec![1, 2, 3], validity);
14189        for (left, right) in [
14190            (&nat_left, &ordered_right),
14191            (&nat_middle_left, &ordered_right),
14192            (&ordered_right, &nat_tail_right),
14193            (&single_nat, &ordered_right),
14194            (&duplicate_left, &ordered_right),
14195            (&late_duplicate_left, &ordered_right),
14196            (&ordered_right, &unsorted_right),
14197            (&ordered_right, &late_unsorted_right),
14198            (&ordered_right, &mixed_right),
14199            (&nullable_left, &ordered_right),
14200        ] {
14201            assert!(
14202                super::ordered_unique_temporal_i64_right_match_positions(left, right).is_none(),
14203                "unsupported temporal RIGHT shape must retain the scalar fallback",
14204            );
14205        }
14206    }
14207
14208    #[test]
14209    #[ignore = "foreground performance probe"]
14210    fn bench_temporal_i64_right_validation_fusion_69e0m() {
14211        let n = 400_000_i64;
14212        let input_len = usize::try_from(n).expect("positive benchmark length");
14213        let left = Column::from_datetime64_values_with_validity(
14214            (0..n).collect(),
14215            ValidityMask::all_valid(input_len),
14216        );
14217        let right = Column::from_datetime64_values_with_validity(
14218            (0..n).map(|value| value * 2).collect(),
14219            ValidityMask::all_valid(input_len),
14220        );
14221
14222        // Exact pre-69e0m body: separate NaT and strict-order scans followed
14223        // by the same right-major two-pointer match.
14224        let former = || {
14225            if !left.validity().all() || !right.validity().all() {
14226                return None;
14227            }
14228            let left_raw = left.as_datetime64_slice()?;
14229            let right_raw = right.as_datetime64_slice()?;
14230            let nat = fp_types::Timestamp::NAT;
14231            if left_raw.contains(&nat) || right_raw.contains(&nat) {
14232                return None;
14233            }
14234            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
14235                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
14236            {
14237                return None;
14238            }
14239
14240            let mut left_positions = Vec::with_capacity(right_raw.len());
14241            let mut left_idx = 0usize;
14242            for &right_value in right_raw {
14243                while left_idx < left_raw.len() && left_raw[left_idx] < right_value {
14244                    left_idx += 1;
14245                }
14246                left_positions.push(
14247                    (left_idx < left_raw.len()
14248                        && matches!(
14249                            left_raw[left_idx].cmp(&right_value),
14250                            std::cmp::Ordering::Equal
14251                        ))
14252                    .then_some(left_idx),
14253                );
14254            }
14255            Some(left_positions)
14256        };
14257        let candidate = || super::ordered_unique_temporal_i64_right_match_positions(&left, &right);
14258
14259        let former_output = former().expect("former temporal RIGHT positions");
14260        let candidate_output = candidate().expect("fused temporal RIGHT positions");
14261        assert_eq!(candidate_output, former_output);
14262        assert_eq!(candidate_output.len(), input_len);
14263        drop((former_output, candidate_output));
14264        for _ in 0..2 {
14265            std::hint::black_box(former());
14266            std::hint::black_box(candidate());
14267        }
14268
14269        let sample = |plan: &dyn Fn() -> Option<Vec<Option<usize>>>| {
14270            let start = std::time::Instant::now();
14271            let output = std::hint::black_box(plan()).expect("supported temporal RIGHT plan");
14272            assert_eq!(std::hint::black_box(output.len()), input_len);
14273            drop(output);
14274            start.elapsed().as_secs_f64() * 1_000.0
14275        };
14276        let mut former_a = Vec::with_capacity(15);
14277        let mut former_b = Vec::with_capacity(15);
14278        let mut candidate_a = Vec::with_capacity(15);
14279        let mut candidate_b = Vec::with_capacity(15);
14280        for round in 0..15 {
14281            if round % 2 == 0 {
14282                former_a.push(sample(&former));
14283                candidate_a.push(sample(&candidate));
14284                candidate_b.push(sample(&candidate));
14285                former_b.push(sample(&former));
14286            } else {
14287                former_b.push(sample(&former));
14288                candidate_b.push(sample(&candidate));
14289                candidate_a.push(sample(&candidate));
14290                former_a.push(sample(&former));
14291            }
14292        }
14293
14294        let report = |label: &str, mut samples: Vec<f64>| {
14295            samples.sort_by(f64::total_cmp);
14296            let p50 = samples[samples.len() / 2];
14297            let p95_idx = samples
14298                .len()
14299                .saturating_mul(95)
14300                .div_ceil(100)
14301                .saturating_sub(1);
14302            println!(
14303                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
14304                samples[p95_idx],
14305                samples[samples.len() - 1],
14306            );
14307        };
14308        report("right_plan_three_pass_former_a", former_a);
14309        report("right_plan_three_pass_former_b", former_b);
14310        report("right_plan_fused_candidate_a", candidate_a);
14311        report("right_plan_fused_candidate_b", candidate_b);
14312    }
14313
14314    #[test]
14315    fn merge_datetime_right_preserves_dtype_order_and_nat_fallback_8tf5c() -> Result<(), JoinError>
14316    {
14317        let left = DataFrame::from_dict(
14318            &["key", "lv"],
14319            vec![
14320                (
14321                    "key",
14322                    vec![
14323                        Scalar::Datetime64(10),
14324                        Scalar::Datetime64(30),
14325                        Scalar::Datetime64(50),
14326                    ],
14327                ),
14328                (
14329                    "lv",
14330                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
14331                ),
14332            ],
14333        )?;
14334        let right = DataFrame::from_dict(
14335            &["key", "rv"],
14336            vec![
14337                (
14338                    "key",
14339                    vec![
14340                        Scalar::Datetime64(0),
14341                        Scalar::Datetime64(10),
14342                        Scalar::Datetime64(40),
14343                        Scalar::Datetime64(50),
14344                        Scalar::Datetime64(60),
14345                    ],
14346                ),
14347                (
14348                    "rv",
14349                    vec![
14350                        Scalar::Int64(100),
14351                        Scalar::Int64(101),
14352                        Scalar::Int64(102),
14353                        Scalar::Int64(103),
14354                        Scalar::Int64(104),
14355                    ],
14356                ),
14357            ],
14358        )?;
14359        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Right)?;
14360        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
14361        assert_eq!(
14362            merged_values(&merged, "key")?,
14363            &[
14364                Scalar::Datetime64(0),
14365                Scalar::Datetime64(10),
14366                Scalar::Datetime64(40),
14367                Scalar::Datetime64(50),
14368                Scalar::Datetime64(60),
14369            ],
14370        );
14371        assert_eq!(
14372            merged_values(&merged, "rv")?,
14373            &[
14374                Scalar::Int64(100),
14375                Scalar::Int64(101),
14376                Scalar::Int64(102),
14377                Scalar::Int64(103),
14378                Scalar::Int64(104),
14379            ],
14380        );
14381        let left_values = merged_values(&merged, "lv")?;
14382        assert_eq!(left_values.len(), 5);
14383        assert!(left_values[0].is_missing());
14384        assert_eq!(left_values[1], Scalar::Float64(0.0));
14385        assert!(left_values[2].is_missing());
14386        assert_eq!(left_values[3], Scalar::Float64(2.0));
14387        assert!(left_values[4].is_missing());
14388
14389        let nat = fp_types::Timestamp::NAT;
14390        let nat_left = DataFrame::from_dict(
14391            &["key", "lv"],
14392            vec![
14393                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
14394                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
14395            ],
14396        )?;
14397        let nat_right = DataFrame::from_dict(
14398            &["key", "rv"],
14399            vec![
14400                (
14401                    "key",
14402                    vec![
14403                        Scalar::Datetime64(nat),
14404                        Scalar::Datetime64(5),
14405                        Scalar::Datetime64(7),
14406                    ],
14407                ),
14408                (
14409                    "rv",
14410                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(12)],
14411                ),
14412            ],
14413        )?;
14414        assert!(
14415            super::ordered_unique_temporal_i64_right_match_positions(
14416                nat_left.column("key").expect("left NaT key"),
14417                nat_right.column("key").expect("right NaT key"),
14418            )
14419            .is_none(),
14420            "NaT must retain the scalar Missing-key fallback",
14421        );
14422        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Right)?;
14423        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
14424        assert_eq!(nat_merged.index.len(), 3);
14425        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
14426        assert_eq!(
14427            &merged_values(&nat_merged, "key")?[1..],
14428            &[Scalar::Datetime64(5), Scalar::Datetime64(7)],
14429        );
14430        let nat_left_values = merged_values(&nat_merged, "lv")?;
14431        assert_eq!(
14432            &nat_left_values[..2],
14433            &[Scalar::Float64(0.0), Scalar::Float64(1.0)]
14434        );
14435        assert!(nat_left_values[2].is_missing());
14436
14437        Ok(())
14438    }
14439
14440    #[test]
14441    fn temporal_i64_outer_key_coalesce_matches_scalar_and_declines_unsupported_i4gzc() {
14442        let left_positions = [None, Some(0), Some(1), None, Some(2), Some(3), None];
14443        let right_positions = [Some(0), Some(1), None, Some(2), Some(3), None, Some(4)];
14444        let left_ns = vec![-20, 10, 30, 50];
14445        let right_ns = vec![-30, -20, 20, 30, 60];
14446        let union_ns = [-30, -20, 10, 20, 30, 50, 60];
14447        let temporal_column = |dtype: &DType, values: Vec<i64>| {
14448            let len = values.len();
14449            match dtype {
14450                DType::Datetime64 { .. } => Column::from_datetime64_values_with_validity(
14451                    values,
14452                    ValidityMask::all_valid(len),
14453                ),
14454                DType::Timedelta64 => Column::from_timedelta64_values_with_validity(
14455                    values,
14456                    ValidityMask::all_valid(len),
14457                ),
14458                _ => unreachable!("test iterates only temporal dtypes"),
14459            }
14460        };
14461
14462        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14463            let left = temporal_column(&temporal, left_ns.clone());
14464            let right = temporal_column(&temporal, right_ns.clone());
14465            let candidate = super::coalesce_temporal_i64_key_column(
14466                &left,
14467                &right,
14468                &left_positions,
14469                &right_positions,
14470            )
14471            .expect("supported temporal key coalesce");
14472            assert_eq!(candidate.dtype(), temporal);
14473            assert!(candidate.validity().all());
14474            let candidate_ns = match &temporal {
14475                DType::Datetime64 { .. } => candidate.as_datetime64_slice(),
14476                DType::Timedelta64 => candidate.as_timedelta64_slice(),
14477                _ => unreachable!("test iterates only temporal dtypes"),
14478            };
14479            assert_eq!(candidate_ns, Some(union_ns.as_slice()));
14480
14481            let reference_values = left_positions
14482                .iter()
14483                .zip(right_positions.iter())
14484                .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
14485                    (Some(pos), _) => left.values()[*pos].clone(),
14486                    (None, Some(pos)) => right.values()[*pos].clone(),
14487                    (None, None) => Scalar::Null(NullKind::Null),
14488                })
14489                .collect::<Vec<_>>();
14490            let reference = Column::from_values(reference_values).expect("scalar reference");
14491            assert_eq!(candidate, reference);
14492        }
14493
14494        let naive_datetime = DType::datetime64_naive();
14495        let datetime_left = temporal_column(&naive_datetime, left_ns);
14496        let datetime_right = temporal_column(&naive_datetime, right_ns);
14497        let timedelta_right = temporal_column(&DType::Timedelta64, vec![-30, -20, 20, 30, 60]);
14498        let mut nullable_validity = ValidityMask::all_valid(datetime_left.len());
14499        nullable_validity.set(1, false);
14500        let nullable_left =
14501            Column::from_datetime64_values_with_validity(vec![-20, 10, 30, 50], nullable_validity);
14502        let nat_left = Column::from_datetime64_values_with_validity(
14503            vec![fp_types::Timestamp::NAT, 10, 30, 50],
14504            ValidityMask::all_valid(4),
14505        );
14506        for (left, right, left_tape, right_tape) in [
14507            (
14508                &nullable_left,
14509                &datetime_right,
14510                left_positions.as_slice(),
14511                right_positions.as_slice(),
14512            ),
14513            (
14514                &datetime_left,
14515                &timedelta_right,
14516                left_positions.as_slice(),
14517                right_positions.as_slice(),
14518            ),
14519            (&nat_left, &datetime_right, &[Some(0)], &[Some(0)]),
14520            (&datetime_left, &datetime_right, &[Some(0)], &[]),
14521            (&datetime_left, &datetime_right, &[Some(99)], &[None]),
14522            (&datetime_left, &datetime_right, &[None], &[None]),
14523        ] {
14524            assert!(
14525                super::coalesce_temporal_i64_key_column(left, right, left_tape, right_tape,)
14526                    .is_none(),
14527                "unsupported temporal key coalesce must retain Scalar fallback",
14528            );
14529        }
14530    }
14531
14532    #[test]
14533    #[ignore = "foreground performance probe"]
14534    fn bench_temporal_i64_outer_key_coalesce_i4gzc() {
14535        let n = 200_000_i64;
14536        let input_len = usize::try_from(n).expect("positive benchmark length");
14537        let left = Column::from_datetime64_values_with_validity(
14538            (0..n).collect(),
14539            ValidityMask::all_valid(input_len),
14540        );
14541        let right = Column::from_datetime64_values_with_validity(
14542            (0..n).map(|value| value * 2).collect(),
14543            ValidityMask::all_valid(input_len),
14544        );
14545        let (left_positions, right_positions) =
14546            super::ordered_unique_temporal_i64_outer_positions(&left, &right)
14547                .expect("ordered temporal position tapes");
14548        let expected_rows = 300_000usize;
14549        assert_eq!(left_positions.len(), expected_rows);
14550
14551        let former = || {
14552            let values = left_positions
14553                .iter()
14554                .zip(right_positions.iter())
14555                .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
14556                    (Some(pos), _) => left.values()[*pos].clone(),
14557                    (None, Some(pos)) => right.values()[*pos].clone(),
14558                    (None, None) => Scalar::Null(NullKind::Null),
14559                })
14560                .collect::<Vec<_>>();
14561            Column::from_values(values).expect("former Scalar key coalesce")
14562        };
14563        let candidate = || {
14564            super::coalesce_temporal_i64_key_column(
14565                &left,
14566                &right,
14567                &left_positions,
14568                &right_positions,
14569            )
14570            .expect("typed temporal key coalesce")
14571        };
14572
14573        let former_output = former();
14574        let candidate_output = candidate();
14575        assert_eq!(candidate_output, former_output);
14576        drop((former_output, candidate_output));
14577        for _ in 0..2 {
14578            std::hint::black_box(former());
14579            std::hint::black_box(candidate());
14580        }
14581
14582        let sample = |build: &dyn Fn() -> Column| {
14583            let start = std::time::Instant::now();
14584            let output = std::hint::black_box(build());
14585            assert_eq!(std::hint::black_box(output.len()), expected_rows);
14586            drop(output);
14587            start.elapsed().as_secs_f64() * 1_000.0
14588        };
14589        let mut former_a = Vec::with_capacity(15);
14590        let mut former_b = Vec::with_capacity(15);
14591        let mut candidate_a = Vec::with_capacity(15);
14592        let mut candidate_b = Vec::with_capacity(15);
14593        for round in 0..15 {
14594            if round % 2 == 0 {
14595                former_a.push(sample(&former));
14596                candidate_a.push(sample(&candidate));
14597                candidate_b.push(sample(&candidate));
14598                former_b.push(sample(&former));
14599            } else {
14600                former_b.push(sample(&former));
14601                candidate_b.push(sample(&candidate));
14602                candidate_a.push(sample(&candidate));
14603                former_a.push(sample(&former));
14604            }
14605        }
14606
14607        let report = |label: &str, mut samples: Vec<f64>| {
14608            samples.sort_by(f64::total_cmp);
14609            let p50 = samples[samples.len() / 2];
14610            let p95_idx = samples
14611                .len()
14612                .saturating_mul(95)
14613                .div_ceil(100)
14614                .saturating_sub(1);
14615            println!(
14616                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
14617                samples[p95_idx],
14618                samples[samples.len() - 1],
14619            );
14620        };
14621        report("outer_key_scalar_former_a", former_a);
14622        report("outer_key_scalar_former_b", former_b);
14623        report("outer_key_typed_candidate_a", candidate_a);
14624        report("outer_key_typed_candidate_b", candidate_b);
14625    }
14626
14627    #[test]
14628    fn temporal_i64_outer_positions_match_ordered_union_and_reject_unsupported_rvb6u() {
14629        let left_ns = [-20, 10, 30, 50];
14630        let right_ns = [-30, -20, 20, 30, 60];
14631        let expected = (
14632            vec![None, Some(0), Some(1), None, Some(2), Some(3), None],
14633            vec![Some(0), Some(1), None, Some(2), Some(3), None, Some(4)],
14634        );
14635        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14636            let scalar = |ns| match &temporal {
14637                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
14638                DType::Timedelta64 => Scalar::Timedelta64(ns),
14639                _ => unreachable!("test iterates only temporal dtypes"),
14640            };
14641            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
14642                .expect("left temporal key");
14643            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
14644                .expect("right temporal key");
14645            assert_eq!(
14646                super::ordered_unique_temporal_i64_outer_positions(&left, &right),
14647                Some(expected.clone()),
14648                "raw-nanosecond OUTER planner must preserve key-sorted optional positions for {temporal:?}",
14649            );
14650        }
14651
14652        let empty_left = Column::from_datetime64_values(Vec::new());
14653        let ordered_right = Column::from_datetime64_values(vec![1, 2, 3]);
14654        assert_eq!(
14655            super::ordered_unique_temporal_i64_outer_positions(&empty_left, &ordered_right),
14656            Some((vec![None; 3], vec![Some(0), Some(1), Some(2)])),
14657        );
14658
14659        let nat = fp_types::Timestamp::NAT;
14660        let nat_left = Column::from_datetime64_values(vec![nat, 1, 2]);
14661        let duplicate_left = Column::from_datetime64_values(vec![1, 1, 2]);
14662        let unsorted_right = Column::from_datetime64_values(vec![2, 1, 3]);
14663        let mixed_right =
14664            Column::from_values([1, 2, 3].into_iter().map(Scalar::Timedelta64).collect())
14665                .expect("mixed timedelta key");
14666        let mut validity = ValidityMask::all_valid(3);
14667        validity.set(1, false);
14668        let nullable_left = Column::from_datetime64_values_with_validity(vec![1, 2, 3], validity);
14669        for (left, right) in [
14670            (&nat_left, &ordered_right),
14671            (&duplicate_left, &ordered_right),
14672            (&ordered_right, &unsorted_right),
14673            (&ordered_right, &mixed_right),
14674            (&nullable_left, &ordered_right),
14675        ] {
14676            assert!(
14677                super::ordered_unique_temporal_i64_outer_positions(left, right).is_none(),
14678                "unsupported temporal OUTER shape must retain the scalar fallback",
14679            );
14680        }
14681    }
14682
14683    #[test]
14684    #[ignore = "foreground performance probe"]
14685    fn bench_temporal_i64_outer_validation_fusion_pizud() {
14686        let n = 400_000_i64;
14687        let input_len = usize::try_from(n).expect("positive benchmark length");
14688        let left = Column::from_datetime64_values_with_validity(
14689            (0..n).collect(),
14690            ValidityMask::all_valid(input_len),
14691        );
14692        let right = Column::from_datetime64_values_with_validity(
14693            (0..n).map(|value| value * 2).collect(),
14694            ValidityMask::all_valid(input_len),
14695        );
14696        let expected_rows = 600_000usize;
14697
14698        // Exact pre-pizud body: separate NaT and strict-order scans followed by
14699        // the same three-way optional-position union.
14700        let former = || {
14701            if !left.validity().all() || !right.validity().all() {
14702                return None;
14703            }
14704            let left_raw = left.as_datetime64_slice()?;
14705            let right_raw = right.as_datetime64_slice()?;
14706            let nat = fp_types::Timestamp::NAT;
14707            if left_raw.contains(&nat) || right_raw.contains(&nat) {
14708                return None;
14709            }
14710            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
14711                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
14712            {
14713                return None;
14714            }
14715
14716            let capacity = left_raw.len().saturating_add(right_raw.len());
14717            let mut left_positions = Vec::<Option<usize>>::with_capacity(capacity);
14718            let mut right_positions = Vec::<Option<usize>>::with_capacity(capacity);
14719            let (mut left_idx, mut right_idx) = (0usize, 0usize);
14720            while left_idx < left_raw.len() && right_idx < right_raw.len() {
14721                match left_raw[left_idx].cmp(&right_raw[right_idx]) {
14722                    std::cmp::Ordering::Equal => {
14723                        left_positions.push(Some(left_idx));
14724                        right_positions.push(Some(right_idx));
14725                        left_idx += 1;
14726                        right_idx += 1;
14727                    }
14728                    std::cmp::Ordering::Less => {
14729                        left_positions.push(Some(left_idx));
14730                        right_positions.push(None);
14731                        left_idx += 1;
14732                    }
14733                    std::cmp::Ordering::Greater => {
14734                        left_positions.push(None);
14735                        right_positions.push(Some(right_idx));
14736                        right_idx += 1;
14737                    }
14738                }
14739            }
14740            while left_idx < left_raw.len() {
14741                left_positions.push(Some(left_idx));
14742                right_positions.push(None);
14743                left_idx += 1;
14744            }
14745            while right_idx < right_raw.len() {
14746                left_positions.push(None);
14747                right_positions.push(Some(right_idx));
14748                right_idx += 1;
14749            }
14750            Some((left_positions, right_positions))
14751        };
14752        let candidate = || super::ordered_unique_temporal_i64_outer_positions(&left, &right);
14753
14754        let former_output = former().expect("former temporal union");
14755        let candidate_output = candidate().expect("fused temporal union");
14756        assert_eq!(candidate_output, former_output);
14757        assert_eq!(candidate_output.0.len(), expected_rows);
14758        drop((former_output, candidate_output));
14759        for _ in 0..2 {
14760            std::hint::black_box(former());
14761            std::hint::black_box(candidate());
14762        }
14763
14764        let sample = |plan: &dyn Fn() -> Option<super::OptionalJoinPositions>| {
14765            let start = std::time::Instant::now();
14766            let output = std::hint::black_box(plan()).expect("supported temporal union");
14767            assert_eq!(std::hint::black_box(output.0.len()), expected_rows);
14768            drop(output);
14769            start.elapsed().as_secs_f64() * 1_000.0
14770        };
14771        let mut former_a = Vec::with_capacity(15);
14772        let mut former_b = Vec::with_capacity(15);
14773        let mut candidate_a = Vec::with_capacity(15);
14774        let mut candidate_b = Vec::with_capacity(15);
14775        for round in 0..15 {
14776            if round % 2 == 0 {
14777                former_a.push(sample(&former));
14778                candidate_a.push(sample(&candidate));
14779                candidate_b.push(sample(&candidate));
14780                former_b.push(sample(&former));
14781            } else {
14782                former_b.push(sample(&former));
14783                candidate_b.push(sample(&candidate));
14784                candidate_a.push(sample(&candidate));
14785                former_a.push(sample(&former));
14786            }
14787        }
14788
14789        let report = |label: &str, mut samples: Vec<f64>| {
14790            samples.sort_by(f64::total_cmp);
14791            let p50 = samples[samples.len() / 2];
14792            let p95_idx = samples
14793                .len()
14794                .saturating_mul(95)
14795                .div_ceil(100)
14796                .saturating_sub(1);
14797            println!(
14798                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
14799                samples[p95_idx],
14800                samples[samples.len() - 1],
14801            );
14802        };
14803        report("outer_plan_three_pass_former_a", former_a);
14804        report("outer_plan_three_pass_former_b", former_b);
14805        report("outer_plan_fused_candidate_a", candidate_a);
14806        report("outer_plan_fused_candidate_b", candidate_b);
14807    }
14808
14809    #[test]
14810    fn merge_temporal_outer_matches_generic_dtype_order_and_null_fill_rvb6u()
14811    -> Result<(), JoinError> {
14812        let left_ns = [-20, 10, 30, 50];
14813        let right_ns = [-30, -20, 20, 30, 60];
14814        let union_ns = [-30, -20, 10, 20, 30, 50, 60];
14815        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14816            let scalar = |ns| match &temporal {
14817                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
14818                DType::Timedelta64 => Scalar::Timedelta64(ns),
14819                _ => unreachable!("test iterates only temporal dtypes"),
14820            };
14821            let left = DataFrame::from_dict(
14822                &["key", "lv"],
14823                vec![
14824                    ("key", left_ns.into_iter().map(scalar).collect()),
14825                    (
14826                        "lv",
14827                        vec![
14828                            Scalar::Int64(100),
14829                            Scalar::Int64(101),
14830                            Scalar::Int64(102),
14831                            Scalar::Int64(103),
14832                        ],
14833                    ),
14834                ],
14835            )?;
14836            let right = DataFrame::from_dict(
14837                &["key", "rv"],
14838                vec![
14839                    ("key", right_ns.into_iter().map(scalar).collect()),
14840                    (
14841                        "rv",
14842                        vec![
14843                            Scalar::Int64(200),
14844                            Scalar::Int64(201),
14845                            Scalar::Int64(202),
14846                            Scalar::Int64(203),
14847                            Scalar::Int64(204),
14848                        ],
14849                    ),
14850                ],
14851            )?;
14852            let candidate = merge_dataframes_on(&left, &right, &["key"], JoinType::Outer)?;
14853            let generic = merge_dataframes_on_with_options(
14854                &left,
14855                &right,
14856                &["key"],
14857                &["key"],
14858                JoinType::Outer,
14859                MergeExecutionOptions {
14860                    sort: true,
14861                    ..MergeExecutionOptions::default()
14862                },
14863            )?;
14864            assert_eq!(candidate, generic, "{temporal:?} OUTER output parity");
14865            assert_eq!(candidate.columns["key"].dtype(), temporal);
14866            assert_eq!(
14867                merged_values(&candidate, "key")?,
14868                union_ns
14869                    .into_iter()
14870                    .map(scalar)
14871                    .collect::<Vec<_>>()
14872                    .as_slice(),
14873            );
14874
14875            let left_values = merged_values(&candidate, "lv")?;
14876            assert!(left_values[0].is_missing());
14877            assert_eq!(left_values[1], Scalar::Float64(100.0));
14878            assert_eq!(left_values[2], Scalar::Float64(101.0));
14879            assert!(left_values[3].is_missing());
14880            assert_eq!(left_values[4], Scalar::Float64(102.0));
14881            assert_eq!(left_values[5], Scalar::Float64(103.0));
14882            assert!(left_values[6].is_missing());
14883
14884            let right_values = merged_values(&candidate, "rv")?;
14885            assert_eq!(right_values[0], Scalar::Float64(200.0));
14886            assert_eq!(right_values[1], Scalar::Float64(201.0));
14887            assert!(right_values[2].is_missing());
14888            assert_eq!(right_values[3], Scalar::Float64(202.0));
14889            assert_eq!(right_values[4], Scalar::Float64(203.0));
14890            assert!(right_values[5].is_missing());
14891            assert_eq!(right_values[6], Scalar::Float64(204.0));
14892        }
14893
14894        let nat = fp_types::Timestamp::NAT;
14895        let nat_left = DataFrame::from_dict(
14896            &["key", "lv"],
14897            vec![
14898                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
14899                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
14900            ],
14901        )?;
14902        let nat_right = DataFrame::from_dict(
14903            &["key", "rv"],
14904            vec![
14905                (
14906                    "key",
14907                    vec![
14908                        Scalar::Datetime64(nat),
14909                        Scalar::Datetime64(5),
14910                        Scalar::Datetime64(7),
14911                    ],
14912                ),
14913                (
14914                    "rv",
14915                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(12)],
14916                ),
14917            ],
14918        )?;
14919        assert!(
14920            super::ordered_unique_temporal_i64_outer_positions(
14921                nat_left.column("key").expect("left NaT key"),
14922                nat_right.column("key").expect("right NaT key"),
14923            )
14924            .is_none(),
14925            "NaT must retain the scalar Missing-key fallback",
14926        );
14927        let nat_candidate = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Outer)?;
14928        let nat_generic = merge_dataframes_on_with_options(
14929            &nat_left,
14930            &nat_right,
14931            &["key"],
14932            &["key"],
14933            JoinType::Outer,
14934            MergeExecutionOptions {
14935                sort: true,
14936                ..MergeExecutionOptions::default()
14937            },
14938        )?;
14939        assert_eq!(nat_candidate, nat_generic);
14940        assert_eq!(
14941            nat_candidate.columns["key"].dtype(),
14942            DType::datetime64_naive()
14943        );
14944        assert!(
14945            merged_values(&nat_candidate, "key")?
14946                .iter()
14947                .any(Scalar::is_missing),
14948        );
14949
14950        Ok(())
14951    }
14952
14953    #[test]
14954    fn merge_composite_datetime_component_is_honored_not_missing_j0in7() -> Result<(), JoinError> {
14955        // A COMPOSITE join key [Utf8, Datetime64] declines the single-key temporal
14956        // fast path (`temporal_i64_inner_positions`) and routes through the generic
14957        // Scalar/`scalar_to_key_component` path. The Datetime64 (and Timedelta64)
14958        // component must map to a Present key by value — NOT collapse to `Missing`.
14959        // If it collapsed to Missing, rows sharing the Utf8 component would match
14960        // regardless of timestamp (Missing == Missing), over-matching. Left has two
14961        // "a" rows at ts=10/20; right has "a" at ts=10/99. Honoring the datetime,
14962        // the only equal composite keys are ("a",10) and ("b",10) => exactly 2 rows.
14963        // Under the old Missing-collapse this would be 5 rows.
14964        let left = DataFrame::from_dict(
14965            &["region", "ts", "lv"],
14966            vec![
14967                (
14968                    "region",
14969                    vec![
14970                        Scalar::Utf8("a".to_owned()),
14971                        Scalar::Utf8("a".to_owned()),
14972                        Scalar::Utf8("b".to_owned()),
14973                    ],
14974                ),
14975                (
14976                    "ts",
14977                    vec![
14978                        Scalar::Datetime64(10),
14979                        Scalar::Datetime64(20),
14980                        Scalar::Datetime64(10),
14981                    ],
14982                ),
14983                (
14984                    "lv",
14985                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
14986                ),
14987            ],
14988        )?;
14989        let right = DataFrame::from_dict(
14990            &["region", "ts", "rv"],
14991            vec![
14992                (
14993                    "region",
14994                    vec![
14995                        Scalar::Utf8("a".to_owned()),
14996                        Scalar::Utf8("a".to_owned()),
14997                        Scalar::Utf8("b".to_owned()),
14998                    ],
14999                ),
15000                (
15001                    "ts",
15002                    vec![
15003                        Scalar::Datetime64(10),
15004                        Scalar::Datetime64(99),
15005                        Scalar::Datetime64(10),
15006                    ],
15007                ),
15008                (
15009                    "rv",
15010                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(102)],
15011                ),
15012            ],
15013        )?;
15014        let merged = merge_dataframes_on(&left, &right, &["region", "ts"], JoinType::Inner)?;
15015        assert_eq!(
15016            merged.index.len(),
15017            2,
15018            "datetime composite component must discriminate, not collapse to Missing"
15019        );
15020        assert_eq!(merged.columns["ts"].dtype(), DType::datetime64_naive());
15021        // Pair (lv, rv) up per output row, order-independently.
15022        let mut pairs: Vec<(i64, i64)> = merged_values(&merged, "lv")?
15023            .iter()
15024            .zip(merged_values(&merged, "rv")?)
15025            .map(|(l, r)| match (l, r) {
15026                (Scalar::Int64(a), Scalar::Int64(b)) => (*a, *b),
15027                _ => panic!("unexpected non-Int64 value column"),
15028            })
15029            .collect();
15030        pairs.sort_unstable();
15031        assert_eq!(pairs, vec![(0, 100), (2, 102)]);
15032
15033        // The Timedelta64 sibling arm must behave identically.
15034        let ltd = DataFrame::from_dict(
15035            &["region", "td", "lv"],
15036            vec![
15037                (
15038                    "region",
15039                    vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("a".to_owned())],
15040                ),
15041                ("td", vec![Scalar::Timedelta64(10), Scalar::Timedelta64(20)]),
15042                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
15043            ],
15044        )?;
15045        let rtd = DataFrame::from_dict(
15046            &["region", "td", "rv"],
15047            vec![
15048                (
15049                    "region",
15050                    vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("a".to_owned())],
15051                ),
15052                ("td", vec![Scalar::Timedelta64(10), Scalar::Timedelta64(99)]),
15053                ("rv", vec![Scalar::Int64(100), Scalar::Int64(101)]),
15054            ],
15055        )?;
15056        let merged_td = merge_dataframes_on(&ltd, &rtd, &["region", "td"], JoinType::Inner)?;
15057        assert_eq!(
15058            merged_td.index.len(),
15059            1,
15060            "timedelta composite component must discriminate, not collapse to Missing"
15061        );
15062        assert_eq!(merged_values(&merged_td, "lv")?, &[Scalar::Int64(0)]);
15063        assert_eq!(merged_values(&merged_td, "rv")?, &[Scalar::Int64(100)]);
15064
15065        Ok(())
15066    }
15067
15068    fn merged_values_where_indicator(
15069        merged: &MergedDataFrame,
15070        column_name: &str,
15071        indicator_name: &str,
15072        indicator_value: &str,
15073    ) -> Result<Vec<Scalar>, JoinError> {
15074        let values = merged_values(merged, column_name)?;
15075        let indicators = merged_values(merged, indicator_name)?;
15076        Ok(values
15077            .iter()
15078            .zip(indicators.iter())
15079            .filter_map(|(value, indicator)| {
15080                if matches!(indicator, Scalar::Utf8(v) if v == indicator_value) {
15081                    Some(value.clone())
15082                } else {
15083                    None
15084                }
15085            })
15086            .collect())
15087    }
15088
15089    #[test]
15090    fn merge_inner_basic() {
15091        let left = make_left_df();
15092        let right = make_right_df();
15093        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15094
15095        assert_eq!(merged.columns.get("id").unwrap().len(), 2);
15096        assert_eq!(
15097            merged.columns.get("id").unwrap().values(),
15098            &[Scalar::Int64(2), Scalar::Int64(3)]
15099        );
15100        assert_eq!(
15101            merged.columns.get("val_a").unwrap().values(),
15102            &[Scalar::Int64(20), Scalar::Int64(30)]
15103        );
15104        assert_eq!(
15105            merged.columns.get("val_b").unwrap().values(),
15106            &[Scalar::Int64(200), Scalar::Int64(300)]
15107        );
15108    }
15109
15110    #[test]
15111    fn merge_inner_single_key_preserves_duplicate_probe_order() {
15112        let left = DataFrame::from_dict(
15113            &["id", "left_value"],
15114            vec![
15115                (
15116                    "id",
15117                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
15118                ),
15119                (
15120                    "left_value",
15121                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
15122                ),
15123            ],
15124        )
15125        .unwrap();
15126        let right = DataFrame::from_dict(
15127            &["id", "right_value"],
15128            vec![
15129                (
15130                    "id",
15131                    vec![Scalar::Int64(2), Scalar::Int64(2), Scalar::Int64(1)],
15132                ),
15133                (
15134                    "right_value",
15135                    vec![Scalar::Int64(200), Scalar::Int64(201), Scalar::Int64(100)],
15136                ),
15137            ],
15138        )
15139        .unwrap();
15140
15141        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15142
15143        assert_eq!(
15144            merged.columns.get("id").unwrap().values(),
15145            &[
15146                Scalar::Int64(2),
15147                Scalar::Int64(2),
15148                Scalar::Int64(1),
15149                Scalar::Int64(2),
15150                Scalar::Int64(2),
15151            ]
15152        );
15153        assert_eq!(
15154            merged.columns.get("left_value").unwrap().values(),
15155            &[
15156                Scalar::Int64(20),
15157                Scalar::Int64(20),
15158                Scalar::Int64(10),
15159                Scalar::Int64(21),
15160                Scalar::Int64(21),
15161            ]
15162        );
15163        assert_eq!(
15164            merged.columns.get("right_value").unwrap().values(),
15165            &[
15166                Scalar::Int64(200),
15167                Scalar::Int64(201),
15168                Scalar::Int64(100),
15169                Scalar::Int64(200),
15170                Scalar::Int64(201),
15171            ]
15172        );
15173    }
15174
15175    #[test]
15176    fn merge_inner_wide_sparse_int64_hash_matches_generic_validated_route() {
15177        let stride = 1_i64 << 30;
15178        let left = DataFrame::from_dict(
15179            &["id", "left_value"],
15180            vec![
15181                (
15182                    "id",
15183                    vec![3, 1, 3, 0, 2]
15184                        .into_iter()
15185                        .map(|v| Scalar::Int64(v * stride))
15186                        .collect(),
15187                ),
15188                (
15189                    "left_value",
15190                    vec![
15191                        Scalar::Int64(10),
15192                        Scalar::Int64(11),
15193                        Scalar::Int64(12),
15194                        Scalar::Int64(13),
15195                        Scalar::Int64(14),
15196                    ],
15197                ),
15198            ],
15199        )
15200        .unwrap();
15201        let right = DataFrame::from_dict(
15202            &["id", "right_value"],
15203            vec![
15204                (
15205                    "id",
15206                    vec![3, 2, 3, 1]
15207                        .into_iter()
15208                        .map(|v| Scalar::Int64(v * stride))
15209                        .collect(),
15210                ),
15211                (
15212                    "right_value",
15213                    vec![
15214                        Scalar::Int64(100),
15215                        Scalar::Int64(101),
15216                        Scalar::Int64(102),
15217                        Scalar::Int64(103),
15218                    ],
15219                ),
15220            ],
15221        )
15222        .unwrap();
15223
15224        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15225        let generic = merge_dataframes_on_with_options(
15226            &left,
15227            &right,
15228            &["id"],
15229            &["id"],
15230            JoinType::Inner,
15231            MergeExecutionOptions {
15232                validate_mode: Some(MergeValidateMode::ManyToMany),
15233                ..MergeExecutionOptions::default()
15234            },
15235        )
15236        .unwrap();
15237
15238        assert_eq!(fast.index, generic.index);
15239        assert_eq!(fast.column_order, generic.column_order);
15240        assert_eq!(fast.columns, generic.columns);
15241        assert_eq!(
15242            fast.columns.get("id").unwrap().values(),
15243            &[
15244                Scalar::Int64(3 * stride),
15245                Scalar::Int64(3 * stride),
15246                Scalar::Int64(stride),
15247                Scalar::Int64(3 * stride),
15248                Scalar::Int64(3 * stride),
15249                Scalar::Int64(2 * stride),
15250            ]
15251        );
15252        assert_eq!(
15253            fast.columns.get("left_value").unwrap().values(),
15254            &[
15255                Scalar::Int64(10),
15256                Scalar::Int64(10),
15257                Scalar::Int64(11),
15258                Scalar::Int64(12),
15259                Scalar::Int64(12),
15260                Scalar::Int64(14),
15261            ]
15262        );
15263        assert_eq!(
15264            fast.columns.get("right_value").unwrap().values(),
15265            &[
15266                Scalar::Int64(100),
15267                Scalar::Int64(102),
15268                Scalar::Int64(103),
15269                Scalar::Int64(100),
15270                Scalar::Int64(102),
15271                Scalar::Int64(101),
15272            ]
15273        );
15274    }
15275
15276    #[test]
15277    fn dense_i64_inner_parallel_output_data_preserves_row_major_order() {
15278        let left_keys = vec![-1, 2, 1, 2, 3, 9];
15279        let min = 1;
15280        let max = 3;
15281        let offsets = vec![0, 2, 3, 5];
15282        let positions = vec![1usize, 4, 0, 2, 3];
15283        let left_values = vec![10, 20, 30, 40, 50, 60];
15284        let right_values = vec![100, 101, 102, 103, 104];
15285        let specs = vec![
15286            FusedInt64OutputColumn {
15287                name: "left".to_string(),
15288                side: FusedInt64Side::Left,
15289                values: &left_values,
15290            },
15291            FusedInt64OutputColumn {
15292                name: "right".to_string(),
15293                side: FusedInt64Side::Right,
15294                values: &right_values,
15295            },
15296        ];
15297
15298        let plan = DenseI64InnerOutputPlan {
15299            left_keys: &left_keys,
15300            min,
15301            max,
15302            offsets: &offsets,
15303            positions: &positions,
15304            output_len: 6,
15305        };
15306        let actual = build_dense_i64_inner_output_data(&specs, &plan);
15307
15308        // 4 matched left rows -> 6 output rows: avg fanout < 2, so the left
15309        // lane stays fully materialized alongside the right lane.
15310        assert_eq!(lane_expanded(&actual[0]), vec![20, 30, 30, 40, 50, 50]);
15311        assert_eq!(
15312            lane_expanded(&actual[1]),
15313            vec![100, 101, 104, 100, 102, 103]
15314        );
15315        assert!(matches!(actual[0], DenseI64LaneData::Full(_)));
15316        assert!(matches!(actual[1], DenseI64LaneData::Full(_)));
15317    }
15318
15319    fn lane_expanded(lane: &DenseI64LaneData) -> Vec<i64> {
15320        match lane {
15321            DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
15322                let mut out = Vec::new();
15323                for (&value, &run_len) in values.iter().zip(run_lens.iter()) {
15324                    out.resize(out.len() + run_len, value);
15325                }
15326                out
15327            }
15328            DenseI64LaneData::RepeatedSlices { data, segments } => {
15329                let mut out = Vec::new();
15330                for &(start, len) in segments.iter() {
15331                    out.extend_from_slice(&data[start..start + len]);
15332                }
15333                out
15334            }
15335            DenseI64LaneData::Full(data) => data.clone(),
15336        }
15337    }
15338
15339    #[test]
15340    fn dense_i64_inner_high_fanout_emits_repeat_run_left_lanes() {
15341        // 2 matched left rows, each matching 3 right rows -> avg fanout 3:
15342        // left lane must come back as repeat runs and the right lane as
15343        // repeated slices. Their expansion equals the old full fill.
15344        let left_keys = vec![1, 7, 2];
15345        let min = 1;
15346        let max = 2;
15347        let offsets = vec![0, 3, 6];
15348        let positions = vec![0usize, 2, 4, 1, 3, 5];
15349        let left_values = vec![10, 20, 30];
15350        let right_values = vec![100, 101, 102, 103, 104, 105];
15351        let specs = vec![
15352            FusedInt64OutputColumn {
15353                name: "left".to_string(),
15354                side: FusedInt64Side::Left,
15355                values: &left_values,
15356            },
15357            FusedInt64OutputColumn {
15358                name: "right".to_string(),
15359                side: FusedInt64Side::Right,
15360                values: &right_values,
15361            },
15362        ];
15363
15364        let plan = DenseI64InnerOutputPlan {
15365            left_keys: &left_keys,
15366            min,
15367            max,
15368            offsets: &offsets,
15369            positions: &positions,
15370            output_len: 6,
15371        };
15372        let actual = build_dense_i64_inner_output_data(&specs, &plan);
15373
15374        assert!(matches!(
15375            actual[0],
15376            DenseI64LaneData::RepeatRunLengths { .. }
15377        ));
15378        assert!(matches!(actual[1], DenseI64LaneData::RepeatedSlices { .. }));
15379        assert_eq!(lane_expanded(&actual[0]), vec![10, 10, 10, 30, 30, 30]);
15380        assert_eq!(
15381            lane_expanded(&actual[1]),
15382            vec![100, 102, 104, 101, 103, 105]
15383        );
15384
15385        // The lazy Column built from shared run lengths is indistinguishable
15386        // from the eagerly materialized one (values, slice view, length,
15387        // equality).
15388        let lazy = fp_columnar::Column::from_i64_repeat_values_run_lengths(
15389            vec![10, 30],
15390            std::sync::Arc::from([3usize, 3]),
15391        );
15392        let eager = fp_columnar::Column::from_i64_values(vec![10, 10, 10, 30, 30, 30]);
15393        assert_eq!(lazy.len(), eager.len());
15394        assert_eq!(lazy.as_i64_slice(), eager.as_i64_slice());
15395        assert_eq!(lazy.values(), eager.values());
15396        assert_eq!(lazy, eager);
15397    }
15398
15399    #[test]
15400    fn dense_cycle_left_join_declines_invented_gaps_66wab() {
15401        let left = DataFrame::from_dict(
15402            &["id", "v"],
15403            vec![
15404                (
15405                    "id",
15406                    vec![
15407                        Scalar::Int64(0),
15408                        Scalar::Int64(1),
15409                        Scalar::Int64(2),
15410                        Scalar::Int64(0),
15411                        Scalar::Int64(1),
15412                        Scalar::Int64(2),
15413                        Scalar::Int64(0),
15414                    ],
15415                ),
15416                (
15417                    "v",
15418                    vec![
15419                        Scalar::Int64(10),
15420                        Scalar::Int64(11),
15421                        Scalar::Int64(12),
15422                        Scalar::Int64(13),
15423                        Scalar::Int64(14),
15424                        Scalar::Int64(15),
15425                        Scalar::Int64(16),
15426                    ],
15427                ),
15428            ],
15429        )
15430        .unwrap();
15431        let right = DataFrame::from_dict(
15432            &["id", "rv"],
15433            vec![
15434                (
15435                    "id",
15436                    vec![
15437                        Scalar::Int64(1),
15438                        Scalar::Int64(2),
15439                        Scalar::Int64(1),
15440                        Scalar::Int64(2),
15441                    ],
15442                ),
15443                (
15444                    "rv",
15445                    vec![
15446                        Scalar::Int64(100),
15447                        Scalar::Int64(200),
15448                        Scalar::Int64(101),
15449                        Scalar::Int64(201),
15450                    ],
15451                ),
15452            ],
15453        )
15454        .unwrap();
15455        let suffixes = ResolvedMergeSuffixes::default();
15456        let left_key = left.column("id").unwrap();
15457        let right_key = right.column("id").unwrap();
15458
15459        let dense_cycle = build_single_key_dense_cycle_i64_left_merge_output(
15460            &left,
15461            &right,
15462            &["id"],
15463            &["id"],
15464            left_key,
15465            right_key,
15466            &suffixes,
15467        )
15468        .unwrap();
15469        assert!(dense_cycle.is_none());
15470        assert!(
15471            build_single_key_dense_i64_left_merge_output(
15472                &left,
15473                &right,
15474                &["id"],
15475                &["id"],
15476                left_key,
15477                right_key,
15478                &suffixes,
15479            )
15480            .unwrap()
15481            .is_none()
15482        );
15483    }
15484
15485    #[test]
15486    fn merge_inner_ordered_identity_matches_generic_validated_route() {
15487        let left = DataFrame::from_dict(
15488            &["id", "v"],
15489            vec![
15490                (
15491                    "id",
15492                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15493                ),
15494                (
15495                    "v",
15496                    vec![
15497                        Scalar::Int64(10),
15498                        Scalar::Null(NullKind::Null),
15499                        Scalar::Int64(30),
15500                    ],
15501                ),
15502            ],
15503        )
15504        .unwrap();
15505        let right = DataFrame::from_dict(
15506            &["id", "w"],
15507            vec![
15508                (
15509                    "id",
15510                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15511                ),
15512                (
15513                    "w",
15514                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
15515                ),
15516            ],
15517        )
15518        .unwrap();
15519
15520        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15521        let generic = merge_dataframes_on_with_options(
15522            &left,
15523            &right,
15524            &["id"],
15525            &["id"],
15526            JoinType::Inner,
15527            MergeExecutionOptions {
15528                validate_mode: Some(MergeValidateMode::OneToOne),
15529                ..MergeExecutionOptions::default()
15530            },
15531        )
15532        .unwrap();
15533
15534        assert_eq!(fast.index, generic.index);
15535        assert_eq!(fast.column_order, generic.column_order);
15536        assert_eq!(fast.columns, generic.columns);
15537    }
15538
15539    #[test]
15540    fn merge_inner_dense_int64_fused_materialization_matches_generic_route() {
15541        let left = DataFrame::from_dict(
15542            &["id", "v", "overlap"],
15543            vec![
15544                (
15545                    "id",
15546                    vec![
15547                        Scalar::Int64(2),
15548                        Scalar::Int64(1),
15549                        Scalar::Int64(2),
15550                        Scalar::Int64(3),
15551                    ],
15552                ),
15553                (
15554                    "v",
15555                    vec![
15556                        Scalar::Int64(20),
15557                        Scalar::Int64(10),
15558                        Scalar::Int64(21),
15559                        Scalar::Int64(30),
15560                    ],
15561                ),
15562                (
15563                    "overlap",
15564                    vec![
15565                        Scalar::Int64(200),
15566                        Scalar::Int64(100),
15567                        Scalar::Int64(201),
15568                        Scalar::Int64(300),
15569                    ],
15570                ),
15571            ],
15572        )
15573        .unwrap();
15574        let right = DataFrame::from_dict(
15575            &["id", "w", "overlap"],
15576            vec![
15577                (
15578                    "id",
15579                    vec![
15580                        Scalar::Int64(2),
15581                        Scalar::Int64(2),
15582                        Scalar::Int64(1),
15583                        Scalar::Int64(4),
15584                    ],
15585                ),
15586                (
15587                    "w",
15588                    vec![
15589                        Scalar::Int64(2000),
15590                        Scalar::Int64(2001),
15591                        Scalar::Int64(1000),
15592                        Scalar::Int64(4000),
15593                    ],
15594                ),
15595                (
15596                    "overlap",
15597                    vec![
15598                        Scalar::Int64(20_000),
15599                        Scalar::Int64(20_001),
15600                        Scalar::Int64(10_000),
15601                        Scalar::Int64(40_000),
15602                    ],
15603                ),
15604            ],
15605        )
15606        .unwrap();
15607
15608        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15609        let generic = merge_dataframes_on_with_options(
15610            &left,
15611            &right,
15612            &["id"],
15613            &["id"],
15614            JoinType::Inner,
15615            MergeExecutionOptions {
15616                validate_mode: Some(MergeValidateMode::ManyToMany),
15617                ..MergeExecutionOptions::default()
15618            },
15619        )
15620        .unwrap();
15621
15622        assert_eq!(fast.index, generic.index);
15623        assert_eq!(fast.column_order, generic.column_order);
15624        assert_eq!(fast.columns, generic.columns);
15625        assert_eq!(
15626            fast.column_order,
15627            ["id", "v", "overlap_x", "w", "overlap_y"]
15628        );
15629        assert_eq!(
15630            fast.columns.get("id").unwrap().values(),
15631            &[
15632                Scalar::Int64(2),
15633                Scalar::Int64(2),
15634                Scalar::Int64(1),
15635                Scalar::Int64(2),
15636                Scalar::Int64(2),
15637            ]
15638        );
15639        assert_eq!(
15640            fast.columns.get("w").unwrap().values(),
15641            &[
15642                Scalar::Int64(2000),
15643                Scalar::Int64(2001),
15644                Scalar::Int64(1000),
15645                Scalar::Int64(2000),
15646                Scalar::Int64(2001),
15647            ]
15648        );
15649        assert!(
15650            fast.columns
15651                .values()
15652                .all(|column| column.as_i64_slice().is_some())
15653        );
15654    }
15655
15656    #[test]
15657    fn merge_inner_ordered_unique_int64_subset_matches_generic_validated_route() {
15658        let left = DataFrame::from_dict(
15659            &["id", "v"],
15660            vec![
15661                (
15662                    "id",
15663                    vec![
15664                        Scalar::Int64(0),
15665                        Scalar::Int64(1),
15666                        Scalar::Int64(2),
15667                        Scalar::Int64(3),
15668                        Scalar::Int64(4),
15669                    ],
15670                ),
15671                (
15672                    "v",
15673                    vec![
15674                        Scalar::Int64(10),
15675                        Scalar::Int64(11),
15676                        Scalar::Int64(12),
15677                        Scalar::Int64(13),
15678                        Scalar::Int64(14),
15679                    ],
15680                ),
15681            ],
15682        )
15683        .unwrap();
15684        let right = DataFrame::from_dict(
15685            &["id", "w"],
15686            vec![
15687                (
15688                    "id",
15689                    vec![
15690                        Scalar::Int64(0),
15691                        Scalar::Int64(2),
15692                        Scalar::Int64(4),
15693                        Scalar::Int64(6),
15694                    ],
15695                ),
15696                (
15697                    "w",
15698                    vec![
15699                        Scalar::Int64(100),
15700                        Scalar::Int64(200),
15701                        Scalar::Int64(300),
15702                        Scalar::Int64(400),
15703                    ],
15704                ),
15705            ],
15706        )
15707        .unwrap();
15708
15709        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15710        let generic = merge_dataframes_on_with_options(
15711            &left,
15712            &right,
15713            &["id"],
15714            &["id"],
15715            JoinType::Inner,
15716            MergeExecutionOptions {
15717                validate_mode: Some(MergeValidateMode::OneToOne),
15718                ..MergeExecutionOptions::default()
15719            },
15720        )
15721        .unwrap();
15722
15723        assert_eq!(fast.index, generic.index);
15724        assert_eq!(fast.column_order, generic.column_order);
15725        assert_eq!(fast.columns, generic.columns);
15726        assert_eq!(
15727            fast.columns.get("id").unwrap().values(),
15728            &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(4)]
15729        );
15730        assert_eq!(
15731            fast.columns.get("v").unwrap().values(),
15732            &[Scalar::Int64(10), Scalar::Int64(12), Scalar::Int64(14)]
15733        );
15734        assert_eq!(
15735            fast.columns.get("w").unwrap().values(),
15736            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
15737        );
15738    }
15739
15740    #[test]
15741    fn merge_inner_ordered_identity_falls_back_for_non_identity_keys() {
15742        let cases = [
15743            (
15744                vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(4)],
15745                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15746            ),
15747            (
15748                vec![
15749                    Scalar::Int64(1),
15750                    Scalar::Null(NullKind::Null),
15751                    Scalar::Int64(3),
15752                ],
15753                vec![
15754                    Scalar::Int64(1),
15755                    Scalar::Null(NullKind::Null),
15756                    Scalar::Int64(3),
15757                ],
15758            ),
15759        ];
15760
15761        for (left_keys, right_keys) in cases {
15762            let left = DataFrame::from_dict(
15763                &["id", "v"],
15764                vec![
15765                    ("id", left_keys),
15766                    (
15767                        "v",
15768                        vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
15769                    ),
15770                ],
15771            )
15772            .unwrap();
15773            let right = DataFrame::from_dict(
15774                &["id", "w"],
15775                vec![
15776                    ("id", right_keys),
15777                    (
15778                        "w",
15779                        vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
15780                    ),
15781                ],
15782            )
15783            .unwrap();
15784
15785            let maybe_fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15786            let generic = merge_dataframes_on_with_options(
15787                &left,
15788                &right,
15789                &["id"],
15790                &["id"],
15791                JoinType::Inner,
15792                MergeExecutionOptions {
15793                    validate_mode: Some(MergeValidateMode::OneToOne),
15794                    ..MergeExecutionOptions::default()
15795                },
15796            )
15797            .unwrap();
15798
15799            assert_eq!(maybe_fast.index, generic.index);
15800            assert_eq!(maybe_fast.column_order, generic.column_order);
15801            assert_eq!(maybe_fast.columns, generic.columns);
15802        }
15803    }
15804
15805    #[test]
15806    fn merge_default_suffixes_match_pandas() {
15807        // Overlapping non-key column "v" gets pandas default _x/_y suffixes.
15808        // Verified vs pandas 2.2.3: left{k:[1,2,3],v:[10,20,30]} merged inner on
15809        // k with right{k:[2,3,4],v:[200,300,400]} -> cols [k,v_x,v_y],
15810        // k=[2,3], v_x=[20,30], v_y=[200,300].
15811        let idx: Vec<_> = (0..3).map(|i| (i as i64).into()).collect();
15812        let left = fp_frame::DataFrame::from_series(vec![
15813            fp_frame::Series::from_values(
15814                "k",
15815                idx.clone(),
15816                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15817            )
15818            .unwrap(),
15819            fp_frame::Series::from_values(
15820                "v",
15821                idx.clone(),
15822                vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
15823            )
15824            .unwrap(),
15825        ])
15826        .unwrap();
15827        let right = fp_frame::DataFrame::from_series(vec![
15828            fp_frame::Series::from_values(
15829                "k",
15830                idx.clone(),
15831                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
15832            )
15833            .unwrap(),
15834            fp_frame::Series::from_values(
15835                "v",
15836                idx,
15837                vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
15838            )
15839            .unwrap(),
15840        ])
15841        .unwrap();
15842        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
15843
15844        assert_eq!(
15845            merged.columns.get("k").unwrap().values(),
15846            &[Scalar::Int64(2), Scalar::Int64(3)],
15847            "k"
15848        );
15849        assert_eq!(
15850            merged.columns.get("v_x").unwrap().values(),
15851            &[Scalar::Int64(20), Scalar::Int64(30)],
15852            "v_x"
15853        );
15854        assert_eq!(
15855            merged.columns.get("v_y").unwrap().values(),
15856            &[Scalar::Int64(200), Scalar::Int64(300)],
15857            "v_y"
15858        );
15859        assert!(
15860            !merged.columns.contains_key("v"),
15861            "bare 'v' should be suffixed away"
15862        );
15863    }
15864
15865    #[test]
15866    fn merge_left_preserves_all_left_rows() {
15867        let left = make_left_df();
15868        let right = make_right_df();
15869        let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15870
15871        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
15872        assert_eq!(
15873            merged.columns.get("val_a").unwrap().values(),
15874            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
15875        );
15876        // val_b widens to Float64 because id=1 invents a missing value.
15877        assert_eq!(merged.columns.get("val_b").unwrap().dtype(), DType::Float64);
15878        assert_eq!(
15879            merged.columns.get("val_b").unwrap().values()[0],
15880            Scalar::Null(NullKind::NaN)
15881        );
15882        assert_eq!(
15883            merged.columns.get("val_b").unwrap().values()[1],
15884            Scalar::Float64(200.0)
15885        );
15886        assert_eq!(
15887            merged.columns.get("val_b").unwrap().values()[2],
15888            Scalar::Float64(300.0)
15889        );
15890    }
15891
15892    #[test]
15893    fn merge_left_ordered_unique_int64_subset_matches_generic_validated_route() {
15894        let left = DataFrame::from_dict(
15895            &["id", "v"],
15896            vec![
15897                (
15898                    "id",
15899                    vec![
15900                        Scalar::Int64(0),
15901                        Scalar::Int64(1),
15902                        Scalar::Int64(2),
15903                        Scalar::Int64(3),
15904                        Scalar::Int64(4),
15905                    ],
15906                ),
15907                (
15908                    "v",
15909                    vec![
15910                        Scalar::Int64(10),
15911                        Scalar::Int64(11),
15912                        Scalar::Int64(12),
15913                        Scalar::Int64(13),
15914                        Scalar::Int64(14),
15915                    ],
15916                ),
15917            ],
15918        )
15919        .unwrap();
15920        let right = DataFrame::from_dict(
15921            &["id", "w"],
15922            vec![
15923                (
15924                    "id",
15925                    vec![
15926                        Scalar::Int64(0),
15927                        Scalar::Int64(2),
15928                        Scalar::Int64(4),
15929                        Scalar::Int64(6),
15930                    ],
15931                ),
15932                (
15933                    "w",
15934                    vec![
15935                        Scalar::Int64(100),
15936                        Scalar::Int64(200),
15937                        Scalar::Int64(300),
15938                        Scalar::Int64(400),
15939                    ],
15940                ),
15941            ],
15942        )
15943        .unwrap();
15944
15945        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15946        let generic = merge_dataframes_on_with_options(
15947            &left,
15948            &right,
15949            &["id"],
15950            &["id"],
15951            JoinType::Left,
15952            MergeExecutionOptions {
15953                validate_mode: Some(MergeValidateMode::OneToOne),
15954                ..MergeExecutionOptions::default()
15955            },
15956        )
15957        .unwrap();
15958
15959        assert_eq!(fast.index, generic.index);
15960        assert_eq!(fast.column_order, generic.column_order);
15961        assert_eq!(fast.columns, generic.columns);
15962        assert_eq!(
15963            fast.columns.get("id").unwrap().values(),
15964            &[
15965                Scalar::Int64(0),
15966                Scalar::Int64(1),
15967                Scalar::Int64(2),
15968                Scalar::Int64(3),
15969                Scalar::Int64(4)
15970            ]
15971        );
15972        let right_values = fast.columns.get("w").unwrap().values();
15973        assert_eq!(right_values[0], Scalar::Float64(100.0));
15974        assert!(right_values[1].is_missing());
15975        assert_eq!(right_values[2], Scalar::Float64(200.0));
15976        assert!(right_values[3].is_missing());
15977        assert_eq!(right_values[4], Scalar::Float64(300.0));
15978    }
15979
15980    #[test]
15981    fn merge_left_ordered_unique_int64_retains_lazy_utf8_payload_plan() {
15982        let left = DataFrame::from_dict(
15983            &["id", "v"],
15984            vec![
15985                ("id", (0..5_i64).map(Scalar::Int64).collect::<Vec<_>>()),
15986                ("v", (10..15_i64).map(Scalar::Int64).collect::<Vec<_>>()),
15987            ],
15988        )
15989        .unwrap();
15990        let right = DataFrame::from_dict(
15991            &["id", "tag"],
15992            vec![
15993                (
15994                    "id",
15995                    [0_i64, 2, 4, 6].into_iter().map(Scalar::Int64).collect(),
15996                ),
15997                (
15998                    "tag",
15999                    ["zero", "two", "four", "six"]
16000                        .into_iter()
16001                        .map(|value| Scalar::Utf8(value.to_owned()))
16002                        .collect(),
16003                ),
16004            ],
16005        )
16006        .unwrap();
16007
16008        let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16009        let tags = merged.columns.get("tag").unwrap().values();
16010        assert_eq!(tags[0], Scalar::Utf8("zero".to_owned()));
16011        assert!(tags[1].is_missing());
16012        assert_eq!(tags[2], Scalar::Utf8("two".to_owned()));
16013        assert!(tags[3].is_missing());
16014        assert_eq!(tags[4], Scalar::Utf8("four".to_owned()));
16015    }
16016
16017    #[test]
16018    fn merge_left_dense_int64_duplicates_matches_generic_validated_route() {
16019        let left = DataFrame::from_dict(
16020            &["id", "v"],
16021            vec![
16022                (
16023                    "id",
16024                    vec![
16025                        Scalar::Int64(2),
16026                        Scalar::Int64(0),
16027                        Scalar::Int64(2),
16028                        Scalar::Int64(1),
16029                        Scalar::Int64(5),
16030                    ],
16031                ),
16032                (
16033                    "v",
16034                    vec![
16035                        Scalar::Int64(10),
16036                        Scalar::Int64(11),
16037                        Scalar::Int64(12),
16038                        Scalar::Int64(13),
16039                        Scalar::Int64(15),
16040                    ],
16041                ),
16042            ],
16043        )
16044        .unwrap();
16045        let right = DataFrame::from_dict(
16046            &["id", "w"],
16047            vec![
16048                (
16049                    "id",
16050                    vec![
16051                        Scalar::Int64(2),
16052                        Scalar::Int64(2),
16053                        Scalar::Int64(3),
16054                        Scalar::Int64(0),
16055                    ],
16056                ),
16057                (
16058                    "w",
16059                    vec![
16060                        Scalar::Int64(200),
16061                        Scalar::Int64(201),
16062                        Scalar::Int64(300),
16063                        Scalar::Int64(400),
16064                    ],
16065                ),
16066            ],
16067        )
16068        .unwrap();
16069
16070        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16071        let generic = merge_dataframes_on_with_options(
16072            &left,
16073            &right,
16074            &["id"],
16075            &["id"],
16076            JoinType::Left,
16077            MergeExecutionOptions {
16078                validate_mode: Some(MergeValidateMode::ManyToMany),
16079                ..MergeExecutionOptions::default()
16080            },
16081        )
16082        .unwrap();
16083
16084        assert_eq!(fast.index, generic.index);
16085        assert_eq!(fast.column_order, generic.column_order);
16086        assert_eq!(fast.columns, generic.columns);
16087        assert_eq!(
16088            fast.columns.get("id").unwrap().values(),
16089            &[
16090                Scalar::Int64(2),
16091                Scalar::Int64(2),
16092                Scalar::Int64(0),
16093                Scalar::Int64(2),
16094                Scalar::Int64(2),
16095                Scalar::Int64(1),
16096                Scalar::Int64(5),
16097            ]
16098        );
16099        let left_values = fast.columns.get("v").unwrap().values();
16100        assert_eq!(left_values[0], Scalar::Int64(10));
16101        assert_eq!(left_values[1], Scalar::Int64(10));
16102        assert_eq!(left_values[2], Scalar::Int64(11));
16103        assert_eq!(left_values[4], Scalar::Int64(12));
16104        assert_eq!(left_values[6], Scalar::Int64(15));
16105        let right_values = fast.columns.get("w").unwrap().values();
16106        assert_eq!(right_values[0], Scalar::Float64(200.0));
16107        assert_eq!(right_values[1], Scalar::Float64(201.0));
16108        assert_eq!(right_values[2], Scalar::Float64(400.0));
16109        assert!(right_values[5].is_missing());
16110        assert!(right_values[6].is_missing());
16111    }
16112
16113    #[test]
16114    fn merge_left_dense_cycle_probe_declines_invented_gaps_66wab() {
16115        let left = DataFrame::from_dict(
16116            &["id", "v"],
16117            vec![
16118                (
16119                    "id",
16120                    vec![
16121                        Scalar::Int64(0),
16122                        Scalar::Int64(1),
16123                        Scalar::Int64(2),
16124                        Scalar::Int64(0),
16125                        Scalar::Int64(1),
16126                    ],
16127                ),
16128                (
16129                    "v",
16130                    vec![
16131                        Scalar::Int64(10),
16132                        Scalar::Int64(11),
16133                        Scalar::Int64(12),
16134                        Scalar::Int64(13),
16135                        Scalar::Int64(14),
16136                    ],
16137                ),
16138            ],
16139        )
16140        .unwrap();
16141        let right = DataFrame::from_dict(
16142            &["id", "w"],
16143            vec![
16144                (
16145                    "id",
16146                    vec![
16147                        Scalar::Int64(1),
16148                        Scalar::Int64(2),
16149                        Scalar::Int64(1),
16150                        Scalar::Int64(2),
16151                    ],
16152                ),
16153                (
16154                    "w",
16155                    vec![
16156                        Scalar::Int64(100),
16157                        Scalar::Int64(200),
16158                        Scalar::Int64(101),
16159                        Scalar::Int64(201),
16160                    ],
16161                ),
16162            ],
16163        )
16164        .unwrap();
16165        let left_key = left.columns().get("id").unwrap();
16166        let right_key = right.columns().get("id").unwrap();
16167        assert!(left_key.int64_dense_cycle_witness().is_some());
16168        assert!(right_key.int64_dense_cycle_witness().is_some());
16169        let suffixes = resolve_merge_suffixes(None);
16170
16171        let fused = build_single_key_dense_i64_left_merge_output(
16172            &left,
16173            &right,
16174            &["id"],
16175            &["id"],
16176            left_key,
16177            right_key,
16178            &suffixes,
16179        )
16180        .unwrap();
16181        assert!(fused.is_none());
16182    }
16183
16184    #[test]
16185    fn partial_int64_merges_promote_invented_gaps_66wab() {
16186        let left = DataFrame::from_dict(
16187            &["id", "v"],
16188            vec![
16189                (
16190                    "id",
16191                    vec![
16192                        Scalar::Int64(0),
16193                        Scalar::Int64(1),
16194                        Scalar::Int64(2),
16195                        Scalar::Int64(0),
16196                        Scalar::Int64(1),
16197                    ],
16198                ),
16199                (
16200                    "v",
16201                    vec![
16202                        Scalar::Int64(10),
16203                        Scalar::Int64(11),
16204                        Scalar::Int64(12),
16205                        Scalar::Int64(13),
16206                        Scalar::Int64(14),
16207                    ],
16208                ),
16209            ],
16210        )
16211        .unwrap();
16212        let right = DataFrame::from_dict(
16213            &["id", "w"],
16214            vec![
16215                (
16216                    "id",
16217                    vec![
16218                        Scalar::Int64(1),
16219                        Scalar::Int64(2),
16220                        Scalar::Int64(1),
16221                        Scalar::Int64(2),
16222                    ],
16223                ),
16224                (
16225                    "w",
16226                    vec![
16227                        Scalar::Int64(100),
16228                        Scalar::Int64(200),
16229                        Scalar::Int64(101),
16230                        Scalar::Int64(201),
16231                    ],
16232                ),
16233            ],
16234        )
16235        .unwrap();
16236
16237        let left_join = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16238        let left_gap_column = left_join.columns.get("w").unwrap();
16239        assert_eq!(left_gap_column.dtype(), DType::Float64);
16240        assert_eq!(left_gap_column.values()[0], Scalar::Null(NullKind::NaN));
16241        assert_eq!(left_gap_column.values()[1], Scalar::Float64(100.0));
16242
16243        let right_join = merge_dataframes(&right, &left, "id", JoinType::Right).unwrap();
16244        let right_gap_column = right_join.columns.get("w").unwrap();
16245        assert_eq!(right_gap_column.dtype(), DType::Float64);
16246        assert_eq!(right_gap_column.values()[0], Scalar::Null(NullKind::NaN));
16247        assert_eq!(right_gap_column.values()[1], Scalar::Float64(100.0));
16248    }
16249
16250    /// A missing value FrankenPandas spells two ways on a float lane: the
16251    /// `Null(NaN)` marker, and a present `Float64` whose bits are NaN (typed
16252    /// kernels emit the latter directly). pandas has ONE representation — the
16253    /// NaN bit pattern in the float64 array — and the fixture format writes
16254    /// either as `na_n`, so a null-kind assertion on a float lane must accept
16255    /// both or it fails on a legitimate representation change. What it must
16256    /// still reject is a carried-over generic `Null(Null)` or a `NaT`.
16257    ///
16258    /// br-frankenpandas-nywa8; the trap is WindyHare's window/derived slice.
16259    fn assert_nan_flavoured(value: &Scalar, what: &str) {
16260        let ok = match value {
16261            Scalar::Null(NullKind::NaN) => true,
16262            Scalar::Float64(v) => v.is_nan(),
16263            _ => false,
16264        };
16265        assert!(
16266            ok,
16267            "{what}: expected a NaN-flavoured missing, got {value:?}"
16268        );
16269    }
16270
16271    /// The four merge fixtures that were the last structural rows on
16272    /// br-frankenpandas-nywa8, run through the SAME entry point the conformance
16273    /// harness uses (`merge_dataframes_on_with_options`) on their exact
16274    /// payloads.
16275    ///
16276    /// THE RULE, and every line of it MEASURED against live pandas 2.2.3 rather
16277    /// than inferred from the differ: a lane widens iff the merge INVENTS a gap
16278    /// in THAT lane. The join type is irrelevant, and a lane that gains no gap
16279    /// keeps int64.
16280    ///
16281    /// ```text
16282    ///   l={'id':[1,2,3],'left_v':[10,20,30],'shared':[1,2,3]}
16283    ///   r={'id':[2],'right_v':[200],'shared':[9]}
16284    ///   l.merge(r, on='id', how='left')
16285    ///     id int64  left_v int64  shared_x int64      no gap  -> unchanged
16286    ///     right_v float64 [nan,200.0,nan]
16287    ///     shared_y float64 [nan,9.0,nan]              gap     -> widened
16288    ///
16289    ///   l={'id':[1,2],'left_v':[11,22]}  r={'id':[2,3],'right_v':[220,330]}
16290    ///   l.merge(r, on='id', how='right')
16291    ///     left_v float64 [22.0,nan]   right_v int64 [220,330]   id int64
16292    ///
16293    ///   l.merge(r, on='id', how='right', sort=True) over id l=[3,1] r=[2,1,3]
16294    ///     id int64 [1,2,3]  left_v float64 [10.0,nan,30.0]  right_v int64
16295    /// ```
16296    ///
16297    /// THE COMPOSITE OUTER CASE IS THE ONE WORTH THE TEST, because a single
16298    /// object column carries nywa8's two rules side by side. Measured on
16299    /// `lk2 = ['a', None, 'c']` outer-merged against `rk2 = ['a', None, 'd']`:
16300    ///
16301    /// ```text
16302    ///   lk2 dtype object, kinds ['str', 'NoneType', 'str', 'float']
16303    ///                                     ^ RULE 2          ^ RULE 1
16304    /// ```
16305    ///
16306    /// Row 1's `None` was SUPPLIED and object can store it, so pandas keeps it.
16307    /// Row 3's gap was INVENTED by the outer join, and pandas writes a float nan
16308    /// there even though the column is object. That is why the rule cannot be
16309    /// "derive the marker from the column dtype" — the same column answers
16310    /// differently per cell, and only the site that invents the gap knows which.
16311    #[test]
16312    fn merge_widens_only_the_lane_that_gains_an_invented_gap_nywa8() {
16313        // FP-P2D-014 dataframe_merge_column_left_missing_hardened
16314        let left = DataFrame::from_dict(
16315            &["id", "left_v", "shared"],
16316            vec![
16317                (
16318                    "id",
16319                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16320                ),
16321                (
16322                    "left_v",
16323                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
16324                ),
16325                (
16326                    "shared",
16327                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16328                ),
16329            ],
16330        )
16331        .unwrap();
16332        let right = DataFrame::from_dict(
16333            &["id", "right_v", "shared"],
16334            vec![
16335                ("id", vec![Scalar::Int64(2)]),
16336                ("right_v", vec![Scalar::Int64(200)]),
16337                ("shared", vec![Scalar::Int64(9)]),
16338            ],
16339        )
16340        .unwrap();
16341        let merged = merge_dataframes_on_with_options(
16342            &left,
16343            &right,
16344            &["id"],
16345            &["id"],
16346            JoinType::Left,
16347            MergeExecutionOptions::default(),
16348        )
16349        .unwrap();
16350        for gapless in ["id", "left_v", "shared_x"] {
16351            assert_eq!(
16352                merged.columns.get(gapless).unwrap().dtype(),
16353                DType::Int64,
16354                "{gapless} gains no gap and must stay int64"
16355            );
16356        }
16357        for gapped in ["right_v", "shared_y"] {
16358            let column = merged.columns.get(gapped).unwrap();
16359            assert_eq!(column.dtype(), DType::Float64, "{gapped} gains a gap");
16360            assert_nan_flavoured(&column.values()[0], gapped);
16361            assert_nan_flavoured(&column.values()[2], gapped);
16362        }
16363        assert_eq!(
16364            merged.columns.get("right_v").unwrap().values()[1],
16365            Scalar::Float64(200.0)
16366        );
16367        assert_eq!(
16368            merged.columns.get("shared_y").unwrap().values()[1],
16369            Scalar::Float64(9.0)
16370        );
16371
16372        // FP-P2D-014 dataframe_merge_column_right_order_strict
16373        let left = DataFrame::from_dict(
16374            &["id", "left_v"],
16375            vec![
16376                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
16377                ("left_v", vec![Scalar::Int64(11), Scalar::Int64(22)]),
16378            ],
16379        )
16380        .unwrap();
16381        let right = DataFrame::from_dict(
16382            &["id", "right_v"],
16383            vec![
16384                ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
16385                ("right_v", vec![Scalar::Int64(220), Scalar::Int64(330)]),
16386            ],
16387        )
16388        .unwrap();
16389        let merged = merge_dataframes_on_with_options(
16390            &left,
16391            &right,
16392            &["id"],
16393            &["id"],
16394            JoinType::Right,
16395            MergeExecutionOptions::default(),
16396        )
16397        .unwrap();
16398        assert_eq!(merged.columns.get("id").unwrap().dtype(), DType::Int64);
16399        assert_eq!(merged.columns.get("right_v").unwrap().dtype(), DType::Int64);
16400        let left_v = merged.columns.get("left_v").unwrap();
16401        assert_eq!(left_v.dtype(), DType::Float64);
16402        assert_eq!(left_v.values()[0], Scalar::Float64(22.0));
16403        assert_nan_flavoured(&left_v.values()[1], "left_v");
16404
16405        // FP-P2D-037 dataframe_merge_sort_true_right_hardened
16406        let left = DataFrame::from_dict(
16407            &["id", "left_v"],
16408            vec![
16409                ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
16410                ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
16411            ],
16412        )
16413        .unwrap();
16414        let right = DataFrame::from_dict(
16415            &["id", "right_v"],
16416            vec![
16417                (
16418                    "id",
16419                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
16420                ),
16421                (
16422                    "right_v",
16423                    vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
16424                ),
16425            ],
16426        )
16427        .unwrap();
16428        let merged = merge_dataframes_on_with_options(
16429            &left,
16430            &right,
16431            &["id"],
16432            &["id"],
16433            JoinType::Right,
16434            MergeExecutionOptions {
16435                sort: true,
16436                ..MergeExecutionOptions::default()
16437            },
16438        )
16439        .unwrap();
16440        assert_eq!(merged.columns.get("id").unwrap().dtype(), DType::Int64);
16441        assert_eq!(merged.columns.get("right_v").unwrap().dtype(), DType::Int64);
16442        let left_v = merged.columns.get("left_v").unwrap();
16443        assert_eq!(left_v.dtype(), DType::Float64);
16444        assert_eq!(left_v.values()[0], Scalar::Float64(10.0));
16445        assert_nan_flavoured(&left_v.values()[1], "left_v");
16446        assert_eq!(left_v.values()[2], Scalar::Float64(30.0));
16447
16448        // FP-P2D-033 dataframe_merge_composite_left_right_alias_outer_hardened
16449        let left = DataFrame::from_dict(
16450            &["lk1", "lk2", "left_v"],
16451            vec![
16452                (
16453                    "lk1",
16454                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16455                ),
16456                (
16457                    "lk2",
16458                    vec![
16459                        Scalar::Utf8("a".to_owned()),
16460                        Scalar::Null(NullKind::Null),
16461                        Scalar::Utf8("c".to_owned()),
16462                    ],
16463                ),
16464                (
16465                    "left_v",
16466                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
16467                ),
16468            ],
16469        )
16470        .unwrap();
16471        let right = DataFrame::from_dict(
16472            &["rk1", "rk2", "right_v"],
16473            vec![
16474                (
16475                    "rk1",
16476                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
16477                ),
16478                (
16479                    "rk2",
16480                    vec![
16481                        Scalar::Utf8("a".to_owned()),
16482                        Scalar::Null(NullKind::Null),
16483                        Scalar::Utf8("d".to_owned()),
16484                    ],
16485                ),
16486                (
16487                    "right_v",
16488                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
16489                ),
16490            ],
16491        )
16492        .unwrap();
16493        let merged = merge_dataframes_on_with_options(
16494            &left,
16495            &right,
16496            &["lk1", "lk2"],
16497            &["rk1", "rk2"],
16498            JoinType::Outer,
16499            MergeExecutionOptions::default(),
16500        )
16501        .unwrap();
16502        // Every numeric lane gains a gap under this outer merge, so all four widen.
16503        for numeric in ["lk1", "rk1", "left_v", "right_v"] {
16504            assert_eq!(
16505                merged.columns.get(numeric).unwrap().dtype(),
16506                DType::Float64,
16507                "{numeric} gains a gap under the outer merge"
16508            );
16509        }
16510        assert_nan_flavoured(&merged.columns.get("lk1").unwrap().values()[3], "lk1");
16511        assert_nan_flavoured(&merged.columns.get("left_v").unwrap().values()[3], "left_v");
16512        assert_nan_flavoured(&merged.columns.get("rk1").unwrap().values()[2], "rk1");
16513        assert_nan_flavoured(
16514            &merged.columns.get("right_v").unwrap().values()[2],
16515            "right_v",
16516        );
16517
16518        // The object lanes are the point: SUPPLIED None survives, INVENTED gap
16519        // is a nan, in the same column.
16520        let lk2 = merged.columns.get("lk2").unwrap();
16521        assert_eq!(lk2.values()[0], Scalar::Utf8("a".to_owned()));
16522        assert_eq!(
16523            lk2.values()[1],
16524            Scalar::Null(NullKind::Null),
16525            "lk2[1]'s None was SUPPLIED and object can hold it (nywa8 Rule 2)"
16526        );
16527        assert_eq!(lk2.values()[2], Scalar::Utf8("c".to_owned()));
16528        assert_nan_flavoured(&lk2.values()[3], "lk2[3] is an INVENTED gap (nywa8 Rule 1)");
16529
16530        let rk2 = merged.columns.get("rk2").unwrap();
16531        assert_eq!(rk2.values()[0], Scalar::Utf8("a".to_owned()));
16532        assert_eq!(
16533            rk2.values()[1],
16534            Scalar::Null(NullKind::Null),
16535            "rk2[1]'s None was SUPPLIED and object can hold it (nywa8 Rule 2)"
16536        );
16537        assert_nan_flavoured(&rk2.values()[2], "rk2[2] is an INVENTED gap (nywa8 Rule 1)");
16538        assert_eq!(rk2.values()[3], Scalar::Utf8("d".to_owned()));
16539    }
16540
16541    #[test]
16542    fn merge_left_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
16543        let left = DataFrame::from_dict(
16544            &["id", "v"],
16545            vec![
16546                (
16547                    "id",
16548                    vec![
16549                        Scalar::Int64(0),
16550                        Scalar::Int64(0),
16551                        Scalar::Int64(1),
16552                        Scalar::Int64(1),
16553                        Scalar::Int64(2),
16554                    ],
16555                ),
16556                (
16557                    "v",
16558                    vec![
16559                        Scalar::Int64(10),
16560                        Scalar::Int64(11),
16561                        Scalar::Int64(20),
16562                        Scalar::Int64(21),
16563                        Scalar::Int64(30),
16564                    ],
16565                ),
16566            ],
16567        )
16568        .unwrap();
16569        let right = DataFrame::from_dict(
16570            &["id", "w"],
16571            vec![
16572                (
16573                    "id",
16574                    vec![
16575                        Scalar::Int64(0),
16576                        Scalar::Int64(0),
16577                        Scalar::Int64(1),
16578                        Scalar::Int64(2),
16579                        Scalar::Int64(2),
16580                    ],
16581                ),
16582                (
16583                    "w",
16584                    vec![
16585                        Scalar::Int64(100),
16586                        Scalar::Int64(101),
16587                        Scalar::Int64(200),
16588                        Scalar::Int64(300),
16589                        Scalar::Int64(301),
16590                    ],
16591                ),
16592            ],
16593        )
16594        .unwrap();
16595
16596        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16597        let generic = merge_dataframes_on_with_options(
16598            &left,
16599            &right,
16600            &["id"],
16601            &["id"],
16602            JoinType::Left,
16603            MergeExecutionOptions {
16604                sort: true,
16605                ..MergeExecutionOptions::default()
16606            },
16607        )
16608        .unwrap();
16609
16610        assert_eq!(fast.index, generic.index);
16611        assert_eq!(fast.column_order, generic.column_order);
16612        assert_eq!(fast.columns, generic.columns);
16613        assert_eq!(
16614            fast.columns.get("id").unwrap().values(),
16615            &[
16616                Scalar::Int64(0),
16617                Scalar::Int64(0),
16618                Scalar::Int64(0),
16619                Scalar::Int64(0),
16620                Scalar::Int64(1),
16621                Scalar::Int64(1),
16622                Scalar::Int64(2),
16623                Scalar::Int64(2),
16624            ]
16625        );
16626        assert_eq!(
16627            fast.columns.get("v").unwrap().values(),
16628            &[
16629                Scalar::Int64(10),
16630                Scalar::Int64(10),
16631                Scalar::Int64(11),
16632                Scalar::Int64(11),
16633                Scalar::Int64(20),
16634                Scalar::Int64(21),
16635                Scalar::Int64(30),
16636                Scalar::Int64(30),
16637            ]
16638        );
16639        assert_eq!(
16640            fast.columns.get("w").unwrap().values(),
16641            &[
16642                Scalar::Int64(100),
16643                Scalar::Int64(101),
16644                Scalar::Int64(100),
16645                Scalar::Int64(101),
16646                Scalar::Int64(200),
16647                Scalar::Int64(200),
16648                Scalar::Int64(300),
16649                Scalar::Int64(301),
16650            ]
16651        );
16652    }
16653
16654    #[test]
16655    fn merge_outer_ordered_unique_int64_subset_matches_generic_validated_route() {
16656        let left = DataFrame::from_dict(
16657            &["id", "v"],
16658            vec![
16659                (
16660                    "id",
16661                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
16662                ),
16663                (
16664                    "v",
16665                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
16666                ),
16667            ],
16668        )
16669        .unwrap();
16670        let right = DataFrame::from_dict(
16671            &["id", "w"],
16672            vec![
16673                (
16674                    "id",
16675                    vec![
16676                        Scalar::Int64(0),
16677                        Scalar::Int64(2),
16678                        Scalar::Int64(3),
16679                        Scalar::Int64(5),
16680                    ],
16681                ),
16682                (
16683                    "w",
16684                    vec![
16685                        Scalar::Int64(100),
16686                        Scalar::Int64(200),
16687                        Scalar::Int64(300),
16688                        Scalar::Int64(500),
16689                    ],
16690                ),
16691            ],
16692        )
16693        .unwrap();
16694
16695        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16696        let generic = merge_dataframes_on_with_options(
16697            &left,
16698            &right,
16699            &["id"],
16700            &["id"],
16701            JoinType::Outer,
16702            MergeExecutionOptions {
16703                validate_mode: Some(MergeValidateMode::OneToOne),
16704                ..MergeExecutionOptions::default()
16705            },
16706        )
16707        .unwrap();
16708
16709        assert_eq!(fast.index, generic.index);
16710        assert_eq!(fast.column_order, generic.column_order);
16711        assert_eq!(fast.columns, generic.columns);
16712        assert_eq!(
16713            fast.columns.get("id").unwrap().values(),
16714            &[
16715                Scalar::Int64(0),
16716                Scalar::Int64(1),
16717                Scalar::Int64(2),
16718                Scalar::Int64(3),
16719                Scalar::Int64(5)
16720            ]
16721        );
16722        let left_values = fast.columns.get("v").unwrap().values();
16723        assert_eq!(left_values[0], Scalar::Float64(10.0));
16724        assert_eq!(left_values[1], Scalar::Float64(11.0));
16725        assert!(left_values[2].is_missing());
16726        assert_eq!(left_values[3], Scalar::Float64(13.0));
16727        assert!(left_values[4].is_missing());
16728        let right_values = fast.columns.get("w").unwrap().values();
16729        assert_eq!(right_values[0], Scalar::Float64(100.0));
16730        assert!(right_values[1].is_missing());
16731        assert_eq!(right_values[2], Scalar::Float64(200.0));
16732        assert_eq!(right_values[3], Scalar::Float64(300.0));
16733        assert_eq!(right_values[4], Scalar::Float64(500.0));
16734    }
16735
16736    #[test]
16737    fn merge_outer_dense_int64_duplicates_matches_generic_validated_route() {
16738        let left = DataFrame::from_dict(
16739            &["id", "v"],
16740            vec![
16741                (
16742                    "id",
16743                    vec![
16744                        Scalar::Int64(2),
16745                        Scalar::Int64(0),
16746                        Scalar::Int64(2),
16747                        Scalar::Int64(1),
16748                        Scalar::Int64(5),
16749                    ],
16750                ),
16751                (
16752                    "v",
16753                    vec![
16754                        Scalar::Int64(10),
16755                        Scalar::Int64(11),
16756                        Scalar::Int64(12),
16757                        Scalar::Int64(13),
16758                        Scalar::Int64(15),
16759                    ],
16760                ),
16761            ],
16762        )
16763        .unwrap();
16764        let right = DataFrame::from_dict(
16765            &["id", "w"],
16766            vec![
16767                (
16768                    "id",
16769                    vec![
16770                        Scalar::Int64(2),
16771                        Scalar::Int64(2),
16772                        Scalar::Int64(3),
16773                        Scalar::Int64(0),
16774                    ],
16775                ),
16776                (
16777                    "w",
16778                    vec![
16779                        Scalar::Int64(200),
16780                        Scalar::Int64(201),
16781                        Scalar::Int64(300),
16782                        Scalar::Int64(400),
16783                    ],
16784                ),
16785            ],
16786        )
16787        .unwrap();
16788
16789        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16790        let generic = merge_dataframes_on_with_options(
16791            &left,
16792            &right,
16793            &["id"],
16794            &["id"],
16795            JoinType::Outer,
16796            MergeExecutionOptions {
16797                validate_mode: Some(MergeValidateMode::ManyToMany),
16798                ..MergeExecutionOptions::default()
16799            },
16800        )
16801        .unwrap();
16802
16803        assert_eq!(fast.index, generic.index);
16804        assert_eq!(fast.column_order, generic.column_order);
16805        assert_eq!(fast.columns, generic.columns);
16806        assert_eq!(
16807            fast.columns.get("id").unwrap().values(),
16808            &[
16809                Scalar::Int64(0),
16810                Scalar::Int64(1),
16811                Scalar::Int64(2),
16812                Scalar::Int64(2),
16813                Scalar::Int64(2),
16814                Scalar::Int64(2),
16815                Scalar::Int64(3),
16816                Scalar::Int64(5),
16817            ]
16818        );
16819        let left_values = fast.columns.get("v").unwrap().values();
16820        assert_eq!(left_values[0], Scalar::Float64(11.0));
16821        assert_eq!(left_values[1], Scalar::Float64(13.0));
16822        assert_eq!(left_values[2], Scalar::Float64(10.0));
16823        assert_eq!(left_values[5], Scalar::Float64(12.0));
16824        assert!(left_values[6].is_missing());
16825        assert_eq!(left_values[7], Scalar::Float64(15.0));
16826        let right_values = fast.columns.get("w").unwrap().values();
16827        assert_eq!(right_values[0], Scalar::Float64(400.0));
16828        assert!(right_values[1].is_missing());
16829        assert_eq!(right_values[2], Scalar::Float64(200.0));
16830        assert_eq!(right_values[3], Scalar::Float64(201.0));
16831        assert!(right_values[7].is_missing());
16832    }
16833
16834    #[test]
16835    fn merge_outer_all_matched_dense_int64_duplicates_matches_generic_validated_route() {
16836        let left = DataFrame::from_dict(
16837            &["id", "v"],
16838            vec![
16839                (
16840                    "id",
16841                    vec![
16842                        Scalar::Int64(2),
16843                        Scalar::Int64(1),
16844                        Scalar::Int64(2),
16845                        Scalar::Int64(1),
16846                    ],
16847                ),
16848                (
16849                    "v",
16850                    vec![
16851                        Scalar::Int64(20),
16852                        Scalar::Int64(10),
16853                        Scalar::Int64(21),
16854                        Scalar::Int64(11),
16855                    ],
16856                ),
16857            ],
16858        )
16859        .unwrap();
16860        let right = DataFrame::from_dict(
16861            &["id", "w"],
16862            vec![
16863                (
16864                    "id",
16865                    vec![
16866                        Scalar::Int64(1),
16867                        Scalar::Int64(2),
16868                        Scalar::Int64(1),
16869                        Scalar::Int64(2),
16870                    ],
16871                ),
16872                (
16873                    "w",
16874                    vec![
16875                        Scalar::Int64(100),
16876                        Scalar::Int64(200),
16877                        Scalar::Int64(101),
16878                        Scalar::Int64(201),
16879                    ],
16880                ),
16881            ],
16882        )
16883        .unwrap();
16884
16885        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16886        let generic = merge_dataframes_on_with_options(
16887            &left,
16888            &right,
16889            &["id"],
16890            &["id"],
16891            JoinType::Outer,
16892            MergeExecutionOptions {
16893                validate_mode: Some(MergeValidateMode::ManyToMany),
16894                ..MergeExecutionOptions::default()
16895            },
16896        )
16897        .unwrap();
16898
16899        assert_eq!(fast.index, generic.index);
16900        assert_eq!(fast.column_order, generic.column_order);
16901        assert_eq!(fast.columns, generic.columns);
16902        assert_eq!(
16903            generic.columns.get("id").unwrap().values(),
16904            &[
16905                Scalar::Int64(1),
16906                Scalar::Int64(1),
16907                Scalar::Int64(1),
16908                Scalar::Int64(1),
16909                Scalar::Int64(2),
16910                Scalar::Int64(2),
16911                Scalar::Int64(2),
16912                Scalar::Int64(2),
16913            ]
16914        );
16915        assert!(
16916            generic
16917                .columns
16918                .values()
16919                .all(|column| column.as_i64_slice().is_some())
16920        );
16921    }
16922
16923    #[test]
16924    fn merge_outer_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
16925        let left = DataFrame::from_dict(
16926            &["id", "v"],
16927            vec![
16928                (
16929                    "id",
16930                    vec![
16931                        Scalar::Int64(2),
16932                        Scalar::Int64(1),
16933                        Scalar::Int64(2),
16934                        Scalar::Int64(1),
16935                    ],
16936                ),
16937                (
16938                    "v",
16939                    vec![
16940                        Scalar::Int64(20),
16941                        Scalar::Int64(10),
16942                        Scalar::Int64(21),
16943                        Scalar::Int64(11),
16944                    ],
16945                ),
16946            ],
16947        )
16948        .unwrap();
16949        let right = DataFrame::from_dict(
16950            &["id", "w"],
16951            vec![
16952                (
16953                    "id",
16954                    vec![
16955                        Scalar::Int64(1),
16956                        Scalar::Int64(2),
16957                        Scalar::Int64(1),
16958                        Scalar::Int64(2),
16959                    ],
16960                ),
16961                (
16962                    "w",
16963                    vec![
16964                        Scalar::Int64(100),
16965                        Scalar::Int64(200),
16966                        Scalar::Int64(101),
16967                        Scalar::Int64(201),
16968                    ],
16969                ),
16970            ],
16971        )
16972        .unwrap();
16973
16974        let fused = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16975        let generic = merge_dataframes_on_with_options(
16976            &left,
16977            &right,
16978            &["id"],
16979            &["id"],
16980            JoinType::Outer,
16981            MergeExecutionOptions {
16982                validate_mode: Some(MergeValidateMode::ManyToMany),
16983                sort: true,
16984                ..MergeExecutionOptions::default()
16985            },
16986        )
16987        .unwrap();
16988
16989        assert_eq!(fused.index, generic.index);
16990        assert_eq!(fused.column_order, generic.column_order);
16991        assert_eq!(fused.columns, generic.columns);
16992    }
16993
16994    #[test]
16995    fn merge_left_contiguous_utf8_duplicates_matches_sorted_generic_route() {
16996        let s = |v: &str| Scalar::Utf8(v.to_owned());
16997        let left = DataFrame::from_dict(
16998            &["id", "v"],
16999            vec![
17000                ("id", vec![s("a"), s("a"), s("b"), s("c")]),
17001                (
17002                    "v",
17003                    vec![
17004                        Scalar::Int64(10),
17005                        Scalar::Int64(11),
17006                        Scalar::Int64(20),
17007                        Scalar::Int64(30),
17008                    ],
17009                ),
17010            ],
17011        )
17012        .unwrap();
17013        let right = DataFrame::from_dict(
17014            &["id", "w"],
17015            vec![
17016                ("id", vec![s("a"), s("a"), s("c")]),
17017                (
17018                    "w",
17019                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(300)],
17020                ),
17021            ],
17022        )
17023        .unwrap();
17024
17025        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
17026        let generic = merge_dataframes_on_with_options(
17027            &left,
17028            &right,
17029            &["id"],
17030            &["id"],
17031            JoinType::Left,
17032            MergeExecutionOptions {
17033                sort: true,
17034                ..MergeExecutionOptions::default()
17035            },
17036        )
17037        .unwrap();
17038
17039        assert_eq!(fast.index, generic.index);
17040        assert_eq!(fast.column_order, generic.column_order);
17041        assert_eq!(fast.columns, generic.columns);
17042        assert_eq!(
17043            fast.columns.get("id").unwrap().values(),
17044            &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c")]
17045        );
17046        assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
17047    }
17048
17049    #[test]
17050    fn merge_outer_object_gaps_are_nan_and_supplied_none_stays_7u2td() {
17051        // pandas 2.2.3: DataFrame({'k':['a','b'],'s':[None,'y']}).merge(
17052        //   DataFrame({'k2':['b','c'],'t':['p','q']}), left_on='k',
17053        //   right_on='k2', how='outer')
17054        //   -> k [a, b, nan]  s [None, y, nan]  k2 [nan, b, c]  t [nan, p, q]
17055        let text = |t: &str| Scalar::Utf8(t.to_owned());
17056        let nan = Scalar::Null(NullKind::NaN);
17057        let left = DataFrame::from_dict(
17058            &["k", "s"],
17059            vec![
17060                ("k", vec![text("a"), text("b")]),
17061                ("s", vec![Scalar::Null(NullKind::Null), text("y")]),
17062            ],
17063        )
17064        .unwrap();
17065        let right = DataFrame::from_dict(
17066            &["k2", "t"],
17067            vec![
17068                ("k2", vec![text("b"), text("c")]),
17069                ("t", vec![text("p"), text("q")]),
17070            ],
17071        )
17072        .unwrap();
17073        let merged = merge_dataframes_on_with_options(
17074            &left,
17075            &right,
17076            &["k"],
17077            &["k2"],
17078            JoinType::Outer,
17079            MergeExecutionOptions::default(),
17080        )
17081        .unwrap();
17082        let column = |name: &str| merged.columns.get(name).unwrap().values().to_vec();
17083        assert_eq!(column("k"), vec![text("a"), text("b"), nan.clone()]);
17084        assert_eq!(column("k2"), vec![nan.clone(), text("b"), text("c")]);
17085        assert_eq!(column("t"), vec![nan.clone(), text("p"), text("q")]);
17086        // NEGATIVE: the supplied None is kept beside the invented NaN.
17087        assert_eq!(
17088            column("s"),
17089            vec![Scalar::Null(NullKind::Null), text("y"), nan]
17090        );
17091    }
17092
17093    #[test]
17094    fn merge_outer_contiguous_utf8_duplicates_matches_sorted_generic_route() {
17095        let s = |v: &str| Scalar::Utf8(v.to_owned());
17096        let left = DataFrame::from_dict(
17097            &["id", "v"],
17098            vec![
17099                ("id", vec![s("a"), s("a"), s("b"), s("d")]),
17100                (
17101                    "v",
17102                    vec![
17103                        Scalar::Int64(10),
17104                        Scalar::Int64(11),
17105                        Scalar::Int64(20),
17106                        Scalar::Int64(40),
17107                    ],
17108                ),
17109            ],
17110        )
17111        .unwrap();
17112        let right = DataFrame::from_dict(
17113            &["id", "w"],
17114            vec![
17115                ("id", vec![s("a"), s("c"), s("a")]),
17116                (
17117                    "w",
17118                    vec![Scalar::Int64(100), Scalar::Int64(300), Scalar::Int64(101)],
17119                ),
17120            ],
17121        )
17122        .unwrap();
17123
17124        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17125        let generic = merge_dataframes_on_with_options(
17126            &left,
17127            &right,
17128            &["id"],
17129            &["id"],
17130            JoinType::Outer,
17131            MergeExecutionOptions {
17132                sort: true,
17133                ..MergeExecutionOptions::default()
17134            },
17135        )
17136        .unwrap();
17137
17138        assert_eq!(fast.index, generic.index);
17139        assert_eq!(fast.column_order, generic.column_order);
17140        assert_eq!(fast.columns, generic.columns);
17141        assert_eq!(
17142            fast.columns.get("id").unwrap().values(),
17143            &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c"), s("d")]
17144        );
17145        assert!(fast.columns.get("v").unwrap().values()[5].is_missing());
17146        assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
17147        assert!(fast.columns.get("w").unwrap().values()[6].is_missing());
17148    }
17149
17150    #[test]
17151    fn merge_outer_fixed_decimal_utf8_all_matched_fuses_sorted_output_wikcu() {
17152        let s = |v: &str| Scalar::Utf8(v.to_owned());
17153        let left = DataFrame::from_dict(
17154            &["id", "lv"],
17155            vec![
17156                (
17157                    "id",
17158                    vec![
17159                        s("k00000002"),
17160                        s("k00000000"),
17161                        s("k00000002"),
17162                        s("k00000001"),
17163                    ],
17164                ),
17165                (
17166                    "lv",
17167                    vec![
17168                        Scalar::Float64(20.0),
17169                        Scalar::Float64(0.0),
17170                        Scalar::Float64(21.0),
17171                        Scalar::Float64(10.0),
17172                    ],
17173                ),
17174            ],
17175        )
17176        .unwrap();
17177        let right = DataFrame::from_dict(
17178            &["id", "rv"],
17179            vec![
17180                ("id", vec![s("k00000000"), s("k00000001"), s("k00000002")]),
17181                (
17182                    "rv",
17183                    vec![
17184                        Scalar::Float64(100.0),
17185                        Scalar::Float64(110.0),
17186                        Scalar::Float64(120.0),
17187                    ],
17188                ),
17189            ],
17190        )
17191        .unwrap();
17192
17193        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17194        let generic = merge_dataframes_on_with_options(
17195            &left,
17196            &right,
17197            &["id"],
17198            &["id"],
17199            JoinType::Outer,
17200            MergeExecutionOptions {
17201                sort: true,
17202                ..MergeExecutionOptions::default()
17203            },
17204        )
17205        .unwrap();
17206
17207        assert_eq!(fast.index, generic.index);
17208        assert_eq!(fast.column_order, generic.column_order);
17209        assert_eq!(fast.columns, generic.columns);
17210        assert_eq!(
17211            fast.columns.get("id").unwrap().values(),
17212            &[
17213                s("k00000000"),
17214                s("k00000001"),
17215                s("k00000002"),
17216                s("k00000002")
17217            ]
17218        );
17219        assert_eq!(
17220            fast.columns.get("lv").unwrap().values(),
17221            &[
17222                Scalar::Float64(0.0),
17223                Scalar::Float64(10.0),
17224                Scalar::Float64(20.0),
17225                Scalar::Float64(21.0),
17226            ]
17227        );
17228    }
17229
17230    #[test]
17231    fn merge_right_dense_int64_duplicates_matches_generic_validated_route() {
17232        let left = DataFrame::from_dict(
17233            &["id", "v"],
17234            vec![
17235                (
17236                    "id",
17237                    vec![
17238                        Scalar::Int64(2),
17239                        Scalar::Int64(0),
17240                        Scalar::Int64(2),
17241                        Scalar::Int64(1),
17242                        Scalar::Int64(5),
17243                    ],
17244                ),
17245                (
17246                    "v",
17247                    vec![
17248                        Scalar::Int64(10),
17249                        Scalar::Int64(11),
17250                        Scalar::Int64(12),
17251                        Scalar::Int64(13),
17252                        Scalar::Int64(15),
17253                    ],
17254                ),
17255            ],
17256        )
17257        .unwrap();
17258        let right = DataFrame::from_dict(
17259            &["id", "w"],
17260            vec![
17261                (
17262                    "id",
17263                    vec![
17264                        Scalar::Int64(2),
17265                        Scalar::Int64(2),
17266                        Scalar::Int64(3),
17267                        Scalar::Int64(0),
17268                    ],
17269                ),
17270                (
17271                    "w",
17272                    vec![
17273                        Scalar::Int64(200),
17274                        Scalar::Int64(201),
17275                        Scalar::Int64(300),
17276                        Scalar::Int64(400),
17277                    ],
17278                ),
17279            ],
17280        )
17281        .unwrap();
17282
17283        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
17284        let generic = merge_dataframes_on_with_options(
17285            &left,
17286            &right,
17287            &["id"],
17288            &["id"],
17289            JoinType::Right,
17290            MergeExecutionOptions {
17291                validate_mode: Some(MergeValidateMode::ManyToMany),
17292                ..MergeExecutionOptions::default()
17293            },
17294        )
17295        .unwrap();
17296
17297        assert_eq!(fast.index, generic.index);
17298        assert_eq!(fast.column_order, generic.column_order);
17299        assert_eq!(fast.columns, generic.columns);
17300        assert_eq!(
17301            fast.columns.get("id").unwrap().values(),
17302            &[
17303                Scalar::Int64(2),
17304                Scalar::Int64(2),
17305                Scalar::Int64(2),
17306                Scalar::Int64(2),
17307                Scalar::Int64(3),
17308                Scalar::Int64(0),
17309            ]
17310        );
17311        let left_values = fast.columns.get("v").unwrap().values();
17312        assert_eq!(left_values[0], Scalar::Float64(10.0));
17313        assert_eq!(left_values[1], Scalar::Float64(12.0));
17314        assert_eq!(left_values[2], Scalar::Float64(10.0));
17315        assert_eq!(left_values[3], Scalar::Float64(12.0));
17316        assert!(left_values[4].is_missing());
17317        assert_eq!(left_values[5], Scalar::Float64(11.0));
17318        let right_values = fast.columns.get("w").unwrap().values();
17319        assert_eq!(right_values[0], Scalar::Int64(200));
17320        assert_eq!(right_values[1], Scalar::Int64(200));
17321        assert_eq!(right_values[2], Scalar::Int64(201));
17322        assert_eq!(right_values[3], Scalar::Int64(201));
17323        assert_eq!(right_values[4], Scalar::Int64(300));
17324        assert_eq!(right_values[5], Scalar::Int64(400));
17325    }
17326
17327    #[test]
17328    fn merge_right_dense_cycle_probe_declines_invented_gaps_66wab() {
17329        let left = DataFrame::from_dict(
17330            &["id", "v"],
17331            vec![
17332                (
17333                    "id",
17334                    vec![
17335                        Scalar::Int64(1),
17336                        Scalar::Int64(2),
17337                        Scalar::Int64(1),
17338                        Scalar::Int64(2),
17339                    ],
17340                ),
17341                (
17342                    "v",
17343                    vec![
17344                        Scalar::Int64(100),
17345                        Scalar::Int64(200),
17346                        Scalar::Int64(101),
17347                        Scalar::Int64(201),
17348                    ],
17349                ),
17350            ],
17351        )
17352        .unwrap();
17353        let right = DataFrame::from_dict(
17354            &["id", "w"],
17355            vec![
17356                (
17357                    "id",
17358                    vec![
17359                        Scalar::Int64(0),
17360                        Scalar::Int64(1),
17361                        Scalar::Int64(2),
17362                        Scalar::Int64(0),
17363                        Scalar::Int64(1),
17364                    ],
17365                ),
17366                (
17367                    "w",
17368                    vec![
17369                        Scalar::Int64(10),
17370                        Scalar::Int64(11),
17371                        Scalar::Int64(12),
17372                        Scalar::Int64(13),
17373                        Scalar::Int64(14),
17374                    ],
17375                ),
17376            ],
17377        )
17378        .unwrap();
17379        let left_key = left.columns().get("id").unwrap();
17380        let right_key = right.columns().get("id").unwrap();
17381        assert!(left_key.int64_dense_cycle_witness().is_some());
17382        assert!(right_key.int64_dense_cycle_witness().is_some());
17383        let suffixes = resolve_merge_suffixes(None);
17384
17385        let fused = build_single_key_dense_i64_right_merge_output(
17386            &left,
17387            &right,
17388            &["id"],
17389            &["id"],
17390            left_key,
17391            right_key,
17392            &suffixes,
17393        )
17394        .unwrap();
17395        assert!(fused.is_none());
17396    }
17397
17398    #[test]
17399    fn merge_left_right_all_matched_dense_int64_duplicates_match_generic_validated_route() {
17400        let left = DataFrame::from_dict(
17401            &["id", "v"],
17402            vec![
17403                (
17404                    "id",
17405                    vec![
17406                        Scalar::Int64(2),
17407                        Scalar::Int64(1),
17408                        Scalar::Int64(2),
17409                        Scalar::Int64(1),
17410                    ],
17411                ),
17412                (
17413                    "v",
17414                    vec![
17415                        Scalar::Int64(20),
17416                        Scalar::Int64(10),
17417                        Scalar::Int64(21),
17418                        Scalar::Int64(11),
17419                    ],
17420                ),
17421            ],
17422        )
17423        .unwrap();
17424        let right = DataFrame::from_dict(
17425            &["id", "w"],
17426            vec![
17427                (
17428                    "id",
17429                    vec![
17430                        Scalar::Int64(1),
17431                        Scalar::Int64(2),
17432                        Scalar::Int64(1),
17433                        Scalar::Int64(2),
17434                    ],
17435                ),
17436                (
17437                    "w",
17438                    vec![
17439                        Scalar::Int64(100),
17440                        Scalar::Int64(200),
17441                        Scalar::Int64(101),
17442                        Scalar::Int64(201),
17443                    ],
17444                ),
17445            ],
17446        )
17447        .unwrap();
17448
17449        for join_type in [JoinType::Left, JoinType::Right] {
17450            let fast = merge_dataframes(&left, &right, "id", join_type).unwrap();
17451            let generic = merge_dataframes_on_with_options(
17452                &left,
17453                &right,
17454                &["id"],
17455                &["id"],
17456                join_type,
17457                MergeExecutionOptions {
17458                    validate_mode: Some(MergeValidateMode::ManyToMany),
17459                    ..MergeExecutionOptions::default()
17460                },
17461            )
17462            .unwrap();
17463
17464            assert_eq!(fast.index, generic.index);
17465            assert_eq!(fast.column_order, generic.column_order);
17466            assert_eq!(fast.columns, generic.columns);
17467            assert!(
17468                generic
17469                    .columns
17470                    .values()
17471                    .all(|column| column.as_i64_slice().is_some())
17472            );
17473        }
17474    }
17475
17476    #[test]
17477    fn merge_right_all_matched_dense_int64_fused_output_matches_dense_materialization() {
17478        let left = DataFrame::from_dict(
17479            &["id", "v"],
17480            vec![
17481                (
17482                    "id",
17483                    vec![
17484                        Scalar::Int64(2),
17485                        Scalar::Int64(1),
17486                        Scalar::Int64(2),
17487                        Scalar::Int64(1),
17488                    ],
17489                ),
17490                (
17491                    "v",
17492                    vec![
17493                        Scalar::Int64(20),
17494                        Scalar::Int64(10),
17495                        Scalar::Int64(21),
17496                        Scalar::Int64(11),
17497                    ],
17498                ),
17499            ],
17500        )
17501        .unwrap();
17502        let right = DataFrame::from_dict(
17503            &["id", "w"],
17504            vec![
17505                (
17506                    "id",
17507                    vec![
17508                        Scalar::Int64(1),
17509                        Scalar::Int64(2),
17510                        Scalar::Int64(1),
17511                        Scalar::Int64(2),
17512                    ],
17513                ),
17514                (
17515                    "w",
17516                    vec![
17517                        Scalar::Int64(100),
17518                        Scalar::Int64(200),
17519                        Scalar::Int64(101),
17520                        Scalar::Int64(201),
17521                    ],
17522                ),
17523            ],
17524        )
17525        .unwrap();
17526
17527        let fused = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
17528        let left_key = left.columns().get("id").unwrap();
17529        let right_key = right.columns().get("id").unwrap();
17530        let (left_positions, right_positions) =
17531            dense_int64_right_positions(left_key, right_key).unwrap();
17532        let suffixes = resolve_merge_suffixes(None);
17533        let materialized = build_single_key_dense_right_merge_output(
17534            &left,
17535            &right,
17536            &["id"],
17537            &["id"],
17538            &left_positions,
17539            &right_positions,
17540            &suffixes,
17541        )
17542        .unwrap();
17543
17544        assert_eq!(fused.index, materialized.index);
17545        assert_eq!(fused.column_order, materialized.column_order);
17546        assert_eq!(fused.columns, materialized.columns);
17547        assert_eq!(
17548            fused.columns.get("id").unwrap().values(),
17549            &[
17550                Scalar::Int64(1),
17551                Scalar::Int64(1),
17552                Scalar::Int64(2),
17553                Scalar::Int64(2),
17554                Scalar::Int64(1),
17555                Scalar::Int64(1),
17556                Scalar::Int64(2),
17557                Scalar::Int64(2),
17558            ]
17559        );
17560        assert!(
17561            fused
17562                .columns
17563                .values()
17564                .all(|column| column.as_i64_slice().is_some())
17565        );
17566    }
17567
17568    #[test]
17569    fn merge_right_ordered_unique_int64_subset_matches_generic_validated_route() {
17570        let left = DataFrame::from_dict(
17571            &["id", "v"],
17572            vec![
17573                (
17574                    "id",
17575                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
17576                ),
17577                (
17578                    "v",
17579                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
17580                ),
17581            ],
17582        )
17583        .unwrap();
17584        let right = DataFrame::from_dict(
17585            &["id", "w"],
17586            vec![
17587                (
17588                    "id",
17589                    vec![
17590                        Scalar::Int64(0),
17591                        Scalar::Int64(2),
17592                        Scalar::Int64(3),
17593                        Scalar::Int64(5),
17594                    ],
17595                ),
17596                (
17597                    "w",
17598                    vec![
17599                        Scalar::Int64(100),
17600                        Scalar::Int64(200),
17601                        Scalar::Int64(300),
17602                        Scalar::Int64(500),
17603                    ],
17604                ),
17605            ],
17606        )
17607        .unwrap();
17608
17609        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
17610        let generic = merge_dataframes_on_with_options(
17611            &left,
17612            &right,
17613            &["id"],
17614            &["id"],
17615            JoinType::Right,
17616            MergeExecutionOptions {
17617                validate_mode: Some(MergeValidateMode::OneToOne),
17618                ..MergeExecutionOptions::default()
17619            },
17620        )
17621        .unwrap();
17622
17623        assert_eq!(fast.index, generic.index);
17624        assert_eq!(fast.column_order, generic.column_order);
17625        assert_eq!(fast.columns, generic.columns);
17626        assert_eq!(
17627            fast.columns.get("id").unwrap().values(),
17628            &[
17629                Scalar::Int64(0),
17630                Scalar::Int64(2),
17631                Scalar::Int64(3),
17632                Scalar::Int64(5)
17633            ]
17634        );
17635        let left_values = fast.columns.get("v").unwrap().values();
17636        assert_eq!(left_values[0], Scalar::Float64(10.0));
17637        assert!(left_values[1].is_missing());
17638        assert_eq!(left_values[2], Scalar::Float64(13.0));
17639        assert!(left_values[3].is_missing());
17640        let right_values = fast.columns.get("w").unwrap().values();
17641        assert_eq!(right_values[0], Scalar::Int64(100));
17642        assert_eq!(right_values[1], Scalar::Int64(200));
17643        assert_eq!(right_values[2], Scalar::Int64(300));
17644        assert_eq!(right_values[3], Scalar::Int64(500));
17645    }
17646
17647    #[test]
17648    fn merge_right_preserves_all_right_rows() {
17649        let left = make_left_df();
17650        let right = make_right_df();
17651        let merged = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
17652
17653        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
17654        assert_eq!(
17655            merged.columns.get("val_b").unwrap().values(),
17656            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
17657        );
17658        // val_a widens to Float64 because id=4 invents a missing value.
17659        assert_eq!(merged.columns.get("val_a").unwrap().dtype(), DType::Float64);
17660        assert_eq!(
17661            merged.columns.get("val_a").unwrap().values()[0],
17662            Scalar::Float64(20.0)
17663        );
17664        assert_eq!(
17665            merged.columns.get("val_a").unwrap().values()[1],
17666            Scalar::Float64(30.0)
17667        );
17668        assert_eq!(
17669            merged.columns.get("val_a").unwrap().values()[2],
17670            Scalar::Null(NullKind::NaN)
17671        );
17672    }
17673
17674    #[test]
17675    fn merge_outer_contains_all_rows() {
17676        let left = make_left_df();
17677        let right = make_right_df();
17678        let merged = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17679
17680        // ids: 1, 2, 3 from left + 4 from right = 4 rows
17681        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
17682    }
17683
17684    #[test]
17685    fn merge_inner_sort_false_preserves_left_key_order() {
17686        let left = DataFrame::from_dict(
17687            &["id", "left_v"],
17688            vec![
17689                (
17690                    "id",
17691                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
17692                ),
17693                (
17694                    "left_v",
17695                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
17696                ),
17697            ],
17698        )
17699        .expect("left");
17700        let right = DataFrame::from_dict(
17701            &["id", "right_v"],
17702            vec![
17703                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17704                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17705            ],
17706        )
17707        .expect("right");
17708
17709        let merged = merge_dataframes_on_with_options(
17710            &left,
17711            &right,
17712            &["id"],
17713            &["id"],
17714            JoinType::Inner,
17715            MergeExecutionOptions::default(),
17716        )
17717        .expect("merge");
17718        assert_eq!(
17719            merged.columns.get("id").expect("id").values(),
17720            &[Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)]
17721        );
17722        assert_eq!(
17723            merged.columns.get("left_v").expect("left_v").values(),
17724            &[Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)]
17725        );
17726        assert_eq!(
17727            merged.columns.get("right_v").expect("right_v").values(),
17728            &[Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(200)]
17729        );
17730    }
17731
17732    #[test]
17733    fn merge_inner_sort_true_orders_join_keys_lexicographically() {
17734        let left = DataFrame::from_dict(
17735            &["id", "left_v"],
17736            vec![
17737                (
17738                    "id",
17739                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
17740                ),
17741                (
17742                    "left_v",
17743                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
17744                ),
17745            ],
17746        )
17747        .expect("left");
17748        let right = DataFrame::from_dict(
17749            &["id", "right_v"],
17750            vec![
17751                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17752                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17753            ],
17754        )
17755        .expect("right");
17756
17757        let merged = merge_dataframes_on_with_options(
17758            &left,
17759            &right,
17760            &["id"],
17761            &["id"],
17762            JoinType::Inner,
17763            MergeExecutionOptions {
17764                sort: true,
17765                ..MergeExecutionOptions::default()
17766            },
17767        )
17768        .expect("merge");
17769        assert_eq!(
17770            merged.columns.get("id").expect("id").values(),
17771            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2)]
17772        );
17773        assert_eq!(
17774            merged.columns.get("left_v").expect("left_v").values(),
17775            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(21)]
17776        );
17777        assert_eq!(
17778            merged.columns.get("right_v").expect("right_v").values(),
17779            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(200)]
17780        );
17781    }
17782
17783    #[test]
17784    fn merge_inner_sort_true_orders_float_keys_numerically() {
17785        let left = DataFrame::from_dict(
17786            &["id", "left_v"],
17787            vec![
17788                (
17789                    "id",
17790                    vec![
17791                        Scalar::Float64(1.5),
17792                        Scalar::Float64(-2.5),
17793                        Scalar::Float64(0.25),
17794                    ],
17795                ),
17796                (
17797                    "left_v",
17798                    vec![Scalar::Int64(15), Scalar::Int64(-25), Scalar::Int64(2)],
17799                ),
17800            ],
17801        )
17802        .expect("left");
17803        let right = DataFrame::from_dict(
17804            &["id", "right_v"],
17805            vec![
17806                (
17807                    "id",
17808                    vec![
17809                        Scalar::Float64(-2.5),
17810                        Scalar::Float64(0.25),
17811                        Scalar::Float64(1.5),
17812                    ],
17813                ),
17814                (
17815                    "right_v",
17816                    vec![Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)],
17817                ),
17818            ],
17819        )
17820        .expect("right");
17821
17822        let merged = merge_dataframes_on_with_options(
17823            &left,
17824            &right,
17825            &["id"],
17826            &["id"],
17827            JoinType::Inner,
17828            MergeExecutionOptions {
17829                sort: true,
17830                ..MergeExecutionOptions::default()
17831            },
17832        )
17833        .expect("merge");
17834
17835        assert_eq!(
17836            merged.columns.get("id").expect("id").values(),
17837            &[
17838                Scalar::Float64(-2.5),
17839                Scalar::Float64(0.25),
17840                Scalar::Float64(1.5)
17841            ]
17842        );
17843        assert_eq!(
17844            merged.columns.get("left_v").expect("left_v").values(),
17845            &[Scalar::Int64(-25), Scalar::Int64(2), Scalar::Int64(15)]
17846        );
17847        assert_eq!(
17848            merged.columns.get("right_v").expect("right_v").values(),
17849            &[Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)]
17850        );
17851    }
17852
17853    #[test]
17854    fn merge_right_sort_true_orders_join_keys_lexicographically() {
17855        let left = DataFrame::from_dict(
17856            &["id", "left_v"],
17857            vec![
17858                ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
17859                ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
17860            ],
17861        )
17862        .expect("left");
17863        let right = DataFrame::from_dict(
17864            &["id", "right_v"],
17865            vec![
17866                (
17867                    "id",
17868                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
17869                ),
17870                (
17871                    "right_v",
17872                    vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
17873                ),
17874            ],
17875        )
17876        .expect("right");
17877
17878        let merged = merge_dataframes_on_with_options(
17879            &left,
17880            &right,
17881            &["id"],
17882            &["id"],
17883            JoinType::Right,
17884            MergeExecutionOptions {
17885                sort: true,
17886                ..MergeExecutionOptions::default()
17887            },
17888        )
17889        .expect("merge");
17890        assert_eq!(
17891            merged.columns.get("id").expect("id").values(),
17892            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
17893        );
17894        assert_eq!(
17895            merged.columns.get("left_v").expect("left_v").values(),
17896            &[
17897                Scalar::Float64(10.0),
17898                Scalar::Null(NullKind::NaN),
17899                Scalar::Float64(30.0)
17900            ]
17901        );
17902        assert_eq!(
17903            merged.columns.get("right_v").expect("right_v").values(),
17904            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
17905        );
17906    }
17907
17908    #[test]
17909    fn merge_column_name_conflict_adds_suffixes() {
17910        let left = DataFrame::from_dict(
17911            &["id", "val"],
17912            vec![
17913                ("id", vec![Scalar::Int64(1)]),
17914                ("val", vec![Scalar::Int64(10)]),
17915            ],
17916        )
17917        .unwrap();
17918        let right = DataFrame::from_dict(
17919            &["id", "val"],
17920            vec![
17921                ("id", vec![Scalar::Int64(1)]),
17922                ("val", vec![Scalar::Int64(99)]),
17923            ],
17924        )
17925        .unwrap();
17926
17927        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
17928        assert!(merged.columns.contains_key("val_x"));
17929        assert!(merged.columns.contains_key("val_y"));
17930        assert_eq!(
17931            merged.columns.get("val_x").unwrap().values(),
17932            &[Scalar::Int64(10)]
17933        );
17934        assert_eq!(
17935            merged.columns.get("val_y").unwrap().values(),
17936            &[Scalar::Int64(99)]
17937        );
17938    }
17939
17940    #[test]
17941    fn merge_column_name_conflict_honors_custom_suffixes() {
17942        let left = DataFrame::from_dict(
17943            &["id", "val"],
17944            vec![
17945                ("id", vec![Scalar::Int64(1)]),
17946                ("val", vec![Scalar::Int64(10)]),
17947            ],
17948        )
17949        .expect("left");
17950        let right = DataFrame::from_dict(
17951            &["id", "val"],
17952            vec![
17953                ("id", vec![Scalar::Int64(1)]),
17954                ("val", vec![Scalar::Int64(99)]),
17955            ],
17956        )
17957        .expect("right");
17958
17959        let merged = merge_dataframes_on_with_options(
17960            &left,
17961            &right,
17962            &["id"],
17963            &["id"],
17964            JoinType::Inner,
17965            MergeExecutionOptions {
17966                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
17967                ..MergeExecutionOptions::default()
17968            },
17969        )
17970        .expect("merge");
17971        assert!(merged.columns.contains_key("val_L"));
17972        assert!(merged.columns.contains_key("val_R"));
17973        assert_eq!(
17974            merged.columns.get("val_L").expect("left suffixed").values(),
17975            &[Scalar::Int64(10)]
17976        );
17977        assert_eq!(
17978            merged
17979                .columns
17980                .get("val_R")
17981                .expect("right suffixed")
17982                .values(),
17983            &[Scalar::Int64(99)]
17984        );
17985    }
17986
17987    #[test]
17988    fn merge_column_name_conflict_allows_one_sided_suffix() {
17989        let left = DataFrame::from_dict(
17990            &["id", "val"],
17991            vec![
17992                ("id", vec![Scalar::Int64(1)]),
17993                ("val", vec![Scalar::Int64(10)]),
17994            ],
17995        )
17996        .expect("left");
17997        let right = DataFrame::from_dict(
17998            &["id", "val"],
17999            vec![
18000                ("id", vec![Scalar::Int64(1)]),
18001                ("val", vec![Scalar::Int64(99)]),
18002            ],
18003        )
18004        .expect("right");
18005
18006        let merged = merge_dataframes_on_with_options(
18007            &left,
18008            &right,
18009            &["id"],
18010            &["id"],
18011            JoinType::Inner,
18012            MergeExecutionOptions {
18013                suffixes: Some([None, Some("_r".to_owned())]),
18014                ..MergeExecutionOptions::default()
18015            },
18016        )
18017        .expect("merge");
18018        assert!(merged.columns.contains_key("val"));
18019        assert!(merged.columns.contains_key("val_r"));
18020        assert_eq!(
18021            merged.columns.get("val").expect("left unsuffixed").values(),
18022            &[Scalar::Int64(10)]
18023        );
18024        assert_eq!(
18025            merged
18026                .columns
18027                .get("val_r")
18028                .expect("right suffixed")
18029                .values(),
18030            &[Scalar::Int64(99)]
18031        );
18032    }
18033
18034    #[test]
18035    fn merge_column_name_conflict_rejects_missing_suffixes_for_overlap() {
18036        let left = DataFrame::from_dict(
18037            &["id", "val"],
18038            vec![
18039                ("id", vec![Scalar::Int64(1)]),
18040                ("val", vec![Scalar::Int64(10)]),
18041            ],
18042        )
18043        .expect("left");
18044        let right = DataFrame::from_dict(
18045            &["id", "val"],
18046            vec![
18047                ("id", vec![Scalar::Int64(1)]),
18048                ("val", vec![Scalar::Int64(99)]),
18049            ],
18050        )
18051        .expect("right");
18052
18053        let err = merge_dataframes_on_with_options(
18054            &left,
18055            &right,
18056            &["id"],
18057            &["id"],
18058            JoinType::Inner,
18059            MergeExecutionOptions {
18060                suffixes: Some([Some(String::new()), Some(String::new())]),
18061                ..MergeExecutionOptions::default()
18062            },
18063        )
18064        .expect_err("merge should reject overlapping columns without suffixes");
18065        assert!(format!("{err}").contains("columns overlap but no suffix specified"));
18066    }
18067
18068    #[test]
18069    fn merge_column_name_conflict_rejects_duplicate_output_columns_from_suffixes() {
18070        let left = DataFrame::from_dict(
18071            &["id", "val", "val_L"],
18072            vec![
18073                ("id", vec![Scalar::Int64(1)]),
18074                ("val", vec![Scalar::Int64(10)]),
18075                ("val_L", vec![Scalar::Int64(77)]),
18076            ],
18077        )
18078        .expect("left");
18079        let right = DataFrame::from_dict(
18080            &["id", "val"],
18081            vec![
18082                ("id", vec![Scalar::Int64(1)]),
18083                ("val", vec![Scalar::Int64(99)]),
18084            ],
18085        )
18086        .expect("right");
18087
18088        let err = merge_dataframes_on_with_options(
18089            &left,
18090            &right,
18091            &["id"],
18092            &["id"],
18093            JoinType::Inner,
18094            MergeExecutionOptions {
18095                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
18096                ..MergeExecutionOptions::default()
18097            },
18098        )
18099        .expect_err("merge should reject duplicate output names caused by suffixes");
18100        assert!(format!("{err}").contains("duplicate column"));
18101    }
18102
18103    #[test]
18104    fn merge_missing_key_column_errors() {
18105        let left = make_left_df();
18106        let right = make_right_df();
18107        let err = merge_dataframes(&left, &right, "nonexistent", JoinType::Inner)
18108            .expect_err("should fail");
18109        assert!(format!("{err}").contains("nonexistent"));
18110    }
18111
18112    #[test]
18113    fn merge_duplicate_keys_multiply_cardinality() {
18114        let left = DataFrame::from_dict(
18115            &["id", "a"],
18116            vec![
18117                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18118                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
18119            ],
18120        )
18121        .unwrap();
18122        let right = DataFrame::from_dict(
18123            &["id", "b"],
18124            vec![
18125                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18126                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
18127            ],
18128        )
18129        .unwrap();
18130
18131        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
18132        // 2 left × 2 right = 4 rows
18133        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
18134    }
18135
18136    #[test]
18137    fn ordered_identity_int64_guard_uses_strict_unique_certificate() {
18138        let left = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
18139        let right = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
18140        assert!(ordered_identity_int64_keys_match(&left, &right));
18141
18142        let duplicate_left = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
18143        let duplicate_right = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
18144        assert!(!ordered_identity_int64_keys_match(
18145            &duplicate_left,
18146            &duplicate_right
18147        ));
18148
18149        let unsorted_left = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
18150        let unsorted_right = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
18151        assert!(ordered_identity_int64_keys_match(
18152            &unsorted_left,
18153            &unsorted_right
18154        ));
18155    }
18156
18157    #[test]
18158    fn affine_i64_inner_plan_solves_nontrivial_stride_intersection() {
18159        let left = super::PositiveAffineI64Witness {
18160            start: -3,
18161            step: 4,
18162            len: 8,
18163        };
18164        let right = super::PositiveAffineI64Witness {
18165            start: 1,
18166            step: 6,
18167            len: 6,
18168        };
18169        assert_eq!(
18170            super::affine_i64_inner_position_plan(left, right),
18171            Some(super::AffineInnerPositionPlan {
18172                left_start: 1,
18173                left_step: 3,
18174                right_start: 0,
18175                right_step: 2,
18176                len: 3,
18177            })
18178        );
18179    }
18180
18181    #[test]
18182    fn affine_i64_inner_plan_matches_brute_force_small_domain() {
18183        const LENGTHS: [usize; 4] = [2, 3, 7, 11];
18184        for left_start in -8i128..=8 {
18185            for right_start in -8i128..=8 {
18186                for left_step in 1i128..=7 {
18187                    for right_step in 1i128..=7 {
18188                        for left_len in LENGTHS {
18189                            for right_len in LENGTHS {
18190                                let left = super::PositiveAffineI64Witness {
18191                                    start: left_start,
18192                                    step: left_step,
18193                                    len: left_len,
18194                                };
18195                                let right = super::PositiveAffineI64Witness {
18196                                    start: right_start,
18197                                    step: right_step,
18198                                    len: right_len,
18199                                };
18200                                let plan = super::affine_i64_inner_position_plan(left, right)
18201                                    .expect("small affine sequences cannot overflow");
18202                                let expected = (0..left_len)
18203                                    .flat_map(|left_row| {
18204                                        (0..right_len).filter_map(move |right_row| {
18205                                            let left_key = left_start
18206                                                + left_step * i128::try_from(left_row).unwrap();
18207                                            let right_key = right_start
18208                                                + right_step * i128::try_from(right_row).unwrap();
18209                                            (left_key == right_key).then_some((left_row, right_row))
18210                                        })
18211                                    })
18212                                    .collect::<Vec<_>>();
18213                                let actual = (0..plan.len)
18214                                    .map(|row| {
18215                                        (
18216                                            plan.left_start + row * plan.left_step,
18217                                            plan.right_start + row * plan.right_step,
18218                                        )
18219                                    })
18220                                    .collect::<Vec<_>>();
18221                                assert_eq!(actual, expected);
18222                            }
18223                        }
18224                    }
18225                }
18226            }
18227        }
18228    }
18229
18230    #[test]
18231    fn affine_i64_inner_merge_matches_left_major_values() {
18232        let left_keys = vec![-3, 1, 5, 9, 13, 17, 21, 25];
18233        let right_keys = vec![1, 7, 13, 19, 25, 31];
18234        let mut left_columns = std::collections::BTreeMap::new();
18235        left_columns.insert("id".to_owned(), Column::from_i64_values(left_keys));
18236        left_columns.insert(
18237            "left_value".to_owned(),
18238            Column::from_f64_values((0..8).map(|row| row as f64 + 0.5).collect()),
18239        );
18240        let left = DataFrame::new_with_column_order(
18241            Index::new_known_unique_int64_unit_range(0, 8),
18242            left_columns,
18243            vec!["id".to_owned(), "left_value".to_owned()],
18244        )
18245        .unwrap();
18246        let mut right_columns = std::collections::BTreeMap::new();
18247        right_columns.insert("id".to_owned(), Column::from_i64_values(right_keys));
18248        right_columns.insert(
18249            "right_value".to_owned(),
18250            Column::from_i64_values((100..106).collect()),
18251        );
18252        let right = DataFrame::new_with_column_order(
18253            Index::new_known_unique_int64_unit_range(0, 6),
18254            right_columns,
18255            vec!["id".to_owned(), "right_value".to_owned()],
18256        )
18257        .unwrap();
18258        let suffixes = resolve_merge_suffixes(None);
18259        let merged = super::build_single_key_affine_i64_inner_merge_output(
18260            &left,
18261            &right,
18262            &["id"],
18263            &["id"],
18264            left.columns().get("id").unwrap(),
18265            right.columns().get("id").unwrap(),
18266            &suffixes,
18267        )
18268        .unwrap()
18269        .expect("certified affine typed inputs must use the fast path");
18270
18271        assert_eq!(
18272            merged.columns.get("id").unwrap().values(),
18273            &[Scalar::Int64(1), Scalar::Int64(13), Scalar::Int64(25)]
18274        );
18275        assert_eq!(
18276            merged.columns.get("left_value").unwrap().values(),
18277            &[
18278                Scalar::Float64(1.5),
18279                Scalar::Float64(4.5),
18280                Scalar::Float64(7.5),
18281            ]
18282        );
18283        assert_eq!(
18284            merged.columns.get("right_value").unwrap().values(),
18285            &[Scalar::Int64(100), Scalar::Int64(102), Scalar::Int64(104)]
18286        );
18287    }
18288
18289    #[test]
18290    fn merge_identical_duplicate_keys_cross_join_values_jdupk() {
18291        // Identical left/right key columns that contain duplicates must NOT take
18292        // the identity 1:1 fast path: pandas cross-joins each duplicate, so a=10
18293        // and a=20 each pair with b=100 and b=200. (br-frankenpandas-jdupk)
18294        let left = DataFrame::from_dict(
18295            &["id", "a"],
18296            vec![
18297                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18298                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
18299            ],
18300        )
18301        .unwrap();
18302        let right = DataFrame::from_dict(
18303            &["id", "b"],
18304            vec![
18305                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18306                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
18307            ],
18308        )
18309        .unwrap();
18310
18311        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
18312        assert_eq!(
18313            merged.columns.get("a").unwrap().values(),
18314            &[
18315                Scalar::Int64(10),
18316                Scalar::Int64(10),
18317                Scalar::Int64(20),
18318                Scalar::Int64(20)
18319            ]
18320        );
18321        assert_eq!(
18322            merged.columns.get("b").unwrap().values(),
18323            &[
18324                Scalar::Int64(100),
18325                Scalar::Int64(200),
18326                Scalar::Int64(100),
18327                Scalar::Int64(200)
18328            ]
18329        );
18330    }
18331
18332    #[test]
18333    fn ordered_unique_utf8_inner_positions_match_left_major_hash_order_53lat() {
18334        let left = contiguous_utf8_column(&["a", "b", "d", "f"]);
18335        let right = contiguous_utf8_column(&["b", "c", "f"]);
18336        let (left_positions, right_positions) =
18337            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18338
18339        assert_eq!(left_positions, vec![1, 3]);
18340        assert_eq!(right_positions, vec![0, 2]);
18341
18342        let merged = merge_dataframes(
18343            &utf8_key_merge_frame(&["a", "b", "d", "f"], "lv", 10),
18344            &utf8_key_merge_frame(&["b", "c", "f"], "rv", 20),
18345            "id",
18346            JoinType::Inner,
18347        )
18348        .unwrap();
18349        assert_eq!(
18350            merged.columns.get("lv").unwrap().values(),
18351            &[Scalar::Int64(11), Scalar::Int64(13)]
18352        );
18353        assert_eq!(
18354            merged.columns.get("rv").unwrap().values(),
18355            &[Scalar::Int64(20), Scalar::Int64(22)]
18356        );
18357    }
18358
18359    #[test]
18360    fn sorted_contiguous_utf8_inner_positions_preserves_duplicate_order_codb() {
18361        let left = contiguous_utf8_column(&["a", "a", "b", "d"]);
18362        let right = contiguous_utf8_column(&["a", "a", "c", "d"]);
18363        let (left_bytes, left_offsets) = left.as_utf8_contiguous().expect("left contiguous");
18364        let (right_bytes, right_offsets) = right.as_utf8_contiguous().expect("right contiguous");
18365
18366        let (left_positions, right_positions) = sorted_contiguous_utf8_inner_positions(
18367            left_bytes,
18368            left_offsets,
18369            right_bytes,
18370            right_offsets,
18371        )
18372        .expect("sorted spans should use two-pointer merge");
18373
18374        assert_eq!(left_positions, vec![0, 0, 1, 1, 3]);
18375        assert_eq!(right_positions, vec![0, 1, 0, 1, 3]);
18376    }
18377
18378    #[test]
18379    fn sorted_contiguous_utf8_inner_positions_rejects_unsorted_input_codb() {
18380        let left = contiguous_utf8_column(&["b", "a"]);
18381        let right = contiguous_utf8_column(&["a", "b"]);
18382        let (left_bytes, left_offsets) = left.as_utf8_contiguous().expect("left contiguous");
18383        let (right_bytes, right_offsets) = right.as_utf8_contiguous().expect("right contiguous");
18384
18385        assert!(
18386            sorted_contiguous_utf8_inner_positions(
18387                left_bytes,
18388                left_offsets,
18389                right_bytes,
18390                right_offsets,
18391            )
18392            .is_none()
18393        );
18394    }
18395
18396    #[test]
18397    fn ordered_unique_utf8_seek_bound_preserves_late_overlap_lr52z() {
18398        let left = contiguous_utf8_column(&["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);
18399        let right = contiguous_utf8_column(&["h", "i", "j", "k"]);
18400        let (left_bytes, left_offsets) =
18401            strictly_increasing_utf8_key_spans(&left).expect("sorted left");
18402
18403        assert_eq!(utf8_span_lower_bound(left_bytes, left_offsets, b"h"), 7);
18404
18405        let (left_positions, right_positions) =
18406            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18407        assert_eq!(left_positions, vec![7, 8, 9]);
18408        assert_eq!(right_positions, vec![0, 1, 2]);
18409
18410        let disjoint_left = contiguous_utf8_column(&["a", "b"]);
18411        let disjoint_right = contiguous_utf8_column(&["c", "d"]);
18412        let (left_positions, right_positions) =
18413            ordered_unique_utf8_inner_positions(&disjoint_left, &disjoint_right)
18414                .expect("ordered disjoint utf8 positions");
18415        assert!(left_positions.is_empty());
18416        assert!(right_positions.is_empty());
18417    }
18418
18419    #[test]
18420    fn ordered_unique_utf8_bulk_fixed_width_window_jbyuc11() {
18421        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
18422        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
18423
18424        let (left_positions, right_positions) =
18425            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18426        assert_eq!(left_positions, vec![2, 3, 4]);
18427        assert_eq!(right_positions, vec![0, 1, 2]);
18428    }
18429
18430    #[test]
18431    fn ordered_unique_utf8_bulk_window_returns_range_plan_jbyuc11111() {
18432        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
18433        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
18434
18435        let plan =
18436            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
18437
18438        assert_eq!(
18439            plan,
18440            InnerPositionPlan::ContiguousRanges {
18441                left_start: 2,
18442                right_start: 0,
18443                len: 3
18444            }
18445        );
18446    }
18447
18448    #[test]
18449    fn ordered_unique_utf8_lower_hex_certificate_returns_range_plan_jbyuc111111() {
18450        let left =
18451            contiguous_utf8_column(&["id_0000000a", "id_0000000b", "id_0000000c", "id_0000000d"]);
18452        let right = contiguous_utf8_column(&["id_0000000c", "id_0000000d", "id_0000000e"]);
18453        let (_, _, left_cert) = left
18454            .as_lower_hex_sequence_utf8_contiguous()
18455            .expect("left sequence certificate");
18456        let (_, _, right_cert) = right
18457            .as_lower_hex_sequence_utf8_contiguous()
18458            .expect("right sequence certificate");
18459
18460        assert_eq!(
18461            ordered_utf8_lower_hex_overlap_len(left_cert, right_cert, 2, 4, 0, 3),
18462            Some(2)
18463        );
18464        assert_eq!(
18465            lower_hex_overlap_plan_from_certificates(&left, &right),
18466            Some(InnerPositionPlan::ContiguousRanges {
18467                left_start: 2,
18468                right_start: 0,
18469                len: 2
18470            })
18471        );
18472        let plan =
18473            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
18474        assert_eq!(
18475            plan,
18476            InnerPositionPlan::ContiguousRanges {
18477                left_start: 2,
18478                right_start: 0,
18479                len: 2
18480            }
18481        );
18482    }
18483
18484    #[test]
18485    fn ordered_unique_utf8_lower_hex_arithmetic_empty_overlap_jbyuc1111111111() {
18486        let left = contiguous_utf8_column(&["id_00000001", "id_00000002", "id_00000003"]);
18487        let right = contiguous_utf8_column(&["id_00000008", "id_00000009"]);
18488
18489        assert_eq!(
18490            lower_hex_overlap_plan_from_certificates(&left, &right),
18491            Some(InnerPositionPlan::Gather {
18492                left_positions: Vec::new(),
18493                right_positions: Vec::new(),
18494            })
18495        );
18496        let (left_positions, right_positions) =
18497            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18498        assert!(left_positions.is_empty());
18499        assert!(right_positions.is_empty());
18500    }
18501
18502    #[test]
18503    fn ordered_unique_utf8_lower_hex_prefix_mismatch_falls_back_jbyuc1111111111() {
18504        let left = contiguous_utf8_column(&["aa_00000001", "aa_00000002", "aa_00000003"]);
18505        let right = contiguous_utf8_column(&["bb_00000001", "bb_00000002", "bb_00000003"]);
18506
18507        assert!(
18508            lower_hex_overlap_plan_from_certificates(&left, &right).is_none(),
18509            "matching lower-hex counters with different prefixes must not use arithmetic overlap"
18510        );
18511        let (left_positions, right_positions) =
18512            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18513        assert!(left_positions.is_empty());
18514        assert!(right_positions.is_empty());
18515    }
18516
18517    #[test]
18518    fn ordered_utf8_contiguous_no_overlap_output_fast_path_jbyuc111111111() -> Result<(), String> {
18519        let left = utf8_key_merge_frame(
18520            &["id_00000000", "id_00000001", "id_00000002", "id_00000003"],
18521            "lv",
18522            10,
18523        );
18524        let right = utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "rv", 100);
18525        let plan = ordered_unique_utf8_inner_position_plan(
18526            left.columns()
18527                .get("id")
18528                .ok_or_else(|| "left key column missing".to_owned())?,
18529            right
18530                .columns()
18531                .get("id")
18532                .ok_or_else(|| "right key column missing".to_owned())?,
18533        )
18534        .ok_or_else(|| "ordered utf8 plan unavailable".to_owned())?;
18535        let InnerPositionPlan::ContiguousRanges {
18536            left_start,
18537            right_start,
18538            len,
18539        } = plan
18540        else {
18541            return Err("expected contiguous range plan".to_owned());
18542        };
18543
18544        let merged = build_single_key_inner_contiguous_no_overlap_output(
18545            &left,
18546            &right,
18547            &["id"],
18548            &["id"],
18549            PositionSelection::ContiguousRange {
18550                start: left_start,
18551                len,
18552            },
18553            PositionSelection::ContiguousRange {
18554                start: right_start,
18555                len,
18556            },
18557        )
18558        .ok_or_else(|| "no-overlap contiguous output fast path missed".to_owned())?;
18559
18560        assert_eq!(merged.column_order, ["id", "lv", "rv"]);
18561        let id_output = merged
18562            .columns
18563            .get("id")
18564            .ok_or_else(|| "id output missing".to_owned())?;
18565        let (prefix, certificate, certificate_len) = id_output
18566            .as_lower_hex_sequence_utf8()
18567            .ok_or_else(|| "id output lost lower-hex sequence witness".to_owned())?;
18568        assert_eq!(prefix, b"id_");
18569        assert_eq!(certificate.start(), 2);
18570        assert_eq!(certificate.hex_width(), 8);
18571        assert_eq!(certificate_len, 2);
18572        assert_eq!(
18573            id_output.values(),
18574            &[
18575                Scalar::Utf8("id_00000002".to_owned()),
18576                Scalar::Utf8("id_00000003".to_owned())
18577            ]
18578        );
18579        assert_eq!(
18580            merged
18581                .columns
18582                .get("lv")
18583                .ok_or_else(|| "lv output missing".to_owned())?
18584                .values(),
18585            &[Scalar::Int64(12), Scalar::Int64(13)]
18586        );
18587        assert_eq!(
18588            merged
18589                .columns
18590                .get("rv")
18591                .ok_or_else(|| "rv output missing".to_owned())?
18592                .values(),
18593            &[Scalar::Int64(100), Scalar::Int64(101)]
18594        );
18595
18596        let overlapping_right =
18597            utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "lv", 100);
18598        assert!(
18599            build_single_key_inner_contiguous_no_overlap_output(
18600                &left,
18601                &overlapping_right,
18602                &["id"],
18603                &["id"],
18604                PositionSelection::ContiguousRange {
18605                    start: left_start,
18606                    len,
18607                },
18608                PositionSelection::ContiguousRange {
18609                    start: right_start,
18610                    len,
18611                },
18612            )
18613            .is_none(),
18614            "overlapping non-key columns must keep the suffix/error generic path"
18615        );
18616        Ok(())
18617    }
18618
18619    #[test]
18620    fn ordered_unique_utf8_uncertified_fixed_width_still_matches_jbyuc111111() {
18621        let left = contiguous_utf8_column(&["k00A", "k00B", "k00C", "k00D"]);
18622        let right = contiguous_utf8_column(&["k00B", "k00D"]);
18623
18624        assert!(left.as_lower_hex_sequence_utf8_contiguous().is_none());
18625        assert!(right.as_lower_hex_sequence_utf8_contiguous().is_none());
18626        let (left_positions, right_positions) =
18627            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18628        assert_eq!(left_positions, vec![1, 3]);
18629        assert_eq!(right_positions, vec![0, 1]);
18630    }
18631
18632    #[test]
18633    fn ordered_unique_utf8_fixed_width_gap_falls_back_jbyuc11() {
18634        let left = contiguous_utf8_column(&["k000", "k001", "k003", "k004"]);
18635        let right = contiguous_utf8_column(&["k001", "k002", "k004"]);
18636
18637        let (left_positions, right_positions) =
18638            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18639        assert_eq!(left_positions, vec![1, 3]);
18640        assert_eq!(right_positions, vec![0, 2]);
18641    }
18642
18643    #[test]
18644    fn ordered_unique_utf8_rejects_unsorted_or_duplicate_keys_53lat() {
18645        let unsorted_left = contiguous_utf8_column(&["b", "a", "b"]);
18646        let duplicate_right = contiguous_utf8_column(&["b", "b", "a"]);
18647        assert!(ordered_unique_utf8_inner_positions(&unsorted_left, &duplicate_right).is_none());
18648
18649        let left = utf8_key_merge_frame(&["b", "a", "b"], "lv", 10);
18650        let right = utf8_key_merge_frame(&["b", "b", "a"], "rv", 20);
18651        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
18652
18653        assert_eq!(
18654            merged.columns.get("lv").unwrap().values(),
18655            &[
18656                Scalar::Int64(10),
18657                Scalar::Int64(10),
18658                Scalar::Int64(11),
18659                Scalar::Int64(12),
18660                Scalar::Int64(12)
18661            ]
18662        );
18663        assert_eq!(
18664            merged.columns.get("rv").unwrap().values(),
18665            &[
18666                Scalar::Int64(20),
18667                Scalar::Int64(21),
18668                Scalar::Int64(22),
18669                Scalar::Int64(20),
18670                Scalar::Int64(21)
18671            ]
18672        );
18673    }
18674
18675    #[test]
18676    fn merge_inner_int64_fast_paths_match_naive_reference_fuzz_jdupk() {
18677        // Differential guard: merge_dataframes dispatches int64 single-key inner
18678        // merges to ordered/identity/dense fast paths. Each MUST equal a naive
18679        // left-major nested-loop join for arbitrary int64 keys (sorted/unsorted,
18680        // unique/duplicate, overlapping/disjoint, negative). This is the
18681        // isomorphism proof those perf paths owe; it caught the identity-path
18682        // row-loss bug. (br-frankenpandas-rw0r5)
18683        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
18684        let mut next = || {
18685            state = state
18686                .wrapping_mul(6_364_136_223_846_793_005)
18687                .wrapping_add(1_442_695_040_888_963_407);
18688            state >> 33
18689        };
18690        for _ in 0..400 {
18691            let nl = (next() % 6 + 1) as usize;
18692            let nr = (next() % 6 + 1) as usize;
18693            // small key range forces collisions; offset gives negatives too
18694            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64 - 2).collect();
18695            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64 - 2).collect();
18696
18697            let left = DataFrame::from_dict(
18698                &["id", "a"],
18699                vec![
18700                    ("id", lk.iter().map(|&k| Scalar::Int64(k)).collect()),
18701                    (
18702                        "a",
18703                        (0..nl).map(|i| Scalar::Int64(i as i64 + 1000)).collect(),
18704                    ),
18705                ],
18706            )
18707            .unwrap();
18708            let right = DataFrame::from_dict(
18709                &["id", "b"],
18710                vec![
18711                    ("id", rk.iter().map(|&k| Scalar::Int64(k)).collect()),
18712                    (
18713                        "b",
18714                        (0..nr).map(|j| Scalar::Int64(j as i64 + 2000)).collect(),
18715                    ),
18716                ],
18717            )
18718            .unwrap();
18719
18720            let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
18721
18722            // Naive reference: pandas inner merge is left-major, right-minor.
18723            let mut exp_a = Vec::new();
18724            let mut exp_b = Vec::new();
18725            for (i, &left_value) in lk.iter().enumerate() {
18726                for (j, &right_value) in rk.iter().enumerate() {
18727                    if left_value == right_value {
18728                        exp_a.push(Scalar::Int64(i as i64 + 1000));
18729                        exp_b.push(Scalar::Int64(j as i64 + 2000));
18730                    }
18731                }
18732            }
18733            assert_eq!(
18734                merged.columns.get("a").unwrap().values(),
18735                exp_a.as_slice(),
18736                "left payload mismatch for lk={lk:?} rk={rk:?}"
18737            );
18738            assert_eq!(
18739                merged.columns.get("b").unwrap().values(),
18740                exp_b.as_slice(),
18741                "right payload mismatch for lk={lk:?} rk={rk:?}"
18742            );
18743
18744            // Cardinality guard for left/right/outer (dtype/order independent —
18745            // catches the row-loss class regardless of int->float promotion).
18746            let inner_pairs = exp_a.len();
18747            let left_only = lk.iter().filter(|&key| !rk.contains(key)).count();
18748            let right_only = rk.iter().filter(|&key| !lk.contains(key)).count();
18749            for (how, expected_rows) in [
18750                (JoinType::Left, inner_pairs + left_only),
18751                (JoinType::Right, inner_pairs + right_only),
18752                (JoinType::Outer, inner_pairs + left_only + right_only),
18753            ] {
18754                let m = merge_dataframes(&left, &right, "id", how).unwrap();
18755                assert_eq!(
18756                    m.columns.get("id").unwrap().len(),
18757                    expected_rows,
18758                    "{how:?} cardinality mismatch for lk={lk:?} rk={rk:?}"
18759                );
18760            }
18761        }
18762    }
18763
18764    #[test]
18765    fn merge_null_nan_keys_metamorphic_unmatched_rows_do_not_disturb_inner_tn6qb8()
18766    -> Result<(), JoinError> {
18767        let left = DataFrame::from_dict(
18768            &["id", "left_v"],
18769            vec![
18770                (
18771                    "id",
18772                    vec![
18773                        Scalar::Float64(1.0),
18774                        Scalar::Null(NullKind::NaN),
18775                        Scalar::Null(NullKind::Null),
18776                        Scalar::Float64(2.0),
18777                    ],
18778                ),
18779                (
18780                    "left_v",
18781                    vec![
18782                        Scalar::Int64(10),
18783                        Scalar::Int64(20),
18784                        Scalar::Int64(21),
18785                        Scalar::Int64(30),
18786                    ],
18787                ),
18788            ],
18789        )?;
18790        let right = DataFrame::from_dict(
18791            &["id", "right_v"],
18792            vec![
18793                (
18794                    "id",
18795                    vec![
18796                        Scalar::Null(NullKind::Null),
18797                        Scalar::Float64(2.0),
18798                        Scalar::Float64(f64::NAN),
18799                    ],
18800                ),
18801                (
18802                    "right_v",
18803                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(201)],
18804                ),
18805            ],
18806        )?;
18807
18808        let baseline = merge_dataframes(&left, &right, "id", JoinType::Inner)?;
18809
18810        let left_with_unmatched = DataFrame::from_dict(
18811            &["id", "left_v"],
18812            vec![
18813                (
18814                    "id",
18815                    vec![
18816                        Scalar::Float64(1.0),
18817                        Scalar::Null(NullKind::NaN),
18818                        Scalar::Null(NullKind::Null),
18819                        Scalar::Float64(2.0),
18820                        Scalar::Float64(99.0),
18821                    ],
18822                ),
18823                (
18824                    "left_v",
18825                    vec![
18826                        Scalar::Int64(10),
18827                        Scalar::Int64(20),
18828                        Scalar::Int64(21),
18829                        Scalar::Int64(30),
18830                        Scalar::Int64(990),
18831                    ],
18832                ),
18833            ],
18834        )?;
18835        let right_with_unmatched = DataFrame::from_dict(
18836            &["id", "right_v"],
18837            vec![
18838                (
18839                    "id",
18840                    vec![
18841                        Scalar::Null(NullKind::Null),
18842                        Scalar::Float64(2.0),
18843                        Scalar::Float64(f64::NAN),
18844                        Scalar::Float64(100.0),
18845                    ],
18846                ),
18847                (
18848                    "right_v",
18849                    vec![
18850                        Scalar::Int64(200),
18851                        Scalar::Int64(300),
18852                        Scalar::Int64(201),
18853                        Scalar::Int64(1000),
18854                    ],
18855                ),
18856            ],
18857        )?;
18858
18859        let transformed = merge_dataframes(
18860            &left_with_unmatched,
18861            &right_with_unmatched,
18862            "id",
18863            JoinType::Inner,
18864        )?;
18865
18866        assert_eq!(
18867            merged_values(&baseline, "left_v")?,
18868            merged_values(&transformed, "left_v")?
18869        );
18870        assert_eq!(
18871            merged_values(&baseline, "right_v")?,
18872            merged_values(&transformed, "right_v")?
18873        );
18874        assert_eq!(
18875            merged_values(&baseline, "left_v")?,
18876            &[
18877                Scalar::Int64(20),
18878                Scalar::Int64(20),
18879                Scalar::Int64(21),
18880                Scalar::Int64(21),
18881                Scalar::Int64(30),
18882            ]
18883        );
18884        assert_eq!(
18885            merged_values(&baseline, "right_v")?,
18886            &[
18887                Scalar::Int64(200),
18888                Scalar::Int64(201),
18889                Scalar::Int64(200),
18890                Scalar::Int64(201),
18891                Scalar::Int64(300),
18892            ]
18893        );
18894
18895        Ok(())
18896    }
18897
18898    #[test]
18899    fn merge_mixed_dtype_missing_keys_metamorphic_outer_both_equals_inner_tn6qb8()
18900    -> Result<(), JoinError> {
18901        let left = DataFrame::from_dict(
18902            &["id", "left_v"],
18903            vec![
18904                (
18905                    "id",
18906                    vec![
18907                        Scalar::Int64(1),
18908                        Scalar::Int64(2),
18909                        Scalar::Null(NullKind::NaN),
18910                        Scalar::Int64(3),
18911                    ],
18912                ),
18913                (
18914                    "left_v",
18915                    vec![
18916                        Scalar::Float64(10.0),
18917                        Scalar::Float64(20.0),
18918                        Scalar::Float64(30.0),
18919                        Scalar::Float64(40.0),
18920                    ],
18921                ),
18922            ],
18923        )?;
18924        let right = DataFrame::from_dict(
18925            &["id", "right_v"],
18926            vec![
18927                (
18928                    "id",
18929                    vec![
18930                        Scalar::Float64(1.0),
18931                        Scalar::Float64(2.5),
18932                        Scalar::Null(NullKind::Null),
18933                        Scalar::Float64(3.0),
18934                    ],
18935                ),
18936                (
18937                    "right_v",
18938                    vec![
18939                        Scalar::Float64(100.0),
18940                        Scalar::Float64(250.0),
18941                        Scalar::Float64(300.0),
18942                        Scalar::Float64(400.0),
18943                    ],
18944                ),
18945            ],
18946        )?;
18947        let options = MergeExecutionOptions {
18948            indicator_name: Some("_merge".to_owned()),
18949            sort: true,
18950            ..MergeExecutionOptions::default()
18951        };
18952
18953        let inner = merge_dataframes_on_with_options(
18954            &left,
18955            &right,
18956            &["id"],
18957            &["id"],
18958            JoinType::Inner,
18959            options.clone(),
18960        )?;
18961        let outer = merge_dataframes_on_with_options(
18962            &left,
18963            &right,
18964            &["id"],
18965            &["id"],
18966            JoinType::Outer,
18967            options,
18968        )?;
18969
18970        assert_eq!(
18971            merged_values(&inner, "left_v")?,
18972            merged_values_where_indicator(&outer, "left_v", "_merge", "both")?
18973        );
18974        assert_eq!(
18975            merged_values(&inner, "right_v")?,
18976            merged_values_where_indicator(&outer, "right_v", "_merge", "both")?
18977        );
18978        assert_eq!(
18979            merged_values(&inner, "left_v")?,
18980            &[
18981                Scalar::Float64(10.0),
18982                Scalar::Float64(40.0),
18983                Scalar::Float64(30.0)
18984            ]
18985        );
18986        assert_eq!(
18987            merged_values(&inner, "right_v")?,
18988            &[
18989                Scalar::Float64(100.0),
18990                Scalar::Float64(400.0),
18991                Scalar::Float64(300.0)
18992            ]
18993        );
18994        assert_eq!(
18995            merged_values(&outer, "_merge")?,
18996            &[
18997                Scalar::Utf8("both".to_owned()),
18998                Scalar::Utf8("left_only".to_owned()),
18999                Scalar::Utf8("right_only".to_owned()),
19000                Scalar::Utf8("both".to_owned()),
19001                Scalar::Utf8("both".to_owned()),
19002            ]
19003        );
19004
19005        Ok(())
19006    }
19007
19008    #[test]
19009    fn merge_cross_cartesian_product() {
19010        let left = make_left_df();
19011        let right = make_right_df();
19012
19013        let merged = merge_dataframes(&left, &right, "unused_key", JoinType::Cross).unwrap();
19014
19015        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
19016        assert_eq!(
19017            &merged.columns.get("id_x").unwrap().values()[0..3],
19018            &[Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)]
19019        );
19020        assert_eq!(
19021            &merged.columns.get("id_y").unwrap().values()[0..3],
19022            &[Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)]
19023        );
19024        assert_eq!(
19025            &merged.columns.get("val_a").unwrap().values()[0..3],
19026            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(10)]
19027        );
19028        assert_eq!(
19029            &merged.columns.get("val_b").unwrap().values()[0..3],
19030            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
19031        );
19032    }
19033
19034    #[test]
19035    fn merge_cross_does_not_require_on_column() {
19036        let left = make_left_df();
19037        let right = make_right_df();
19038
19039        let merged =
19040            merge_dataframes(&left, &right, "definitely_missing", JoinType::Cross).unwrap();
19041        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
19042    }
19043
19044    #[test]
19045    fn merge_cross_with_empty_side_yields_empty_rows() {
19046        let left = DataFrame::from_dict(
19047            &["l"],
19048            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
19049        )
19050        .unwrap();
19051        let right = DataFrame::from_dict(&["r"], vec![("r", vec![])]).unwrap();
19052
19053        let merged = merge_dataframes(&left, &right, "ignored", JoinType::Cross).unwrap();
19054        assert_eq!(merged.index.labels().len(), 0);
19055        assert!(merged.columns.get("l").unwrap().values().is_empty());
19056        assert!(merged.columns.get("r").unwrap().values().is_empty());
19057    }
19058
19059    /// A cross merge keeps each side's own column order, as pandas (the
19060    /// columns came back sorted by name; buwrx).
19061    #[test]
19062    fn merge_cross_keeps_each_sides_column_order_buwrx() {
19063        let ints = |values: [i64; 2]| values.map(Scalar::Int64).to_vec();
19064        let left = DataFrame::from_dict(
19065            &["z", "k", "a"],
19066            vec![
19067                ("z", ints([1, 2])),
19068                ("k", ints([3, 4])),
19069                ("a", ints([5, 6])),
19070            ],
19071        )
19072        .unwrap();
19073        let right = DataFrame::from_dict(
19074            &["k", "w", "b"],
19075            vec![
19076                ("k", ints([7, 8])),
19077                ("w", ints([9, 10])),
19078                ("b", ints([11, 12])),
19079            ],
19080        )
19081        .unwrap();
19082        let merged = merge_dataframes(&left, &right, "ignored", JoinType::Cross).unwrap();
19083        assert_eq!(merged.column_order, ["z", "k_x", "a", "k_y", "w", "b"]);
19084        assert_eq!(
19085            merged.columns.get("w").unwrap().values(),
19086            [9, 10, 9, 10].map(Scalar::Int64)
19087        );
19088        // NEGATIVE: the rows are still left-major.
19089        assert_eq!(
19090            merged.columns.get("z").unwrap().values(),
19091            [1, 1, 2, 2].map(Scalar::Int64)
19092        );
19093    }
19094
19095    #[test]
19096    fn text_and_int_keys_join_as_codes_in_row_order_j4657() {
19097        // A (text, int) merge key's text joins as int64 codes over both
19098        // sides' strings: an inner / left merge pairs each left row with its
19099        // equal right rows in their order (a left row without one kept by
19100        // the left join), as a loop over the rows pairs them; a contiguous
19101        // and a Scalar text column alike. NEGATIVE: "a" never meets "A" or
19102        // "a " (codes per byte string), a right-only string matches nothing,
19103        // the right's first string ("q") is not the left's first code's, an
19104        // outer merge sorts by the strings (codes would put "b" first), and
19105        // a missing text key still joins its missing peer (the generic path).
19106        // No inner merge here is as long as the left frame, where pandas 2.2
19107        // reorders the rows (br-frankenpandas-ml0az; br-frankenpandas-j4657).
19108        let left_text = ["b", "a", "A", "a", "c", "b", "a "];
19109        let left_int = [1_i64, 2, 2, 2, 7, 1, 2];
19110        let right_text = ["q", "a", "b", "a", "b", "A", "c", "c", "b"];
19111        let right_int = [5_i64, 2, 1, 2, 3, 9, 7, 7, 1];
19112        let frame = |text: Column, ints: &[i64], value: &str, base: i64| {
19113            let rows = ints.len();
19114            let mut columns = ColumnStore::new();
19115            columns.insert("t".to_owned(), text);
19116            columns.insert("i".to_owned(), Column::from_i64_values(ints.to_vec()));
19117            columns.insert(
19118                value.to_owned(),
19119                Column::from_i64_values((0..rows as i64).map(|row| base + row).collect()),
19120            );
19121            DataFrame::new_with_column_order(
19122                Index::new((0..rows as i64).map(IndexLabel::Int64).collect()),
19123                columns,
19124                vec!["t".to_owned(), "i".to_owned(), value.to_owned()],
19125            )
19126            .unwrap()
19127        };
19128        let scalar_text = |values: &[&str]| {
19129            Column::from_values(
19130                values
19131                    .iter()
19132                    .map(|value| Scalar::Utf8((*value).to_owned()))
19133                    .collect(),
19134            )
19135            .unwrap()
19136        };
19137        for contiguous in [true, false] {
19138            let text = |values: &[&str]| {
19139                if contiguous {
19140                    contiguous_utf8_column(values)
19141                } else {
19142                    scalar_text(values)
19143                }
19144            };
19145            let left = frame(text(&left_text), &left_int, "lv", 100);
19146            let right = frame(text(&right_text), &right_int, "rv", 200);
19147            for join_type in [JoinType::Inner, JoinType::Left] {
19148                let mut want: Vec<(Scalar, Scalar)> = Vec::new();
19149                for (l, key) in left_text.iter().zip(&left_int).enumerate() {
19150                    let matches: Vec<usize> = right_text
19151                        .iter()
19152                        .zip(&right_int)
19153                        .enumerate()
19154                        .filter(|(_, right_key)| *right_key == key)
19155                        .map(|(r, _)| r)
19156                        .collect();
19157                    for &r in &matches {
19158                        want.push((Scalar::Int64(100 + l as i64), Scalar::Int64(200 + r as i64)));
19159                    }
19160                    if matches.is_empty() && matches!(join_type, JoinType::Left) {
19161                        want.push((Scalar::Int64(100 + l as i64), Scalar::Null(NullKind::NaN)));
19162                    }
19163                }
19164                let merged = merge_dataframes_on(&left, &right, &["t", "i"], join_type).unwrap();
19165                let got: Vec<(Scalar, Scalar)> = merged
19166                    .columns
19167                    .get("lv")
19168                    .unwrap()
19169                    .values()
19170                    .iter()
19171                    .cloned()
19172                    .zip(merged.columns.get("rv").unwrap().values().iter().cloned())
19173                    .collect();
19174                assert_eq!(got.len(), want.len(), "{contiguous} {join_type:?}");
19175                for ((got_l, got_r), (want_l, want_r)) in got.iter().zip(&want) {
19176                    assert_eq!(got_l, want_l, "{contiguous} {join_type:?}");
19177                    assert_eq!(got_r.is_missing(), want_r.is_missing());
19178                    if !want_r.is_missing() {
19179                        assert_eq!(got_r.to_f64().ok(), want_r.to_f64().ok());
19180                    }
19181                }
19182                // The key columns are the strings, not their codes.
19183                let keys: Vec<Scalar> = want
19184                    .iter()
19185                    .map(|(l, _)| match l {
19186                        Scalar::Int64(row) => {
19187                            Scalar::Utf8(left_text[(*row - 100) as usize].to_owned())
19188                        }
19189                        _ => unreachable!(),
19190                    })
19191                    .collect();
19192                assert_eq!(merged.columns.get("t").unwrap().values(), keys.as_slice());
19193            }
19194            // Inner pairs: b/1's two left rows with right rows 2 and 8, a/2's
19195            // two with rows 1 and 3, c/7 with rows 6 and 7; A/2 none (right A
19196            // is 9), "a " none.
19197            let inner = merge_dataframes_on(&left, &right, &["t", "i"], JoinType::Inner).unwrap();
19198            assert_eq!(inner.columns.get("lv").unwrap().len(), 10);
19199            let outer = merge_dataframes_on(&left, &right, &["t", "i"], JoinType::Outer).unwrap();
19200            let outer_keys: Vec<String> = outer
19201                .columns
19202                .get("t")
19203                .unwrap()
19204                .values()
19205                .iter()
19206                .map(|value| match value {
19207                    Scalar::Utf8(text) => text.clone(),
19208                    other => format!("{other:?}"),
19209                })
19210                .collect();
19211            let mut sorted = outer_keys.clone();
19212            sorted.sort();
19213            assert_eq!(outer_keys, sorted, "{contiguous}");
19214        }
19215        // A missing text key meets its missing peer through the generic path.
19216        let left = frame(
19217            Column::from_values(vec![
19218                Scalar::Utf8("a".to_owned()),
19219                Scalar::Null(NullKind::Null),
19220            ])
19221            .unwrap(),
19222            &[1, 1],
19223            "lv",
19224            100,
19225        );
19226        let right = frame(
19227            Column::from_values(vec![
19228                Scalar::Null(NullKind::Null),
19229                Scalar::Utf8("a".to_owned()),
19230            ])
19231            .unwrap(),
19232            &[1, 1],
19233            "rv",
19234            200,
19235        );
19236        let merged = merge_dataframes_on(&left, &right, &["t", "i"], JoinType::Inner).unwrap();
19237        assert_eq!(
19238            merged.columns.get("lv").unwrap().values(),
19239            &[Scalar::Int64(100), Scalar::Int64(101)]
19240        );
19241        assert_eq!(
19242            merged.columns.get("rv").unwrap().values(),
19243            &[Scalar::Int64(201), Scalar::Int64(200)]
19244        );
19245    }
19246
19247    #[test]
19248    fn merge_composite_inner_multiplies_cardinality_for_duplicates() {
19249        let left = DataFrame::from_dict(
19250            &["k1", "k2", "left_v"],
19251            vec![
19252                (
19253                    "k1",
19254                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
19255                ),
19256                (
19257                    "k2",
19258                    vec![
19259                        Scalar::Utf8("a".to_owned()),
19260                        Scalar::Utf8("a".to_owned()),
19261                        Scalar::Utf8("b".to_owned()),
19262                    ],
19263                ),
19264                (
19265                    "left_v",
19266                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
19267                ),
19268            ],
19269        )
19270        .unwrap();
19271        let right = DataFrame::from_dict(
19272            &["k1", "k2", "right_v"],
19273            vec![
19274                (
19275                    "k1",
19276                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
19277                ),
19278                (
19279                    "k2",
19280                    vec![
19281                        Scalar::Utf8("a".to_owned()),
19282                        Scalar::Utf8("a".to_owned()),
19283                        Scalar::Utf8("c".to_owned()),
19284                    ],
19285                ),
19286                (
19287                    "right_v",
19288                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
19289                ),
19290            ],
19291        )
19292        .unwrap();
19293
19294        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
19295        assert_eq!(merged.columns.get("k1").unwrap().len(), 4);
19296        assert_eq!(
19297            merged.columns.get("k1").unwrap().values(),
19298            &[
19299                Scalar::Int64(1),
19300                Scalar::Int64(1),
19301                Scalar::Int64(1),
19302                Scalar::Int64(1)
19303            ]
19304        );
19305        assert_eq!(
19306            merged.columns.get("k2").unwrap().values(),
19307            &[
19308                Scalar::Utf8("a".to_owned()),
19309                Scalar::Utf8("a".to_owned()),
19310                Scalar::Utf8("a".to_owned()),
19311                Scalar::Utf8("a".to_owned())
19312            ]
19313        );
19314        assert_eq!(
19315            merged.columns.get("left_v").unwrap().values(),
19316            &[
19317                Scalar::Int64(10),
19318                Scalar::Int64(10),
19319                Scalar::Int64(20),
19320                Scalar::Int64(20)
19321            ]
19322        );
19323        assert_eq!(
19324            merged.columns.get("right_v").unwrap().values(),
19325            &[
19326                Scalar::Int64(100),
19327                Scalar::Int64(200),
19328                Scalar::Int64(100),
19329                Scalar::Int64(200)
19330            ]
19331        );
19332    }
19333
19334    #[test]
19335    fn merge_composite_outer_sorts_join_keys_lexicographically() {
19336        let left = DataFrame::from_dict(
19337            &["k1", "k2", "left_v"],
19338            vec![
19339                ("k1", vec![Scalar::Int64(2), Scalar::Int64(1)]),
19340                (
19341                    "k2",
19342                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("x".to_owned())],
19343                ),
19344                ("left_v", vec![Scalar::Int64(20), Scalar::Int64(10)]),
19345            ],
19346        )
19347        .unwrap();
19348        let right = DataFrame::from_dict(
19349            &["k1", "k2", "right_v"],
19350            vec![
19351                ("k1", vec![Scalar::Int64(2), Scalar::Int64(3)]),
19352                (
19353                    "k2",
19354                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("z".to_owned())],
19355                ),
19356                ("right_v", vec![Scalar::Int64(200), Scalar::Int64(300)]),
19357            ],
19358        )
19359        .unwrap();
19360
19361        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
19362        assert_eq!(
19363            merged.columns.get("k1").unwrap().values(),
19364            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
19365        );
19366        assert_eq!(
19367            merged.columns.get("k2").unwrap().values(),
19368            &[
19369                Scalar::Utf8("x".to_owned()),
19370                Scalar::Utf8("y".to_owned()),
19371                Scalar::Utf8("z".to_owned())
19372            ]
19373        );
19374        assert_eq!(
19375            merged.columns.get("left_v").unwrap().values(),
19376            &[
19377                Scalar::Float64(10.0),
19378                Scalar::Float64(20.0),
19379                Scalar::Null(NullKind::NaN)
19380            ]
19381        );
19382        assert_eq!(
19383            merged.columns.get("right_v").unwrap().values(),
19384            &[
19385                Scalar::Null(NullKind::NaN),
19386                Scalar::Float64(200.0),
19387                Scalar::Float64(300.0)
19388            ]
19389        );
19390    }
19391
19392    #[test]
19393    fn merge_composite_outer_contiguous_utf8_key_coalesce_matches_scalar_route_blackthrush() {
19394        let contiguous_frame =
19395            |k1: &[&str], k2: &[&str], value_name: &str, values: &[i64]| -> DataFrame {
19396                let index = Index::new(
19397                    (0..k1.len())
19398                        .map(|row| IndexLabel::Int64(row as i64))
19399                        .collect(),
19400                );
19401                let mut columns = ColumnStore::new();
19402                columns.insert("k1".to_owned(), contiguous_utf8_column(k1));
19403                columns.insert("k2".to_owned(), contiguous_utf8_column(k2));
19404                columns.insert(
19405                    value_name.to_owned(),
19406                    Column::from_i64_values(values.to_vec()),
19407                );
19408                DataFrame::new_with_column_order(
19409                    index,
19410                    columns,
19411                    vec!["k1".to_owned(), "k2".to_owned(), value_name.to_owned()],
19412                )
19413                .expect("contiguous frame")
19414            };
19415        let scalar_frame =
19416            |k1: &[&str], k2: &[&str], value_name: &str, values: &[i64]| -> DataFrame {
19417                DataFrame::from_dict(
19418                    &["k1", "k2", value_name],
19419                    vec![
19420                        (
19421                            "k1",
19422                            k1.iter()
19423                                .map(|value| Scalar::Utf8((*value).to_owned()))
19424                                .collect(),
19425                        ),
19426                        (
19427                            "k2",
19428                            k2.iter()
19429                                .map(|value| Scalar::Utf8((*value).to_owned()))
19430                                .collect(),
19431                        ),
19432                        (
19433                            value_name,
19434                            values.iter().copied().map(Scalar::Int64).collect(),
19435                        ),
19436                    ],
19437                )
19438                .expect("scalar frame")
19439            };
19440
19441        let left_fast =
19442            contiguous_frame(&["b", "a", "c"], &["y", "x", "z"], "left_v", &[20, 10, 30]);
19443        let right_fast = contiguous_frame(&["b", "d"], &["y", "w"], "right_v", &[200, 400]);
19444        let left_scalar = scalar_frame(&["b", "a", "c"], &["y", "x", "z"], "left_v", &[20, 10, 30]);
19445        let right_scalar = scalar_frame(&["b", "d"], &["y", "w"], "right_v", &[200, 400]);
19446
19447        let fast =
19448            merge_dataframes_on(&left_fast, &right_fast, &["k1", "k2"], JoinType::Outer).unwrap();
19449        let scalar =
19450            merge_dataframes_on(&left_scalar, &right_scalar, &["k1", "k2"], JoinType::Outer)
19451                .unwrap();
19452
19453        for name in ["k1", "k2", "left_v", "right_v"] {
19454            assert_eq!(
19455                fast.columns.get(name).unwrap().values(),
19456                scalar.columns.get(name).unwrap().values(),
19457                "column {name}"
19458            );
19459        }
19460        assert!(
19461            fast.columns
19462                .get("k1")
19463                .unwrap()
19464                .as_utf8_contiguous()
19465                .is_some()
19466        );
19467        assert!(
19468            fast.columns
19469                .get("k2")
19470                .unwrap()
19471                .as_utf8_contiguous()
19472                .is_some()
19473        );
19474    }
19475
19476    #[test]
19477    fn merge_composite_inner_matches_missing_key_components() {
19478        let left = DataFrame::from_dict(
19479            &["k1", "k2", "left_v"],
19480            vec![
19481                ("k1", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19482                (
19483                    "k2",
19484                    vec![Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())],
19485                ),
19486                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19487            ],
19488        )
19489        .unwrap();
19490        let right = DataFrame::from_dict(
19491            &["k1", "k2", "right_v"],
19492            vec![
19493                (
19494                    "k1",
19495                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
19496                ),
19497                (
19498                    "k2",
19499                    vec![
19500                        Scalar::Null(NullKind::Null),
19501                        Scalar::Utf8("a".to_owned()),
19502                        Scalar::Null(NullKind::Null),
19503                    ],
19504                ),
19505                (
19506                    "right_v",
19507                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
19508                ),
19509            ],
19510        )
19511        .unwrap();
19512
19513        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
19514        assert_eq!(
19515            merged.columns.get("k1").unwrap().values(),
19516            &[Scalar::Int64(1), Scalar::Int64(1)]
19517        );
19518        assert_eq!(
19519            merged.columns.get("k2").unwrap().values(),
19520            &[Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())]
19521        );
19522        assert_eq!(
19523            merged.columns.get("left_v").unwrap().values(),
19524            &[Scalar::Int64(10), Scalar::Int64(20)]
19525        );
19526        assert_eq!(
19527            merged.columns.get("right_v").unwrap().values(),
19528            &[Scalar::Int64(100), Scalar::Int64(200)]
19529        );
19530    }
19531
19532    #[test]
19533    fn merge_composite_outer_keeps_right_only_rows_with_missing_keys() {
19534        let left = DataFrame::from_dict(
19535            &["k1", "k2", "left_v"],
19536            vec![
19537                ("k1", vec![Scalar::Int64(1)]),
19538                ("k2", vec![Scalar::Null(NullKind::Null)]),
19539                ("left_v", vec![Scalar::Int64(10)]),
19540            ],
19541        )
19542        .unwrap();
19543        let right = DataFrame::from_dict(
19544            &["k1", "k2", "right_v"],
19545            vec![
19546                ("k1", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19547                (
19548                    "k2",
19549                    vec![Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)],
19550                ),
19551                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19552            ],
19553        )
19554        .unwrap();
19555
19556        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
19557        assert_eq!(
19558            merged.columns.get("k1").unwrap().values(),
19559            &[Scalar::Int64(1), Scalar::Int64(2)]
19560        );
19561        assert_eq!(
19562            merged.columns.get("k2").unwrap().values(),
19563            &[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)]
19564        );
19565        assert_eq!(
19566            merged.columns.get("left_v").unwrap().values(),
19567            &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
19568        );
19569        assert_eq!(
19570            merged.columns.get("right_v").unwrap().values(),
19571            &[Scalar::Int64(100), Scalar::Int64(200)]
19572        );
19573    }
19574
19575    #[test]
19576    fn merge_composite_missing_key_column_errors() {
19577        let left = DataFrame::from_dict(
19578            &["k1", "k2", "left_v"],
19579            vec![
19580                ("k1", vec![Scalar::Int64(1)]),
19581                ("k2", vec![Scalar::Utf8("x".to_owned())]),
19582                ("left_v", vec![Scalar::Int64(10)]),
19583            ],
19584        )
19585        .unwrap();
19586        let right = DataFrame::from_dict(
19587            &["k1", "right_v"],
19588            vec![
19589                ("k1", vec![Scalar::Int64(1)]),
19590                ("right_v", vec![Scalar::Int64(100)]),
19591            ],
19592        )
19593        .unwrap();
19594
19595        let err = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner)
19596            .expect_err("should fail");
19597        assert!(format!("{err}").contains("right DataFrame missing key column 'k2'"));
19598    }
19599
19600    #[test]
19601    fn merge_composite_key_alias_inner_keeps_both_key_sets() {
19602        let left = DataFrame::from_dict(
19603            &["lk1", "lk2", "left_v"],
19604            vec![
19605                (
19606                    "lk1",
19607                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
19608                ),
19609                (
19610                    "lk2",
19611                    vec![
19612                        Scalar::Utf8("a".to_owned()),
19613                        Scalar::Utf8("b".to_owned()),
19614                        Scalar::Utf8("c".to_owned()),
19615                    ],
19616                ),
19617                (
19618                    "left_v",
19619                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
19620                ),
19621            ],
19622        )
19623        .unwrap();
19624        let right = DataFrame::from_dict(
19625            &["rk1", "rk2", "right_v"],
19626            vec![
19627                (
19628                    "rk1",
19629                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
19630                ),
19631                (
19632                    "rk2",
19633                    vec![
19634                        Scalar::Utf8("b".to_owned()),
19635                        Scalar::Utf8("c".to_owned()),
19636                        Scalar::Utf8("d".to_owned()),
19637                    ],
19638                ),
19639                (
19640                    "right_v",
19641                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
19642                ),
19643            ],
19644        )
19645        .unwrap();
19646
19647        let merged = merge_dataframes_on_with(
19648            &left,
19649            &right,
19650            &["lk1", "lk2"],
19651            &["rk1", "rk2"],
19652            JoinType::Inner,
19653        )
19654        .unwrap();
19655        assert_eq!(
19656            merged.columns.get("lk1").unwrap().values(),
19657            &[Scalar::Int64(2), Scalar::Int64(3)]
19658        );
19659        assert_eq!(
19660            merged.columns.get("lk2").unwrap().values(),
19661            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
19662        );
19663        assert_eq!(
19664            merged.columns.get("left_v").unwrap().values(),
19665            &[Scalar::Int64(20), Scalar::Int64(30)]
19666        );
19667        assert_eq!(
19668            merged.columns.get("rk1").unwrap().values(),
19669            &[Scalar::Int64(2), Scalar::Int64(3)]
19670        );
19671        assert_eq!(
19672            merged.columns.get("rk2").unwrap().values(),
19673            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
19674        );
19675        assert_eq!(
19676            merged.columns.get("right_v").unwrap().values(),
19677            &[Scalar::Int64(200), Scalar::Int64(300)]
19678        );
19679    }
19680
19681    #[test]
19682    fn merge_composite_key_alias_outer_propagates_missing_per_side() {
19683        let left = DataFrame::from_dict(
19684            &["lk1", "lk2", "left_v"],
19685            vec![
19686                (
19687                    "lk1",
19688                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
19689                ),
19690                (
19691                    "lk2",
19692                    vec![
19693                        Scalar::Utf8("a".to_owned()),
19694                        Scalar::Null(NullKind::Null),
19695                        Scalar::Utf8("c".to_owned()),
19696                    ],
19697                ),
19698                (
19699                    "left_v",
19700                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
19701                ),
19702            ],
19703        )
19704        .unwrap();
19705        let right = DataFrame::from_dict(
19706            &["rk1", "rk2", "right_v"],
19707            vec![
19708                (
19709                    "rk1",
19710                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
19711                ),
19712                (
19713                    "rk2",
19714                    vec![
19715                        Scalar::Utf8("a".to_owned()),
19716                        Scalar::Null(NullKind::Null),
19717                        Scalar::Utf8("d".to_owned()),
19718                    ],
19719                ),
19720                (
19721                    "right_v",
19722                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
19723                ),
19724            ],
19725        )
19726        .unwrap();
19727
19728        let merged = merge_dataframes_on_with(
19729            &left,
19730            &right,
19731            &["lk1", "lk2"],
19732            &["rk1", "rk2"],
19733            JoinType::Outer,
19734        )
19735        .unwrap();
19736
19737        assert_eq!(
19738            merged.columns.get("lk1").unwrap().values(),
19739            &[
19740                Scalar::Float64(1.0),
19741                Scalar::Float64(2.0),
19742                Scalar::Float64(3.0),
19743                Scalar::Null(NullKind::NaN)
19744            ]
19745        );
19746        assert_eq!(
19747            merged.columns.get("rk1").unwrap().values(),
19748            &[
19749                Scalar::Float64(1.0),
19750                Scalar::Float64(2.0),
19751                Scalar::Null(NullKind::NaN),
19752                Scalar::Float64(4.0)
19753            ]
19754        );
19755        assert_eq!(
19756            merged.columns.get("left_v").unwrap().values(),
19757            &[
19758                Scalar::Float64(10.0),
19759                Scalar::Float64(20.0),
19760                Scalar::Float64(30.0),
19761                Scalar::Null(NullKind::NaN)
19762            ]
19763        );
19764        assert_eq!(
19765            merged.columns.get("right_v").unwrap().values(),
19766            &[
19767                Scalar::Float64(100.0),
19768                Scalar::Float64(200.0),
19769                Scalar::Null(NullKind::NaN),
19770                Scalar::Float64(400.0)
19771            ]
19772        );
19773    }
19774
19775    #[test]
19776    fn merge_key_alias_lists_must_have_equal_lengths() {
19777        let left = make_left_df();
19778        let right = make_right_df();
19779        let err = merge_dataframes_on_with(&left, &right, &["id", "id"], &["id"], JoinType::Inner)
19780            .expect_err("should fail");
19781        assert!(format!("{err}").contains("equal length"));
19782    }
19783
19784    #[test]
19785    fn merge_indicator_default_name_tracks_row_provenance() {
19786        let left = make_left_df();
19787        let right = make_right_df();
19788
19789        let merged = merge_dataframes_on_with_options(
19790            &left,
19791            &right,
19792            &["id"],
19793            &["id"],
19794            JoinType::Outer,
19795            MergeExecutionOptions {
19796                indicator_name: Some("_merge".to_owned()),
19797                ..MergeExecutionOptions::default()
19798            },
19799        )
19800        .expect("merge");
19801
19802        let indicator = merged.columns.get("_merge").expect("indicator");
19803        assert_eq!(
19804            indicator.values(),
19805            &[
19806                Scalar::Utf8("left_only".to_owned()),
19807                Scalar::Utf8("both".to_owned()),
19808                Scalar::Utf8("both".to_owned()),
19809                Scalar::Utf8("right_only".to_owned())
19810            ]
19811        );
19812        // pandas 2.2.3: _merge is a category over the fixed [left_only,
19813        // right_only, both] (br-frankenpandas-hrxn9), not an object column.
19814        assert_eq!(indicator.dtype(), fp_types::DType::Categorical);
19815        assert_eq!(
19816            indicator.categorical().map(|meta| meta.categories.clone()),
19817            Some(
19818                ["left_only", "right_only", "both"]
19819                    .map(|c| Scalar::Utf8(c.to_owned()))
19820                    .to_vec()
19821            )
19822        );
19823    }
19824
19825    #[test]
19826    fn merge_indicator_custom_name_preserves_suffix_behavior() {
19827        let left = DataFrame::from_dict(
19828            &["id", "val"],
19829            vec![
19830                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19831                ("val", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19832            ],
19833        )
19834        .unwrap();
19835        let right = DataFrame::from_dict(
19836            &["id", "val"],
19837            vec![
19838                ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
19839                ("val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
19840            ],
19841        )
19842        .unwrap();
19843
19844        let merged = merge_dataframes_on_with_options(
19845            &left,
19846            &right,
19847            &["id"],
19848            &["id"],
19849            JoinType::Outer,
19850            MergeExecutionOptions {
19851                indicator_name: Some("origin".to_owned()),
19852                ..MergeExecutionOptions::default()
19853            },
19854        )
19855        .expect("merge");
19856
19857        assert!(merged.columns.contains_key("val_x"));
19858        assert!(merged.columns.contains_key("val_y"));
19859        assert_eq!(
19860            merged.columns.get("origin").expect("indicator").values(),
19861            &[
19862                Scalar::Utf8("left_only".to_owned()),
19863                Scalar::Utf8("both".to_owned()),
19864                Scalar::Utf8("right_only".to_owned())
19865            ]
19866        );
19867    }
19868
19869    #[test]
19870    fn merge_indicator_rejects_conflicting_column_name() {
19871        let left = make_left_df();
19872        let right = make_right_df();
19873
19874        let err = merge_dataframes_on_with_options(
19875            &left,
19876            &right,
19877            &["id"],
19878            &["id"],
19879            JoinType::Inner,
19880            MergeExecutionOptions {
19881                indicator_name: Some("id".to_owned()),
19882                ..MergeExecutionOptions::default()
19883            },
19884        )
19885        .expect_err("expected indicator name conflict");
19886        assert!(format!("{err}").contains("conflicts with an existing column"));
19887    }
19888
19889    #[test]
19890    fn merge_cross_indicator_marks_all_rows_both() {
19891        // Restored after br-frankenpandas-glsam revert: pandas 2.2.3
19892        // supports `how='cross', indicator=...` and emits "both" for every
19893        // cross-product row (verified against FP-P2D-039 fixture provenance
19894        // pandas_version=2.2.3). The Explore-agent claim that pandas raises
19895        // was incorrect; this test locks in the actual pandas behavior.
19896        let left = DataFrame::from_dict(
19897            &["l"],
19898            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
19899        )
19900        .unwrap();
19901        let right = DataFrame::from_dict(&["r"], vec![("r", vec![Scalar::Int64(9)])]).unwrap();
19902
19903        let merged = merge_dataframes_on_with_options(
19904            &left,
19905            &right,
19906            &["ignored"],
19907            &["ignored"],
19908            JoinType::Cross,
19909            MergeExecutionOptions {
19910                indicator_name: Some("_merge".to_owned()),
19911                ..MergeExecutionOptions::default()
19912            },
19913        )
19914        .expect("cross merge");
19915        assert_eq!(
19916            merged.columns.get("_merge").expect("indicator").values(),
19917            &[
19918                Scalar::Utf8("both".to_owned()),
19919                Scalar::Utf8("both".to_owned())
19920            ]
19921        );
19922    }
19923
19924    #[test]
19925    fn merge_cross_validate_mode_contract_ohb5f() {
19926        let left = DataFrame::from_dict(
19927            &["l"],
19928            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
19929        )
19930        .expect("left");
19931        let right = DataFrame::from_dict(
19932            &["r"],
19933            vec![("r", vec![Scalar::Int64(10), Scalar::Int64(20)])],
19934        )
19935        .expect("right");
19936
19937        let many_to_many = merge_dataframes_on_with_options(
19938            &left,
19939            &right,
19940            &["missing_left_key"],
19941            &["missing_right_key"],
19942            JoinType::Cross,
19943            MergeExecutionOptions {
19944                validate_mode: Some(MergeValidateMode::ManyToMany),
19945                ..MergeExecutionOptions::default()
19946            },
19947        )
19948        .expect("cross merge validate=many_to_many");
19949        assert_eq!(many_to_many.index.len(), 4);
19950
19951        for validate_mode in [
19952            MergeValidateMode::OneToOne,
19953            MergeValidateMode::OneToMany,
19954            MergeValidateMode::ManyToOne,
19955        ] {
19956            let err = merge_dataframes_on_with_options(
19957                &left,
19958                &right,
19959                &["missing_left_key"],
19960                &["missing_right_key"],
19961                JoinType::Cross,
19962                MergeExecutionOptions {
19963                    validate_mode: Some(validate_mode),
19964                    ..MergeExecutionOptions::default()
19965                },
19966            )
19967            .expect_err("enforcing validate modes are not meaningful for cross joins");
19968            let message = format!("{err}");
19969            assert!(message.contains(validate_mode.as_str()));
19970            assert!(message.contains("not supported for cross join"));
19971        }
19972    }
19973
19974    #[test]
19975    fn merge_validate_one_to_one_rejects_duplicate_left_keys() {
19976        let left = DataFrame::from_dict(
19977            &["id", "left_v"],
19978            vec![
19979                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19980                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19981            ],
19982        )
19983        .expect("left frame");
19984        let right = DataFrame::from_dict(
19985            &["id", "right_v"],
19986            vec![
19987                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19988                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19989            ],
19990        )
19991        .expect("right frame");
19992
19993        let err = merge_dataframes_on_with_options(
19994            &left,
19995            &right,
19996            &["id"],
19997            &["id"],
19998            JoinType::Inner,
19999            MergeExecutionOptions {
20000                validate_mode: Some(MergeValidateMode::OneToOne),
20001                ..MergeExecutionOptions::default()
20002            },
20003        )
20004        .expect_err("one_to_one must reject duplicate left keys");
20005        assert!(format!("{err}").contains("left keys are not unique"));
20006    }
20007
20008    #[test]
20009    fn repeated_non_key_columns_keep_their_own_data_through_merge_i17d4() {
20010        // pandas 2.2.3: merging a frame whose columns are ['a', 'a', 'k'] on
20011        // 'k' keeps both 'a' columns, each its own data (the first was read
20012        // for both); when the other side has an 'a' too, each copy takes its
20013        // side's suffix (a_x, a_x beside a_y).
20014        let f = Scalar::Float64;
20015        let column = |values: [f64; 2]| {
20016            Column::new(DType::Float64, values.iter().map(|v| f(*v)).collect()).expect("column")
20017        };
20018        let left = DataFrame::new_with_column_order(
20019            Index::new(vec![0_i64.into(), 1_i64.into()]),
20020            ColumnStore::from_pairs(vec![
20021                ("a".to_owned(), column([1.0, 4.0])),
20022                ("a".to_owned(), column([5.75, 2.25])),
20023                ("k".to_owned(), column([1.0, 2.0])),
20024            ]),
20025            vec!["a".to_owned(), "a".to_owned(), "k".to_owned()],
20026        )
20027        .expect("left frame");
20028        let right = |other: &str| {
20029            DataFrame::from_dict(
20030                &["k", other],
20031                vec![("k", vec![f(1.0), f(2.0)]), (other, vec![f(5.0), f(6.0)])],
20032            )
20033            .expect("right frame")
20034        };
20035        let merge = |right: &DataFrame| {
20036            merge_dataframes_on_with_options(
20037                &left,
20038                right,
20039                &["k"],
20040                &["k"],
20041                JoinType::Inner,
20042                MergeExecutionOptions::default(),
20043            )
20044            .expect("merge")
20045        };
20046        let merged = merge(&right("z"));
20047        assert_eq!(merged.column_order, vec!["a", "a", "k", "z"]);
20048        let second_a = merged.columns.get_all("a").nth(1).expect("second a");
20049        assert_eq!(second_a.values(), &[f(5.75), f(2.25)]);
20050
20051        let suffixed = merge(&right("a"));
20052        assert_eq!(suffixed.column_order, vec!["a_x", "a_x", "k", "a_y"]);
20053        let second_x = suffixed.columns.get_all("a_x").nth(1).expect("second a_x");
20054        assert_eq!(second_x.values(), &[f(5.75), f(2.25)]);
20055        let right_a = suffixed.columns.get("a_y").expect("a_y");
20056        assert_eq!(right_a.values(), &[f(5.0), f(6.0)]);
20057
20058        // NEGATIVE: unique keys merge under their own names, unsuffixed.
20059        let plain = merge_dataframes_on_with_options(
20060            &right("q"),
20061            &right("z"),
20062            &["k"],
20063            &["k"],
20064            JoinType::Inner,
20065            MergeExecutionOptions::default(),
20066        )
20067        .expect("plain merge");
20068        assert_eq!(plain.column_order, vec!["k", "q", "z"]);
20069    }
20070
20071    #[test]
20072    fn merge_validate_one_to_one_names_both_sides_when_both_duplicate_z6jxh() {
20073        let left = DataFrame::from_dict(
20074            &["id", "left_v"],
20075            vec![
20076                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20077                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20078            ],
20079        )
20080        .expect("left frame");
20081        let right = DataFrame::from_dict(
20082            &["id", "right_v"],
20083            vec![
20084                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20085                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20086            ],
20087        )
20088        .expect("right frame");
20089
20090        let err = merge_dataframes_on_with_options(
20091            &left,
20092            &right,
20093            &["id"],
20094            &["id"],
20095            JoinType::Inner,
20096            MergeExecutionOptions {
20097                validate_mode: Some(MergeValidateMode::OneToOne),
20098                ..MergeExecutionOptions::default()
20099            },
20100        )
20101        .expect_err("one_to_one must reject keys repeated on both sides");
20102        // pandas 2.2.3: 'Merge keys are not unique in either left or right
20103        // dataset' - both sides named, not the left first (z6jxh).
20104        assert!(format!("{err}").contains("left and right keys are not unique"));
20105
20106        // The composite-key path (text keys) answers alike; NEGATIVE: with
20107        // only the right side repeating, only the right is named.
20108        let text_keys = |values: [&str; 2]| {
20109            DataFrame::from_dict(
20110                &["id"],
20111                vec![(
20112                    "id",
20113                    values.iter().map(|v| Scalar::Utf8((*v).into())).collect(),
20114                )],
20115            )
20116            .expect("text-keyed frame")
20117        };
20118        let validate = |left: &DataFrame, right: &DataFrame| {
20119            merge_dataframes_on_with_options(
20120                left,
20121                right,
20122                &["id"],
20123                &["id"],
20124                JoinType::Inner,
20125                MergeExecutionOptions {
20126                    validate_mode: Some(MergeValidateMode::OneToOne),
20127                    ..MergeExecutionOptions::default()
20128                },
20129            )
20130            .expect_err("one_to_one must reject a repeated key")
20131            .to_string()
20132        };
20133        let both = validate(&text_keys(["a", "a"]), &text_keys(["a", "a"]));
20134        assert!(
20135            both.contains("left and right keys are not unique"),
20136            "{both}"
20137        );
20138        let right_only = validate(&text_keys(["a", "b"]), &text_keys(["a", "a"]));
20139        assert!(
20140            right_only.contains(": right keys are not unique"),
20141            "{right_only}"
20142        );
20143    }
20144
20145    #[test]
20146    fn merge_validate_one_to_many_allows_duplicate_right_keys() {
20147        let left = DataFrame::from_dict(
20148            &["id", "left_v"],
20149            vec![
20150                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20151                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20152            ],
20153        )
20154        .expect("left frame");
20155        let right = DataFrame::from_dict(
20156            &["id", "right_v"],
20157            vec![
20158                (
20159                    "id",
20160                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
20161                ),
20162                (
20163                    "right_v",
20164                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(200)],
20165                ),
20166            ],
20167        )
20168        .expect("right frame");
20169
20170        let merged = merge_dataframes_on_with_options(
20171            &left,
20172            &right,
20173            &["id"],
20174            &["id"],
20175            JoinType::Inner,
20176            MergeExecutionOptions {
20177                validate_mode: Some(MergeValidateMode::OneToMany),
20178                ..MergeExecutionOptions::default()
20179            },
20180        )
20181        .expect("one_to_many should allow duplicate right keys");
20182        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
20183    }
20184
20185    #[test]
20186    fn merge_validate_one_to_many_rejects_duplicate_left_keys_9hsb3() {
20187        let left = DataFrame::from_dict(
20188            &["id", "left_v"],
20189            vec![
20190                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20191                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20192            ],
20193        )
20194        .expect("left frame");
20195        let right = DataFrame::from_dict(
20196            &["id", "right_v"],
20197            vec![
20198                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20199                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20200            ],
20201        )
20202        .expect("right frame");
20203
20204        let err = merge_dataframes_on_with_options(
20205            &left,
20206            &right,
20207            &["id"],
20208            &["id"],
20209            JoinType::Inner,
20210            MergeExecutionOptions {
20211                validate_mode: Some(MergeValidateMode::OneToMany),
20212                ..MergeExecutionOptions::default()
20213            },
20214        )
20215        .expect_err("one_to_many must reject duplicate left keys");
20216        assert!(format!("{err}").contains("left keys are not unique"));
20217    }
20218
20219    #[test]
20220    fn merge_validate_many_to_one_rejects_duplicate_right_keys() {
20221        let left = DataFrame::from_dict(
20222            &["id", "left_v"],
20223            vec![
20224                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20225                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20226            ],
20227        )
20228        .expect("left frame");
20229        let right = DataFrame::from_dict(
20230            &["id", "right_v"],
20231            vec![
20232                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20233                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(101)]),
20234            ],
20235        )
20236        .expect("right frame");
20237
20238        let err = merge_dataframes_on_with_options(
20239            &left,
20240            &right,
20241            &["id"],
20242            &["id"],
20243            JoinType::Inner,
20244            MergeExecutionOptions {
20245                validate_mode: Some(MergeValidateMode::ManyToOne),
20246                ..MergeExecutionOptions::default()
20247            },
20248        )
20249        .expect_err("many_to_one must reject duplicate right keys");
20250        assert!(format!("{err}").contains("right keys are not unique"));
20251    }
20252
20253    #[test]
20254    fn merge_validate_many_to_one_allows_duplicate_left_keys_9hsb3() {
20255        let left = DataFrame::from_dict(
20256            &["id", "left_v"],
20257            vec![
20258                (
20259                    "id",
20260                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
20261                ),
20262                (
20263                    "left_v",
20264                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(20)],
20265                ),
20266            ],
20267        )
20268        .expect("left frame");
20269        let right = DataFrame::from_dict(
20270            &["id", "right_v"],
20271            vec![
20272                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20273                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20274            ],
20275        )
20276        .expect("right frame");
20277
20278        let merged = merge_dataframes_on_with_options(
20279            &left,
20280            &right,
20281            &["id"],
20282            &["id"],
20283            JoinType::Inner,
20284            MergeExecutionOptions {
20285                validate_mode: Some(MergeValidateMode::ManyToOne),
20286                ..MergeExecutionOptions::default()
20287            },
20288        )
20289        .expect("many_to_one should allow duplicate left keys");
20290        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
20291    }
20292
20293    #[test]
20294    fn merge_validate_many_to_many_allows_duplicates_on_both_sides() {
20295        let left = DataFrame::from_dict(
20296            &["id", "left_v"],
20297            vec![
20298                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20299                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20300            ],
20301        )
20302        .expect("left frame");
20303        let right = DataFrame::from_dict(
20304            &["id", "right_v"],
20305            vec![
20306                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20307                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20308            ],
20309        )
20310        .expect("right frame");
20311
20312        let merged = merge_dataframes_on_with_options(
20313            &left,
20314            &right,
20315            &["id"],
20316            &["id"],
20317            JoinType::Inner,
20318            MergeExecutionOptions {
20319                validate_mode: Some(MergeValidateMode::ManyToMany),
20320                ..MergeExecutionOptions::default()
20321            },
20322        )
20323        .expect("many_to_many should allow duplicate keys on both sides");
20324        assert_eq!(merged.columns.get("id").expect("id").values().len(), 4);
20325    }
20326
20327    #[test]
20328    fn join_series_cross_cartesian_product() {
20329        let left = Series::from_values(
20330            "left",
20331            vec!["a".into(), "b".into()],
20332            vec![Scalar::Int64(1), Scalar::Int64(2)],
20333        )
20334        .unwrap();
20335        let right = Series::from_values(
20336            "right",
20337            vec!["x".into(), "y".into()],
20338            vec![Scalar::Int64(10), Scalar::Int64(20)],
20339        )
20340        .unwrap();
20341
20342        let out = join_series(&left, &right, JoinType::Cross).unwrap();
20343        assert_eq!(out.index.labels().len(), 4);
20344        assert_eq!(
20345            out.left_values.values(),
20346            &[
20347                Scalar::Int64(1),
20348                Scalar::Int64(1),
20349                Scalar::Int64(2),
20350                Scalar::Int64(2)
20351            ]
20352        );
20353        assert_eq!(
20354            out.right_values.values(),
20355            &[
20356                Scalar::Int64(10),
20357                Scalar::Int64(20),
20358                Scalar::Int64(10),
20359                Scalar::Int64(20)
20360            ]
20361        );
20362    }
20363
20364    // ── DataFrameMergeExt trait tests ──
20365
20366    #[test]
20367    fn dataframe_merge_via_trait() {
20368        use fp_frame::DataFrame;
20369
20370        use super::{DataFrameMergeExt, merge_dataframes_on};
20371
20372        let left = DataFrame::from_series(vec![
20373            Series::from_values(
20374                "key",
20375                vec![0_i64.into(), 1_i64.into()],
20376                vec![Scalar::Int64(1), Scalar::Int64(2)],
20377            )
20378            .unwrap(),
20379            Series::from_values(
20380                "val_l",
20381                vec![0_i64.into(), 1_i64.into()],
20382                vec![Scalar::Int64(10), Scalar::Int64(20)],
20383            )
20384            .unwrap(),
20385        ])
20386        .unwrap();
20387
20388        let right = DataFrame::from_series(vec![
20389            Series::from_values(
20390                "key",
20391                vec![0_i64.into(), 1_i64.into()],
20392                vec![Scalar::Int64(1), Scalar::Int64(3)],
20393            )
20394            .unwrap(),
20395            Series::from_values(
20396                "val_r",
20397                vec![0_i64.into(), 1_i64.into()],
20398                vec![Scalar::Int64(100), Scalar::Int64(300)],
20399            )
20400            .unwrap(),
20401        ])
20402        .unwrap();
20403
20404        // Instance method
20405        let result = left.merge(&right, &["key"], JoinType::Inner).unwrap();
20406        assert_eq!(result.index.len(), 1); // only key=1 matches
20407
20408        // Standalone function should give same result
20409        let result2 = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner).unwrap();
20410        assert_eq!(result.index.len(), result2.index.len());
20411    }
20412
20413    // ── merge_asof tests ──
20414
20415    fn compute_asof_matches_datetime64_former_nsslz(
20416        left: super::Datetime64AsofKey<'_>,
20417        right: super::Datetime64AsofKey<'_>,
20418        direction: super::AsofDirection,
20419        allow_exact_matches: bool,
20420        tolerance: Option<f64>,
20421    ) -> Vec<Option<usize>> {
20422        let mut right_valid_values = Vec::new();
20423        let mut right_valid_positions = Vec::new();
20424        for i in 0..right.data.len() {
20425            if right.is_valid(i) {
20426                right_valid_values.push(right.data[i]);
20427                right_valid_positions.push(i);
20428            }
20429        }
20430        super::compute_asof_matches_datetime64_prepared(
20431            left,
20432            &right_valid_values,
20433            Some(&right_valid_positions),
20434            direction,
20435            allow_exact_matches,
20436            tolerance,
20437        )
20438    }
20439
20440    #[test]
20441    fn merge_asof_datetime64_borrowed_dense_right_matches_former_nsslz() {
20442        let dense_left = Column::from_datetime64_values_with_validity(
20443            vec![-15, -10, -5, 0, 5, 30, 35],
20444            ValidityMask::all_valid(7),
20445        );
20446        let dense_right = Column::from_datetime64_values_with_validity(
20447            vec![-10, 0, 10, 20, 30],
20448            ValidityMask::all_valid(5),
20449        );
20450
20451        let nat_right = Column::from_datetime64_values_with_validity(
20452            vec![fp_types::Timestamp::NAT, -10, 0, 20, 30],
20453            ValidityMask::all_valid(5),
20454        );
20455        let nat_left = Column::from_datetime64_values_with_validity(
20456            vec![fp_types::Timestamp::NAT, -10, -5, 0, 5, 30, 35],
20457            ValidityMask::all_valid(7),
20458        );
20459
20460        for (left, right) in [
20461            (&dense_left, &dense_right),
20462            (&dense_left, &nat_right),
20463            (&nat_left, &dense_right),
20464        ] {
20465            let left_key = super::datetime64_key_parts(left).expect("Datetime64 left key");
20466            let right_key = super::datetime64_key_parts(right).expect("Datetime64 right key");
20467            for direction in [
20468                super::AsofDirection::Backward,
20469                super::AsofDirection::Forward,
20470                super::AsofDirection::Nearest,
20471            ] {
20472                for allow_exact_matches in [false, true] {
20473                    for tolerance in [None, Some(7.0)] {
20474                        assert_eq!(
20475                            super::compute_asof_matches_datetime64(
20476                                left_key,
20477                                right_key,
20478                                direction,
20479                                allow_exact_matches,
20480                                tolerance,
20481                            ),
20482                            compute_asof_matches_datetime64_former_nsslz(
20483                                left_key,
20484                                right_key,
20485                                direction,
20486                                allow_exact_matches,
20487                                tolerance,
20488                            ),
20489                            "direction={direction:?} exact={allow_exact_matches} tolerance={tolerance:?}",
20490                        );
20491                    }
20492                }
20493            }
20494        }
20495    }
20496
20497    #[test]
20498    #[ignore = "foreground release A/B only"]
20499    fn datetime64_asof_borrowed_dense_right_ab_nsslz() {
20500        use std::{hint::black_box, time::Instant};
20501
20502        const ITEMS: usize = 131_072;
20503        const SAMPLES: usize = 10;
20504
20505        fn elapsed(run: impl FnOnce() -> Vec<Option<usize>>) -> u128 {
20506            let started = Instant::now();
20507            let output = black_box(run());
20508            black_box(output.len());
20509            let elapsed = started.elapsed().as_nanos();
20510            drop(output);
20511            elapsed
20512        }
20513
20514        let left = Column::from_datetime64_values_with_validity(
20515            (0..ITEMS).map(|i| i as i64 * 4 + 1).collect(),
20516            ValidityMask::all_valid(ITEMS),
20517        );
20518        let right = Column::from_datetime64_values_with_validity(
20519            (0..ITEMS).map(|i| i as i64 * 4).collect(),
20520            ValidityMask::all_valid(ITEMS),
20521        );
20522        let left_key = super::datetime64_key_parts(&left).expect("Datetime64 left key");
20523        let right_key = super::datetime64_key_parts(&right).expect("Datetime64 right key");
20524        let former = || {
20525            compute_asof_matches_datetime64_former_nsslz(
20526                left_key,
20527                right_key,
20528                super::AsofDirection::Backward,
20529                true,
20530                None,
20531            )
20532        };
20533        let candidate = || {
20534            super::compute_asof_matches_datetime64(
20535                left_key,
20536                right_key,
20537                super::AsofDirection::Backward,
20538                true,
20539                None,
20540            )
20541        };
20542
20543        assert_eq!(candidate(), former());
20544        black_box(former());
20545        black_box(candidate());
20546
20547        let mut former_ns = Vec::with_capacity(SAMPLES);
20548        let mut candidate_ns = Vec::with_capacity(SAMPLES);
20549        for sample in 0..SAMPLES {
20550            if sample.is_multiple_of(2) {
20551                former_ns.push(elapsed(former));
20552                candidate_ns.push(elapsed(candidate));
20553            } else {
20554                candidate_ns.push(elapsed(candidate));
20555                former_ns.push(elapsed(former));
20556            }
20557        }
20558        former_ns.sort_unstable();
20559        candidate_ns.sort_unstable();
20560        let former_p50 = former_ns[SAMPLES / 2];
20561        let candidate_p50 = candidate_ns[SAMPLES / 2];
20562        println!(
20563            "datetime64_asof_borrowed_dense_right_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}x",
20564            former_p50 as f64 / candidate_p50 as f64,
20565        );
20566        println!("former_samples_ns={former_ns:?}");
20567        println!("candidate_samples_ns={candidate_ns:?}");
20568    }
20569
20570    #[test]
20571    fn merge_asof_backward() {
20572        use super::DataFrameMergeExt;
20573
20574        // Left: trades at times 1, 3, 5, 7
20575        let left = fp_frame::DataFrame::from_dict(
20576            &["time", "price"],
20577            vec![
20578                (
20579                    "time",
20580                    vec![
20581                        Scalar::Int64(1),
20582                        Scalar::Int64(3),
20583                        Scalar::Int64(5),
20584                        Scalar::Int64(7),
20585                    ],
20586                ),
20587                (
20588                    "price",
20589                    vec![
20590                        Scalar::Float64(100.0),
20591                        Scalar::Float64(101.0),
20592                        Scalar::Float64(102.0),
20593                        Scalar::Float64(103.0),
20594                    ],
20595                ),
20596            ],
20597        )
20598        .unwrap();
20599
20600        // Right: quotes at times 2, 4, 6
20601        let right = fp_frame::DataFrame::from_dict(
20602            &["time", "bid"],
20603            vec![
20604                (
20605                    "time",
20606                    vec![Scalar::Int64(2), Scalar::Int64(4), Scalar::Int64(6)],
20607                ),
20608                (
20609                    "bid",
20610                    vec![
20611                        Scalar::Float64(99.5),
20612                        Scalar::Float64(100.5),
20613                        Scalar::Float64(101.5),
20614                    ],
20615                ),
20616            ],
20617        )
20618        .unwrap();
20619
20620        let result = left.merge_asof(&right, "time", "backward").unwrap();
20621        // For time=1: no right row <= 1, so bid=NaN
20622        // For time=3: last right row <= 3 is time=2 → bid=99.5
20623        // For time=5: last right row <= 5 is time=4 → bid=100.5
20624        // For time=7: last right row <= 7 is time=6 → bid=101.5
20625        let bid_col = result.columns.get("bid").unwrap();
20626        assert!(bid_col.values()[0].is_missing());
20627        assert_eq!(bid_col.values()[1], Scalar::Float64(99.5));
20628        assert_eq!(bid_col.values()[2], Scalar::Float64(100.5));
20629        assert_eq!(bid_col.values()[3], Scalar::Float64(101.5));
20630    }
20631
20632    /// A right column that gains an UNMATCHED row gains a gap, and an all-valid
20633    /// numpy int64 cannot hold one — pandas widens that column to float64,
20634    /// exactly as it does across the join family.
20635    ///
20636    /// Measured, live pandas 2.2.3:
20637    /// ```text
20638    ///   L = DataFrame({'time':[1,5,10], 'left_val':[10,50,100]})
20639    ///   R = DataFrame({'time':[2,6],    'right_val':[20,60]})
20640    ///   pd.merge_asof(L, R, on='time', direction='forward')
20641    ///     right_val -> [20.0, 60.0, NaN]  dtype float64
20642    ///     dtypes: time int64, left_val int64, right_val float64
20643    ///
20644    ///   L2 = DataFrame({'time':[1,5]}, ...); R2 = DataFrame({'time':[2,4]}, ...)
20645    ///   pd.merge_asof(L2, R2, on='time', direction='backward')
20646    ///     right_val -> [NaN, 40.0]        dtype float64
20647    ///
20648    ///   with every left row matched (times 3,7 against 2,4)
20649    ///     right_val -> [20, 40]           dtype int64
20650    /// ```
20651    /// The rule is PER COLUMN here — `time` and `left_val` gain no gap and stay
20652    /// int64 — unlike `Series.unstack`, where a gap widens the whole frame
20653    /// because it reshapes one block. Both fixtures on FP-P2D-056 pinned the
20654    /// present values as int64 beside the NaN, which is FrankenPandas' own
20655    /// pre-fix answer.
20656    #[test]
20657    fn merge_asof_unmatched_row_widens_that_column_to_float64() {
20658        use super::DataFrameMergeExt;
20659
20660        let int_frame = |name: &str, times: Vec<i64>, vals: Vec<i64>| {
20661            fp_frame::DataFrame::from_dict(
20662                &["time", name],
20663                vec![
20664                    (
20665                        "time",
20666                        times.into_iter().map(Scalar::Int64).collect::<Vec<_>>(),
20667                    ),
20668                    (
20669                        name,
20670                        vals.into_iter().map(Scalar::Int64).collect::<Vec<_>>(),
20671                    ),
20672                ],
20673            )
20674            .unwrap()
20675        };
20676
20677        let left = int_frame("left_val", vec![1, 5, 10], vec![10, 50, 100]);
20678        let right = int_frame("right_val", vec![2, 6], vec![20, 60]);
20679        let forward = left.merge_asof(&right, "time", "forward").unwrap();
20680        assert_eq!(
20681            forward.columns.get("right_val").unwrap().values(),
20682            &[
20683                Scalar::Float64(20.0),
20684                Scalar::Float64(60.0),
20685                Scalar::Null(NullKind::NaN),
20686            ]
20687        );
20688        // The columns that gain NO gap keep int64 — this is per column, not
20689        // frame-wide.
20690        assert_eq!(
20691            forward.columns.get("left_val").unwrap().values(),
20692            &[Scalar::Int64(10), Scalar::Int64(50), Scalar::Int64(100)]
20693        );
20694        assert_eq!(
20695            forward.columns.get("time").unwrap().dtype(),
20696            fp_types::DType::Int64
20697        );
20698
20699        let backward = int_frame("left_val", vec![1, 5], vec![10, 50])
20700            .merge_asof(
20701                &int_frame("right_val", vec![2, 4], vec![20, 40]),
20702                "time",
20703                "backward",
20704            )
20705            .unwrap();
20706        assert_eq!(
20707            backward.columns.get("right_val").unwrap().values(),
20708            &[Scalar::Null(NullKind::NaN), Scalar::Float64(40.0)]
20709        );
20710
20711        // The control that this is about the GAP and not about merge_asof always
20712        // widening: with every left row matched, right_val stays int64.
20713        let matched = int_frame("left_val", vec![3, 7], vec![10, 50])
20714            .merge_asof(
20715                &int_frame("right_val", vec![2, 4], vec![20, 40]),
20716                "time",
20717                "backward",
20718            )
20719            .unwrap();
20720        assert_eq!(
20721            matched.columns.get("right_val").unwrap().values(),
20722            &[Scalar::Int64(20), Scalar::Int64(40)]
20723        );
20724    }
20725
20726    #[test]
20727    fn merge_asof_forward() {
20728        use super::AsofDirection;
20729
20730        let left = fp_frame::DataFrame::from_dict(
20731            &["time", "val"],
20732            vec![
20733                ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
20734                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(30.0)]),
20735            ],
20736        )
20737        .unwrap();
20738
20739        let right = fp_frame::DataFrame::from_dict(
20740            &["time", "quote"],
20741            vec![
20742                ("time", vec![Scalar::Int64(2), Scalar::Int64(5)]),
20743                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(50.0)]),
20744            ],
20745        )
20746        .unwrap();
20747
20748        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
20749        // time=1: first right >= 1 is time=2 → quote=20
20750        // time=3: first right >= 3 is time=5 → quote=50
20751        let quote_col = result.columns.get("quote").unwrap();
20752        assert_eq!(quote_col.values()[0], Scalar::Float64(20.0));
20753        assert_eq!(quote_col.values()[1], Scalar::Float64(50.0));
20754    }
20755
20756    #[test]
20757    fn merge_asof_nearest() {
20758        use super::AsofDirection;
20759
20760        let left = fp_frame::DataFrame::from_dict(
20761            &["time", "val"],
20762            vec![
20763                ("time", vec![Scalar::Int64(3), Scalar::Int64(7)]),
20764                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
20765            ],
20766        )
20767        .unwrap();
20768
20769        let right = fp_frame::DataFrame::from_dict(
20770            &["time", "ref_val"],
20771            vec![
20772                (
20773                    "time",
20774                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
20775                ),
20776                (
20777                    "ref_val",
20778                    vec![
20779                        Scalar::Float64(100.0),
20780                        Scalar::Float64(500.0),
20781                        Scalar::Float64(1000.0),
20782                    ],
20783                ),
20784            ],
20785        )
20786        .unwrap();
20787
20788        let result = super::merge_asof(&left, &right, "time", AsofDirection::Nearest).unwrap();
20789        // time=3: nearest is 1(dist=2) or 5(dist=2), first found = 1 → ref_val=100
20790        // Actually: for nearest, it finds the one with smallest dist. dist(3,1)=2, dist(3,5)=2
20791        // ties go to first found, so ref_val = 100
20792        // time=7: nearest is 5(dist=2) or 10(dist=3) → ref_val=500
20793        let ref_col = result.columns.get("ref_val").unwrap();
20794        assert_eq!(ref_col.values()[1], Scalar::Float64(500.0)); // time=7 → 5 is nearest
20795    }
20796
20797    #[test]
20798    fn merge_asof_nearest_excludes_exact_finds_neighbor() {
20799        // Regression: with direction=nearest and allow_exact_matches=false,
20800        // an exact-equal key must be skipped over to reach the nearest
20801        // non-equal key, rather than yielding no match. Verified against
20802        // pandas 2.2.3: merge_asof(left=5, right=[3,5,5], nearest,
20803        // allow_exact_matches=False) -> matches value 3.
20804        use super::{AsofDirection, MergeAsofOptions};
20805
20806        let left = fp_frame::DataFrame::from_dict(
20807            &["time", "val"],
20808            vec![
20809                ("time", vec![Scalar::Int64(5)]),
20810                ("val", vec![Scalar::Int64(1)]),
20811            ],
20812        )
20813        .unwrap();
20814        let right = fp_frame::DataFrame::from_dict(
20815            &["time", "ref_val"],
20816            vec![
20817                (
20818                    "time",
20819                    vec![Scalar::Int64(3), Scalar::Int64(5), Scalar::Int64(5)],
20820                ),
20821                (
20822                    "ref_val",
20823                    vec![
20824                        Scalar::Float64(10.0),
20825                        Scalar::Float64(20.0),
20826                        Scalar::Float64(30.0),
20827                    ],
20828                ),
20829            ],
20830        )
20831        .unwrap();
20832
20833        let opts = MergeAsofOptions::new().allow_exact_matches(false);
20834        let result =
20835            super::merge_asof_with_options(&left, &right, "time", AsofDirection::Nearest, opts)
20836                .unwrap();
20837        let ref_col = result.columns.get("ref_val").unwrap();
20838        assert_eq!(ref_col.values()[0], Scalar::Float64(10.0)); // value 3 is nearest non-exact
20839    }
20840
20841    #[test]
20842    fn merge_asof_exact_match() {
20843        use super::AsofDirection;
20844
20845        let left = fp_frame::DataFrame::from_dict(
20846            &["time", "val"],
20847            vec![
20848                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
20849                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
20850            ],
20851        )
20852        .unwrap();
20853
20854        let right = fp_frame::DataFrame::from_dict(
20855            &["time", "quote"],
20856            vec![
20857                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
20858                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(40.0)]),
20859            ],
20860        )
20861        .unwrap();
20862
20863        // Backward: exact match should work (right_val <= left_val includes ==).
20864        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20865        assert_eq!(
20866            result.columns.get("quote").unwrap().values()[0],
20867            Scalar::Float64(20.0)
20868        );
20869        assert_eq!(
20870            result.columns.get("quote").unwrap().values()[1],
20871            Scalar::Float64(40.0)
20872        );
20873
20874        // Forward: exact match should work (right_val >= left_val includes ==).
20875        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
20876        assert_eq!(
20877            result.columns.get("quote").unwrap().values()[0],
20878            Scalar::Float64(20.0)
20879        );
20880    }
20881
20882    #[test]
20883    fn merge_asof_datetime64_wide_ns_range_uses_i64_path() {
20884        use super::AsofDirection;
20885
20886        let day_ns = 86_400_000_000_000i64;
20887        let base = 1_600_000_000_000_000_000i64;
20888        let dt = |days: i64| Scalar::Datetime64(base + days * day_ns);
20889
20890        let left = fp_frame::DataFrame::from_dict(
20891            &["time", "val"],
20892            vec![
20893                ("time", vec![dt(0), dt(200), dt(400)]),
20894                (
20895                    "val",
20896                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
20897                ),
20898            ],
20899        )
20900        .unwrap();
20901
20902        let right = fp_frame::DataFrame::from_dict(
20903            &["time", "quote"],
20904            vec![
20905                ("time", vec![dt(-1), dt(199), dt(401)]),
20906                (
20907                    "quote",
20908                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
20909                ),
20910            ],
20911        )
20912        .unwrap();
20913
20914        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20915        let quote_col = result.columns.get("quote").unwrap();
20916        assert_eq!(quote_col.values()[0], Scalar::Int64(10));
20917        assert_eq!(quote_col.values()[1], Scalar::Int64(20));
20918        assert_eq!(quote_col.values()[2], Scalar::Int64(20));
20919    }
20920
20921    #[test]
20922    fn merge_asof_no_matches_backward() {
20923        use super::AsofDirection;
20924
20925        let left = fp_frame::DataFrame::from_dict(
20926            &["time", "val"],
20927            vec![
20928                ("time", vec![Scalar::Int64(1)]),
20929                ("val", vec![Scalar::Float64(10.0)]),
20930            ],
20931        )
20932        .unwrap();
20933
20934        // Right starts at time=5, so backward from time=1 finds nothing.
20935        let right = fp_frame::DataFrame::from_dict(
20936            &["time", "quote"],
20937            vec![
20938                ("time", vec![Scalar::Int64(5)]),
20939                ("quote", vec![Scalar::Float64(50.0)]),
20940            ],
20941        )
20942        .unwrap();
20943
20944        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20945        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
20946    }
20947
20948    #[test]
20949    fn merge_asof_no_matches_forward() {
20950        use super::AsofDirection;
20951
20952        let left = fp_frame::DataFrame::from_dict(
20953            &["time", "val"],
20954            vec![
20955                ("time", vec![Scalar::Int64(10)]),
20956                ("val", vec![Scalar::Float64(10.0)]),
20957            ],
20958        )
20959        .unwrap();
20960
20961        // Right ends at time=5, so forward from time=10 finds nothing.
20962        let right = fp_frame::DataFrame::from_dict(
20963            &["time", "quote"],
20964            vec![
20965                ("time", vec![Scalar::Int64(5)]),
20966                ("quote", vec![Scalar::Float64(50.0)]),
20967            ],
20968        )
20969        .unwrap();
20970
20971        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
20972        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
20973    }
20974
20975    #[test]
20976    fn merge_asof_nan_in_key() {
20977        use super::AsofDirection;
20978
20979        let left = fp_frame::DataFrame::from_dict(
20980            &["time", "val"],
20981            vec![
20982                (
20983                    "time",
20984                    vec![
20985                        Scalar::Int64(1),
20986                        Scalar::Null(NullKind::NaN),
20987                        Scalar::Int64(5),
20988                    ],
20989                ),
20990                (
20991                    "val",
20992                    vec![
20993                        Scalar::Float64(10.0),
20994                        Scalar::Float64(20.0),
20995                        Scalar::Float64(30.0),
20996                    ],
20997                ),
20998            ],
20999        )
21000        .unwrap();
21001
21002        let right = fp_frame::DataFrame::from_dict(
21003            &["time", "quote"],
21004            vec![
21005                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
21006                (
21007                    "quote",
21008                    vec![Scalar::Float64(200.0), Scalar::Float64(400.0)],
21009                ),
21010            ],
21011        )
21012        .unwrap();
21013
21014        // With matching key dtypes, pandas merge_asof accepts NaN keys: the
21015        // NaN row gets no match (null in joined columns).
21016        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
21017        assert!(result.columns.get("quote").unwrap().values()[1].is_missing());
21018        // time=5 → backward match to time=4 → quote=400
21019        assert_eq!(
21020            result.columns.get("quote").unwrap().values()[2],
21021            Scalar::Float64(400.0)
21022        );
21023    }
21024
21025    #[test]
21026    fn merge_asof_rejects_incompatible_key_dtypes_sopel() {
21027        use super::{AsofDirection, MergeAsofOptions};
21028
21029        // pandas 2.2.3: a NaN makes the left `time` column float64, and
21030        // `merge_asof` refuses it against an int64 right key rather than
21031        // coercing both to a common numeric lane.
21032        let left = fp_frame::DataFrame::from_dict(
21033            &["time", "left_val", "group"],
21034            vec![
21035                (
21036                    "time",
21037                    vec![
21038                        Scalar::Float64(1.0),
21039                        Scalar::Null(NullKind::NaN),
21040                        Scalar::Float64(4.0),
21041                    ],
21042                ),
21043                (
21044                    "left_val",
21045                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
21046                ),
21047                (
21048                    "group",
21049                    vec![
21050                        Scalar::Utf8("a".into()),
21051                        Scalar::Utf8("a".into()),
21052                        Scalar::Utf8("a".into()),
21053                    ],
21054                ),
21055            ],
21056        )
21057        .unwrap();
21058        let right = fp_frame::DataFrame::from_dict(
21059            &["time", "right_val", "group"],
21060            vec![
21061                ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
21062                ("right_val", vec![Scalar::Int64(100), Scalar::Int64(300)]),
21063                (
21064                    "group",
21065                    vec![Scalar::Utf8("a".into()), Scalar::Utf8("a".into())],
21066                ),
21067            ],
21068        )
21069        .unwrap();
21070
21071        for options in [
21072            MergeAsofOptions::new(),
21073            MergeAsofOptions::new().by(vec!["group".to_owned()]),
21074        ] {
21075            let error = super::merge_asof_with_options(
21076                &left,
21077                &right,
21078                "time",
21079                AsofDirection::Backward,
21080                options,
21081            )
21082            .expect_err("mixed float64/int64 asof keys must be rejected");
21083            assert!(matches!(
21084                error,
21085                super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
21086                    if message.contains("incompatible merge keys")
21087                        && message.contains("float64")
21088                        && message.contains("int64")
21089            ));
21090        }
21091
21092        // This is the fixture-shaped representation: the null marker makes
21093        // the left lane nullable Int64, while the all-valid right lane stays
21094        // numpy int64. pandas rejects that pair as incompatible too.
21095        let mut nullable_columns = ColumnStore::new();
21096        nullable_columns.insert(
21097            "time".to_owned(),
21098            Column::new(
21099                DType::Int64Nullable,
21100                vec![
21101                    Scalar::Int64(1),
21102                    Scalar::Null(NullKind::NaN),
21103                    Scalar::Int64(4),
21104                ],
21105            )
21106            .unwrap(),
21107        );
21108        nullable_columns.insert(
21109            "left_val".to_owned(),
21110            Column::from_i64_values(vec![10, 20, 30]),
21111        );
21112        let nullable_left = fp_frame::DataFrame::new_with_column_order(
21113            Index::new_known_unique_int64_unit_range(0, 3),
21114            nullable_columns,
21115            vec!["time".to_owned(), "left_val".to_owned()],
21116        )
21117        .unwrap();
21118        let error = super::merge_asof(&nullable_left, &right, "time", AsofDirection::Backward)
21119            .expect_err("nullable Int64 and int64 asof keys must be rejected");
21120        assert!(matches!(
21121            error,
21122            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
21123                if message.contains("incompatible merge keys")
21124                    && message.contains("left dtype('Int64')")
21125                    && message.contains("right dtype('int64')")
21126        ));
21127    }
21128
21129    #[test]
21130    fn merge_asof_nan_in_right_key() {
21131        use super::AsofDirection;
21132
21133        // Symmetric to merge_asof_nan_in_key: NaN keys on the right side
21134        // also get treated as no-candidate (pandas does NOT raise). Other
21135        // left rows still match to non-NaN right rows.
21136        let left = fp_frame::DataFrame::from_dict(
21137            &["time", "val"],
21138            vec![
21139                (
21140                    "time",
21141                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(5)],
21142                ),
21143                (
21144                    "val",
21145                    vec![
21146                        Scalar::Float64(10.0),
21147                        Scalar::Float64(20.0),
21148                        Scalar::Float64(30.0),
21149                    ],
21150                ),
21151            ],
21152        )
21153        .unwrap();
21154
21155        let right = fp_frame::DataFrame::from_dict(
21156            &["time", "quote"],
21157            vec![
21158                (
21159                    "time",
21160                    vec![
21161                        Scalar::Int64(2),
21162                        Scalar::Null(NullKind::NaN),
21163                        Scalar::Int64(4),
21164                    ],
21165                ),
21166                (
21167                    "quote",
21168                    vec![
21169                        Scalar::Float64(200.0),
21170                        Scalar::Float64(999.0),
21171                        Scalar::Float64(400.0),
21172                    ],
21173                ),
21174            ],
21175        )
21176        .unwrap();
21177
21178        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
21179        // left time=1 → no right ≤ 1 → null
21180        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
21181        // left time=3 → right time=2 → 200.0 (NaN right row never matches)
21182        assert_eq!(
21183            result.columns.get("quote").unwrap().values()[1],
21184            Scalar::Float64(200.0)
21185        );
21186        // left time=5 → right time=4 → 400.0
21187        assert_eq!(
21188            result.columns.get("quote").unwrap().values()[2],
21189            Scalar::Float64(400.0)
21190        );
21191    }
21192
21193    #[test]
21194    fn merge_asof_overlapping_columns_apply_suffixes() {
21195        use super::AsofDirection;
21196
21197        let left = fp_frame::DataFrame::from_dict(
21198            &["time", "shared", "left_only"],
21199            vec![
21200                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
21201                ("shared", vec![Scalar::Int64(10), Scalar::Int64(20)]),
21202                ("left_only", vec![Scalar::Int64(1), Scalar::Int64(2)]),
21203            ],
21204        )
21205        .unwrap();
21206
21207        let right = fp_frame::DataFrame::from_dict(
21208            &["time", "shared", "right_only"],
21209            vec![
21210                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
21211                ("shared", vec![Scalar::Int64(100), Scalar::Int64(200)]),
21212                ("right_only", vec![Scalar::Int64(9), Scalar::Int64(8)]),
21213            ],
21214        )
21215        .unwrap();
21216
21217        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
21218        let shared_left = result.columns.get("shared_x").unwrap().values();
21219        let shared_right = result.columns.get("shared_y").unwrap().values();
21220
21221        assert_eq!(shared_left[0], Scalar::Int64(10));
21222        assert_eq!(shared_left[1], Scalar::Int64(20));
21223        assert_eq!(shared_right[0], Scalar::Int64(100));
21224        assert_eq!(shared_right[1], Scalar::Int64(200));
21225    }
21226
21227    #[test]
21228    fn merge_asof_duplicate_column_gets_suffix() {
21229        use super::AsofDirection;
21230
21231        // Both left and right have a "val" column besides the key.
21232        let left = fp_frame::DataFrame::from_dict(
21233            &["time", "val"],
21234            vec![
21235                ("time", vec![Scalar::Int64(1)]),
21236                ("val", vec![Scalar::Float64(10.0)]),
21237            ],
21238        )
21239        .unwrap();
21240
21241        let right = fp_frame::DataFrame::from_dict(
21242            &["time", "val"],
21243            vec![
21244                ("time", vec![Scalar::Int64(1)]),
21245                ("val", vec![Scalar::Float64(99.0)]),
21246            ],
21247        )
21248        .unwrap();
21249
21250        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
21251        // Overlapping columns should receive default merge suffixes.
21252        assert!(result.columns.contains_key("val_x"));
21253        assert!(result.columns.contains_key("val_y"));
21254        assert_eq!(
21255            result.columns.get("val_x").unwrap().values()[0],
21256            Scalar::Float64(10.0)
21257        );
21258        assert_eq!(
21259            result.columns.get("val_y").unwrap().values()[0],
21260            Scalar::Float64(99.0)
21261        );
21262    }
21263
21264    #[test]
21265    fn merge_asof_missing_column_errors() {
21266        use super::AsofDirection;
21267
21268        let left =
21269            fp_frame::DataFrame::from_dict(&["a"], vec![("a", vec![Scalar::Int64(1)])]).unwrap();
21270
21271        let right =
21272            fp_frame::DataFrame::from_dict(&["b"], vec![("b", vec![Scalar::Int64(1)])]).unwrap();
21273
21274        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward);
21275        assert!(err.is_err());
21276    }
21277
21278    #[test]
21279    fn merge_asof_invalid_direction_errors() {
21280        let left =
21281            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
21282                .unwrap();
21283        let right =
21284            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
21285                .unwrap();
21286
21287        let err = left.merge_asof(&right, "time", "sideways");
21288        assert!(matches!(
21289            err,
21290            Err(super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg)))
21291                if msg.contains("invalid direction")
21292        ));
21293    }
21294
21295    #[test]
21296    fn merge_asof_unsorted_left_errors() {
21297        use super::AsofDirection;
21298
21299        let left = fp_frame::DataFrame::from_dict(
21300            &["time", "val"],
21301            vec![
21302                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
21303                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
21304            ],
21305        )
21306        .unwrap();
21307
21308        let right = fp_frame::DataFrame::from_dict(
21309            &["time", "quote"],
21310            vec![
21311                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
21312                (
21313                    "quote",
21314                    vec![Scalar::Float64(100.0), Scalar::Float64(200.0)],
21315                ),
21316            ],
21317        )
21318        .unwrap();
21319
21320        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
21321            .expect_err("unsorted left should error");
21322        assert!(matches!(
21323            err,
21324            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
21325                if msg.contains("sorted")
21326        ));
21327    }
21328
21329    #[test]
21330    fn merge_asof_unsorted_right_errors() {
21331        use super::AsofDirection;
21332
21333        let left = fp_frame::DataFrame::from_dict(
21334            &["time", "val"],
21335            vec![
21336                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
21337                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
21338            ],
21339        )
21340        .unwrap();
21341
21342        let right = fp_frame::DataFrame::from_dict(
21343            &["time", "quote"],
21344            vec![
21345                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
21346                (
21347                    "quote",
21348                    vec![Scalar::Float64(200.0), Scalar::Float64(100.0)],
21349                ),
21350            ],
21351        )
21352        .unwrap();
21353
21354        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
21355            .expect_err("unsorted right should error");
21356        assert!(matches!(
21357            err,
21358            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
21359                if msg.contains("sorted")
21360        ));
21361    }
21362
21363    #[test]
21364    fn merge_asof_non_numeric_key_errors() {
21365        use super::AsofDirection;
21366
21367        let left = fp_frame::DataFrame::from_dict(
21368            &["time", "val"],
21369            vec![
21370                ("time", vec![Scalar::Utf8("a".into())]),
21371                ("val", vec![Scalar::Float64(10.0)]),
21372            ],
21373        )
21374        .unwrap();
21375
21376        let right = fp_frame::DataFrame::from_dict(
21377            &["time", "quote"],
21378            vec![
21379                ("time", vec![Scalar::Utf8("b".into())]),
21380                ("quote", vec![Scalar::Float64(20.0)]),
21381            ],
21382        )
21383        .unwrap();
21384
21385        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
21386            .expect_err("non-numeric key should error");
21387        assert!(matches!(
21388            err,
21389            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
21390                if msg.contains("numeric")
21391        ));
21392    }
21393
21394    #[test]
21395    fn merge_asof_preserves_all_left_rows() {
21396        use super::AsofDirection;
21397
21398        let left = fp_frame::DataFrame::from_dict(
21399            &["time", "val"],
21400            vec![
21401                (
21402                    "time",
21403                    vec![
21404                        Scalar::Int64(1),
21405                        Scalar::Int64(2),
21406                        Scalar::Int64(3),
21407                        Scalar::Int64(4),
21408                        Scalar::Int64(5),
21409                    ],
21410                ),
21411                (
21412                    "val",
21413                    vec![
21414                        Scalar::Float64(10.0),
21415                        Scalar::Float64(20.0),
21416                        Scalar::Float64(30.0),
21417                        Scalar::Float64(40.0),
21418                        Scalar::Float64(50.0),
21419                    ],
21420                ),
21421            ],
21422        )
21423        .unwrap();
21424
21425        let right = fp_frame::DataFrame::from_dict(
21426            &["time", "quote"],
21427            vec![
21428                ("time", vec![Scalar::Int64(3)]),
21429                ("quote", vec![Scalar::Float64(300.0)]),
21430            ],
21431        )
21432        .unwrap();
21433
21434        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
21435        // All 5 left rows should be present.
21436        assert_eq!(result.index.len(), 5);
21437    }
21438
21439    // ── merge_asof options tests ──
21440
21441    #[test]
21442    fn merge_asof_allow_exact_matches_false_backward() {
21443        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
21444
21445        // Left: keys 1, 2, 3
21446        let left = fp_frame::DataFrame::from_dict(
21447            &["time", "val"],
21448            vec![
21449                (
21450                    "time",
21451                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
21452                ),
21453                (
21454                    "val",
21455                    vec![
21456                        Scalar::Float64(10.0),
21457                        Scalar::Float64(20.0),
21458                        Scalar::Float64(30.0),
21459                    ],
21460                ),
21461            ],
21462        )
21463        .unwrap();
21464
21465        // Right: keys 1, 2, 3 (exact matches exist)
21466        let right = fp_frame::DataFrame::from_dict(
21467            &["time", "quote"],
21468            vec![
21469                (
21470                    "time",
21471                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
21472                ),
21473                (
21474                    "quote",
21475                    vec![
21476                        Scalar::Float64(100.0),
21477                        Scalar::Float64(200.0),
21478                        Scalar::Float64(300.0),
21479                    ],
21480                ),
21481            ],
21482        )
21483        .unwrap();
21484
21485        // With allow_exact_matches=true (default), all should match
21486        let result_with_exact = merge_asof_with_options(
21487            &left,
21488            &right,
21489            "time",
21490            AsofDirection::Backward,
21491            MergeAsofOptions::new(),
21492        )
21493        .unwrap();
21494
21495        let quote_col = result_with_exact.columns.get("quote").unwrap();
21496        assert_eq!(quote_col.values()[0], Scalar::Float64(100.0)); // 1 matches 1
21497        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0)); // 2 matches 2
21498        assert_eq!(quote_col.values()[2], Scalar::Float64(300.0)); // 3 matches 3
21499
21500        // With allow_exact_matches=false, exact matches should be excluded
21501        let result_no_exact = merge_asof_with_options(
21502            &left,
21503            &right,
21504            "time",
21505            AsofDirection::Backward,
21506            MergeAsofOptions::new().allow_exact_matches(false),
21507        )
21508        .unwrap();
21509
21510        let quote_col_no_exact = result_no_exact.columns.get("quote").unwrap();
21511        // 1 has no previous right key, should be null
21512        assert!(matches!(quote_col_no_exact.values()[0], Scalar::Null(_)));
21513        // 2 should match previous (1)
21514        assert_eq!(quote_col_no_exact.values()[1], Scalar::Float64(100.0));
21515        // 3 should match previous (2)
21516        assert_eq!(quote_col_no_exact.values()[2], Scalar::Float64(200.0));
21517    }
21518
21519    #[test]
21520    fn merge_asof_tolerance() {
21521        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
21522
21523        // Left: keys 1, 5, 10
21524        let left = fp_frame::DataFrame::from_dict(
21525            &["time", "val"],
21526            vec![
21527                (
21528                    "time",
21529                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
21530                ),
21531                (
21532                    "val",
21533                    vec![
21534                        Scalar::Float64(10.0),
21535                        Scalar::Float64(50.0),
21536                        Scalar::Float64(100.0),
21537                    ],
21538                ),
21539            ],
21540        )
21541        .unwrap();
21542
21543        // Right: keys 2, 6
21544        let right = fp_frame::DataFrame::from_dict(
21545            &["time", "quote"],
21546            vec![
21547                ("time", vec![Scalar::Int64(2), Scalar::Int64(6)]),
21548                (
21549                    "quote",
21550                    vec![Scalar::Float64(200.0), Scalar::Float64(600.0)],
21551                ),
21552            ],
21553        )
21554        .unwrap();
21555
21556        // With tolerance=2, matches within 2 units are valid
21557        let result = merge_asof_with_options(
21558            &left,
21559            &right,
21560            "time",
21561            AsofDirection::Backward,
21562            MergeAsofOptions::new().tolerance(2.0),
21563        )
21564        .unwrap();
21565
21566        let quote_col = result.columns.get("quote").unwrap();
21567        // 1 < 2, no previous match, null
21568        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
21569        // 5 finds 2 (diff = 3), but tolerance is 2, so null
21570        assert!(matches!(quote_col.values()[1], Scalar::Null(_)));
21571        // 10 finds 6 (diff = 4), but tolerance is 2, so null
21572        assert!(matches!(quote_col.values()[2], Scalar::Null(_)));
21573
21574        // With tolerance=5, all should match
21575        let result_wider = merge_asof_with_options(
21576            &left,
21577            &right,
21578            "time",
21579            AsofDirection::Backward,
21580            MergeAsofOptions::new().tolerance(5.0),
21581        )
21582        .unwrap();
21583
21584        let quote_col_wider = result_wider.columns.get("quote").unwrap();
21585        // 1 < 2, still no previous
21586        assert!(matches!(quote_col_wider.values()[0], Scalar::Null(_)));
21587        // 5 finds 2 (diff = 3 <= 5)
21588        assert_eq!(quote_col_wider.values()[1], Scalar::Float64(200.0));
21589        // 10 finds 6 (diff = 4 <= 5)
21590        assert_eq!(quote_col_wider.values()[2], Scalar::Float64(600.0));
21591    }
21592
21593    #[test]
21594    fn merge_asof_by_column() {
21595        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
21596
21597        // Left: two groups (A and B), each with times
21598        let left = fp_frame::DataFrame::from_dict(
21599            &["group", "time", "val"],
21600            vec![
21601                (
21602                    "group",
21603                    vec![
21604                        Scalar::Utf8("A".into()),
21605                        Scalar::Utf8("A".into()),
21606                        Scalar::Utf8("B".into()),
21607                        Scalar::Utf8("B".into()),
21608                    ],
21609                ),
21610                (
21611                    "time",
21612                    vec![
21613                        Scalar::Int64(1),
21614                        Scalar::Int64(2),
21615                        Scalar::Int64(3),
21616                        Scalar::Int64(4),
21617                    ],
21618                ),
21619                (
21620                    "val",
21621                    vec![
21622                        Scalar::Float64(10.0),
21623                        Scalar::Float64(30.0),
21624                        Scalar::Float64(20.0),
21625                        Scalar::Float64(40.0),
21626                    ],
21627                ),
21628            ],
21629        )
21630        .unwrap();
21631
21632        // Right: same groups with quotes
21633        let right = fp_frame::DataFrame::from_dict(
21634            &["group", "time", "quote"],
21635            vec![
21636                (
21637                    "group",
21638                    vec![
21639                        Scalar::Utf8("A".into()),
21640                        Scalar::Utf8("B".into()),
21641                        Scalar::Utf8("A".into()),
21642                    ],
21643                ),
21644                (
21645                    "time",
21646                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
21647                ),
21648                (
21649                    "quote",
21650                    vec![
21651                        Scalar::Float64(200.0),
21652                        Scalar::Float64(400.0),
21653                        Scalar::Float64(300.0),
21654                    ],
21655                ),
21656            ],
21657        )
21658        .unwrap();
21659
21660        // Merge with 'by' column
21661        let result = merge_asof_with_options(
21662            &left,
21663            &right,
21664            "time",
21665            AsofDirection::Backward,
21666            MergeAsofOptions::new().by(vec!["group".to_string()]),
21667        )
21668        .unwrap();
21669
21670        let quote_col = result.columns.get("quote").unwrap();
21671        // Left after 2d3338b1's reorder is (A,1), (A,2), (B,3), (B,4) — globally
21672        // sorted by time. Right is (A,2), (B,3), (A,4). Backward grouped asof:
21673        // Row 0: (A,1) → no right A with time <= 1 → null
21674        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
21675        // Row 1: (A,2) → right A time=2 → 200.0
21676        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0));
21677        // Row 2: (B,3) → right B time=3 → 400.0
21678        assert_eq!(quote_col.values()[2], Scalar::Float64(400.0));
21679        // Row 3: (B,4) → right B time=3 (latest <= 4) → 400.0
21680        assert_eq!(quote_col.values()[3], Scalar::Float64(400.0));
21681    }
21682
21683    #[test]
21684    fn merge_asof_by_column_requires_globally_sorted_left_keys() {
21685        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
21686
21687        let left = fp_frame::DataFrame::from_dict(
21688            &["group", "time"],
21689            vec![
21690                (
21691                    "group",
21692                    vec![
21693                        Scalar::Utf8("A".into()),
21694                        Scalar::Utf8("A".into()),
21695                        Scalar::Utf8("B".into()),
21696                        Scalar::Utf8("B".into()),
21697                    ],
21698                ),
21699                (
21700                    "time",
21701                    vec![
21702                        Scalar::Int64(1),
21703                        Scalar::Int64(3),
21704                        Scalar::Int64(1),
21705                        Scalar::Int64(2),
21706                    ],
21707                ),
21708            ],
21709        )
21710        .unwrap();
21711        let right = fp_frame::DataFrame::from_dict(
21712            &["group", "time", "quote"],
21713            vec![
21714                (
21715                    "group",
21716                    vec![
21717                        Scalar::Utf8("A".into()),
21718                        Scalar::Utf8("B".into()),
21719                        Scalar::Utf8("A".into()),
21720                    ],
21721                ),
21722                (
21723                    "time",
21724                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
21725                ),
21726                (
21727                    "quote",
21728                    vec![
21729                        Scalar::Float64(10.0),
21730                        Scalar::Float64(20.0),
21731                        Scalar::Float64(30.0),
21732                    ],
21733                ),
21734            ],
21735        )
21736        .unwrap();
21737
21738        let err = merge_asof_with_options(
21739            &left,
21740            &right,
21741            "time",
21742            AsofDirection::Backward,
21743            MergeAsofOptions::new().by(vec!["group".to_string()]),
21744        )
21745        .expect_err("pandas requires globally sorted left keys even with by=");
21746        assert!(matches!(
21747            err,
21748            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
21749                if message.contains("left") && message.contains("sorted")
21750        ));
21751    }
21752
21753    #[test]
21754    fn merge_asof_by_column_requires_globally_sorted_right_keys() {
21755        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
21756
21757        let left = fp_frame::DataFrame::from_dict(
21758            &["group", "time"],
21759            vec![
21760                (
21761                    "group",
21762                    vec![
21763                        Scalar::Utf8("A".into()),
21764                        Scalar::Utf8("B".into()),
21765                        Scalar::Utf8("A".into()),
21766                    ],
21767                ),
21768                (
21769                    "time",
21770                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
21771                ),
21772            ],
21773        )
21774        .unwrap();
21775        let right = fp_frame::DataFrame::from_dict(
21776            &["group", "time", "quote"],
21777            vec![
21778                (
21779                    "group",
21780                    vec![
21781                        Scalar::Utf8("A".into()),
21782                        Scalar::Utf8("A".into()),
21783                        Scalar::Utf8("B".into()),
21784                    ],
21785                ),
21786                (
21787                    "time",
21788                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(2)],
21789                ),
21790                (
21791                    "quote",
21792                    vec![
21793                        Scalar::Float64(10.0),
21794                        Scalar::Float64(30.0),
21795                        Scalar::Float64(20.0),
21796                    ],
21797                ),
21798            ],
21799        )
21800        .unwrap();
21801
21802        let err = merge_asof_with_options(
21803            &left,
21804            &right,
21805            "time",
21806            AsofDirection::Backward,
21807            MergeAsofOptions::new().by(vec!["group".to_string()]),
21808        )
21809        .expect_err("pandas requires globally sorted right keys even with by=");
21810        assert!(matches!(
21811            err,
21812            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
21813                if message.contains("right") && message.contains("sorted")
21814        ));
21815    }
21816
21817    #[test]
21818    fn merge_ordered_sorts_and_ffills_values() {
21819        let left = fp_frame::DataFrame::from_dict(
21820            &["date", "left_val"],
21821            vec![
21822                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
21823                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
21824            ],
21825        )
21826        .unwrap();
21827
21828        let right = fp_frame::DataFrame::from_dict(
21829            &["date", "right_val"],
21830            vec![
21831                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
21832                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
21833            ],
21834        )
21835        .unwrap();
21836
21837        let result = super::merge_ordered(&left, &right, &["date"], Some("ffill")).unwrap();
21838        let frame = fp_frame::DataFrame::new(result.index, result.columns).unwrap();
21839
21840        assert_eq!(
21841            frame.column("date").unwrap().values(),
21842            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
21843        );
21844        // TEST-CHANGE (hayfo): left_val is int64, as live pandas 2.2.3's
21845        // (it asserted the float64 the value fill left behind).
21846        assert_eq!(
21847            frame.column("left_val").unwrap().values(),
21848            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(30)]
21849        );
21850        // NEGATIVE: a leading gap stays NaN, so the column stays float64.
21851        assert_eq!(
21852            frame.column("right_val").unwrap().values(),
21853            &[
21854                Scalar::Null(NullKind::NaN),
21855                Scalar::Float64(200.0),
21856                Scalar::Float64(300.0),
21857            ]
21858        );
21859    }
21860
21861    /// A filled bool column stays bool, a suffixed overlap its side's int64
21862    /// (live pandas 2.2.3: v bool, s_x int64, s_y float64).
21863    #[test]
21864    fn merge_ordered_ffill_keeps_each_sides_dtype() {
21865        let left = fp_frame::DataFrame::from_dict(
21866            &["k", "v", "s"],
21867            vec![
21868                ("k", vec![Scalar::Int64(1), Scalar::Int64(3)]),
21869                ("v", vec![Scalar::Bool(true), Scalar::Bool(false)]),
21870                ("s", vec![Scalar::Int64(1), Scalar::Int64(2)]),
21871            ],
21872        )
21873        .unwrap();
21874        let right = fp_frame::DataFrame::from_dict(
21875            &["k", "s"],
21876            vec![
21877                ("k", vec![Scalar::Int64(2), Scalar::Int64(3)]),
21878                ("s", vec![Scalar::Int64(5), Scalar::Int64(6)]),
21879            ],
21880        )
21881        .unwrap();
21882        let result = super::merge_ordered(&left, &right, &["k"], Some("ffill")).unwrap();
21883        let frame = fp_frame::DataFrame::new(result.index, result.columns).unwrap();
21884        assert_eq!(
21885            frame.column("v").unwrap().values(),
21886            &[Scalar::Bool(true), Scalar::Bool(true), Scalar::Bool(false)]
21887        );
21888        assert_eq!(
21889            frame.column("s_x").unwrap().values(),
21890            &[Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)]
21891        );
21892        assert_eq!(frame.column("s_y").unwrap().dtype(), DType::Float64);
21893    }
21894
21895    #[test]
21896    fn merge_ordered_invalid_fill_method_errors() {
21897        let left = fp_frame::DataFrame::from_dict(
21898            &["date", "left_val"],
21899            vec![
21900                ("date", vec![Scalar::Int64(1)]),
21901                ("left_val", vec![Scalar::Int64(10)]),
21902            ],
21903        )
21904        .unwrap();
21905
21906        let right = fp_frame::DataFrame::from_dict(
21907            &["date", "right_val"],
21908            vec![
21909                ("date", vec![Scalar::Int64(2)]),
21910                ("right_val", vec![Scalar::Int64(200)]),
21911            ],
21912        )
21913        .unwrap();
21914
21915        let err = super::merge_ordered(&left, &right, &["date"], Some("sideways"))
21916            .expect_err("invalid fill method should error");
21917        assert!(matches!(
21918            err,
21919            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
21920                if message.contains("fill_method must be 'ffill' or None")
21921        ));
21922    }
21923
21924    #[test]
21925    fn merge_ordered_rejects_bfill_like_pandas() {
21926        let left = fp_frame::DataFrame::from_dict(
21927            &["date", "left_val"],
21928            vec![
21929                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
21930                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
21931            ],
21932        )
21933        .unwrap();
21934
21935        let right = fp_frame::DataFrame::from_dict(
21936            &["date", "right_val"],
21937            vec![
21938                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
21939                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
21940            ],
21941        )
21942        .unwrap();
21943
21944        let err = super::merge_ordered(&left, &right, &["date"], Some("bfill"))
21945            .expect_err("pandas only accepts fill_method='ffill' or None");
21946        assert!(matches!(
21947            err,
21948            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
21949                if message.contains("fill_method must be 'ffill' or None")
21950        ));
21951    }
21952
21953    // ── join() pandas-named alias (br-frankenpandas-nk54a) ──────────────
21954
21955    #[test]
21956    fn dataframe_join_aliases_join_on_index() {
21957        use std::collections::BTreeMap;
21958
21959        use fp_columnar::Column;
21960        use fp_frame::DataFrame;
21961        use fp_index::Index;
21962        use fp_types::{DType, Scalar};
21963
21964        use super::DataFrameMergeExt;
21965
21966        fn build(name1: &str, name2: &str, vals1: &[i64], vals2: &[i64]) -> DataFrame {
21967            let mut cols = BTreeMap::new();
21968            cols.insert(
21969                name1.to_owned(),
21970                Column::new(
21971                    DType::Int64,
21972                    vals1.iter().map(|v| Scalar::Int64(*v)).collect(),
21973                )
21974                .unwrap(),
21975            );
21976            cols.insert(
21977                name2.to_owned(),
21978                Column::new(
21979                    DType::Int64,
21980                    vals2.iter().map(|v| Scalar::Int64(*v)).collect(),
21981                )
21982                .unwrap(),
21983            );
21984            DataFrame::new_with_column_order(
21985                Index::new(
21986                    (0..vals1.len() as i64)
21987                        .map(fp_index::IndexLabel::Int64)
21988                        .collect(),
21989                ),
21990                cols,
21991                vec![name1.to_owned(), name2.to_owned()],
21992            )
21993            .unwrap()
21994        }
21995
21996        let left = build("a", "b", &[10, 20, 30], &[1, 2, 3]);
21997        let right = build("c", "d", &[100, 200, 300], &[7, 8, 9]);
21998
21999        let via_join = left.join(&right, super::JoinType::Inner).unwrap();
22000        let via_join_on_index = left.join_on_index(&right, super::JoinType::Inner).unwrap();
22001
22002        // Both produce the same MergedDataFrame shape & values.
22003        let join_keys: Vec<&String> = via_join.columns.keys().collect();
22004        let idx_keys: Vec<&String> = via_join_on_index.columns.keys().collect();
22005        assert_eq!(join_keys, idx_keys);
22006        assert_eq!(via_join.index, via_join_on_index.index);
22007        for k in via_join.columns.keys() {
22008            assert_eq!(
22009                via_join.columns.get(k).unwrap().values(),
22010                via_join_on_index.columns.get(k).unwrap().values(),
22011                "column {k} differs"
22012            );
22013        }
22014    }
22015
22016    /// The branch-free ordered outer merge answers the three-way merge's
22017    /// positions - interleaved, equal and disjoint keys, either side
22018    /// exhausted first, an empty side (br-frankenpandas-m3z4g). NEGATIVE:
22019    /// a key that is not strictly increasing takes no ordered merge.
22020    #[test]
22021    fn ordered_outer_positions_match_the_three_way_merge_m3z4g() {
22022        type Positions = (Vec<Option<usize>>, Vec<Option<usize>>);
22023        let reference = |left: &[i64], right: &[i64]| -> Positions {
22024            let (mut l, mut r) = (0, 0);
22025            let (mut out_left, mut out_right) = (Vec::new(), Vec::new());
22026            while l < left.len() || r < right.len() {
22027                let take_left = r == right.len() || (l < left.len() && left[l] <= right[r]);
22028                let take_right = l == left.len() || (r < right.len() && right[r] <= left[l]);
22029                out_left.push(take_left.then_some(l));
22030                out_right.push(take_right.then_some(r));
22031                l += usize::from(take_left);
22032                r += usize::from(take_right);
22033            }
22034            (out_left, out_right)
22035        };
22036        let twos: Vec<i64> = (0..40).map(|k| k * 2).collect();
22037        let threes: Vec<i64> = (0..40).map(|k| k * 3).collect();
22038        let late: Vec<i64> = (100..110).collect();
22039        let cases: [(&[i64], &[i64]); 6] = [
22040            (&twos, &threes),
22041            (&threes, &twos),
22042            (&twos, &twos),
22043            (&twos, &late),
22044            (&late, &twos),
22045            (&twos, &[]),
22046        ];
22047        for (left, right) in cases {
22048            let got = ordered_unique_int64_outer_positions(
22049                &Column::from_i64_values(left.to_vec()),
22050                &Column::from_i64_values(right.to_vec()),
22051            );
22052            assert_eq!(got, Some(reference(left, right)), "{left:?} {right:?}");
22053        }
22054        let repeated = Column::from_i64_values(vec![1, 2, 2, 3]);
22055        assert!(
22056            ordered_unique_int64_outer_positions(&repeated, &Column::from_i64_values(vec![1]))
22057                .is_none()
22058        );
22059    }
22060}
22061
22062#[cfg(test)]
22063mod typed_validate_cardinality_uza04 {
22064    //! `validate=` must stop costing the whole fast-path family.
22065    //!
22066    //! br-frankenpandas-uza04. `validate_merge_cardinality` lives in exactly
22067    //! one place — the generic `collect_composite_keys` branch — so
22068    //! `validate_mode_allows_fast_positions` returned false for every enforcing
22069    //! mode purely to route execution there. Asking for a cardinality guarantee
22070    //! therefore disabled `dense_packed_int64_inner_positions`, the typed
22071    //! two-key and multi-key position paths, and the single-key inner/left
22072    //! shortcuts, and additionally built a `Vec<CompositeJoinKey>` off
22073    //! `column.values()[row]` on both sides.
22074    //!
22075    //! `typed_validate_merge_cardinality` settles the common shape (one
22076    //! all-valid Int64 key) off the raw buffer, so a PASSING validation lets
22077    //! the merge take the same path it would have taken with no `validate=`.
22078    //! These tests pin the two things that has to preserve: the rejections, and
22079    //! the output.
22080
22081    use fp_columnar::Column;
22082    use fp_frame::DataFrame;
22083    use fp_index::Index;
22084    use fp_types::{NullKind, Scalar};
22085
22086    use super::{
22087        JoinType, MergeExecutionOptions, MergeValidateMode, merge_dataframes_on_with_options,
22088        typed_single_int64_key_has_duplicates,
22089    };
22090
22091    fn int_frame(name: &str, keys: Vec<i64>, payload: Vec<i64>) -> DataFrame {
22092        let index = Index::new_known_unique_int64_unit_range(0, keys.len());
22093        DataFrame::new_with_column_order(
22094            index,
22095            std::collections::BTreeMap::from([
22096                ("id".to_owned(), Column::from_i64_values(keys)),
22097                (name.to_owned(), Column::from_i64_values(payload)),
22098            ]),
22099            vec!["id".to_owned(), name.to_owned()],
22100        )
22101        .expect("typed int frame")
22102    }
22103
22104    fn merge(
22105        left: &DataFrame,
22106        right: &DataFrame,
22107        validate: Option<MergeValidateMode>,
22108    ) -> Result<super::MergedDataFrame, super::JoinError> {
22109        merge_dataframes_on_with_options(
22110            left,
22111            right,
22112            &["id"],
22113            &["id"],
22114            JoinType::Inner,
22115            MergeExecutionOptions {
22116                validate_mode: validate,
22117                ..MergeExecutionOptions::default()
22118            },
22119        )
22120    }
22121
22122    /// THE DUPLICATE-KEY NEGATIVE CASE. The typed checker is now what rejects a
22123    /// non-unique left key under `one_to_many`, so it has to reject with the
22124    /// same message the generic checker produced — a caller cannot tell which
22125    /// one ran.
22126    #[test]
22127    fn duplicate_left_keys_still_reject_under_one_to_many_uza04() {
22128        let left = int_frame("left_v", vec![1, 2, 2, 3], vec![10, 20, 21, 30]);
22129        let right = int_frame("right_v", vec![1, 2, 3], vec![100, 200, 300]);
22130        let error = merge(&left, &right, Some(MergeValidateMode::OneToMany))
22131            .expect_err("duplicate left keys must be rejected");
22132        assert!(
22133            format!("{error}")
22134                .contains("merge validate='one_to_many' failed: left keys are not unique"),
22135            "message must match the generic checker exactly, got: {error}"
22136        );
22137    }
22138
22139    #[test]
22140    fn duplicate_right_keys_still_reject_under_many_to_one_uza04() {
22141        let left = int_frame("left_v", vec![1, 2, 3], vec![10, 20, 30]);
22142        let right = int_frame("right_v", vec![1, 2, 2], vec![100, 200, 201]);
22143        let error = merge(&left, &right, Some(MergeValidateMode::ManyToOne))
22144            .expect_err("duplicate right keys must be rejected");
22145        assert!(
22146            format!("{error}")
22147                .contains("merge validate='many_to_one' failed: right keys are not unique"),
22148            "message must match the generic checker exactly, got: {error}"
22149        );
22150    }
22151
22152    /// PRECEDENCE. With BOTH sides duplicated under `one_to_one`, pandas —
22153    /// and the generic checker — name BOTH sides ('not unique in either left
22154    /// or right dataset'; this pinned a left-first report pandas 2.2.3 does
22155    /// not make, z6jxh). The typed checker must not answer from whichever
22156    /// side it happened to inspect first.
22157    #[test]
22158    fn one_to_one_names_both_sides_when_both_repeat_uza04() {
22159        let left = int_frame("left_v", vec![1, 1, 2], vec![10, 11, 20]);
22160        let right = int_frame("right_v", vec![1, 1, 2], vec![100, 101, 200]);
22161        let error = merge(&left, &right, Some(MergeValidateMode::OneToOne))
22162            .expect_err("both sides duplicated must be rejected");
22163        let message = format!("{error}");
22164        assert!(
22165            message.contains("left and right keys are not unique"),
22166            "both sides must be named, got: {message}"
22167        );
22168    }
22169
22170    #[test]
22171    fn one_to_one_still_catches_a_right_only_duplicate_uza04() {
22172        let left = int_frame("left_v", vec![1, 2, 3], vec![10, 20, 30]);
22173        let right = int_frame("right_v", vec![1, 2, 2], vec![100, 200, 201]);
22174        let error = merge(&left, &right, Some(MergeValidateMode::OneToOne))
22175            .expect_err("right duplicate must be rejected");
22176        assert!(
22177            format!("{error}")
22178                .contains("merge validate='one_to_one' failed: right keys are not unique"),
22179            "got: {error}"
22180        );
22181    }
22182
22183    /// THE SAFETY PROPERTY OF THE WHOLE LEVER: a validation that PASSES must
22184    /// leave the merge output byte-identical to the unvalidated merge, because
22185    /// it now takes the same fast path. If enabling those paths changed row
22186    /// order, pairing, or column content, this is what catches it.
22187    #[test]
22188    fn a_passing_validation_produces_the_unvalidated_output_uza04() {
22189        let left = int_frame("left_v", vec![5, 1, 4, 2, 3], vec![50, 10, 40, 20, 30]);
22190        let right = int_frame("right_v", vec![3, 1, 2, 9], vec![300, 100, 200, 900]);
22191
22192        let unvalidated = merge(&left, &right, None).expect("plain merge");
22193        for mode in [
22194            MergeValidateMode::OneToOne,
22195            MergeValidateMode::OneToMany,
22196            MergeValidateMode::ManyToOne,
22197            MergeValidateMode::ManyToMany,
22198        ] {
22199            let validated = merge(&left, &right, Some(mode)).expect("validation should pass");
22200            assert_eq!(
22201                validated.index.len(),
22202                unvalidated.index.len(),
22203                "{mode:?}: row count changed"
22204            );
22205            assert_eq!(
22206                validated.column_order, unvalidated.column_order,
22207                "{mode:?}: column order changed"
22208            );
22209            for name in ["id", "left_v", "right_v"] {
22210                assert_eq!(
22211                    validated.columns.get(name).expect("column").values(),
22212                    unvalidated.columns.get(name).expect("column").values(),
22213                    "{mode:?}: column {name} differs from the unvalidated merge"
22214                );
22215            }
22216        }
22217    }
22218
22219    /// NON-VACUITY, both directions. Every assertion above would still pass if
22220    /// the typed checker declined everything and the generic path did all the
22221    /// work — the lever would simply not exist.
22222    #[test]
22223    fn the_typed_checker_fires_on_typed_keys_and_declines_otherwise_uza04() {
22224        let unique = Column::from_i64_values(vec![1, 2, 3]);
22225        assert_eq!(
22226            typed_single_int64_key_has_duplicates(&[&unique]),
22227            Some(false),
22228            "an all-valid Int64 key must be answered typed"
22229        );
22230        let duplicated = Column::from_i64_values(vec![1, 2, 2]);
22231        assert_eq!(
22232            typed_single_int64_key_has_duplicates(&[&duplicated]),
22233            Some(true),
22234            "and duplicates must be seen"
22235        );
22236
22237        // A key with a missing value has no contiguous all-valid buffer, so the
22238        // typed checker declines and null-key duplicate semantics stay owned by
22239        // the generic path.
22240        let nullable = Column::from_values(vec![
22241            Scalar::Int64(1),
22242            Scalar::Null(NullKind::Null),
22243            Scalar::Int64(3),
22244        ])
22245        .expect("nullable int column");
22246        assert_eq!(
22247            typed_single_int64_key_has_duplicates(&[&nullable]),
22248            None,
22249            "a nullable key must decline"
22250        );
22251
22252        // Utf8 keys decline too (this lever is Int64-only for now).
22253        let text = Column::from_values(vec![
22254            Scalar::Utf8("a".to_owned()),
22255            Scalar::Utf8("b".to_owned()),
22256        ])
22257        .expect("utf8 column");
22258        assert_eq!(
22259            typed_single_int64_key_has_duplicates(&[&text]),
22260            None,
22261            "a Utf8 key must decline"
22262        );
22263
22264        // Multi-key merges decline: the composite question is not this one.
22265        assert_eq!(
22266            typed_single_int64_key_has_duplicates(&[&unique, &duplicated]),
22267            None,
22268            "more than one key column must decline"
22269        );
22270    }
22271
22272    /// A shape the typed checker DECLINES must still be validated — the generic
22273    /// path has to keep running for it. A nullable left key with a repeated
22274    /// value under `one_to_many` is the case that would silently start passing
22275    /// if the skip flag were set too broadly.
22276    #[test]
22277    fn a_declined_shape_is_still_validated_by_the_generic_path_uza04() {
22278        let index = Index::new_known_unique_int64_unit_range(0, 3);
22279        let left = DataFrame::new_with_column_order(
22280            index,
22281            std::collections::BTreeMap::from([
22282                (
22283                    "id".to_owned(),
22284                    Column::from_values(vec![
22285                        Scalar::Int64(1),
22286                        Scalar::Int64(1),
22287                        Scalar::Null(NullKind::Null),
22288                    ])
22289                    .expect("nullable id column"),
22290                ),
22291                (
22292                    "left_v".to_owned(),
22293                    Column::from_i64_values(vec![10, 11, 30]),
22294                ),
22295            ]),
22296            vec!["id".to_owned(), "left_v".to_owned()],
22297        )
22298        .expect("nullable left frame");
22299        let right = int_frame("right_v", vec![1, 2, 3], vec![100, 200, 300]);
22300
22301        let error = merge(&left, &right, Some(MergeValidateMode::OneToMany))
22302            .expect_err("a duplicated nullable left key must still be rejected");
22303        assert!(
22304            format!("{error}").contains("left keys are not unique"),
22305            "the generic checker must still own declined shapes, got: {error}"
22306        );
22307    }
22308
22309    #[test]
22310    fn merge_suffix_collision_preserves_duplicate_columns() {
22311        let left = fp_frame::DataFrame::from_dict_with_index(
22312            vec![
22313                ("key", vec![Scalar::Int64(1)]),
22314                ("a", vec![Scalar::Int64(10)]),
22315                ("a_y", vec![Scalar::Int64(20)]),
22316            ],
22317            vec![0_i64.into()],
22318        )
22319        .unwrap();
22320
22321        let right = fp_frame::DataFrame::from_dict_with_index(
22322            vec![
22323                ("key", vec![Scalar::Int64(1)]),
22324                ("a", vec![Scalar::Int64(30)]),
22325            ],
22326            vec![0_i64.into()],
22327        )
22328        .unwrap();
22329
22330        let options = MergeExecutionOptions {
22331            suffixes: Some([Some("_x".to_string()), Some("_y".to_string())]),
22332            ..MergeExecutionOptions::default()
22333        };
22334
22335        let merged = merge_dataframes_on_with_options(
22336            &left,
22337            &right,
22338            &["key"],
22339            &["key"],
22340            JoinType::Inner,
22341            options,
22342        )
22343        .expect("merge with suffix collision should succeed and produce duplicate columns");
22344
22345        assert_eq!(
22346            merged.column_order,
22347            vec![
22348                "key".to_string(),
22349                "a_x".to_string(),
22350                "a_y".to_string(),
22351                "a_y".to_string()
22352            ]
22353        );
22354        assert_eq!(merged.columns.occurrences("a_y"), 2);
22355        assert_eq!(
22356            merged.columns.column_at(2).unwrap().values(),
22357            &[Scalar::Int64(20)]
22358        );
22359        assert_eq!(
22360            merged.columns.column_at(3).unwrap().values(),
22361            &[Scalar::Int64(30)]
22362        );
22363    }
22364
22365    #[test]
22366    fn merge_suffixes_intra_frame_duplicate_rejected() {
22367        // Left side collision: left has val and val_L, suffix _L produces duplicate val_L
22368        let left = fp_frame::DataFrame::from_dict_with_index(
22369            vec![
22370                ("id", vec![Scalar::Int64(1)]),
22371                ("val", vec![Scalar::Int64(10)]),
22372                ("val_L", vec![Scalar::Int64(77)]),
22373            ],
22374            vec![0_i64.into()],
22375        )
22376        .unwrap();
22377
22378        let right = fp_frame::DataFrame::from_dict_with_index(
22379            vec![
22380                ("id", vec![Scalar::Int64(1)]),
22381                ("val", vec![Scalar::Int64(100)]),
22382            ],
22383            vec![0_i64.into()],
22384        )
22385        .unwrap();
22386
22387        let options = MergeExecutionOptions {
22388            suffixes: Some([Some("_L".to_string()), Some("_R".to_string())]),
22389            ..MergeExecutionOptions::default()
22390        };
22391
22392        let err = merge_dataframes_on_with_options(
22393            &left,
22394            &right,
22395            &["id"],
22396            &["id"],
22397            JoinType::Inner,
22398            options.clone(),
22399        )
22400        .expect_err("merge causing duplicate column within left must be rejected");
22401
22402        assert!(
22403            format!("{err}").contains("duplicate columns {'val_L'}"),
22404            "expected duplicate columns error, got: {err}"
22405        );
22406
22407        // Right side collision: right has val and val_R, suffix _R produces duplicate val_R
22408        let right_with_dup = fp_frame::DataFrame::from_dict_with_index(
22409            vec![
22410                ("id", vec![Scalar::Int64(1)]),
22411                ("val", vec![Scalar::Int64(100)]),
22412                ("val_R", vec![Scalar::Int64(88)]),
22413            ],
22414            vec![0_i64.into()],
22415        )
22416        .unwrap();
22417
22418        let left_simple = fp_frame::DataFrame::from_dict_with_index(
22419            vec![
22420                ("id", vec![Scalar::Int64(1)]),
22421                ("val", vec![Scalar::Int64(10)]),
22422            ],
22423            vec![0_i64.into()],
22424        )
22425        .unwrap();
22426
22427        let err_r = merge_dataframes_on_with_options(
22428            &left_simple,
22429            &right_with_dup,
22430            &["id"],
22431            &["id"],
22432            JoinType::Inner,
22433            options,
22434        )
22435        .expect_err("merge causing duplicate column within right must be rejected");
22436
22437        assert!(
22438            format!("{err_r}").contains("duplicate columns {'val_R'}"),
22439            "expected duplicate columns error, got: {err_r}"
22440        );
22441    }
22442}