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, 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            (Present(IndexLabel::Period(a)), Present(IndexLabel::Period(b))) => a.cmp(b),
940            (Present(IndexLabel::Interval(a)), Present(IndexLabel::Interval(b))) => {
941                if a.left == b.left && a.right == b.right {
942                    // pandas orders equal-endpoint intervals by the spelling
943                    // of closed: both, left, neither, right. The core enum's
944                    // declaration order is different.
945                    let closed_rank = |value: &fp_types::Interval| match (
946                        value.closed.left_closed(),
947                        value.closed.right_closed(),
948                    ) {
949                        (true, true) => 0,
950                        (true, false) => 1,
951                        (false, false) => 2,
952                        (false, true) => 3,
953                    };
954                    closed_rank(a).cmp(&closed_rank(b))
955                } else {
956                    a.cmp(b)
957                }
958            }
959            // Typed-null labels sort after every concrete label (nulls-last,
960            // consistent with the derived IndexLabel Ord) but before Missing.
961            // Unreachable today: join key extraction maps missing to Missing,
962            // never Present(Null).
963            (Present(IndexLabel::Null(a)), Present(IndexLabel::Null(b))) => a.cmp(b),
964            (Present(IndexLabel::Null(_)), Present(_)) => Ordering::Greater,
965            (Present(_), Present(IndexLabel::Null(_))) => Ordering::Less,
966            (Present(IndexLabel::Null(_)), FloatBits(_)) => Ordering::Greater,
967            (FloatBits(_), Present(IndexLabel::Null(_))) => Ordering::Less,
968            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Less,
969            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Int64(_))) => Ordering::Greater,
970            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Int64(_))) => {
971                Ordering::Greater
972            }
973            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Utf8(_))) => {
974                Ordering::Greater
975            }
976            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
977            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
978            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Int64(_))) => {
979                Ordering::Greater
980            }
981            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Greater,
982            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Timedelta64(_))) => {
983                Ordering::Greater
984            }
985            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
986            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
987            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Datetime64(_))) => {
988                Ordering::Less
989            }
990            (Present(IndexLabel::Int64(a)), FloatBits(bits)) => {
991                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
992                if ord == Ordering::Equal {
993                    Ordering::Less
994                } else {
995                    ord
996                }
997            }
998            (FloatBits(bits), Present(IndexLabel::Int64(a))) => {
999                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
1000                if ord == Ordering::Equal {
1001                    Ordering::Greater
1002                } else {
1003                    ord
1004                }
1005            }
1006            (Present(IndexLabel::Timedelta64(a)), FloatBits(bits)) => {
1007                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
1008                if ord == Ordering::Equal {
1009                    Ordering::Less
1010                } else {
1011                    ord
1012                }
1013            }
1014            (FloatBits(bits), Present(IndexLabel::Timedelta64(a))) => {
1015                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
1016                if ord == Ordering::Equal {
1017                    Ordering::Greater
1018                } else {
1019                    ord
1020                }
1021            }
1022            (Present(IndexLabel::Datetime64(a)), FloatBits(bits)) => {
1023                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
1024                if ord == Ordering::Equal {
1025                    Ordering::Less
1026                } else {
1027                    ord
1028                }
1029            }
1030            (FloatBits(bits), Present(IndexLabel::Datetime64(a))) => {
1031                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
1032                if ord == Ordering::Equal {
1033                    Ordering::Greater
1034                } else {
1035                    ord
1036                }
1037            }
1038            (FloatBits(a_bits), FloatBits(b_bits)) => {
1039                f64::from_bits(*a_bits).total_cmp(&f64::from_bits(*b_bits))
1040            }
1041            (FloatBits(_), Present(IndexLabel::Utf8(_))) => Ordering::Less,
1042            (Present(IndexLabel::Utf8(_)), FloatBits(_)) => Ordering::Greater,
1043            // Extension values follow strings and integers, so they must
1044            // also follow floats to keep mixed-key comparisons transitive.
1045            (FloatBits(_), Present(IndexLabel::Period(_) | IndexLabel::Interval(_))) => {
1046                Ordering::Less
1047            }
1048            (Present(IndexLabel::Period(_) | IndexLabel::Interval(_)), FloatBits(_)) => {
1049                Ordering::Greater
1050            }
1051            // Float64/Bool index labels (br-frankenpandas-i10en). Join key
1052            // extraction maps float keys to FloatBits and bool keys to Int64, so
1053            // a Present(Float64)/Present(Bool) join key is unreachable today;
1054            // these arms only keep the manual `Ord` total (same-variant compares
1055            // by value, cross-variant by a stable variant rank).
1056            (Present(IndexLabel::Float64(a)), Present(IndexLabel::Float64(b))) => a.cmp(b),
1057            (Present(IndexLabel::Bool(a)), Present(IndexLabel::Bool(b))) => a.cmp(b),
1058            (Present(IndexLabel::Object(a)), Present(IndexLabel::Object(b))) => a.cmp(b),
1059            (a, b) => join_component_rank(a).cmp(&join_component_rank(b)),
1060        }
1061    }
1062}
1063
1064/// Stable per-variant fallback for comparisons without a dedicated arm.
1065/// Numeric keys and their relation to extension keys are handled above.
1066fn join_component_rank(c: &JoinKeyComponent) -> u8 {
1067    use JoinKeyComponent::{FloatBits, Missing, Present};
1068    match c {
1069        Present(IndexLabel::Int64(_)) => 0,
1070        Present(IndexLabel::Float64(_)) => 1,
1071        Present(IndexLabel::Bool(_)) => 2,
1072        Present(IndexLabel::Utf8(_)) => 3,
1073        Present(IndexLabel::Timedelta64(_)) => 4,
1074        Present(IndexLabel::Datetime64(_)) => 5,
1075        Present(IndexLabel::Object(_)) => 6,
1076        Present(IndexLabel::Period(_)) => 7,
1077        Present(IndexLabel::Interval(_)) => 8,
1078        Present(IndexLabel::Null(_)) => 9,
1079        FloatBits(_) => 10,
1080        Missing => 11,
1081    }
1082}
1083
1084impl PartialOrd for JoinKeyComponent {
1085    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1086        Some(self.cmp(other))
1087    }
1088}
1089
1090fn scalar_to_key_component(s: &fp_types::Scalar) -> JoinKeyComponent {
1091    match s {
1092        fp_types::Scalar::Int64(v) => JoinKeyComponent::Present(IndexLabel::Int64(*v)),
1093        fp_types::Scalar::Float64(v) if !v.is_nan() => {
1094            if *v == v.trunc() && *v >= i64::MIN as f64 && *v < 9223372036854775808.0 {
1095                JoinKeyComponent::Present(IndexLabel::Int64(*v as i64))
1096            } else {
1097                JoinKeyComponent::FloatBits(v.to_bits())
1098            }
1099        }
1100        fp_types::Scalar::Utf8(v) => JoinKeyComponent::Present(IndexLabel::Utf8(v.clone())),
1101        fp_types::Scalar::Bool(b) => JoinKeyComponent::Present(IndexLabel::Int64(i64::from(*b))),
1102        fp_types::Scalar::Timedelta64(v) if *v != fp_types::Timedelta::NAT => {
1103            JoinKeyComponent::Present(IndexLabel::Timedelta64(*v))
1104        }
1105        fp_types::Scalar::Datetime64(v) if *v != fp_types::Timestamp::NAT => {
1106            JoinKeyComponent::Present(IndexLabel::Datetime64(*v))
1107        }
1108        fp_types::Scalar::Period(value) if !value.is_nat() => {
1109            JoinKeyComponent::Present(IndexLabel::Period(*value))
1110        }
1111        fp_types::Scalar::Interval(value) => {
1112            JoinKeyComponent::Present(IndexLabel::Interval(*value))
1113        }
1114        fp_types::Scalar::Object(object @ fp_types::ObjectValue::Bytes(_)) => {
1115            JoinKeyComponent::Present(IndexLabel::Object(object.clone()))
1116        }
1117        // Enumerate the missing/unsupported representations so adding a new
1118        // scalar kind cannot silently turn every value of that kind into the
1119        // same missing join key. List/host objects are rejected by
1120        // validate_object_join_keys before key collection.
1121        fp_types::Scalar::Null(_)
1122        | fp_types::Scalar::Float64(_)
1123        | fp_types::Scalar::Timedelta64(_)
1124        | fp_types::Scalar::Datetime64(_)
1125        | fp_types::Scalar::Period(_)
1126        | fp_types::Scalar::Object(_) => JoinKeyComponent::Missing,
1127    }
1128}
1129
1130/// A row's composite join key. Inline storage for the single-key case (the
1131/// overwhelmingly common join shape) avoids a heap allocation per row during
1132/// key extraction; multi-column keys spill to the heap as before. `SmallVec`
1133/// shares `Vec`'s `Hash`/`Eq`/`Ord`/`Deref<[T]>` semantics, so the join result
1134/// (key equality, grouping, output order) is bit-identical.
1135type CompositeJoinKey = smallvec::SmallVec<[JoinKeyComponent; 1]>;
1136
1137/// `(left_positions, right_positions, out_row_keys)` produced by the merge
1138/// position-computation phase. `out_row_keys` is `Some` only when the rows must
1139/// be reordered by join key (sort or outer join).
1140type MergeRowPositions = (
1141    Vec<Option<usize>>,
1142    Vec<Option<usize>>,
1143    Option<Vec<CompositeJoinKey>>,
1144);
1145type JoinPositionBucket = smallvec::SmallVec<[usize; 1]>;
1146
1147/// Unsupported object keys must fail before either a typed fast path or the
1148/// generic key collector can mistake them for missing values. Matching the
1149/// variant avoids calling an opaque host object's repr, hash or equality.
1150fn validate_object_join_keys(column: &Column) -> Result<(), JoinError> {
1151    // These representations hold only text and missing markers. Preserve the
1152    // typed string fast paths without allocating a Scalar/String per key.
1153    if column.as_utf8_window().is_some() || column.as_nullable_utf8_contiguous().is_some() {
1154        return Ok(());
1155    }
1156    if matches!(column.dtype(), DType::Utf8 | DType::Categorical)
1157        && column.values().iter().any(|value| {
1158            matches!(
1159                value,
1160                Scalar::Object(fp_types::ObjectValue::List(_) | fp_types::ObjectValue::Host(_))
1161            )
1162        })
1163    {
1164        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1165            "list and host object join keys are unsupported; bytes keys are supported".to_owned(),
1166        )));
1167    }
1168    Ok(())
1169}
1170
1171fn collect_join_key_columns<'a>(
1172    frame: &'a fp_frame::DataFrame,
1173    on: &[&str],
1174    side: &str,
1175) -> Result<Vec<&'a Column>, JoinError> {
1176    let mut key_columns = Vec::with_capacity(on.len());
1177    for key_name in on {
1178        let key_column = frame.column(key_name).ok_or_else(|| {
1179            JoinError::Frame(FrameError::CompatibilityRejected(format!(
1180                "{side} DataFrame missing key column '{key_name}'"
1181            )))
1182        })?;
1183        validate_object_join_keys(key_column)?;
1184        key_columns.push(key_column);
1185    }
1186    Ok(key_columns)
1187}
1188
1189fn collect_composite_keys(key_columns: &[&Column]) -> Vec<CompositeJoinKey> {
1190    let row_count = key_columns.first().map_or(0, |column| column.len());
1191    let mut out = Vec::with_capacity(row_count);
1192
1193    for row in 0..row_count {
1194        let mut parts: CompositeJoinKey = smallvec::SmallVec::with_capacity(key_columns.len());
1195        for column in key_columns {
1196            parts.push(scalar_to_key_component(&column.values()[row]));
1197        }
1198        out.push(parts);
1199    }
1200
1201    out
1202}
1203
1204fn collect_single_join_keys(column: &Column) -> Vec<JoinKeyComponent> {
1205    column
1206        .values()
1207        .iter()
1208        .map(scalar_to_key_component)
1209        .collect()
1210}
1211
1212fn has_duplicate_composite_keys(keys: &[CompositeJoinKey]) -> bool {
1213    let mut seen = FxHashSet::with_capacity_and_hasher(keys.len(), Default::default());
1214    for key in keys {
1215        if !seen.insert(key) {
1216            return true;
1217        }
1218    }
1219    false
1220}
1221
1222/// validate='one_to_one' with repeated keys on both sides, which pandas
1223/// reports as 'not unique in either left or right dataset'.
1224const ONE_TO_ONE_BOTH_SIDES_DUPLICATED: &str =
1225    "merge validate='one_to_one' failed: left and right keys are not unique";
1226
1227fn validate_merge_cardinality(
1228    validate_mode: MergeValidateMode,
1229    left_keys: &[CompositeJoinKey],
1230    right_keys: &[CompositeJoinKey],
1231) -> Result<(), JoinError> {
1232    let fail = |message: &str| {
1233        Err(JoinError::Frame(FrameError::CompatibilityRejected(
1234            message.to_owned(),
1235        )))
1236    };
1237
1238    match validate_mode {
1239        MergeValidateMode::OneToOne => {
1240            // pandas names both sides when neither is unique ('not unique in
1241            // either left or right dataset'), else the one that is not (the
1242            // left failure was reported first whatever the right held;
1243            // br-frankenpandas-z6jxh).
1244            match (
1245                has_duplicate_composite_keys(left_keys),
1246                has_duplicate_composite_keys(right_keys),
1247            ) {
1248                (true, true) => return fail(ONE_TO_ONE_BOTH_SIDES_DUPLICATED),
1249                (true, false) => {
1250                    return fail("merge validate='one_to_one' failed: left keys are not unique");
1251                }
1252                (false, true) => {
1253                    return fail("merge validate='one_to_one' failed: right keys are not unique");
1254                }
1255                (false, false) => {}
1256            }
1257        }
1258        MergeValidateMode::OneToMany => {
1259            if has_duplicate_composite_keys(left_keys) {
1260                return fail("merge validate='one_to_many' failed: left keys are not unique");
1261            }
1262        }
1263        MergeValidateMode::ManyToOne => {
1264            if has_duplicate_composite_keys(right_keys) {
1265                return fail("merge validate='many_to_one' failed: right keys are not unique");
1266            }
1267        }
1268        MergeValidateMode::ManyToMany => {}
1269    }
1270
1271    Ok(())
1272}
1273
1274fn validate_mode_allows_fast_positions(validate_mode: Option<MergeValidateMode>) -> bool {
1275    matches!(validate_mode, None | Some(MergeValidateMode::ManyToMany))
1276}
1277
1278/// Duplicate detection straight off a single all-valid `Int64` key buffer.
1279///
1280/// br-frankenpandas-uza04. `has_duplicate_composite_keys` needs a
1281/// `Vec<CompositeJoinKey>`, which `collect_composite_keys` builds by reading
1282/// `column.values()[row]` — the 32 B/elem `Scalar` spine plus a `SmallVec` per
1283/// row. For one all-valid Int64 column the same question is an `FxHashSet<i64>`
1284/// over the contiguous buffer, pre-sized so the build side never rehashes.
1285///
1286/// Returns `None` when this shape does not apply (more than one key column, a
1287/// non-`Int64` dtype, or any missing value — `as_i64_slice` answers only for
1288/// all-valid `DType::Int64`), and the caller keeps the generic path, which is
1289/// also where null-key duplicate semantics stay owned.
1290fn typed_single_int64_key_has_duplicates(key_columns: &[&Column]) -> Option<bool> {
1291    let [column] = key_columns else {
1292        return None;
1293    };
1294    let data = column.as_i64_slice()?;
1295    let mut seen = FxHashSet::with_capacity_and_hasher(data.len(), Default::default());
1296    Some(!data.iter().all(|&key| seen.insert(key)))
1297}
1298
1299/// Typed sibling of [`validate_merge_cardinality`]: enforce the mode off raw
1300/// key buffers, and report whether it was able to.
1301///
1302/// `Ok(true)` means the mode was fully enforced here and PASSED, so the caller
1303/// may use the fast positions paths. `Ok(false)` means this shape is not
1304/// covered and the generic path must still run `validate_merge_cardinality`.
1305/// `Err` is a real validation failure and carries the SAME message the generic
1306/// checker produces, because the two must be indistinguishable to a caller.
1307///
1308/// Precedence matters and is preserved: `OneToOne` reports a left-side failure
1309/// before looking at the right, exactly as the generic checker does. It also
1310/// declines outright unless BOTH sides are typed, so it can never report a
1311/// right-side failure that the generic checker would have pre-empted with a
1312/// left-side one it could not see.
1313fn typed_validate_merge_cardinality(
1314    validate_mode: MergeValidateMode,
1315    left_key_columns: &[&Column],
1316    right_key_columns: &[&Column],
1317) -> Result<bool, JoinError> {
1318    let fail = |message: &str| {
1319        Err(JoinError::Frame(FrameError::CompatibilityRejected(
1320            message.to_owned(),
1321        )))
1322    };
1323
1324    match validate_mode {
1325        MergeValidateMode::ManyToMany => Ok(true),
1326        MergeValidateMode::OneToMany => {
1327            match typed_single_int64_key_has_duplicates(left_key_columns) {
1328                Some(true) => fail("merge validate='one_to_many' failed: left keys are not unique"),
1329                Some(false) => Ok(true),
1330                None => Ok(false),
1331            }
1332        }
1333        MergeValidateMode::ManyToOne => {
1334            match typed_single_int64_key_has_duplicates(right_key_columns) {
1335                Some(true) => {
1336                    fail("merge validate='many_to_one' failed: right keys are not unique")
1337                }
1338                Some(false) => Ok(true),
1339                None => Ok(false),
1340            }
1341        }
1342        MergeValidateMode::OneToOne => {
1343            // Both sides must be typed before deciding anything: the failure
1344            // names each side that repeats, so answering from one side alone
1345            // could surface the wrong message.
1346            let Some(left_duplicated) = typed_single_int64_key_has_duplicates(left_key_columns)
1347            else {
1348                return Ok(false);
1349            };
1350            let Some(right_duplicated) = typed_single_int64_key_has_duplicates(right_key_columns)
1351            else {
1352                return Ok(false);
1353            };
1354            match (left_duplicated, right_duplicated) {
1355                (true, true) => fail(ONE_TO_ONE_BOTH_SIDES_DUPLICATED),
1356                (true, false) => {
1357                    fail("merge validate='one_to_one' failed: left keys are not unique")
1358                }
1359                (false, true) => {
1360                    fail("merge validate='one_to_one' failed: right keys are not unique")
1361                }
1362                (false, false) => Ok(true),
1363            }
1364        }
1365    }
1366}
1367
1368fn reorder_vec_by_index<T: Clone>(values: &mut Vec<T>, order: &[usize]) {
1369    let existing = values.clone();
1370    values.clear();
1371    values.reserve(order.len());
1372    for &idx in order {
1373        values.push(existing[idx].clone());
1374    }
1375}
1376
1377/// Merge sorting follows each pair of source dtypes. Temporal NaT and a
1378/// compatible categorical's missing code precede its values; ordinary nulls
1379/// sort last. Categorical values use the left dictionary's order, including
1380/// unordered dictionaries whose right side is a permutation of the same set.
1381#[derive(Default)]
1382struct MergeKeySortOrder {
1383    missing_first: bool,
1384    category_ranks: Option<FxHashMap<JoinKeyComponent, usize>>,
1385}
1386
1387impl MergeKeySortOrder {
1388    fn for_columns(left: &Column, right: &Column) -> Self {
1389        if let (Some(left), Some(right)) = (left.categorical(), right.categorical()) {
1390            let left_dtype = fp_types::infer_dtype(&left.categories).ok();
1391            let right_dtype = fp_types::infer_dtype(&right.categories).ok();
1392            if left.ordered != right.ordered
1393                || left.categories.len() != right.categories.len()
1394                || left_dtype.is_none()
1395                || left_dtype != right_dtype
1396            {
1397                return Self::default();
1398            }
1399            let ranks: FxHashMap<_, _> = left
1400                .categories
1401                .iter()
1402                .enumerate()
1403                .map(|(rank, value)| (scalar_to_key_component(value), rank))
1404                .collect();
1405            // Category identity includes the categories' dtype: equal-valued
1406            // integer and floating IntervalIndexes are different dictionaries.
1407            let compatible = ranks.len() == left.categories.len()
1408                && !ranks.contains_key(&JoinKeyComponent::Missing)
1409                && right
1410                    .categories
1411                    .iter()
1412                    .enumerate()
1413                    .all(|(position, value)| {
1414                        let Some(&rank) = ranks.get(&scalar_to_key_component(value)) else {
1415                            return false;
1416                        };
1417                        if left.ordered && rank != position {
1418                            return false;
1419                        }
1420                        match (&left.categories[rank], value) {
1421                            (Scalar::Interval(a), Scalar::Interval(b)) => a.subtype == b.subtype,
1422                            _ => true,
1423                        }
1424                    });
1425            return if compatible {
1426                Self {
1427                    missing_first: true,
1428                    category_ranks: Some(ranks),
1429                }
1430            } else {
1431                Self::default()
1432            };
1433        }
1434        // A categorical that is coerced to its values during a mixed-dtype
1435        // merge retains ordinary null ordering, even for temporal categories.
1436        let temporal = matches!(
1437            (left.dtype(), right.dtype()),
1438            (DType::Period, DType::Period)
1439                | (DType::Timedelta64, DType::Timedelta64)
1440                | (DType::Datetime64 { .. }, DType::Datetime64 { .. })
1441        );
1442        Self {
1443            missing_first: temporal,
1444            category_ranks: None,
1445        }
1446    }
1447
1448    fn compare(&self, left: &JoinKeyComponent, right: &JoinKeyComponent) -> Ordering {
1449        if self.missing_first {
1450            match (left, right) {
1451                (JoinKeyComponent::Missing, JoinKeyComponent::Missing) => return Ordering::Equal,
1452                (JoinKeyComponent::Missing, _) => return Ordering::Less,
1453                (_, JoinKeyComponent::Missing) => return Ordering::Greater,
1454                _ => {}
1455            }
1456        }
1457        if let Some(ranks) = &self.category_ranks
1458            && let (Some(left_rank), Some(right_rank)) = (ranks.get(left), ranks.get(right))
1459        {
1460            return left_rank.cmp(right_rank);
1461        }
1462        left.cmp(right)
1463    }
1464}
1465
1466fn sort_merge_rows_by_join_keys(
1467    left_keys: &[CompositeJoinKey],
1468    right_keys: &[CompositeJoinKey],
1469    left_key_columns: &[&Column],
1470    right_key_columns: &[&Column],
1471    left_positions: &mut Vec<Option<usize>>,
1472    right_positions: &mut Vec<Option<usize>>,
1473) {
1474    let n = left_positions.len();
1475    if n <= 1 {
1476        return;
1477    }
1478    // pandas sorts merge output by the join key. The naive O(n·log n) COMPARISON
1479    // sort re-compares full keys (string compares for Utf8) on every step. Instead
1480    // FACTORIZE the keys to dense ranks (sort only the DISTINCT keys once, d≪n)
1481    // then STABLE counting-sort the rows by rank — O(n + d·log d). Crucially, each
1482    // output row's key is read BY REFERENCE from the already-built left_keys /
1483    // right_keys via its position (matched / unmatched-left rows take the left key,
1484    // unmatched-right rows take the right key — exactly what the removed per-row
1485    // `out_row_keys` clone stored), so the ~n String-owning CompositeJoinKey clones
1486    // that dominated outer merge are gone. Bit-identical to the prior path: same
1487    // per-row key, same `cmp`-ordered ranks (over a superset of distinct keys —
1488    // unused ranks are just empty counting-sort buckets), same stable
1489    // ascending-index emission within each rank.
1490    let mut distinct: Vec<&CompositeJoinKey> = {
1491        let mut set = FxHashSet::default();
1492        left_keys
1493            .iter()
1494            .chain(right_keys.iter())
1495            .filter(|k| set.insert(*k))
1496            .collect()
1497    };
1498    let orders: Vec<_> = left_key_columns
1499        .iter()
1500        .zip(right_key_columns)
1501        .map(|(left, right)| MergeKeySortOrder::for_columns(left, right))
1502        .collect();
1503    if orders
1504        .iter()
1505        .all(|order| !order.missing_first && order.category_ranks.is_none())
1506    {
1507        distinct.sort_unstable();
1508    } else {
1509        distinct.sort_unstable_by(|left, right| {
1510            for ((left, right), order) in left.iter().zip(right.iter()).zip(&orders) {
1511                let comparison = order.compare(left, right);
1512                if comparison != Ordering::Equal {
1513                    return comparison;
1514                }
1515            }
1516            Ordering::Equal
1517        });
1518    }
1519    let d = distinct.len();
1520    let mut rank_of: FxHashMap<&CompositeJoinKey, u32> = FxHashMap::default();
1521    rank_of.reserve(d);
1522    for (r, k) in distinct.iter().enumerate() {
1523        rank_of.insert(*k, r as u32);
1524    }
1525    let left_rank: Vec<u32> = left_keys.iter().map(|k| rank_of[k]).collect();
1526    let right_rank: Vec<u32> = right_keys.iter().map(|k| rank_of[k]).collect();
1527    let ranks: Vec<u32> = left_positions
1528        .iter()
1529        .zip(right_positions.iter())
1530        .map(|(lp, rp)| match lp {
1531            Some(p) => left_rank[*p],
1532            None => right_rank[rp.expect("an unmatched merge row has a right position")],
1533        })
1534        .collect();
1535    let mut counts = vec![0usize; d + 1];
1536    for &r in &ranks {
1537        counts[r as usize + 1] += 1;
1538    }
1539    for i in 0..d {
1540        counts[i + 1] += counts[i];
1541    }
1542    // `order[new_slot] = old_idx`, matching the comparison sort's permutation —
1543    // stable because rows are scattered in ascending original-index order.
1544    let mut cursor = counts;
1545    let mut order = vec![0usize; n];
1546    for (i, &r) in ranks.iter().enumerate() {
1547        let slot = cursor[r as usize];
1548        order[slot] = i;
1549        cursor[r as usize] = slot + 1;
1550    }
1551    reorder_vec_by_index(left_positions, &order);
1552    reorder_vec_by_index(right_positions, &order);
1553}
1554
1555/// Match pandas `libjoin.inner_join(..., sort=False)` when `output_len == left.len()`
1556/// but not every left row matched once (some left row matched multiple times and
1557/// another matched zero times, so `left_positions != 0..left.len()`).
1558///
1559/// In pandas 2.2.3 `inner_join(..., sort=False)` groups matched rows by the
1560/// factorized left group codes (`0, 1, 2, ...` in first-seen left order, with
1561/// single-key missing values assigned the sentinel bucket after all non-null
1562/// keys) and then reorders by `rev = np.empty(len(left)); rev[left_sorter] = np.arange(len(left))`
1563/// whenever `len(left_indexer) == len(left)` (br-frankenpandas-ml0az).
1564fn permute_inner_merge_equal_left_len_positions(
1565    left_key_columns: &[&Column],
1566    left_positions: &mut [usize],
1567    right_positions: &mut [usize],
1568) {
1569    let Some(first_col) = left_key_columns.first() else {
1570        return;
1571    };
1572    let left_len = first_col.len();
1573    if left_len < 2
1574        || left_positions.len() != left_len
1575        || right_positions.len() != left_len
1576        || !left_positions.iter().enumerate().any(|(i, &l)| l != i)
1577    {
1578        return;
1579    }
1580
1581    let left_codes: Vec<usize> = if left_key_columns.len() == 1 {
1582        let keys = collect_single_join_keys(first_col);
1583        let mut code_map = FxHashMap::<JoinKeyComponent, usize>::with_capacity_and_hasher(
1584            left_len,
1585            Default::default(),
1586        );
1587        let mut next_code = 0usize;
1588        keys.into_iter()
1589            .map(|key| {
1590                if matches!(key, JoinKeyComponent::Missing) {
1591                    usize::MAX
1592                } else {
1593                    *code_map.entry(key).or_insert_with(|| {
1594                        let code = next_code;
1595                        next_code += 1;
1596                        code
1597                    })
1598                }
1599            })
1600            .collect()
1601    } else {
1602        let keys = collect_composite_keys(left_key_columns);
1603        let mut code_map = FxHashMap::<CompositeJoinKey, usize>::with_capacity_and_hasher(
1604            left_len,
1605            Default::default(),
1606        );
1607        let mut next_code = 0usize;
1608        keys.into_iter()
1609            .map(|key| {
1610                *code_map.entry(key).or_insert_with(|| {
1611                    let code = next_code;
1612                    next_code += 1;
1613                    code
1614                })
1615            })
1616            .collect()
1617    };
1618
1619    let mut left_sorter: Vec<usize> = (0..left_len).collect();
1620    left_sorter.sort_by_key(|&r| left_codes[r]);
1621
1622    let mut rev = vec![0usize; left_len];
1623    for (sorted_pos, orig_row) in left_sorter.into_iter().enumerate() {
1624        rev[orig_row] = sorted_pos;
1625    }
1626
1627    let mut grouped: Vec<(usize, usize)> = left_positions
1628        .iter()
1629        .copied()
1630        .zip(right_positions.iter().copied())
1631        .collect();
1632    grouped.sort_by_key(|&(l_pos, _)| left_codes[l_pos]);
1633
1634    for (out_idx, &sorted_idx) in rev.iter().enumerate() {
1635        let (l_pos, r_pos) = grouped[sorted_idx];
1636        left_positions[out_idx] = l_pos;
1637        right_positions[out_idx] = r_pos;
1638    }
1639}
1640
1641fn push_merge_row_key(out_row_keys: &mut Option<Vec<CompositeJoinKey>>, key: &CompositeJoinKey) {
1642    if let Some(out_row_keys) = out_row_keys {
1643        out_row_keys.push(key.clone());
1644    }
1645}
1646
1647#[derive(Debug, Clone, PartialEq, Eq)]
1648struct ResolvedMergeSuffixes {
1649    left: Option<String>,
1650    right: Option<String>,
1651}
1652
1653impl Default for ResolvedMergeSuffixes {
1654    fn default() -> Self {
1655        Self {
1656            left: Some("_x".to_owned()),
1657            right: Some("_y".to_owned()),
1658        }
1659    }
1660}
1661
1662fn resolve_merge_suffixes(suffixes: Option<[Option<String>; 2]>) -> ResolvedMergeSuffixes {
1663    match suffixes {
1664        Some([left, right]) => ResolvedMergeSuffixes { left, right },
1665        None => ResolvedMergeSuffixes::default(),
1666    }
1667}
1668
1669fn suffix_is_present(suffix: Option<&str>) -> bool {
1670    suffix.is_some_and(|value| !value.is_empty())
1671}
1672
1673fn apply_merge_suffix(name: &str, suffix: Option<&str>) -> String {
1674    match suffix {
1675        Some(value) if !value.is_empty() => format!("{name}{value}"),
1676        _ => name.to_owned(),
1677    }
1678}
1679
1680fn collect_overlapping_column_names(
1681    left_col_names: &HashSet<&String>,
1682    right_col_names: &HashSet<&String>,
1683    excluded_names: &HashSet<&str>,
1684) -> Vec<String> {
1685    let mut overlaps = left_col_names
1686        .iter()
1687        .filter(|name| right_col_names.contains(*name) && !excluded_names.contains(name.as_str()))
1688        .map(|name| (*name).clone())
1689        .collect::<Vec<_>>();
1690    overlaps.sort();
1691    overlaps
1692}
1693
1694const SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT: usize = 8;
1695
1696fn column_name_lookup_contains(
1697    names: &[&String],
1698    hashed_names: Option<&HashSet<&str>>,
1699    target: &str,
1700) -> bool {
1701    if let Some(hashed_names) = hashed_names {
1702        hashed_names.contains(target)
1703    } else {
1704        names.iter().any(|name| name.as_str() == target)
1705    }
1706}
1707
1708fn ensure_merge_suffixes_for_overlaps(
1709    overlap_names: &[String],
1710    suffixes: &ResolvedMergeSuffixes,
1711) -> Result<(), JoinError> {
1712    if overlap_names.is_empty() {
1713        return Ok(());
1714    }
1715    if !suffix_is_present(suffixes.left.as_deref()) && !suffix_is_present(suffixes.right.as_deref())
1716    {
1717        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1718            format!(
1719                "columns overlap but no suffix specified: {}",
1720                overlap_names.join(", ")
1721            ),
1722        )));
1723    }
1724    Ok(())
1725}
1726
1727fn validate_merge_suffixes_intra_frame(
1728    left_cols: &[&String],
1729    right_cols: &[&String],
1730    shared_key_names: &HashSet<&str>,
1731    suffixes: &ResolvedMergeSuffixes,
1732) -> Result<(), JoinError> {
1733    let left_col_names: HashSet<&String> = left_cols.iter().copied().collect();
1734    let right_col_names: HashSet<&String> = right_cols.iter().copied().collect();
1735    let overlap_names =
1736        collect_overlapping_column_names(&left_col_names, &right_col_names, shared_key_names);
1737    ensure_merge_suffixes_for_overlaps(&overlap_names, suffixes)?;
1738
1739    let overlap_set: HashSet<&str> = overlap_names.iter().map(|s| s.as_str()).collect();
1740    let mut dups = Vec::new();
1741
1742    // Check left frame for duplicates caused by suffixes
1743    let mut left_seen_orig = HashSet::new();
1744    let mut left_orig_dups = HashSet::new();
1745    for &name in left_cols {
1746        if !left_seen_orig.insert(name.as_str()) {
1747            left_orig_dups.insert(name.as_str());
1748        }
1749    }
1750
1751    let mut left_renamed_seen = HashSet::new();
1752    for &name in left_cols {
1753        let renamed = if overlap_set.contains(name.as_str()) {
1754            apply_merge_suffix(name, suffixes.left.as_deref())
1755        } else {
1756            name.clone()
1757        };
1758        if !left_renamed_seen.insert(renamed.clone()) && !left_orig_dups.contains(name.as_str()) {
1759            dups.push(renamed);
1760        }
1761    }
1762
1763    // Check right frame for duplicates caused by suffixes (excluding shared keys dropped from right output)
1764    let right_output_cols: Vec<&String> = right_cols
1765        .iter()
1766        .copied()
1767        .filter(|name| !shared_key_names.contains(name.as_str()))
1768        .collect();
1769
1770    let mut right_seen_orig = HashSet::new();
1771    let mut right_orig_dups = HashSet::new();
1772    for &name in &right_output_cols {
1773        if !right_seen_orig.insert(name.as_str()) {
1774            right_orig_dups.insert(name.as_str());
1775        }
1776    }
1777
1778    let mut right_renamed_seen = HashSet::new();
1779    for &name in &right_output_cols {
1780        let renamed = if overlap_set.contains(name.as_str()) {
1781            apply_merge_suffix(name, suffixes.right.as_deref())
1782        } else {
1783            (*name).clone()
1784        };
1785        if !right_renamed_seen.insert(renamed.clone()) && !right_orig_dups.contains(name.as_str()) {
1786            dups.push(renamed);
1787        }
1788    }
1789
1790    if !dups.is_empty() {
1791        dups.sort();
1792        dups.dedup();
1793        let formatted = format!(
1794            "{{{}}}",
1795            dups.iter()
1796                .map(|d| format!("'{d}'"))
1797                .collect::<Vec<_>>()
1798                .join(", ")
1799        );
1800        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1801            format!("Passing 'suffixes' which cause duplicate columns {formatted} is not allowed."),
1802        )));
1803    }
1804
1805    Ok(())
1806}
1807
1808fn insert_merged_output_column(
1809    output_columns: &mut ColumnStore,
1810    order: &mut Vec<String>,
1811    name: String,
1812    column: Column,
1813) -> Result<(), JoinError> {
1814    order.push(name.clone());
1815    output_columns.push(name, column);
1816    Ok(())
1817}
1818
1819fn ordered_identity_int64_keys_match(left_key: &Column, right_key: &Column) -> bool {
1820    if left_key.len() != right_key.len()
1821        || !matches!(left_key.dtype(), DType::Int64)
1822        || !matches!(right_key.dtype(), DType::Int64)
1823        || !left_key.validity().all()
1824        || !right_key.validity().all()
1825    {
1826        return false;
1827    }
1828
1829    if let (Some(left), Some(right)) = (left_key.as_i64_slice(), right_key.as_i64_slice()) {
1830        let mut previous = None;
1831        let mut strictly_increasing = true;
1832        for (&left_value, &right_value) in left.iter().zip(right) {
1833            if left_value != right_value {
1834                return false;
1835            }
1836            if previous.is_some_and(|previous| left_value <= previous) {
1837                strictly_increasing = false;
1838                break;
1839            }
1840            previous = Some(left_value);
1841        }
1842        if strictly_increasing {
1843            return true;
1844        }
1845    }
1846
1847    // The identity fast path emits a 1:1 positional merge, which is only correct
1848    // when keys are UNIQUE. With duplicate keys pandas multiplies cardinality
1849    // (each duplicate on the left cross-joins every duplicate on the right), so
1850    // identical-but-duplicated keys must fall through to the general cartesian
1851    // path. (br-frankenpandas-jdupk)
1852    let mut seen = FxHashSet::<i64>::with_capacity_and_hasher(left_key.len(), Default::default());
1853    for (left, right) in left_key.values().iter().zip(right_key.values()) {
1854        match (left, right) {
1855            (Scalar::Int64(left), Scalar::Int64(right))
1856                if matches!(left.cmp(right), Ordering::Equal) =>
1857            {
1858                if !seen.insert(*left) {
1859                    return false;
1860                }
1861            }
1862            _ => return false,
1863        }
1864    }
1865    true
1866}
1867
1868fn strictly_increasing_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1869    if column.dtype() != DType::Int64 || !column.validity().all() {
1870        return None;
1871    }
1872
1873    let values = column.values();
1874    let mut previous = None;
1875    for value in values {
1876        let current = match value {
1877            Scalar::Int64(value) => *value,
1878            _ => return None,
1879        };
1880        if previous.is_some_and(|previous| current <= previous) {
1881            return None;
1882        }
1883        previous = Some(current);
1884    }
1885    Some(values)
1886}
1887
1888fn all_valid_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1889    if column.dtype() != DType::Int64 || !column.validity().all() {
1890        return None;
1891    }
1892
1893    let values = column.values();
1894    if values.iter().all(|value| matches!(value, Scalar::Int64(_))) {
1895        Some(values)
1896    } else {
1897        None
1898    }
1899}
1900
1901#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1902struct PositiveAffineI64Witness {
1903    start: i128,
1904    step: i128,
1905    len: usize,
1906}
1907
1908#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1909struct AffineInnerPositionPlan {
1910    left_start: usize,
1911    left_step: usize,
1912    right_start: usize,
1913    right_step: usize,
1914    len: usize,
1915}
1916
1917const AFFINE_I64_INNER_MAX_MORSELS: usize = 64;
1918
1919fn affine_inner_worker_count() -> usize {
1920    fp_columnar::cached_available_parallelism().min(AFFINE_I64_INNER_MAX_MORSELS)
1921}
1922
1923fn balanced_partition(total: usize, index: usize, parts: usize) -> (usize, usize) {
1924    debug_assert!(parts > 0);
1925    debug_assert!(index < parts);
1926    let base = total / parts;
1927    let remainder = total % parts;
1928    let start = index * base + index.min(remainder);
1929    let end = start + base + usize::from(index < remainder);
1930    (start, end)
1931}
1932
1933fn positive_affine_i64_shape(values: &[i64]) -> Option<PositiveAffineI64Witness> {
1934    if values.len() < 2 {
1935        return None;
1936    }
1937    let start = i128::from(values[0]);
1938    let step = i128::from(values[1]) - start;
1939    // Keeping the step within positive i64 makes every CRT intermediate below
1940    // fit i128. Rarer two-point sequences spanning more than i64::MAX retain
1941    // the existing ordered/hash route.
1942    if step <= 0 || step > i128::from(i64::MAX) {
1943        return None;
1944    }
1945    Some(PositiveAffineI64Witness {
1946        start,
1947        step,
1948        len: values.len(),
1949    })
1950}
1951
1952/// Prove two positive affine i64 key sequences with independent row morsels.
1953///
1954/// Every adjacent edge is checked exactly once, including boundaries between
1955/// morsels. A failed proof simply declines the affine route; no result is
1956/// emitted from speculative work. Large ordered joins therefore replace two
1957/// serial O(n) order scans with up to 64 shared-nothing scans while preserving
1958/// the exact strict-unique certificate required by pandas inner-join semantics.
1959fn certify_positive_affine_i64_pair(
1960    left: &[i64],
1961    right: &[i64],
1962) -> Option<(PositiveAffineI64Witness, PositiveAffineI64Witness)> {
1963    let left_shape = positive_affine_i64_shape(left)?;
1964    let right_shape = positive_affine_i64_shape(right)?;
1965    let left_edges = left.len() - 1;
1966    let right_edges = right.len() - 1;
1967    let max_edges = left_edges.max(right_edges);
1968    let worker_count = affine_inner_worker_count().min(max_edges.max(1));
1969
1970    let matches_shape = |values: &[i64], shape: PositiveAffineI64Witness| {
1971        values
1972            .windows(2)
1973            .all(|pair| i128::from(pair[1]) - i128::from(pair[0]) == shape.step)
1974    };
1975    if max_edges < DENSE_I64_INNER_PARALLEL_MIN_VALUES || worker_count < 2 {
1976        return (matches_shape(left, left_shape) && matches_shape(right, right_shape))
1977            .then_some((left_shape, right_shape));
1978    }
1979
1980    let proved = std::thread::scope(|scope| {
1981        let mut handles = Vec::with_capacity(worker_count);
1982        for worker in 0..worker_count {
1983            handles.push(scope.spawn(move || {
1984                let (left_start, left_end) = balanced_partition(left_edges, worker, worker_count);
1985                let (right_start, right_end) =
1986                    balanced_partition(right_edges, worker, worker_count);
1987                let left_ok = (left_start..left_end).all(|idx| {
1988                    i128::from(left[idx + 1]) - i128::from(left[idx]) == left_shape.step
1989                });
1990                let right_ok = (right_start..right_end).all(|idx| {
1991                    i128::from(right[idx + 1]) - i128::from(right[idx]) == right_shape.step
1992                });
1993                left_ok && right_ok
1994            }));
1995        }
1996        handles
1997            .into_iter()
1998            .all(|handle| handle.join().expect("affine join proof worker panicked"))
1999    });
2000    proved.then_some((left_shape, right_shape))
2001}
2002
2003fn positive_i128_gcd(mut left: i128, mut right: i128) -> i128 {
2004    debug_assert!(left > 0 && right > 0);
2005    while right != 0 {
2006        let remainder = left % right;
2007        left = right;
2008        right = remainder;
2009    }
2010    left
2011}
2012
2013fn coprime_mod_inverse(value: i128, modulus: i128) -> Option<i128> {
2014    debug_assert!(value > 0 && modulus > 1);
2015    let (mut old_remainder, mut remainder) = (value, modulus);
2016    let (mut old_coefficient, mut coefficient) = (1i128, 0i128);
2017    while remainder != 0 {
2018        let quotient = old_remainder / remainder;
2019        (old_remainder, remainder) = (
2020            remainder,
2021            old_remainder.checked_sub(quotient.checked_mul(remainder)?)?,
2022        );
2023        (old_coefficient, coefficient) = (
2024            coefficient,
2025            old_coefficient.checked_sub(quotient.checked_mul(coefficient)?)?,
2026        );
2027    }
2028    (old_remainder == 1).then(|| old_coefficient.rem_euclid(modulus))
2029}
2030
2031fn empty_affine_inner_position_plan() -> AffineInnerPositionPlan {
2032    AffineInnerPositionPlan {
2033        left_start: 0,
2034        left_step: 1,
2035        right_start: 0,
2036        right_step: 1,
2037        len: 0,
2038    }
2039}
2040
2041/// Intersect two certified positive affine sequences analytically.
2042///
2043/// The generalized CRT yields the first shared key and the common step. Those
2044/// map back to affine row selections on each input, so the join needs neither
2045/// the serial two-pointer merge nor its two O(matches) position vectors.
2046fn affine_i64_inner_position_plan(
2047    left: PositiveAffineI64Witness,
2048    right: PositiveAffineI64Witness,
2049) -> Option<AffineInnerPositionPlan> {
2050    let left_last = left
2051        .start
2052        .checked_add(left.step.checked_mul(i128::try_from(left.len - 1).ok()?)?)?;
2053    let right_last = right.start.checked_add(
2054        right
2055            .step
2056            .checked_mul(i128::try_from(right.len - 1).ok()?)?,
2057    )?;
2058    let low = left.start.max(right.start);
2059    let high = left_last.min(right_last);
2060    if low > high {
2061        return Some(empty_affine_inner_position_plan());
2062    }
2063
2064    let gcd = positive_i128_gcd(left.step, right.step);
2065    let difference = right.start.checked_sub(left.start)?;
2066    if difference % gcd != 0 {
2067        return Some(empty_affine_inner_position_plan());
2068    }
2069    let left_reduced = left.step / gcd;
2070    let right_reduced = right.step / gcd;
2071    let left_solution = if right_reduced == 1 {
2072        0
2073    } else {
2074        let inverse = coprime_mod_inverse(left_reduced.rem_euclid(right_reduced), right_reduced)?;
2075        difference
2076            .checked_div(gcd)?
2077            .checked_mul(inverse)?
2078            .rem_euclid(right_reduced)
2079    };
2080    let common_step = left.step.checked_mul(right_reduced)?;
2081    let mut first = left
2082        .start
2083        .checked_add(left.step.checked_mul(left_solution)?)?;
2084    if first < low {
2085        let delta = low.checked_sub(first)?;
2086        let jumps = delta
2087            .checked_add(common_step - 1)?
2088            .checked_div(common_step)?;
2089        first = first.checked_add(jumps.checked_mul(common_step)?)?;
2090    }
2091    if first > high {
2092        return Some(empty_affine_inner_position_plan());
2093    }
2094
2095    let len = usize::try_from((high - first) / common_step + 1).ok()?;
2096    let left_start = usize::try_from((first - left.start) / left.step).ok()?;
2097    let right_start = usize::try_from((first - right.start) / right.step).ok()?;
2098    let left_step = usize::try_from(common_step / left.step).ok()?;
2099    let right_step = usize::try_from(common_step / right.step).ok()?;
2100    debug_assert!(
2101        left_start
2102            .checked_add(left_step.saturating_mul(len.saturating_sub(1)))
2103            .is_some_and(|last| last < left.len)
2104    );
2105    debug_assert!(
2106        right_start
2107            .checked_add(right_step.saturating_mul(len.saturating_sub(1)))
2108            .is_some_and(|last| last < right.len)
2109    );
2110    Some(AffineInnerPositionPlan {
2111        left_start,
2112        left_step,
2113        right_start,
2114        right_step,
2115        len,
2116    })
2117}
2118
2119enum AffineInnerOutputLane<'a> {
2120    Int64 {
2121        source: &'a [i64],
2122        start: usize,
2123        step: usize,
2124    },
2125    Built(Box<Column>),
2126}
2127
2128struct AffineInnerOutputSpec<'a> {
2129    name: String,
2130    lane: AffineInnerOutputLane<'a>,
2131}
2132
2133fn affine_selection_positions(start: usize, step: usize, len: usize) -> Vec<usize> {
2134    (0..len).map(|idx| start + idx * step).collect()
2135}
2136
2137fn affine_inner_output_lane<'a>(
2138    column: &'a Column,
2139    start: usize,
2140    step: usize,
2141    len: usize,
2142) -> Option<AffineInnerOutputLane<'a>> {
2143    if let Some(source) = column.as_i64_slice() {
2144        return Some(AffineInnerOutputLane::Int64 {
2145            source,
2146            start,
2147            step,
2148        });
2149    }
2150    column.as_f64_slice()?;
2151    let built = if len == 0 {
2152        Column::from_f64_values(Vec::new())
2153    } else if let Some(view) = isize::try_from(step).ok().and_then(|step| {
2154        column.take_affine_positions_without_materialized_positions(start, step, len)
2155    }) {
2156        view
2157    } else {
2158        let positions = affine_selection_positions(start, step, len);
2159        column.take_positions(&positions)
2160    };
2161    Some(AffineInnerOutputLane::Built(Box::new(built)))
2162}
2163
2164/// Zero-copy Int64 output for a unit-stride side of an affine match.
2165///
2166/// Shared inner-join keys are byte-identical on both sides. If either side's
2167/// matched rows form one contiguous range, reuse that immutable Arc-backed
2168/// range as a one-chunk output instead of filling an O(matches) key buffer.
2169fn affine_unit_stride_i64_view(
2170    column: &Column,
2171    start: usize,
2172    step: usize,
2173    len: usize,
2174) -> Option<Column> {
2175    if len == 0 {
2176        return Some(Column::from_i64_values_owned(Vec::new()));
2177    }
2178    if step != 1 {
2179        return None;
2180    }
2181    let (data, base) = column.as_i64_arc_view_source()?;
2182    let view_start = base.checked_add(start)?;
2183    view_start
2184        .checked_add(len)
2185        .filter(|&end| end <= data.len())?;
2186    Some(Column::from_i64_all_valid_chunks(
2187        vec![(data, view_start, len)],
2188        len,
2189    ))
2190}
2191
2192/// Fill all Int64 affine output lanes by row morsel into disjoint buffers.
2193/// Float64 lanes are descriptor-only strided views and never enter this fill.
2194fn build_affine_inner_i64_lanes(sources: &[(&[i64], usize, usize)], len: usize) -> Vec<Vec<i64>> {
2195    let mut output: Vec<Vec<i64>> = sources.iter().map(|_| vec![0i64; len]).collect();
2196    if sources.is_empty() || len == 0 {
2197        return output;
2198    }
2199    let worker_count = affine_inner_worker_count().min(len);
2200    if len < DENSE_I64_INNER_PARALLEL_MIN_VALUES || worker_count < 2 {
2201        for (lane, &(source, start, step)) in output.iter_mut().zip(sources) {
2202            for (row, value) in lane.iter_mut().enumerate() {
2203                *value = source[start + row * step];
2204            }
2205        }
2206        return output;
2207    }
2208
2209    let mut bundles: Vec<Vec<&mut [i64]>> = (0..worker_count)
2210        .map(|_| Vec::with_capacity(output.len()))
2211        .collect();
2212    for lane in &mut output {
2213        let mut remainder = lane.as_mut_slice();
2214        for (worker, bundle) in bundles.iter_mut().enumerate() {
2215            let (row_start, row_end) = balanced_partition(len, worker, worker_count);
2216            let (chunk, tail) = remainder.split_at_mut(row_end - row_start);
2217            bundle.push(chunk);
2218            remainder = tail;
2219        }
2220    }
2221
2222    std::thread::scope(|scope| {
2223        for (worker, mut bundle) in bundles.into_iter().enumerate() {
2224            let (row_start, _) = balanced_partition(len, worker, worker_count);
2225            scope.spawn(move || {
2226                for (lane, &(source, start, step)) in bundle.iter_mut().zip(sources) {
2227                    for (local_row, value) in lane.iter_mut().enumerate() {
2228                        *value = source[start + (row_start + local_row) * step];
2229                    }
2230                }
2231            });
2232        }
2233    });
2234    output
2235}
2236
2237/// Shared-nothing affine Int64 inner merge.
2238///
2239/// This is deliberately narrow but structural: all-valid typed Int64 keys are
2240/// certified as positive affine sequences; every carried lane must be an
2241/// all-valid Int64 or Float64. The match relation is then a pair of affine row
2242/// selections. Float64 payloads become zero-copy strided views, while all
2243/// Int64 lanes are filled together across row morsels. Any unsupported shape
2244/// falls through to the general ordered/dense/hash implementations.
2245fn build_single_key_affine_i64_inner_merge_output(
2246    left: &fp_frame::DataFrame,
2247    right: &fp_frame::DataFrame,
2248    left_on: &[&str],
2249    right_on: &[&str],
2250    left_key: &Column,
2251    right_key: &Column,
2252    suffixes: &ResolvedMergeSuffixes,
2253) -> Result<Option<MergedDataFrame>, JoinError> {
2254    debug_assert_eq!(left_on.len(), 1);
2255    debug_assert_eq!(right_on.len(), 1);
2256    let (Some(left_keys), Some(right_keys)) = (left_key.as_i64_slice(), right_key.as_i64_slice())
2257    else {
2258        return Ok(None);
2259    };
2260    let Some((left_shape, right_shape)) = certify_positive_affine_i64_pair(left_keys, right_keys)
2261    else {
2262        return Ok(None);
2263    };
2264    let Some(plan) = affine_i64_inner_position_plan(left_shape, right_shape) else {
2265        return Ok(None);
2266    };
2267
2268    let left_col_names: HashSet<&String> = left.columns().keys().collect();
2269    let right_col_names: HashSet<&String> = right.columns().keys().collect();
2270    let shared_key_names = if left_on[0] == right_on[0] {
2271        [left_on[0]].into_iter().collect::<HashSet<&str>>()
2272    } else {
2273        HashSet::new()
2274    };
2275    let overlapping_names =
2276        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
2277    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
2278
2279    let mut specs = Vec::<AffineInnerOutputSpec<'_>>::new();
2280    for name in left.column_names() {
2281        let column = left
2282            .columns()
2283            .get(name)
2284            .expect("left column listed in column_names must exist");
2285        let out_name = if name.as_str() == left_on[0] {
2286            name.clone()
2287        } else if right_col_names.contains(name) {
2288            apply_merge_suffix(name, suffixes.left.as_deref())
2289        } else {
2290            name.clone()
2291        };
2292        let shared_key_view = (name.as_str() == left_on[0] && left_on[0] == right_on[0])
2293            .then(|| {
2294                affine_unit_stride_i64_view(left_key, plan.left_start, plan.left_step, plan.len)
2295                    .or_else(|| {
2296                        affine_unit_stride_i64_view(
2297                            right_key,
2298                            plan.right_start,
2299                            plan.right_step,
2300                            plan.len,
2301                        )
2302                    })
2303                    .map(Box::new)
2304                    .map(AffineInnerOutputLane::Built)
2305            })
2306            .flatten();
2307        let Some(lane) = shared_key_view.or_else(|| {
2308            affine_inner_output_lane(column, plan.left_start, plan.left_step, plan.len)
2309        }) else {
2310            return Ok(None);
2311        };
2312        specs.push(AffineInnerOutputSpec {
2313            name: out_name,
2314            lane,
2315        });
2316    }
2317    for name in right.column_names() {
2318        if name.as_str() == right_on[0] && shared_key_names.contains(name.as_str()) {
2319            continue;
2320        }
2321        let column = right
2322            .columns()
2323            .get(name)
2324            .expect("right column listed in column_names must exist");
2325        let out_name = if left_col_names.contains(name) {
2326            apply_merge_suffix(name, suffixes.right.as_deref())
2327        } else {
2328            name.clone()
2329        };
2330        let Some(lane) =
2331            affine_inner_output_lane(column, plan.right_start, plan.right_step, plan.len)
2332        else {
2333            return Ok(None);
2334        };
2335        specs.push(AffineInnerOutputSpec {
2336            name: out_name,
2337            lane,
2338        });
2339    }
2340
2341    let i64_sources: Vec<(&[i64], usize, usize)> = specs
2342        .iter()
2343        .filter_map(|spec| match &spec.lane {
2344            AffineInnerOutputLane::Int64 {
2345                source,
2346                start,
2347                step,
2348            } => Some((*source, *start, *step)),
2349            AffineInnerOutputLane::Built(_) => None,
2350        })
2351        .collect();
2352    let mut i64_lanes = build_affine_inner_i64_lanes(&i64_sources, plan.len).into_iter();
2353    let index = Index::new_known_unique_int64_unit_range(0, plan.len);
2354    let mut columns = ColumnStore::new();
2355    let mut column_order = Vec::with_capacity(specs.len());
2356    for spec in specs {
2357        let column = match spec.lane {
2358            AffineInnerOutputLane::Int64 { .. } => Column::from_i64_values_owned(
2359                i64_lanes
2360                    .next()
2361                    .expect("one filled lane for every affine Int64 output"),
2362            ),
2363            AffineInnerOutputLane::Built(column) => *column,
2364        };
2365        debug_assert_eq!(column.len(), plan.len);
2366        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
2367    }
2368    Ok(Some(MergedDataFrame {
2369        index,
2370        columns,
2371        column_order,
2372    }))
2373}
2374
2375fn ordered_unique_int64_inner_positions(
2376    left_key: &Column,
2377    right_key: &Column,
2378) -> Option<(Vec<usize>, Vec<usize>)> {
2379    // Typed fast path (see ordered_unique_int64_left_match_positions): walk the
2380    // ordered intersection over raw &[i64] when both keys carry a contiguous
2381    // Int64 backing, skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB
2382    // per merge at 1M rows). Bit-identical: same strictly-increasing gate and
2383    // the same monotone merge emitting the same (left_idx, right_idx) pairs.
2384    if let (Some(left_values), Some(right_values)) = (
2385        strictly_increasing_i64_slice(left_key),
2386        strictly_increasing_i64_slice(right_key),
2387    ) {
2388        let mut left_positions =
2389            Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
2390        let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2391        let (mut left_idx, mut right_idx) = (0usize, 0usize);
2392        while left_idx < left_values.len() && right_idx < right_values.len() {
2393            match left_values[left_idx].cmp(&right_values[right_idx]) {
2394                Ordering::Equal => {
2395                    left_positions.push(left_idx);
2396                    right_positions.push(right_idx);
2397                    left_idx += 1;
2398                    right_idx += 1;
2399                }
2400                Ordering::Less => left_idx += 1,
2401                Ordering::Greater => right_idx += 1,
2402            }
2403        }
2404        return Some((left_positions, right_positions));
2405    }
2406
2407    let left_values = strictly_increasing_int64_key_values(left_key)?;
2408    let right_values = strictly_increasing_int64_key_values(right_key)?;
2409
2410    let mut left_positions = Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
2411    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2412    let mut left_idx = 0usize;
2413    let mut right_idx = 0usize;
2414
2415    while left_idx < left_values.len() && right_idx < right_values.len() {
2416        let left_value = match &left_values[left_idx] {
2417            Scalar::Int64(value) => *value,
2418            _ => return None,
2419        };
2420        let right_value = match &right_values[right_idx] {
2421            Scalar::Int64(value) => *value,
2422            _ => return None,
2423        };
2424
2425        match left_value.cmp(&right_value) {
2426            Ordering::Equal => {
2427                left_positions.push(left_idx);
2428                right_positions.push(right_idx);
2429                left_idx += 1;
2430                right_idx += 1;
2431            }
2432            Ordering::Less => left_idx += 1,
2433            Ordering::Greater => right_idx += 1,
2434        }
2435    }
2436
2437    Some((left_positions, right_positions))
2438}
2439
2440fn strictly_increasing_utf8_key_spans(column: &Column) -> Option<(&[u8], &[usize])> {
2441    column.as_strictly_increasing_utf8_contiguous()
2442}
2443
2444fn utf8_span<'a>(bytes: &'a [u8], offsets: &[usize], pos: usize) -> &'a [u8] {
2445    &bytes[offsets[pos]..offsets[pos + 1]]
2446}
2447
2448fn utf8_offsets_are_sorted(bytes: &[u8], offsets: &[usize]) -> bool {
2449    offsets
2450        .windows(3)
2451        .all(|window| bytes[window[0]..window[1]] <= bytes[window[1]..window[2]])
2452}
2453
2454fn sorted_contiguous_utf8_inner_positions(
2455    left_bytes: &[u8],
2456    left_offsets: &[usize],
2457    right_bytes: &[u8],
2458    right_offsets: &[usize],
2459) -> Option<(Vec<usize>, Vec<usize>)> {
2460    if !utf8_offsets_are_sorted(left_bytes, left_offsets)
2461        || !utf8_offsets_are_sorted(right_bytes, right_offsets)
2462    {
2463        return None;
2464    }
2465
2466    let left_n = left_offsets.len() - 1;
2467    let right_n = right_offsets.len() - 1;
2468    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
2469    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2470    let mut left_pos = 0usize;
2471    let mut right_pos = 0usize;
2472
2473    while left_pos < left_n && right_pos < right_n {
2474        let left_span = utf8_span(left_bytes, left_offsets, left_pos);
2475        let right_span = utf8_span(right_bytes, right_offsets, right_pos);
2476        match left_span.cmp(right_span) {
2477            Ordering::Less => left_pos += 1,
2478            Ordering::Greater => right_pos += 1,
2479            Ordering::Equal => {
2480                let left_start = left_pos;
2481                let right_start = right_pos;
2482                while left_pos < left_n
2483                    && utf8_span(left_bytes, left_offsets, left_pos) == left_span
2484                {
2485                    left_pos += 1;
2486                }
2487                while right_pos < right_n
2488                    && utf8_span(right_bytes, right_offsets, right_pos) == right_span
2489                {
2490                    right_pos += 1;
2491                }
2492                for matched_left in left_start..left_pos {
2493                    for matched_right in right_start..right_pos {
2494                        left_positions.push(matched_left);
2495                        right_positions.push(matched_right);
2496                    }
2497                }
2498            }
2499        }
2500    }
2501
2502    Some((left_positions, right_positions))
2503}
2504
2505fn utf8_span_lower_bound(bytes: &[u8], offsets: &[usize], needle: &[u8]) -> usize {
2506    let mut lo = 0usize;
2507    let mut hi = offsets.len() - 1;
2508    while lo < hi {
2509        let mid = lo + (hi - lo) / 2;
2510        if utf8_span(bytes, offsets, mid) < needle {
2511            lo = mid + 1;
2512        } else {
2513            hi = mid;
2514        }
2515    }
2516    lo
2517}
2518
2519fn ordered_unique_utf8_fixed_width(left_key: &Column, right_key: &Column) -> Option<usize> {
2520    let (_, _, left_width) = left_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
2521    let (_, _, right_width) = right_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
2522    (left_width == right_width && left_width > 0).then_some(left_width)
2523}
2524
2525fn ordered_utf8_lower_hex_overlap_len(
2526    left_cert: Utf8LowerHexSequence,
2527    right_cert: Utf8LowerHexSequence,
2528    left_idx: usize,
2529    left_n: usize,
2530    right_idx: usize,
2531    right_n: usize,
2532) -> Option<usize> {
2533    if !left_cert.same_shape(right_cert) {
2534        return None;
2535    }
2536    let left_value = left_cert.value_at(left_idx)?;
2537    let right_value = right_cert.value_at(right_idx)?;
2538    if left_value != right_value {
2539        return None;
2540    }
2541    Some(left_n.saturating_sub(left_idx).min(right_n - right_idx))
2542}
2543
2544fn lower_hex_overlap_plan_from_certificates(
2545    left_key: &Column,
2546    right_key: &Column,
2547) -> Option<InnerPositionPlan> {
2548    let (left_prefix, left_cert, left_n) = left_key.as_lower_hex_sequence_utf8()?;
2549    let (right_prefix, right_cert, right_n) = right_key.as_lower_hex_sequence_utf8()?;
2550    if !left_cert.same_shape(right_cert) {
2551        return None;
2552    }
2553    if left_prefix != right_prefix {
2554        return None;
2555    }
2556
2557    let left_n = u64::try_from(left_n).ok()?;
2558    let right_n = u64::try_from(right_n).ok()?;
2559    if left_n == 0 || right_n == 0 {
2560        return Some(InnerPositionPlan::Gather {
2561            left_positions: Vec::new(),
2562            right_positions: Vec::new(),
2563        });
2564    }
2565
2566    let left_start_value = left_cert.start();
2567    let right_start_value = right_cert.start();
2568    let left_end_value = left_start_value.checked_add(left_n)?;
2569    let right_end_value = right_start_value.checked_add(right_n)?;
2570    let overlap_start = left_start_value.max(right_start_value);
2571    let overlap_end = left_end_value.min(right_end_value);
2572    if overlap_start >= overlap_end {
2573        return Some(InnerPositionPlan::Gather {
2574            left_positions: Vec::new(),
2575            right_positions: Vec::new(),
2576        });
2577    }
2578
2579    let len = usize::try_from(overlap_end.checked_sub(overlap_start)?).ok()?;
2580    let left_start = usize::try_from(overlap_start.checked_sub(left_start_value)?).ok()?;
2581    let right_start = usize::try_from(overlap_start.checked_sub(right_start_value)?).ok()?;
2582    let left_len = usize::try_from(left_n).ok()?;
2583    let right_len = usize::try_from(right_n).ok()?;
2584    let left_end = left_start.checked_add(len)?;
2585    let right_end = right_start.checked_add(len)?;
2586    if left_end > left_len || right_end > right_len {
2587        return None;
2588    }
2589
2590    Some(InnerPositionPlan::ContiguousRanges {
2591        left_start,
2592        right_start,
2593        len,
2594    })
2595}
2596
2597#[derive(Debug, Clone, PartialEq, Eq)]
2598enum InnerPositionPlan {
2599    Gather {
2600        left_positions: Vec<usize>,
2601        right_positions: Vec<usize>,
2602    },
2603    ContiguousRanges {
2604        left_start: usize,
2605        right_start: usize,
2606        len: usize,
2607    },
2608}
2609
2610impl InnerPositionPlan {
2611    #[cfg(test)]
2612    fn into_positions(self) -> (Vec<usize>, Vec<usize>) {
2613        match self {
2614            Self::Gather {
2615                left_positions,
2616                right_positions,
2617            } => (left_positions, right_positions),
2618            Self::ContiguousRanges {
2619                left_start,
2620                right_start,
2621                len,
2622            } => (
2623                (left_start..left_start + len).collect(),
2624                (right_start..right_start + len).collect(),
2625            ),
2626        }
2627    }
2628}
2629
2630/// Hash-free ordered merge for all-valid, strictly increasing contiguous-Utf8
2631/// keys. This is the string-key analogue of
2632/// [`ordered_unique_int64_inner_positions`]: each side is unique and already in
2633/// key order, so a two-cursor byte-span merge emits the exact same 1:1
2634/// `(left_pos, right_pos)` pairs as the hash path while skipping hash table
2635/// build/probe entirely. Duplicate or unsorted inputs fall back to the
2636/// left-major byte-span hash path, preserving pandas row order.
2637fn ordered_unique_utf8_inner_position_plan(
2638    left_key: &Column,
2639    right_key: &Column,
2640) -> Option<InnerPositionPlan> {
2641    if let Some(plan) = lower_hex_overlap_plan_from_certificates(left_key, right_key) {
2642        return Some(plan);
2643    }
2644
2645    let (left_bytes, left_offsets) = strictly_increasing_utf8_key_spans(left_key)?;
2646    let (right_bytes, right_offsets) = strictly_increasing_utf8_key_spans(right_key)?;
2647    let left_n = left_offsets.len() - 1;
2648    let right_n = right_offsets.len() - 1;
2649    let fixed_width = ordered_unique_utf8_fixed_width(left_key, right_key);
2650
2651    if left_n == 0 || right_n == 0 {
2652        return Some(InnerPositionPlan::Gather {
2653            left_positions: Vec::new(),
2654            right_positions: Vec::new(),
2655        });
2656    }
2657
2658    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
2659    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2660
2661    let first_left = utf8_span(left_bytes, left_offsets, 0);
2662    let last_left = utf8_span(left_bytes, left_offsets, left_n - 1);
2663    let first_right = utf8_span(right_bytes, right_offsets, 0);
2664    let last_right = utf8_span(right_bytes, right_offsets, right_n - 1);
2665    if last_left < first_right || last_right < first_left {
2666        return Some(InnerPositionPlan::Gather {
2667            left_positions,
2668            right_positions,
2669        });
2670    }
2671
2672    let mut left_idx = utf8_span_lower_bound(left_bytes, left_offsets, first_right);
2673    let mut right_idx = if left_idx < left_n {
2674        utf8_span_lower_bound(
2675            right_bytes,
2676            right_offsets,
2677            utf8_span(left_bytes, left_offsets, left_idx),
2678        )
2679    } else {
2680        right_n
2681    };
2682    let mut fixed_width_bulk_attempted = false;
2683
2684    while left_idx < left_n && right_idx < right_n {
2685        let left_span = utf8_span(left_bytes, left_offsets, left_idx);
2686        let right_span = utf8_span(right_bytes, right_offsets, right_idx);
2687
2688        match left_span.cmp(right_span) {
2689            Ordering::Equal => {
2690                if let Some(width) = fixed_width
2691                    && !fixed_width_bulk_attempted
2692                {
2693                    fixed_width_bulk_attempted = true;
2694                    // This branch is reached only after the current left/right
2695                    // key spans compare equal. Matching lower-hex shapes then
2696                    // prove the remaining shifted windows without a full
2697                    // byte-window memcmp.
2698                    let lower_hex_sequences = match (
2699                        left_key.as_lower_hex_sequence_utf8_contiguous(),
2700                        right_key.as_lower_hex_sequence_utf8_contiguous(),
2701                    ) {
2702                        (Some((_, _, left_cert)), Some((_, _, right_cert))) => {
2703                            Some((left_cert, right_cert))
2704                        }
2705                        _ => None,
2706                    };
2707                    if let Some((left_cert, right_cert)) = lower_hex_sequences
2708                        && let Some(run_len) = ordered_utf8_lower_hex_overlap_len(
2709                            left_cert, right_cert, left_idx, left_n, right_idx, right_n,
2710                        )
2711                        && run_len > 1
2712                    {
2713                        if left_positions.is_empty() {
2714                            return Some(InnerPositionPlan::ContiguousRanges {
2715                                left_start: left_idx,
2716                                right_start: right_idx,
2717                                len: run_len,
2718                            });
2719                        }
2720                        left_positions.extend(left_idx..left_idx + run_len);
2721                        right_positions.extend(right_idx..right_idx + run_len);
2722                        left_idx += run_len;
2723                        right_idx += run_len;
2724                        continue;
2725                    }
2726                    let run_len = left_n.saturating_sub(left_idx).min(right_n - right_idx);
2727                    if run_len > 1
2728                        && let Some(byte_len) = run_len.checked_mul(width)
2729                    {
2730                        let left_start = left_offsets[left_idx];
2731                        let right_start = right_offsets[right_idx];
2732                        let left_end = left_start + byte_len;
2733                        let right_end = right_start + byte_len;
2734                        if left_end <= left_bytes.len()
2735                            && right_end <= right_bytes.len()
2736                            && left_bytes[left_start..left_end]
2737                                == right_bytes[right_start..right_end]
2738                        {
2739                            if left_positions.is_empty() {
2740                                return Some(InnerPositionPlan::ContiguousRanges {
2741                                    left_start: left_idx,
2742                                    right_start: right_idx,
2743                                    len: run_len,
2744                                });
2745                            }
2746                            left_positions.extend(left_idx..left_idx + run_len);
2747                            right_positions.extend(right_idx..right_idx + run_len);
2748                            left_idx += run_len;
2749                            right_idx += run_len;
2750                            continue;
2751                        }
2752                    }
2753                }
2754                left_positions.push(left_idx);
2755                right_positions.push(right_idx);
2756                left_idx += 1;
2757                right_idx += 1;
2758            }
2759            Ordering::Less => left_idx += 1,
2760            Ordering::Greater => right_idx += 1,
2761        }
2762    }
2763
2764    Some(InnerPositionPlan::Gather {
2765        left_positions,
2766        right_positions,
2767    })
2768}
2769
2770#[cfg(test)]
2771fn ordered_unique_utf8_inner_positions(
2772    left_key: &Column,
2773    right_key: &Column,
2774) -> Option<(Vec<usize>, Vec<usize>)> {
2775    ordered_unique_utf8_inner_position_plan(left_key, right_key)
2776        .map(InnerPositionPlan::into_positions)
2777}
2778
2779/// Strictly-increasing check over a column's contiguous `&[i64]` backing,
2780/// returning the raw slice. The typed analogue of
2781/// `strictly_increasing_int64_key_values` that skips the `Vec<Scalar>`
2782/// materialization (32 B/elem) — `as_i64_slice` is `Some` only for an
2783/// all-valid contiguous Int64 column, the same gate as the Scalar version
2784/// (dtype Int64 + `validity().all()` + every value `Scalar::Int64`).
2785fn strictly_increasing_i64_slice(column: &Column) -> Option<&[i64]> {
2786    let data = column.as_i64_slice()?;
2787    if data.windows(2).any(|pair| pair[1] <= pair[0]) {
2788        return None;
2789    }
2790    Some(data)
2791}
2792
2793fn ordered_unique_int64_left_match_positions(
2794    left_key: &Column,
2795    right_key: &Column,
2796) -> Option<Vec<Option<usize>>> {
2797    // Typed fast path: both keys carry a contiguous Int64 backing, so run the
2798    // ordered two-pointer match over raw `&[i64]` (8 B/elem, cache-friendly)
2799    // instead of materializing two `Vec<Scalar>` (32 B/elem — ~32 MB per side
2800    // at 1M rows, the tax that left-join paid but the typed inner path did
2801    // not). Bit-identical: same strictly-increasing gate and the same
2802    // monotone walk producing the same `right_idx` per left row.
2803    if let (Some(left_values), Some(right_values)) = (
2804        strictly_increasing_i64_slice(left_key),
2805        strictly_increasing_i64_slice(right_key),
2806    ) {
2807        let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2808        let mut right_idx = 0usize;
2809        for &left_value in left_values {
2810            while right_idx < right_values.len() && right_values[right_idx] < left_value {
2811                right_idx += 1;
2812            }
2813            let matched = match right_values.get(right_idx) {
2814                Some(&right_value) if right_value == left_value => Some(right_idx),
2815                _ => None,
2816            };
2817            right_positions.push(matched);
2818        }
2819        return Some(right_positions);
2820    }
2821
2822    let left_values = strictly_increasing_int64_key_values(left_key)?;
2823    let right_values = strictly_increasing_int64_key_values(right_key)?;
2824
2825    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2826    let mut right_idx = 0usize;
2827
2828    for left_value in left_values {
2829        let Scalar::Int64(left_value) = left_value else {
2830            return None;
2831        };
2832        while let Some(Scalar::Int64(right_value)) = right_values.get(right_idx)
2833            && right_value < left_value
2834        {
2835            right_idx += 1;
2836        }
2837
2838        let matched = match right_values.get(right_idx) {
2839            Some(Scalar::Int64(right_value)) if right_value == left_value => Some(right_idx),
2840            Some(Scalar::Int64(_)) | None => None,
2841            Some(_) => return None,
2842        };
2843        right_positions.push(matched);
2844    }
2845
2846    Some(right_positions)
2847}
2848
2849fn ordered_unique_int64_right_match_positions(
2850    left_key: &Column,
2851    right_key: &Column,
2852) -> Option<Vec<Option<usize>>> {
2853    // Typed fast path (mirror of ordered_unique_int64_left_match_positions):
2854    // walk over raw &[i64] when both keys carry a contiguous Int64 backing,
2855    // skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB per merge at
2856    // 1M rows). Bit-identical: same strictly-increasing gate and the same
2857    // monotone walk producing the same left_idx per right row.
2858    if let (Some(left_values), Some(right_values)) = (
2859        strictly_increasing_i64_slice(left_key),
2860        strictly_increasing_i64_slice(right_key),
2861    ) {
2862        let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2863        let mut left_idx = 0usize;
2864        for &right_value in right_values {
2865            while left_idx < left_values.len() && left_values[left_idx] < right_value {
2866                left_idx += 1;
2867            }
2868            let matched = match left_values.get(left_idx) {
2869                Some(&left_value) if left_value == right_value => Some(left_idx),
2870                _ => None,
2871            };
2872            left_positions.push(matched);
2873        }
2874        return Some(left_positions);
2875    }
2876
2877    let left_values = strictly_increasing_int64_key_values(left_key)?;
2878    let right_values = strictly_increasing_int64_key_values(right_key)?;
2879
2880    let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2881    let mut left_idx = 0usize;
2882
2883    for right_value in right_values {
2884        let Scalar::Int64(right_value) = right_value else {
2885            return None;
2886        };
2887        while let Some(Scalar::Int64(left_value)) = left_values.get(left_idx)
2888            && left_value < right_value
2889        {
2890            left_idx += 1;
2891        }
2892
2893        let matched = match left_values.get(left_idx) {
2894            Some(Scalar::Int64(left_value)) if left_value == right_value => Some(left_idx),
2895            Some(Scalar::Int64(_)) | None => None,
2896            Some(_) => return None,
2897        };
2898        left_positions.push(matched);
2899    }
2900
2901    Some(left_positions)
2902}
2903
2904type OptionalJoinPositions = (Vec<Option<usize>>, Vec<Option<usize>>);
2905
2906/// Direct-address unique-key fast path for a bounded-span Int64 left/inner
2907/// join. When the right keys are *unique* within their value span, the
2908/// counting-sort CSR (count + prefix-sum + scatter + per-bucket emit, over
2909/// several span-sized `usize` arrays) collapses to a single fill pass over one
2910/// compact `u32` table (`pos+1`, `0` == empty) plus a single probe pass — ~14x
2911/// faster at 1M (and faster than open-addressing hashing, no hash/probe).
2912///
2913/// Returns `None` (caller falls back to the CSR path) when: a key column is not
2914/// a contiguous `&[i64]`, the right side is empty, the span exceeds the dense
2915/// gate, the row count would overflow `u32`, or a *duplicate* right key is seen
2916/// (then the CSR path's per-bucket emission is required). For unique right keys
2917/// the emitted `(Some(left_pos), match)` pairs are byte-identical to the CSR
2918/// path: one row per left key in left order, matching the single right position
2919/// in its bucket (or `None` when absent / out of span).
2920fn dense_int64_unique_right_left_positions(
2921    left_key: &Column,
2922    right_key: &Column,
2923) -> Option<OptionalJoinPositions> {
2924    let left_values = left_key.as_i64_slice()?;
2925    let right_values = right_key.as_i64_slice()?;
2926    if right_values.is_empty() || left_values.len() > u32::MAX as usize {
2927        return None;
2928    }
2929
2930    let mut min_key = i64::MAX;
2931    let mut max_key = i64::MIN;
2932    for &key in right_values {
2933        min_key = min_key.min(key);
2934        max_key = max_key.max(key);
2935    }
2936
2937    let span = i128::from(max_key)
2938        .checked_sub(i128::from(min_key))?
2939        .checked_add(1)?;
2940    let row_count = left_values.len().saturating_add(right_values.len());
2941    let max_dense_span = row_count.saturating_mul(4).max(1024);
2942    if span > max_dense_span as i128 {
2943        return None;
2944    }
2945    let span = usize::try_from(span).ok()?;
2946    let span_i128 = i128::try_from(span).ok()?;
2947
2948    // Fill the direct-address table; a non-empty slot means a duplicate right
2949    // key, so bail to the CSR path (which handles many-to-many emission).
2950    let mut table = vec![0u32; span];
2951    for (pos, &key) in right_values.iter().enumerate() {
2952        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2953        if table[bucket] != 0 {
2954            return None;
2955        }
2956        table[bucket] = (pos as u32).checked_add(1)?;
2957    }
2958
2959    let mut left_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2960    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2961    for (left_pos, &key) in left_values.iter().enumerate() {
2962        let offset = i128::from(key) - i128::from(min_key);
2963        let matched = if (0..span_i128).contains(&offset) {
2964            match table[offset as usize] {
2965                0 => None,
2966                slot => Some(slot as usize - 1),
2967            }
2968        } else {
2969            None
2970        };
2971        left_positions.push(Some(left_pos));
2972        right_positions.push(matched);
2973    }
2974
2975    Some((left_positions, right_positions))
2976}
2977
2978fn dense_int64_left_positions(
2979    left_key: &Column,
2980    right_key: &Column,
2981) -> Option<OptionalJoinPositions> {
2982    if let Some(direct) = dense_int64_unique_right_left_positions(left_key, right_key) {
2983        return Some(direct);
2984    }
2985    let left_values = all_valid_int64_key_values(left_key)?;
2986    let right_values = all_valid_int64_key_values(right_key)?;
2987
2988    if right_values.is_empty() {
2989        let left_positions = (0..left_values.len()).map(Some).collect::<Vec<_>>();
2990        let right_positions = vec![None; left_values.len()];
2991        return Some((left_positions, right_positions));
2992    }
2993
2994    let mut min_key = i64::MAX;
2995    let mut max_key = i64::MIN;
2996    for value in right_values {
2997        let Scalar::Int64(key) = value else {
2998            return None;
2999        };
3000        min_key = min_key.min(*key);
3001        max_key = max_key.max(*key);
3002    }
3003
3004    let span = i128::from(max_key)
3005        .checked_sub(i128::from(min_key))?
3006        .checked_add(1)?;
3007    let row_count = left_values.len().saturating_add(right_values.len());
3008    let max_dense_span = row_count.saturating_mul(4).max(1024);
3009    if span > max_dense_span as i128 {
3010        return None;
3011    }
3012    let span = usize::try_from(span).ok()?;
3013    let span_i128 = i128::try_from(span).ok()?;
3014
3015    let mut right_counts = vec![0usize; span];
3016    for value in right_values {
3017        let Scalar::Int64(key) = value else {
3018            return None;
3019        };
3020        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
3021        right_counts[bucket] = right_counts[bucket].checked_add(1)?;
3022    }
3023
3024    let mut right_offsets = Vec::<usize>::with_capacity(span + 1);
3025    right_offsets.push(0);
3026    let mut running = 0usize;
3027    for count in &right_counts {
3028        running = running.checked_add(*count)?;
3029        right_offsets.push(running);
3030    }
3031
3032    let mut write_offsets = right_offsets[..span].to_vec();
3033    let mut right_positions_by_bucket = vec![0usize; right_values.len()];
3034    for (pos, value) in right_values.iter().enumerate() {
3035        let Scalar::Int64(key) = value else {
3036            return None;
3037        };
3038        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
3039        let write_idx = write_offsets[bucket];
3040        right_positions_by_bucket[write_idx] = pos;
3041        write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
3042    }
3043
3044    let mut output_len = 0usize;
3045    for value in left_values {
3046        let Scalar::Int64(key) = value else {
3047            return None;
3048        };
3049        let offset = i128::from(*key) - i128::from(min_key);
3050        let bucket_rows = if (0..span_i128).contains(&offset) {
3051            let bucket = usize::try_from(offset).ok()?;
3052            right_counts[bucket].max(1)
3053        } else {
3054            1
3055        };
3056        output_len = output_len.checked_add(bucket_rows)?;
3057    }
3058
3059    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
3060    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
3061    for (left_pos, value) in left_values.iter().enumerate() {
3062        let Scalar::Int64(key) = value else {
3063            return None;
3064        };
3065        let offset = i128::from(*key) - i128::from(min_key);
3066        if (0..span_i128).contains(&offset) {
3067            let bucket = usize::try_from(offset).ok()?;
3068            let start = right_offsets[bucket];
3069            let end = right_offsets[bucket + 1];
3070            if start != end {
3071                for &right_pos in &right_positions_by_bucket[start..end] {
3072                    left_positions.push(Some(left_pos));
3073                    right_positions.push(Some(right_pos));
3074                }
3075                continue;
3076            }
3077        }
3078        left_positions.push(Some(left_pos));
3079        right_positions.push(None);
3080    }
3081
3082    Some((left_positions, right_positions))
3083}
3084
3085/// Direct-address unique-key fast path for a bounded-span Int64 right join —
3086/// the mirror of [`dense_int64_unique_right_left_positions`]. When the *left*
3087/// (build-side) keys are unique within their span, a single fill + single probe
3088/// over one compact `u32` table replaces the CSR. Keeps every right row; bails
3089/// (caller falls back to the CSR path) on a duplicate left key, non-contiguous
3090/// backing, empty left, oversized span, or `u32` row overflow.
3091fn dense_int64_unique_left_right_positions(
3092    left_key: &Column,
3093    right_key: &Column,
3094) -> Option<OptionalJoinPositions> {
3095    let left_values = left_key.as_i64_slice()?;
3096    let right_values = right_key.as_i64_slice()?;
3097    if left_values.is_empty() || left_values.len() > u32::MAX as usize {
3098        return None;
3099    }
3100
3101    let mut min_key = i64::MAX;
3102    let mut max_key = i64::MIN;
3103    for &key in left_values {
3104        min_key = min_key.min(key);
3105        max_key = max_key.max(key);
3106    }
3107
3108    let span = i128::from(max_key)
3109        .checked_sub(i128::from(min_key))?
3110        .checked_add(1)?;
3111    let row_count = left_values.len().saturating_add(right_values.len());
3112    let max_dense_span = row_count.saturating_mul(4).max(1024);
3113    if span > max_dense_span as i128 {
3114        return None;
3115    }
3116    let span = usize::try_from(span).ok()?;
3117    let span_i128 = i128::try_from(span).ok()?;
3118
3119    let mut table = vec![0u32; span];
3120    for (pos, &key) in left_values.iter().enumerate() {
3121        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
3122        if table[bucket] != 0 {
3123            return None;
3124        }
3125        table[bucket] = (pos as u32).checked_add(1)?;
3126    }
3127
3128    let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
3129    let mut right_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
3130    for (right_pos, &key) in right_values.iter().enumerate() {
3131        let offset = i128::from(key) - i128::from(min_key);
3132        let matched = if (0..span_i128).contains(&offset) {
3133            match table[offset as usize] {
3134                0 => None,
3135                slot => Some(slot as usize - 1),
3136            }
3137        } else {
3138            None
3139        };
3140        left_positions.push(matched);
3141        right_positions.push(Some(right_pos));
3142    }
3143
3144    Some((left_positions, right_positions))
3145}
3146
3147fn dense_int64_right_positions(
3148    left_key: &Column,
3149    right_key: &Column,
3150) -> Option<OptionalJoinPositions> {
3151    if let Some(direct) = dense_int64_unique_left_right_positions(left_key, right_key) {
3152        return Some(direct);
3153    }
3154    let left_values = all_valid_int64_key_values(left_key)?;
3155    let right_values = all_valid_int64_key_values(right_key)?;
3156
3157    if left_values.is_empty() {
3158        let left_positions = vec![None; right_values.len()];
3159        let right_positions = (0..right_values.len()).map(Some).collect::<Vec<_>>();
3160        return Some((left_positions, right_positions));
3161    }
3162
3163    let mut min_key = i64::MAX;
3164    let mut max_key = i64::MIN;
3165    for value in left_values {
3166        let Scalar::Int64(key) = value else {
3167            return None;
3168        };
3169        min_key = min_key.min(*key);
3170        max_key = max_key.max(*key);
3171    }
3172
3173    let span = i128::from(max_key)
3174        .checked_sub(i128::from(min_key))?
3175        .checked_add(1)?;
3176    let row_count = left_values.len().saturating_add(right_values.len());
3177    let max_dense_span = row_count.saturating_mul(4).max(1024);
3178    if span > max_dense_span as i128 {
3179        return None;
3180    }
3181    let span = usize::try_from(span).ok()?;
3182    let span_i128 = i128::try_from(span).ok()?;
3183
3184    let mut left_counts = vec![0usize; span];
3185    for value in left_values {
3186        let Scalar::Int64(key) = value else {
3187            return None;
3188        };
3189        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
3190        left_counts[bucket] = left_counts[bucket].checked_add(1)?;
3191    }
3192
3193    let mut left_offsets = Vec::<usize>::with_capacity(span + 1);
3194    left_offsets.push(0);
3195    let mut running = 0usize;
3196    for count in &left_counts {
3197        running = running.checked_add(*count)?;
3198        left_offsets.push(running);
3199    }
3200
3201    let mut write_offsets = left_offsets[..span].to_vec();
3202    let mut left_positions_by_bucket = vec![0usize; left_values.len()];
3203    for (pos, value) in left_values.iter().enumerate() {
3204        let Scalar::Int64(key) = value else {
3205            return None;
3206        };
3207        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
3208        let write_idx = write_offsets[bucket];
3209        left_positions_by_bucket[write_idx] = pos;
3210        write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
3211    }
3212
3213    let mut output_len = 0usize;
3214    for value in right_values {
3215        let Scalar::Int64(key) = value else {
3216            return None;
3217        };
3218        let offset = i128::from(*key) - i128::from(min_key);
3219        let bucket_rows = if (0..span_i128).contains(&offset) {
3220            let bucket = usize::try_from(offset).ok()?;
3221            left_counts[bucket].max(1)
3222        } else {
3223            1
3224        };
3225        output_len = output_len.checked_add(bucket_rows)?;
3226    }
3227
3228    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
3229    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
3230    for (right_pos, value) in right_values.iter().enumerate() {
3231        let Scalar::Int64(key) = value else {
3232            return None;
3233        };
3234        let offset = i128::from(*key) - i128::from(min_key);
3235        if (0..span_i128).contains(&offset) {
3236            let bucket = usize::try_from(offset).ok()?;
3237            let start = left_offsets[bucket];
3238            let end = left_offsets[bucket + 1];
3239            if start != end {
3240                for &left_pos in &left_positions_by_bucket[start..end] {
3241                    left_positions.push(Some(left_pos));
3242                    right_positions.push(Some(right_pos));
3243                }
3244                continue;
3245            }
3246        }
3247        left_positions.push(None);
3248        right_positions.push(Some(right_pos));
3249    }
3250
3251    Some((left_positions, right_positions))
3252}
3253
3254/// Direct-address unique-key fast path for a bounded-span Int64 full-outer join.
3255/// When BOTH key sides are unique within the joint span, two compact `u32`
3256/// tables (`pos+1`, `0` == empty) plus a single ascending scan over `0..span`
3257/// replace the CSR's `Vec<Vec<usize>>` (one heap `Vec` per bucket — `span`
3258/// allocations) and the `Vec<Scalar>` materialization. Bails (caller falls back
3259/// to the bucket-list CSR) on a duplicate key on either side, non-contiguous
3260/// backing, oversized span, or `u32` row overflow.
3261///
3262/// Bit-identical for unique keys: the CSR emits one row per bucket in ascending
3263/// key (bucket) order — matched `(Some,Some)`, left-only `(Some,None)`,
3264/// right-only `(None,Some)` — which is exactly the per-bucket scan here.
3265fn dense_int64_unique_outer_positions(
3266    left_key: &Column,
3267    right_key: &Column,
3268) -> Option<OptionalJoinPositions> {
3269    let left_values = left_key.as_i64_slice()?;
3270    let right_values = right_key.as_i64_slice()?;
3271    if left_values.len() > u32::MAX as usize || right_values.len() > u32::MAX as usize {
3272        return None;
3273    }
3274
3275    let mut min_key = i64::MAX;
3276    let mut max_key = i64::MIN;
3277    let mut any = false;
3278    for &key in left_values.iter().chain(right_values.iter()) {
3279        min_key = min_key.min(key);
3280        max_key = max_key.max(key);
3281        any = true;
3282    }
3283    if !any {
3284        return Some((Vec::new(), Vec::new()));
3285    }
3286
3287    let span = i128::from(max_key)
3288        .checked_sub(i128::from(min_key))?
3289        .checked_add(1)?;
3290    let row_count = left_values.len().saturating_add(right_values.len());
3291    let max_dense_span = row_count.saturating_mul(4).max(1024);
3292    if span > max_dense_span as i128 {
3293        return None;
3294    }
3295    let span = usize::try_from(span).ok()?;
3296
3297    let mut left_table = vec![0u32; span];
3298    let mut right_table = vec![0u32; span];
3299    for (pos, &key) in left_values.iter().enumerate() {
3300        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
3301        if left_table[bucket] != 0 {
3302            return None;
3303        }
3304        left_table[bucket] = (pos as u32).checked_add(1)?;
3305    }
3306    for (pos, &key) in right_values.iter().enumerate() {
3307        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
3308        if right_table[bucket] != 0 {
3309            return None;
3310        }
3311        right_table[bucket] = (pos as u32).checked_add(1)?;
3312    }
3313
3314    let mut left_positions = Vec::<Option<usize>>::new();
3315    let mut right_positions = Vec::<Option<usize>>::new();
3316    for bucket in 0..span {
3317        match (left_table[bucket], right_table[bucket]) {
3318            (0, 0) => {}
3319            (l, 0) => {
3320                left_positions.push(Some(l as usize - 1));
3321                right_positions.push(None);
3322            }
3323            (0, r) => {
3324                left_positions.push(None);
3325                right_positions.push(Some(r as usize - 1));
3326            }
3327            (l, r) => {
3328                left_positions.push(Some(l as usize - 1));
3329                right_positions.push(Some(r as usize - 1));
3330            }
3331        }
3332    }
3333
3334    Some((left_positions, right_positions))
3335}
3336
3337fn dense_int64_outer_positions(
3338    left_key: &Column,
3339    right_key: &Column,
3340) -> Option<OptionalJoinPositions> {
3341    if let Some(direct) = dense_int64_unique_outer_positions(left_key, right_key) {
3342        return Some(direct);
3343    }
3344    let left_values = int64_key_values(left_key)?;
3345    let right_values = int64_key_values(right_key)?;
3346
3347    let fold_span = |(lo, hi): (i64, i64), &key: &i64| (lo.min(key), hi.max(key));
3348    let (min_key, max_key) = left_values
3349        .iter()
3350        .chain(right_values.iter())
3351        .fold((i64::MAX, i64::MIN), fold_span);
3352    if min_key > max_key {
3353        return Some((Vec::new(), Vec::new()));
3354    }
3355    let span = i128::from(max_key)
3356        .checked_sub(i128::from(min_key))?
3357        .checked_add(1)?;
3358    let row_count = left_values.len().saturating_add(right_values.len());
3359    let max_dense_span = row_count.saturating_mul(4).max(1024);
3360    if span > max_dense_span as i128 {
3361        return None;
3362    }
3363    let span = usize::try_from(span).ok()?;
3364    let bucket_of = |key: i64| (i128::from(key) - i128::from(min_key)) as usize;
3365
3366    // Each side's rows grouped by key in one counting pass - a bucket's
3367    // start in `starts`, its rows in position order in `rows` - where a Vec
3368    // a key was allocated, two per possible key, over the keys made Scalars
3369    // (an outer merge of 50k rows 0.75x pandas; br-frankenpandas-e186m).
3370    // The pairs come out exactly as before: keys ascending, a key's left
3371    // rows in order, each with its right rows in order.
3372    let grouped = |values: &[i64]| {
3373        let mut starts = vec![0_usize; span + 1];
3374        for &key in values {
3375            starts[bucket_of(key) + 1] += 1;
3376        }
3377        for bucket in 0..span {
3378            starts[bucket + 1] += starts[bucket];
3379        }
3380        let mut cursor = starts.clone();
3381        let mut rows = vec![0_usize; values.len()];
3382        for (pos, &key) in values.iter().enumerate() {
3383            let slot = &mut cursor[bucket_of(key)];
3384            rows[*slot] = pos;
3385            *slot += 1;
3386        }
3387        (starts, rows)
3388    };
3389    let (left_starts, left_rows) = grouped(&left_values);
3390    let (right_starts, right_rows) = grouped(&right_values);
3391
3392    let mut output_len = 0usize;
3393    for at in 0..span {
3394        let (lefts, rights) = (
3395            left_starts[at + 1] - left_starts[at],
3396            right_starts[at + 1] - right_starts[at],
3397        );
3398        let bucket_rows = match (lefts, rights) {
3399            (0, rights) => rights,
3400            (lefts, 0) => lefts,
3401            (lefts, rights) => lefts.checked_mul(rights)?,
3402        };
3403        output_len = output_len.checked_add(bucket_rows)?;
3404    }
3405
3406    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
3407    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
3408    for at in 0..span {
3409        let lefts = &left_rows[left_starts[at]..left_starts[at + 1]];
3410        let rights = &right_rows[right_starts[at]..right_starts[at + 1]];
3411        match (lefts.is_empty(), rights.is_empty()) {
3412            (false, false) => {
3413                for &left_pos in lefts {
3414                    for &right_pos in rights {
3415                        left_positions.push(Some(left_pos));
3416                        right_positions.push(Some(right_pos));
3417                    }
3418                }
3419            }
3420            (false, true) => {
3421                for &left_pos in lefts {
3422                    left_positions.push(Some(left_pos));
3423                    right_positions.push(None);
3424                }
3425            }
3426            (true, false) => {
3427                for &right_pos in rights {
3428                    left_positions.push(None);
3429                    right_positions.push(Some(right_pos));
3430                }
3431            }
3432            (true, true) => {}
3433        }
3434    }
3435
3436    Some((left_positions, right_positions))
3437}
3438
3439/// An all-valid int64 key column's values: its typed buffer, or its Scalar
3440/// view's ints ([`all_valid_int64_key_values`]).
3441fn int64_key_values(column: &Column) -> Option<std::borrow::Cow<'_, [i64]>> {
3442    if column.dtype() != DType::Int64 {
3443        return None;
3444    }
3445    if let Some(values) = column.as_i64_slice() {
3446        return Some(std::borrow::Cow::Borrowed(values));
3447    }
3448    let values = all_valid_int64_key_values(column)?;
3449    values
3450        .iter()
3451        .map(|value| match value {
3452            Scalar::Int64(key) => Some(*key),
3453            _ => None,
3454        })
3455        .collect::<Option<Vec<i64>>>()
3456        .map(std::borrow::Cow::Owned)
3457}
3458
3459fn ordered_unique_int64_outer_positions(
3460    left_key: &Column,
3461    right_key: &Column,
3462) -> Option<OptionalJoinPositions> {
3463    // Typed fast path (see ordered_unique_int64_left_match_positions): merge the
3464    // ordered union over raw &[i64] when both keys carry a contiguous Int64
3465    // backing, skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB per
3466    // merge at 1M rows). Bit-identical: same strictly-increasing gate and the
3467    // same three-way merge emitting the same (Option,Option) position pairs and
3468    // the same drain order.
3469    if let (Some(left_values), Some(right_values)) = (
3470        strictly_increasing_i64_slice(left_key),
3471        strictly_increasing_i64_slice(right_key),
3472    ) {
3473        let cap = left_values.len().saturating_add(right_values.len());
3474        // Branch-free steps: each side taken where its key is the smaller
3475        // (both when equal) and advanced by that flag - the three-way match
3476        // mispredicted on interleaved keys (two stepped 200k indexes' outer
3477        // merge 57% of 6.7 ms, 0.47x pandas; br-frankenpandas-m3z4g). The
3478        // steps counted first, then each side's positions collected over
3479        // that many steps, written in place: a push a row spilled both
3480        // vectors' lengths.
3481        let (mut left_idx, mut right_idx) = (0usize, 0usize);
3482        let mut steps = 0_usize;
3483        while left_idx < left_values.len() && right_idx < right_values.len() {
3484            let (left_value, right_value) = (left_values[left_idx], right_values[right_idx]);
3485            left_idx += usize::from(left_value <= right_value);
3486            right_idx += usize::from(right_value <= left_value);
3487            steps += 1;
3488        }
3489        let side = |left_side: bool| {
3490            let mut positions = Vec::<Option<usize>>::with_capacity(cap);
3491            let (mut left_at, mut right_at) = (0usize, 0usize);
3492            positions.extend((0..steps).map(|_| {
3493                let (left_value, right_value) = (left_values[left_at], right_values[right_at]);
3494                let take_left = left_value <= right_value;
3495                let take_right = right_value <= left_value;
3496                let taken = if left_side {
3497                    take_left.then_some(left_at)
3498                } else {
3499                    take_right.then_some(right_at)
3500                };
3501                left_at += usize::from(take_left);
3502                right_at += usize::from(take_right);
3503                taken
3504            }));
3505            positions
3506        };
3507        let mut left_positions = side(true);
3508        let mut right_positions = side(false);
3509        // The tails (one of them empty) in bulk: a push a row spilled both
3510        // lengths, and an outer join of two disjoint indexes is all tail
3511        // (br-frankenpandas-m3z4g).
3512        let left_rest = left_values.len() - left_idx;
3513        left_positions.extend((left_idx..left_values.len()).map(Some));
3514        right_positions.extend(std::iter::repeat_n(None, left_rest));
3515        let right_rest = right_values.len() - right_idx;
3516        left_positions.extend(std::iter::repeat_n(None, right_rest));
3517        right_positions.extend((right_idx..right_values.len()).map(Some));
3518        return Some((left_positions, right_positions));
3519    }
3520
3521    let left_values = strictly_increasing_int64_key_values(left_key)?;
3522    let right_values = strictly_increasing_int64_key_values(right_key)?;
3523
3524    let mut left_positions =
3525        Vec::<Option<usize>>::with_capacity(left_values.len().saturating_add(right_values.len()));
3526    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_positions.capacity());
3527    let mut left_idx = 0usize;
3528    let mut right_idx = 0usize;
3529
3530    while left_idx < left_values.len() && right_idx < right_values.len() {
3531        let left_value = match &left_values[left_idx] {
3532            Scalar::Int64(value) => *value,
3533            _ => return None,
3534        };
3535        let right_value = match &right_values[right_idx] {
3536            Scalar::Int64(value) => *value,
3537            _ => return None,
3538        };
3539
3540        match left_value.cmp(&right_value) {
3541            Ordering::Equal => {
3542                left_positions.push(Some(left_idx));
3543                right_positions.push(Some(right_idx));
3544                left_idx += 1;
3545                right_idx += 1;
3546            }
3547            Ordering::Less => {
3548                left_positions.push(Some(left_idx));
3549                right_positions.push(None);
3550                left_idx += 1;
3551            }
3552            Ordering::Greater => {
3553                left_positions.push(None);
3554                right_positions.push(Some(right_idx));
3555                right_idx += 1;
3556            }
3557        }
3558    }
3559
3560    while left_idx < left_values.len() {
3561        left_positions.push(Some(left_idx));
3562        right_positions.push(None);
3563        left_idx += 1;
3564    }
3565    while right_idx < right_values.len() {
3566        left_positions.push(None);
3567        right_positions.push(Some(right_idx));
3568        right_idx += 1;
3569    }
3570
3571    Some((left_positions, right_positions))
3572}
3573
3574fn identity_merge_column(
3575    column: &Column,
3576    row_count: usize,
3577    identity_positions: &mut Option<Vec<usize>>,
3578) -> Column {
3579    if column.validity().all() {
3580        return column.clone();
3581    }
3582
3583    let positions = identity_positions.get_or_insert_with(|| (0..row_count).collect());
3584    column.take_positions(positions)
3585}
3586
3587fn resolve_merge_indicator_name(indicator_name: Option<&str>) -> Result<Option<String>, JoinError> {
3588    let Some(name) = indicator_name else {
3589        return Ok(None);
3590    };
3591    if name.trim().is_empty() {
3592        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
3593            "merge indicator column name must be non-empty".to_owned(),
3594        )));
3595    }
3596    Ok(Some(name.to_owned()))
3597}
3598
3599fn build_merge_indicator_column(
3600    left_positions: &[Option<usize>],
3601    right_positions: &[Option<usize>],
3602) -> Column {
3603    // pandas makes `_merge` a category with the fixed categories
3604    // [left_only, right_only, both] - all three, in that order, whichever rows
3605    // appear (br-frankenpandas-hrxn9; it was an object column) - held as each
3606    // row's code into them, as pandas' Categorical: a String a row made a
3607    // Scalar-backed categorical every reader re-scanned (the merge paid
3608    // 10.7 ms for it at 190k rows, `_merge == 'both'` 0.00x pandas;
3609    // br-frankenpandas-fl3f0).
3610    let codes = left_positions
3611        .iter()
3612        .zip(right_positions.iter())
3613        .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
3614            (Some(_), None) => 0,
3615            (None, Some(_)) => 1,
3616            (Some(_), Some(_)) => 2,
3617            (None, None) => -1,
3618        })
3619        .collect::<Vec<i32>>();
3620    let categories = ["left_only", "right_only", "both"]
3621        .map(|category| fp_types::Scalar::Utf8(category.to_owned()))
3622        .to_vec();
3623    Column::from_categorical_codes(codes, fp_types::CategoricalMetadata::new(categories, false))
3624}
3625
3626fn ensure_indicator_name_available(
3627    indicator_name: &str,
3628    left_col_names: &HashSet<&String>,
3629    right_col_names: &HashSet<&String>,
3630    output_columns: &ColumnStore,
3631) -> Result<(), JoinError> {
3632    if left_col_names
3633        .iter()
3634        .any(|name| name.as_str() == indicator_name)
3635        || right_col_names
3636            .iter()
3637            .any(|name| name.as_str() == indicator_name)
3638        || output_columns.contains_key(indicator_name)
3639    {
3640        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
3641            format!("merge indicator column '{indicator_name}' conflicts with an existing column"),
3642        )));
3643    }
3644    Ok(())
3645}
3646
3647/// Positional gather that keeps an all-valid Int64 output column TYPED.
3648///
3649/// `Column::take_positions` already typed-fast-paths all-valid Float64 (it
3650/// gathers into a contiguous `Vec<f64>` behind `lazy_all_valid_float64`), but
3651/// for all-valid Int64 it materializes a `Vec<Scalar::Int64>` (32 B/elem). On
3652/// the inner-merge output build — one gather per carried column — that Scalar
3653/// rebuild dominates for integer payloads. Here we gather the contiguous `i64`
3654/// buffer directly and hand it to `from_i64_values`, which yields the same
3655/// lazy-typed all-valid Int64 column.
3656///
3657/// Bit-identical to `take_positions`: for an all-valid Int64 column the latter
3658/// produces `Scalar::Int64(slice[pos])` at every output slot with an all-valid
3659/// mask; `from_i64_values(gathered)` materializes exactly those scalars with the
3660/// same all-valid mask (no NaN coercion path for i64), and `Column` equality
3661/// ignores the internal data cache. `as_i64_slice` returns `Some` only for an
3662/// all-valid, typed-backed Int64 column, so every other dtype / any-missing
3663/// column falls through to the unchanged `take_positions`.
3664fn take_positions_typed(column: &Column, positions: &[usize]) -> Column {
3665    if let Some(slice) = column.as_i64_slice() {
3666        let mut data = Vec::with_capacity(positions.len());
3667        for &pos in positions {
3668            data.push(slice[pos]);
3669        }
3670        return Column::from_i64_values(data);
3671    }
3672    column.take_positions(positions)
3673}
3674
3675#[derive(Clone, Copy)]
3676enum PositionSelection<'a> {
3677    Positions(&'a [usize]),
3678    ContiguousRange { start: usize, len: usize },
3679}
3680
3681impl PositionSelection<'_> {
3682    fn len(self) -> usize {
3683        match self {
3684            Self::Positions(positions) => positions.len(),
3685            Self::ContiguousRange { len, .. } => len,
3686        }
3687    }
3688}
3689
3690fn take_position_selection_typed(column: &Column, selection: PositionSelection<'_>) -> Column {
3691    match selection {
3692        PositionSelection::Positions(positions) => take_positions_typed(column, positions),
3693        PositionSelection::ContiguousRange { start, len } => {
3694            column.take_contiguous_range(start, len)
3695        }
3696    }
3697}
3698
3699fn take_lower_hex_sequence_range(column: &Column, start: usize, len: usize) -> Option<Column> {
3700    let (prefix, certificate, source_len) = column.as_lower_hex_sequence_utf8()?;
3701    let end = start.checked_add(len)?;
3702    if end > source_len {
3703        return None;
3704    }
3705    let start_value = certificate.value_at(start)?;
3706    Column::from_lower_hex_sequence_utf8(prefix, start_value, len, certificate.hex_width())
3707}
3708
3709#[derive(Clone, Copy)]
3710enum FusedInt64Side {
3711    Left,
3712    Right,
3713}
3714
3715struct FusedInt64OutputColumn<'a> {
3716    name: String,
3717    side: FusedInt64Side,
3718    values: &'a [i64],
3719}
3720
3721struct FusedInt64MergeOptions<'a> {
3722    suffixes: &'a ResolvedMergeSuffixes,
3723    require_all_left_keys_matched: bool,
3724}
3725
3726#[cfg(not(test))]
3727const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1 << 18;
3728#[cfg(test)]
3729const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1;
3730const DENSE_I64_INNER_PARALLEL_MAX_CHUNKS: usize = 16;
3731
3732fn join_parallel_thread_count() -> usize {
3733    static THREAD_COUNT: OnceLock<usize> = OnceLock::new();
3734    *THREAD_COUNT.get_or_init(|| {
3735        fp_columnar::cached_available_parallelism().min(DENSE_I64_INNER_PARALLEL_MAX_CHUNKS)
3736    })
3737}
3738
3739struct DenseI64InnerOutputPlan<'a> {
3740    left_keys: &'a [i64],
3741    min: i64,
3742    max: i64,
3743    offsets: &'a [usize],
3744    positions: &'a [usize],
3745    output_len: usize,
3746}
3747
3748/// One output lane of the dense i64 inner merge.
3749enum DenseI64LaneData {
3750    /// Left lane carried as per-run values plus a shared run-length descriptor
3751    /// — O(matched) memory, expanded lazily by column consumers
3752    /// (br-frankenpandas-3ad4n, br-frankenpandas-l4adm).
3753    RepeatRunLengths {
3754        values: Vec<i64>,
3755        run_lens: Arc<[usize]>,
3756    },
3757    /// Right lane carried as repeated slices of one bucket-order value tape —
3758    /// O(right + matched) memory until a consumer forces a contiguous view.
3759    RepeatedSlices {
3760        data: Vec<i64>,
3761        segments: Arc<[(usize, usize)]>,
3762    },
3763    /// Fully materialized contiguous values.
3764    Full(Vec<i64>),
3765}
3766
3767/// Row-chunked disjoint-write fill (br-frankenpandas-6bsw3) with lazy
3768/// repeat-run left lanes (br-frankenpandas-3ad4n).
3769///
3770/// One probe walk records every matched left row as `(left_pos,
3771/// bucket_start, run_len)`. Left lanes are pure repeat runs (each left value
3772/// repeated `run_len` times), so when the average fanout is >= 2 they are
3773/// emitted as `(value, run_len)` pairs — O(matched) memory instead of
3774/// O(output) — and expanded only if a downstream consumer reads the values.
3775/// Remaining lanes (right lanes always; left lanes too on low-fanout joins
3776/// where a 16 B run would exceed the expanded bytes) are materialized by the
3777/// 6bsw3 scheme: up to [`DENSE_I64_INNER_PARALLEL_MAX_CHUNKS`] output-size-
3778/// balanced chunks of the matched list, each worker filling its disjoint
3779/// `split_at_mut` slice of every full lane (left repeat-runs via
3780/// `slice::fill`, right bucket ranges via `copy_from_slice` from the shared
3781/// muis1 value tapes).
3782///
3783/// Bit-identical: the matched list IS the left probe order; expanding a
3784/// `RepeatRunLengths` lane reproduces exactly the values the `Full` fill
3785/// writes, and chunks partition the matched list so concatenated output equals
3786/// the single-threaded walk byte for byte.
3787fn build_dense_i64_inner_output_data(
3788    specs: &[FusedInt64OutputColumn<'_>],
3789    plan: &DenseI64InnerOutputPlan<'_>,
3790) -> Vec<DenseI64LaneData> {
3791    // Single probe walk shared by every lane: matched left rows in probe
3792    // order as (left_pos, bucket_start, run_len).
3793    let mut matched: Vec<(usize, usize, usize)> = Vec::new();
3794    for (left_pos, &v) in plan.left_keys.iter().enumerate() {
3795        if v < plan.min || v > plan.max {
3796            continue;
3797        }
3798        let bucket = (v - plan.min) as usize;
3799        if bucket + 1 >= plan.offsets.len() {
3800            continue;
3801        }
3802        let start = plan.offsets[bucket];
3803        let run_len = plan.offsets[bucket + 1] - start;
3804        if run_len == 0 {
3805            continue;
3806        }
3807        matched.push((left_pos, start, run_len));
3808    }
3809    debug_assert_eq!(
3810        matched
3811            .iter()
3812            .map(|&(_, _, run_len)| run_len)
3813            .sum::<usize>(),
3814        plan.output_len
3815    );
3816
3817    // A (value, run_len) pair is 16 B vs 8 B x run_len expanded: repeat runs
3818    // only pay when the average fanout is >= 2 (1:1 joins stay materialized).
3819    let use_repeat_runs = plan.output_len >= matched.len().saturating_mul(2);
3820
3821    let use_repeated_slices = use_repeat_runs;
3822    let repeat_run_lens: Option<Arc<[usize]>> = if use_repeat_runs {
3823        Some(
3824            matched
3825                .iter()
3826                .map(|&(_, _, run_len)| run_len)
3827                .collect::<Vec<_>>()
3828                .into(),
3829        )
3830    } else {
3831        None
3832    };
3833    let repeated_segments: Option<Arc<[(usize, usize)]>> = if use_repeated_slices {
3834        Some(
3835            matched
3836                .iter()
3837                .map(|&(_, start, run_len)| (start, run_len))
3838                .collect::<Vec<_>>()
3839                .into(),
3840        )
3841    } else {
3842        None
3843    };
3844
3845    let full_specs: Vec<usize> = specs
3846        .iter()
3847        .enumerate()
3848        .filter(|(_, spec)| {
3849            !(use_repeat_runs && matches!(spec.side, FusedInt64Side::Left))
3850                && !(use_repeated_slices && matches!(spec.side, FusedInt64Side::Right))
3851        })
3852        .map(|(idx, _)| idx)
3853        .collect();
3854
3855    // Fill the full lanes first (right lanes always; left lanes on
3856    // low-fanout joins).
3857    let mut full_data: Vec<Vec<i64>> = Vec::new();
3858    let thread_count = join_parallel_thread_count();
3859    if !full_specs.is_empty()
3860        && plan.output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES
3861        && thread_count > 1
3862    {
3863        // Replay buckets from a value tape per right-side column (one gather
3864        // of right values into bucket order, per br-frankenpandas-muis1),
3865        // shared read-only across all chunk workers.
3866        let tapes: Vec<Option<Vec<i64>>> = full_specs
3867            .iter()
3868            .map(|&spec_idx| match specs[spec_idx].side {
3869                FusedInt64Side::Left => None,
3870                FusedInt64Side::Right => Some(
3871                    plan.positions
3872                        .iter()
3873                        .map(|&right_pos| specs[spec_idx].values[right_pos])
3874                        .collect(),
3875                ),
3876            })
3877            .collect();
3878
3879        // Chunk boundaries (matched_idx, out_pos), balanced by OUTPUT size
3880        // so a few hot buckets cannot starve the other workers.
3881        let target = plan.output_len.div_ceil(thread_count).max(1);
3882        let mut boundaries = vec![(0usize, 0usize)];
3883        let mut cumulative = 0usize;
3884        let mut next_target = target;
3885        for (matched_idx, &(_, _, run_len)) in matched.iter().enumerate() {
3886            cumulative += run_len;
3887            if cumulative >= next_target && matched_idx + 1 < matched.len() {
3888                boundaries.push((matched_idx + 1, cumulative));
3889                next_target = cumulative.saturating_add(target);
3890            }
3891        }
3892        boundaries.push((matched.len(), plan.output_len));
3893        let chunk_count = boundaries.len() - 1;
3894
3895        // Pre-size every full lane, then hand each chunk worker its disjoint
3896        // slice of every lane via progressive split_at_mut.
3897        let mut column_bufs: Vec<Vec<i64>> = full_specs
3898            .iter()
3899            .map(|_| vec![0i64; plan.output_len])
3900            .collect();
3901        let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
3902            .map(|_| Vec::with_capacity(full_specs.len()))
3903            .collect();
3904        for buf in &mut column_bufs {
3905            let mut rest: &mut [i64] = buf.as_mut_slice();
3906            let mut prev = 0usize;
3907            for (chunk_idx, window) in boundaries.windows(2).enumerate() {
3908                let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
3909                prev = window[1].1;
3910                rest = tail;
3911                bundles[chunk_idx].push(chunk_slice);
3912            }
3913        }
3914
3915        let matched = &matched;
3916        let full_specs = &full_specs;
3917        std::thread::scope(|scope| {
3918            let mut handles = Vec::with_capacity(chunk_count);
3919            for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
3920                let (matched_start, out_start) = boundaries[chunk_idx];
3921                let (matched_end, out_end) = boundaries[chunk_idx + 1];
3922                let tapes = &tapes;
3923                handles.push(scope.spawn(move || {
3924                    let mut cursor = 0usize;
3925                    for &(left_pos, start, run_len) in &matched[matched_start..matched_end] {
3926                        for (slice, (&spec_idx, tape)) in
3927                            bundle.iter_mut().zip(full_specs.iter().zip(tapes.iter()))
3928                        {
3929                            match specs[spec_idx].side {
3930                                FusedInt64Side::Left => {
3931                                    slice[cursor..cursor + run_len]
3932                                        .fill(specs[spec_idx].values[left_pos]);
3933                                }
3934                                FusedInt64Side::Right => {
3935                                    slice[cursor..cursor + run_len].copy_from_slice(
3936                                        &tape.as_ref().expect("right spec must have a bucket tape")
3937                                            [start..start + run_len],
3938                                    );
3939                                }
3940                            }
3941                        }
3942                        cursor += run_len;
3943                    }
3944                    debug_assert_eq!(cursor, out_end - out_start);
3945                }));
3946            }
3947            for handle in handles {
3948                handle
3949                    .join()
3950                    .expect("dense i64 output worker must not panic");
3951            }
3952        });
3953        full_data = column_bufs;
3954    } else if !full_specs.is_empty() {
3955        full_data = full_specs
3956            .iter()
3957            .map(|_| Vec::<i64>::with_capacity(plan.output_len))
3958            .collect();
3959        for &(left_pos, start, run_len) in &matched {
3960            for (out, &spec_idx) in full_data.iter_mut().zip(full_specs.iter()) {
3961                match specs[spec_idx].side {
3962                    FusedInt64Side::Left => {
3963                        out.resize(out.len() + run_len, specs[spec_idx].values[left_pos]);
3964                    }
3965                    FusedInt64Side::Right => {
3966                        for &right_pos in &plan.positions[start..start + run_len] {
3967                            out.push(specs[spec_idx].values[right_pos]);
3968                        }
3969                    }
3970                }
3971            }
3972        }
3973        debug_assert!(full_data.iter().all(|data| data.len() == plan.output_len));
3974    }
3975
3976    // Assemble lanes in spec order: repeat runs for the lazy left lanes,
3977    // filled buffers for everything else.
3978    let mut full_iter = full_data.into_iter();
3979    specs
3980        .iter()
3981        .map(|spec| {
3982            if use_repeat_runs && matches!(spec.side, FusedInt64Side::Left) {
3983                DenseI64LaneData::RepeatRunLengths {
3984                    values: matched
3985                        .iter()
3986                        .map(|&(left_pos, _, _)| spec.values[left_pos])
3987                        .collect(),
3988                    run_lens: Arc::clone(
3989                        repeat_run_lens
3990                            .as_ref()
3991                            .expect("repeat run lengths must exist"),
3992                    ),
3993                }
3994            } else if use_repeated_slices && matches!(spec.side, FusedInt64Side::Right) {
3995                DenseI64LaneData::RepeatedSlices {
3996                    data: plan
3997                        .positions
3998                        .iter()
3999                        .map(|&right_pos| spec.values[right_pos])
4000                        .collect(),
4001                    segments: Arc::clone(
4002                        repeated_segments
4003                            .as_ref()
4004                            .expect("repeated slice segments must exist"),
4005                    ),
4006                }
4007            } else {
4008                DenseI64LaneData::Full(
4009                    full_iter
4010                        .next()
4011                        .expect("full lane buffer must exist for every non-run spec"),
4012                )
4013            }
4014        })
4015        .collect()
4016}
4017
4018/// Which typed lane an output column of the dense inner merge uses, recorded in
4019/// column-encounter order so the i64 (lazy) and f64 (materialized) builds can be
4020/// re-interleaved into the original column order (br-frankenpandas-jzrem).
4021enum DenseInnerSpecKind {
4022    I64,
4023    F64,
4024}
4025
4026/// One Float64 output lane of the dense inner merge (br-frankenpandas-jzrem).
4027struct FusedF64OutputColumn<'a> {
4028    name: String,
4029    side: FusedInt64Side,
4030    values: &'a [f64],
4031}
4032
4033/// The matched-left-row list `(left_pos, bucket_start, run_len)` in probe order
4034/// — identical to the walk inside [`build_dense_i64_inner_output_data`], so the
4035/// Float64 lanes materialize in the exact same row order as the i64 lanes and
4036/// the flat `take_positions` path.
4037fn dense_inner_matched_runs(plan: &DenseI64InnerOutputPlan<'_>) -> Vec<(usize, usize, usize)> {
4038    let mut matched = Vec::new();
4039    for (left_pos, &v) in plan.left_keys.iter().enumerate() {
4040        if v < plan.min || v > plan.max {
4041            continue;
4042        }
4043        let bucket = (v - plan.min) as usize;
4044        if bucket + 1 >= plan.offsets.len() {
4045            continue;
4046        }
4047        let start = plan.offsets[bucket];
4048        let run_len = plan.offsets[bucket + 1] - start;
4049        if run_len == 0 {
4050            continue;
4051        }
4052        matched.push((left_pos, start, run_len));
4053    }
4054    matched
4055}
4056
4057/// Build one Float64 inner-merge output column as a LAZY representation
4058/// (br-frankenpandas-jzrem) — O(matched + right_len), never the O(output_len)
4059/// materialization:
4060///   * a Left column becomes a repeat-values lane: one value per matched run
4061///     (`values[left_pos]`) over the shared `run_lens` descriptor;
4062///   * a Right column becomes a repeated-slices lane over the bucket-ordered
4063///     value tape (`values` gathered by `positions`, one scattered pass) with
4064///     the shared `segments` descriptor.
4065///
4066/// Both materialize, only when a consumer reads them, to exactly the values
4067/// `take_position_selection_typed` would produce on the flat `(left_positions,
4068/// right_positions)` vectors — same values, same row order (matched-run probe
4069/// order == flat position order). Mirrors the i64 lazy lanes the all-Int64 path
4070/// already emits, so a join whose output is only sized (not consumed) stays
4071/// near-free instead of writing the whole fanned-out column.
4072fn build_dense_inner_f64_column(
4073    side: FusedInt64Side,
4074    values: &[f64],
4075    matched: &[(usize, usize, usize)],
4076    positions: &[usize],
4077    run_lens: &Arc<[usize]>,
4078    segments: &Arc<[(usize, usize)]>,
4079    output_len: usize,
4080) -> Column {
4081    match side {
4082        FusedInt64Side::Left => {
4083            let run_values: Vec<f64> = matched
4084                .iter()
4085                .map(|&(left_pos, _, _)| values[left_pos])
4086                .collect();
4087            Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
4088        }
4089        FusedInt64Side::Right => {
4090            let tape: Vec<f64> = positions.iter().map(|&p| values[p]).collect();
4091            Column::from_f64_repeated_slices_shared(tape, Arc::clone(segments), output_len)
4092        }
4093    }
4094}
4095
4096/// Build every Float64 inner-merge output column, one worker per column when the
4097/// pool is worth it (the fu8f5 column-parallel pattern). Returns `(name, column)`
4098/// pairs in `specs` order. `run_lens`/`segments` are the shared lazy-lane
4099/// descriptors derived from the matched-run list (one per matched run).
4100fn build_dense_inner_f64_columns(
4101    specs: Vec<FusedF64OutputColumn<'_>>,
4102    matched: &[(usize, usize, usize)],
4103    positions: &[usize],
4104    output_len: usize,
4105) -> Vec<(String, Column)> {
4106    if specs.is_empty() {
4107        return Vec::new();
4108    }
4109    let run_lens: Arc<[usize]> = matched.iter().map(|&(_, _, run_len)| run_len).collect();
4110    let segments: Arc<[(usize, usize)]> = matched
4111        .iter()
4112        .map(|&(_, bucket_start, run_len)| (bucket_start, run_len))
4113        .collect();
4114
4115    let worker_count = join_parallel_thread_count().min(specs.len());
4116    if worker_count < 2 {
4117        return specs
4118            .into_iter()
4119            .map(|s| {
4120                (
4121                    s.name,
4122                    build_dense_inner_f64_column(
4123                        s.side, s.values, matched, positions, &run_lens, &segments, output_len,
4124                    ),
4125                )
4126            })
4127            .collect();
4128    }
4129
4130    let next = std::sync::atomic::AtomicUsize::new(0);
4131    let specs_ref = &specs;
4132    let run_lens_ref = &run_lens;
4133    let segments_ref = &segments;
4134    let built_by_worker = std::thread::scope(|scope| {
4135        let mut handles = Vec::with_capacity(worker_count);
4136        for _ in 0..worker_count {
4137            let next = &next;
4138            handles.push(scope.spawn(move || {
4139                let mut local: Vec<(usize, Column)> = Vec::new();
4140                loop {
4141                    let idx = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4142                    if idx >= specs_ref.len() {
4143                        break;
4144                    }
4145                    let s = &specs_ref[idx];
4146                    local.push((
4147                        idx,
4148                        build_dense_inner_f64_column(
4149                            s.side,
4150                            s.values,
4151                            matched,
4152                            positions,
4153                            run_lens_ref,
4154                            segments_ref,
4155                            output_len,
4156                        ),
4157                    ));
4158                }
4159                local
4160            }));
4161        }
4162        let mut all: Vec<(usize, Column)> = Vec::new();
4163        for handle in handles {
4164            all.extend(
4165                handle
4166                    .join()
4167                    .expect("f64 inner-merge column worker panicked"),
4168            );
4169        }
4170        all
4171    });
4172
4173    let mut built: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
4174    for (idx, column) in built_by_worker {
4175        built[idx] = Some(column);
4176    }
4177    specs
4178        .into_iter()
4179        .zip(built)
4180        .map(|(s, column)| {
4181            (
4182                s.name,
4183                column.expect("every f64 column index is built once"),
4184            )
4185        })
4186        .collect()
4187}
4188
4189fn build_single_key_dense_i64_inner_merge_output(
4190    left: &fp_frame::DataFrame,
4191    right: &fp_frame::DataFrame,
4192    left_on: &[&str],
4193    right_on: &[&str],
4194    left_key: &Column,
4195    right_key: &Column,
4196    options: FusedInt64MergeOptions<'_>,
4197) -> Result<Option<MergedDataFrame>, JoinError> {
4198    debug_assert_eq!(left_on.len(), 1);
4199    debug_assert_eq!(right_on.len(), 1);
4200
4201    let Some(left_keys) = left_key.as_i64_slice() else {
4202        return Ok(None);
4203    };
4204    let Some(right_keys) = right_key.as_i64_slice() else {
4205        return Ok(None);
4206    };
4207
4208    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4209    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4210    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4211    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4212    let shared_key_names = if left_on[0] == right_on[0] {
4213        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4214    } else {
4215        HashSet::new()
4216    };
4217    let overlapping_names =
4218        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4219
4220    // Collect output specs in column-encounter order, accepting BOTH typed
4221    // all-valid Int64 and typed all-valid Float64 columns (br-frankenpandas-jzrem).
4222    // Int64 columns keep the lazy repeat-run / repeated-slice representation;
4223    // Float64 columns are materialized cache-efficiently below. Any other dtype,
4224    // a nullable column, or a NaN-bearing Float64 (as_f64_slice gates on
4225    // validity.all()) declines the whole fast path (Ok(None)) and falls back to
4226    // the flat gather, exactly as before.
4227    let mut i64_specs = Vec::<FusedInt64OutputColumn<'_>>::new();
4228    let mut f64_specs = Vec::<FusedF64OutputColumn<'_>>::new();
4229    let mut order_kinds = Vec::<DenseInnerSpecKind>::new();
4230
4231    for name in left.column_names() {
4232        let col = left
4233            .columns()
4234            .get(name)
4235            .expect("left column listed in column_names must exist");
4236        let out_name = if left_key_name_set.contains(name.as_str()) {
4237            name.clone()
4238        } else if right_col_names.contains(name) {
4239            apply_merge_suffix(name, options.suffixes.left.as_deref())
4240        } else {
4241            name.clone()
4242        };
4243        if let Some(values) = col.as_i64_slice() {
4244            i64_specs.push(FusedInt64OutputColumn {
4245                name: out_name,
4246                side: FusedInt64Side::Left,
4247                values,
4248            });
4249            order_kinds.push(DenseInnerSpecKind::I64);
4250        } else if let Some(values) = col.as_f64_slice() {
4251            f64_specs.push(FusedF64OutputColumn {
4252                name: out_name,
4253                side: FusedInt64Side::Left,
4254                values,
4255            });
4256            order_kinds.push(DenseInnerSpecKind::F64);
4257        } else {
4258            return Ok(None);
4259        }
4260    }
4261
4262    for name in right.column_names() {
4263        let col = right
4264            .columns()
4265            .get(name)
4266            .expect("right column listed in column_names must exist");
4267        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4268            continue;
4269        }
4270        let out_name = if left_col_names.contains(name) {
4271            apply_merge_suffix(name, options.suffixes.right.as_deref())
4272        } else {
4273            name.clone()
4274        };
4275        if let Some(values) = col.as_i64_slice() {
4276            i64_specs.push(FusedInt64OutputColumn {
4277                name: out_name,
4278                side: FusedInt64Side::Right,
4279                values,
4280            });
4281            order_kinds.push(DenseInnerSpecKind::I64);
4282        } else if let Some(values) = col.as_f64_slice() {
4283            f64_specs.push(FusedF64OutputColumn {
4284                name: out_name,
4285                side: FusedInt64Side::Right,
4286                values,
4287            });
4288            order_kinds.push(DenseInnerSpecKind::F64);
4289        } else {
4290            return Ok(None);
4291        }
4292    }
4293
4294    ensure_merge_suffixes_for_overlaps(&overlapping_names, options.suffixes)?;
4295
4296    if left_keys.is_empty() || right_keys.is_empty() {
4297        if options.require_all_left_keys_matched && !left_keys.is_empty() {
4298            return Ok(None);
4299        }
4300        let mut columns = ColumnStore::new();
4301        let mut column_order = Vec::with_capacity(order_kinds.len());
4302        let mut i64_it = i64_specs.into_iter();
4303        let mut f64_it = f64_specs.into_iter();
4304        for kind in &order_kinds {
4305            match kind {
4306                DenseInnerSpecKind::I64 => {
4307                    let spec = i64_it.next().expect("i64 spec for each I64 kind");
4308                    insert_merged_output_column(
4309                        &mut columns,
4310                        &mut column_order,
4311                        spec.name,
4312                        Column::from_i64_values(Vec::new()),
4313                    )?;
4314                }
4315                DenseInnerSpecKind::F64 => {
4316                    let spec = f64_it.next().expect("f64 spec for each F64 kind");
4317                    insert_merged_output_column(
4318                        &mut columns,
4319                        &mut column_order,
4320                        spec.name,
4321                        Column::from_f64_values(Vec::new()),
4322                    )?;
4323                }
4324            }
4325        }
4326        return Ok(Some(MergedDataFrame {
4327            index: Index::new(Vec::new()),
4328            columns,
4329            column_order,
4330        }));
4331    }
4332
4333    let mut min = right_keys[0];
4334    let mut max = right_keys[0];
4335    for &v in right_keys {
4336        if v < min {
4337            min = v;
4338        }
4339        if v > max {
4340            max = v;
4341        }
4342    }
4343    let span = (max as i128) - (min as i128) + 1;
4344    if span > (1i128 << 24) || span > 16 * (right_keys.len() as i128) {
4345        return Ok(None);
4346    }
4347    let range = span as usize;
4348
4349    let mut offsets = vec![0usize; range + 1];
4350    for &v in right_keys {
4351        offsets[(v - min) as usize + 1] += 1;
4352    }
4353    for i in 0..range {
4354        offsets[i + 1] += offsets[i];
4355    }
4356    let mut positions = vec![0usize; right_keys.len()];
4357    let mut cursor = offsets.clone();
4358    for (pos, &v) in right_keys.iter().enumerate() {
4359        let bucket = (v - min) as usize;
4360        positions[cursor[bucket]] = pos;
4361        cursor[bucket] += 1;
4362    }
4363
4364    let mut output_len = 0usize;
4365    let mut all_left_matched_once = true;
4366    for &v in left_keys {
4367        if v < min || v > max {
4368            if options.require_all_left_keys_matched {
4369                return Ok(None);
4370            }
4371            all_left_matched_once = false;
4372            continue;
4373        }
4374        let bucket = (v - min) as usize;
4375        let bucket_len = offsets[bucket + 1] - offsets[bucket];
4376        if bucket_len == 0 {
4377            if options.require_all_left_keys_matched {
4378                return Ok(None);
4379            }
4380            all_left_matched_once = false;
4381            continue;
4382        }
4383        if bucket_len != 1 {
4384            all_left_matched_once = false;
4385        }
4386        let Some(new_output_len) = output_len.checked_add(bucket_len) else {
4387            return Ok(None);
4388        };
4389        output_len = new_output_len;
4390    }
4391    // When `output_len == left_keys.len()` via duplicate matches + unmatched
4392    // left rows, pandas `libjoin.inner_join(..., sort=False)` applies its
4393    // `len(left_indexer) == len(left)` rev[left_sorter] permutation; hand off
4394    // to the position-based inner merge path so `permute_inner_merge_equal_left_len_positions`
4395    // orders the rows identically (br-frankenpandas-ml0az).
4396    if !options.require_all_left_keys_matched
4397        && output_len == left_keys.len()
4398        && !all_left_matched_once
4399    {
4400        return Ok(None);
4401    }
4402
4403    let output_plan = DenseI64InnerOutputPlan {
4404        left_keys,
4405        min,
4406        max,
4407        offsets: &offsets,
4408        positions: &positions,
4409        output_len,
4410    };
4411    let i64_lanes = build_dense_i64_inner_output_data(&i64_specs, &output_plan);
4412    // Float64 lanes materialized cache-efficiently in the same probe row order
4413    // (br-frankenpandas-jzrem); the matched-run walk is only needed when there
4414    // are Float64 columns to build.
4415    let matched = if f64_specs.is_empty() {
4416        Vec::new()
4417    } else {
4418        dense_inner_matched_runs(&output_plan)
4419    };
4420    let f64_columns = build_dense_inner_f64_columns(f64_specs, &matched, &positions, output_len);
4421
4422    // Lazy unit-range output index: identical labels (0..output_len as
4423    // IndexLabel::Int64, materialized on demand), pre-proven unique and
4424    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
4425    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4426    let mut columns = ColumnStore::new();
4427    let mut column_order = Vec::with_capacity(order_kinds.len());
4428    let mut i64_it = i64_specs.into_iter().zip(i64_lanes);
4429    let mut f64_it = f64_columns.into_iter();
4430    for kind in &order_kinds {
4431        match kind {
4432            DenseInnerSpecKind::I64 => {
4433                let (spec, lane) = i64_it.next().expect("i64 lane for each I64 kind");
4434                let column = match lane {
4435                    DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
4436                        Column::from_i64_repeat_values_run_lengths(values, run_lens)
4437                    }
4438                    DenseI64LaneData::RepeatedSlices { data, segments } => {
4439                        Column::from_i64_repeated_slices_shared(data, segments, output_len)
4440                    }
4441                    DenseI64LaneData::Full(data) => Column::from_i64_values(data),
4442                };
4443                debug_assert_eq!(column.len(), output_len);
4444                insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
4445            }
4446            DenseInnerSpecKind::F64 => {
4447                let (name, column) = f64_it.next().expect("f64 column for each F64 kind");
4448                debug_assert_eq!(column.len(), output_len);
4449                insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
4450            }
4451        }
4452    }
4453
4454    Ok(Some(MergedDataFrame {
4455        index,
4456        columns,
4457        column_order,
4458    }))
4459}
4460
4461fn push_join_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
4462    if len == 0 {
4463        return;
4464    }
4465    if let Some((last_start, last_len)) = ranges.last_mut()
4466        && last_start.checked_add(*last_len) == Some(start)
4467    {
4468        *last_len += len;
4469        return;
4470    }
4471    ranges.push((start, len));
4472}
4473
4474fn dense_cycle_key_at(witness: Int64DenseCycleWitness, row: usize) -> Option<i64> {
4475    let offset = i64::try_from(row % witness.period).ok()?;
4476    witness.start.checked_add(offset)
4477}
4478
4479fn dense_cycle_left_join_shape(
4480    left_witness: Int64DenseCycleWitness,
4481    right_witness: Int64DenseCycleWitness,
4482) -> Option<(usize, ValidityMask)> {
4483    let mut output_len = 0usize;
4484    let mut invalid_ranges = Vec::<(usize, usize)>::new();
4485    for left_pos in 0..left_witness.len {
4486        let key = dense_cycle_key_at(left_witness, left_pos)?;
4487        if let Some((_, right_count)) = right_witness.offset_count_for_key(key) {
4488            output_len = output_len.checked_add(right_count)?;
4489        } else {
4490            push_join_invalid_range(&mut invalid_ranges, output_len, 1);
4491            output_len = output_len.checked_add(1)?;
4492        }
4493    }
4494    let right_validity = ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len);
4495    Some((output_len, right_validity))
4496}
4497
4498/// Dense-cycle LEFT merge builder (br-frankenpandas-yq96z).
4499///
4500/// For certified `key[row] = start + (row % period)` Int64 keys, the previous
4501/// high-fanout left path still built an O(left_rows) plan, right segment tape,
4502/// and one repeat-run descriptor per left lane. This path keeps the same
4503/// left-major pandas order but stores only the two key witnesses:
4504///
4505/// - output length/right validity are derived by scanning the left witness once;
4506/// - left lanes read `source[left_pos]` and repeat by the matching right count;
4507/// - right lanes replay positions `right_offset + k * right_period`;
4508/// - unmatched left rows emit one right null at the same output slot.
4509///
4510/// The route accepts only all-valid Int64 columns. Any other dtype/null shape
4511/// falls back to the existing materialized-plan builder.
4512fn build_single_key_dense_cycle_i64_left_merge_output(
4513    left: &fp_frame::DataFrame,
4514    right: &fp_frame::DataFrame,
4515    left_on: &[&str],
4516    right_on: &[&str],
4517    left_key: &Column,
4518    right_key: &Column,
4519    suffixes: &ResolvedMergeSuffixes,
4520) -> Result<Option<MergedDataFrame>, JoinError> {
4521    debug_assert_eq!(left_on.len(), 1);
4522    debug_assert_eq!(right_on.len(), 1);
4523
4524    let Some(left_witness) = left_key
4525        .int64_dense_cycle_witness()
4526        .filter(|witness| witness.len == left_key.len())
4527    else {
4528        return Ok(None);
4529    };
4530    let Some(right_witness) = right_key
4531        .int64_dense_cycle_witness()
4532        .filter(|witness| witness.len == right_key.len())
4533    else {
4534        return Ok(None);
4535    };
4536    let Some((output_len, right_validity)) =
4537        dense_cycle_left_join_shape(left_witness, right_witness)
4538    else {
4539        return Ok(None);
4540    };
4541    if !right_validity.all() {
4542        // The generic gather promotes all-valid Int64 lanes when this join
4543        // invents a gap. This lazy i64-only representation cannot do so.
4544        return Ok(None);
4545    }
4546
4547    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4548    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4549    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4550    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4551    let shared_key_names = if left_on[0] == right_on[0] {
4552        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4553    } else {
4554        HashSet::new()
4555    };
4556    let overlapping_names =
4557        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4558
4559    enum DenseCycleLeftLane {
4560        Left,
4561        Right,
4562    }
4563    let mut spec_names = Vec::<String>::new();
4564    let mut spec_kinds = Vec::<DenseCycleLeftLane>::new();
4565    let mut spec_sources = Vec::<Arc<[i64]>>::new();
4566
4567    for name in left.column_names() {
4568        let col = left
4569            .columns()
4570            .get(name)
4571            .expect("left column listed in column_names must exist");
4572        let Some(source) = col.as_i64_arc() else {
4573            return Ok(None);
4574        };
4575        let out_name = if left_key_name_set.contains(name.as_str()) {
4576            name.clone()
4577        } else if right_col_names.contains(name) {
4578            apply_merge_suffix(name, suffixes.left.as_deref())
4579        } else {
4580            name.clone()
4581        };
4582        spec_names.push(out_name);
4583        spec_kinds.push(DenseCycleLeftLane::Left);
4584        spec_sources.push(source);
4585    }
4586
4587    for name in right.column_names() {
4588        let col = right
4589            .columns()
4590            .get(name)
4591            .expect("right column listed in column_names must exist");
4592        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4593            continue;
4594        }
4595        let Some(source) = col.as_i64_arc() else {
4596            return Ok(None);
4597        };
4598        let out_name = if left_col_names.contains(name) {
4599            apply_merge_suffix(name, suffixes.right.as_deref())
4600        } else {
4601            name.clone()
4602        };
4603        spec_names.push(out_name);
4604        spec_kinds.push(DenseCycleLeftLane::Right);
4605        spec_sources.push(source);
4606    }
4607    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4608
4609    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4610    let mut columns = ColumnStore::new();
4611    let mut column_order = Vec::with_capacity(spec_names.len());
4612    for ((name, kind), source) in spec_names.into_iter().zip(spec_kinds).zip(spec_sources) {
4613        let column = match kind {
4614            DenseCycleLeftLane::Left => Column::from_i64_left_join_dense_cycle_left(
4615                source,
4616                left_witness,
4617                right_witness,
4618                output_len,
4619            ),
4620            DenseCycleLeftLane::Right => Column::from_i64_left_join_dense_cycle_right_nullable(
4621                source,
4622                left_witness,
4623                right_witness,
4624                right_validity.clone(),
4625                output_len,
4626            ),
4627        };
4628        debug_assert_eq!(column.len(), output_len);
4629        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
4630    }
4631
4632    Ok(Some(MergedDataFrame {
4633        index,
4634        columns,
4635        column_order,
4636    }))
4637}
4638
4639/// Fused dense-i64 LEFT merge builder (br-frankenpandas-7wxoc).
4640///
4641/// The partial-match left join previously materialized TWO
4642/// `Vec<Option<usize>>` of output length (16 B/slot each — ~627 MB of
4643/// intermediate on a 19.6M-row join) in `dense_int64_left_positions`, then
4644/// re-walked them per column through `reindex_by_positions`. Here the probe
4645/// emits a compact matched plan (`(left_pos, bucket_start, run_len)`, with
4646/// `usize::MAX` as the bucket sentinel for unmatched left rows that emit one
4647/// null-right row), and the output lanes are built with the proven inner-
4648/// builder machinery: muis1 right value tapes, 6bsw3 row-chunked disjoint
4649/// `split_at_mut` fills, 3ad4n lazy repeat-run left lanes, plus ONE shared
4650/// validity mask for every right lane (the null pattern is identical across
4651/// them — word-wise run fills, cloned per lane).
4652///
4653/// Bit-identical to the position-vector path: the plan is the same left
4654/// probe order; matched runs replay the same CSR bucket ranges; right lanes
4655/// keep dtype Int64 with `Null(NullKind::Null)` at unmatched rows (exactly
4656/// `reindex_by_positions`' missing semantics); left lanes repeat the left
4657/// value `run_len` times as `take_positions` would.
4658fn build_single_key_dense_i64_left_merge_output(
4659    left: &fp_frame::DataFrame,
4660    right: &fp_frame::DataFrame,
4661    left_on: &[&str],
4662    right_on: &[&str],
4663    left_key: &Column,
4664    right_key: &Column,
4665    suffixes: &ResolvedMergeSuffixes,
4666) -> Result<Option<MergedDataFrame>, JoinError> {
4667    debug_assert_eq!(left_on.len(), 1);
4668    debug_assert_eq!(right_on.len(), 1);
4669
4670    let Some(left_keys) = left_key.as_i64_slice() else {
4671        return Ok(None);
4672    };
4673    let Some(right_keys) = right_key.as_i64_slice() else {
4674        return Ok(None);
4675    };
4676    // Empty sides are rare and the position-vector path handles their edge
4677    // semantics; the dense-span gate below also needs a non-empty right.
4678    if left_keys.is_empty() || right_keys.is_empty() {
4679        return Ok(None);
4680    }
4681
4682    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4683    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4684    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4685    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4686    let shared_key_names = if left_on[0] == right_on[0] {
4687        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4688    } else {
4689        HashSet::new()
4690    };
4691    let overlapping_names =
4692        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4693
4694    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
4695    let mut sources = Vec::<Arc<[i64]>>::new();
4696    for name in left.column_names() {
4697        let col = left
4698            .columns()
4699            .get(name)
4700            .expect("left column listed in column_names must exist");
4701        let Some(values) = col.as_i64_slice() else {
4702            return Ok(None);
4703        };
4704        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4705        let out_name = if left_key_name_set.contains(name.as_str()) {
4706            name.clone()
4707        } else if right_col_names.contains(name) {
4708            apply_merge_suffix(name, suffixes.left.as_deref())
4709        } else {
4710            name.clone()
4711        };
4712        specs.push(FusedInt64OutputColumn {
4713            name: out_name,
4714            side: FusedInt64Side::Left,
4715            values,
4716        });
4717        sources.push(source);
4718    }
4719    for name in right.column_names() {
4720        let col = right
4721            .columns()
4722            .get(name)
4723            .expect("right column listed in column_names must exist");
4724        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4725            continue;
4726        }
4727        let Some(values) = col.as_i64_slice() else {
4728            return Ok(None);
4729        };
4730        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4731        let out_name = if left_col_names.contains(name) {
4732            apply_merge_suffix(name, suffixes.right.as_deref())
4733        } else {
4734            name.clone()
4735        };
4736        specs.push(FusedInt64OutputColumn {
4737            name: out_name,
4738            side: FusedInt64Side::Right,
4739            values,
4740        });
4741        sources.push(source);
4742    }
4743    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4744
4745    let row_count = left_keys.len().saturating_add(right_keys.len());
4746    let max_dense_span = row_count.saturating_mul(4).max(1024);
4747    let left_witness = left_key
4748        .int64_dense_cycle_witness()
4749        .filter(|witness| witness.len == left_keys.len());
4750    let right_witness = right_key
4751        .int64_dense_cycle_witness()
4752        .filter(|witness| witness.len == right_keys.len());
4753    if let (Some(left_witness), Some(right_witness), Some((right_min, right_max))) = (
4754        left_witness,
4755        right_witness,
4756        right_witness.and_then(dense_cycle_domain),
4757    ) {
4758        let right_span = i128::from(right_max) - i128::from(right_min) + 1;
4759        if right_span <= max_dense_span as i128
4760            && let Some((output_len, right_validity)) =
4761                dense_cycle_probe_output_len_and_validity(left_witness, right_witness)
4762        {
4763            if !right_validity.all() {
4764                // Fall through to the typed gather below, which widens the
4765                // gap-bearing Int64 lanes to Float64 like pandas.
4766            } else {
4767                let index = Index::new_known_unique_int64_unit_range(0, output_len);
4768                let mut columns = ColumnStore::new();
4769                let mut column_order = Vec::with_capacity(specs.len());
4770                for (spec, source) in specs.into_iter().zip(sources) {
4771                    let column = match spec.side {
4772                        FusedInt64Side::Left => Column::from_i64_dense_cycle_probe_repeat(
4773                            source,
4774                            left_witness,
4775                            right_witness,
4776                            output_len,
4777                        ),
4778                        FusedInt64Side::Right => {
4779                            Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
4780                                source,
4781                                left_witness,
4782                                right_witness,
4783                                right_validity.clone(),
4784                                output_len,
4785                            )
4786                        }
4787                    };
4788                    debug_assert_eq!(column.len(), output_len);
4789                    insert_merged_output_column(
4790                        &mut columns,
4791                        &mut column_order,
4792                        spec.name,
4793                        column,
4794                    )?;
4795                }
4796                return Ok(Some(MergedDataFrame {
4797                    index,
4798                    columns,
4799                    column_order,
4800                }));
4801            }
4802        }
4803    }
4804
4805    // Dense CSR over the RIGHT key range — same gate as the position path
4806    // (span <= 4*(rows)+1024) so routing between fused/fallback matches
4807    // dense_int64_left_positions' accept set.
4808    let mut min_key = right_keys[0];
4809    let mut max_key = right_keys[0];
4810    for &key in right_keys {
4811        min_key = min_key.min(key);
4812        max_key = max_key.max(key);
4813    }
4814    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
4815    if span > max_dense_span as i128 {
4816        return Ok(None);
4817    }
4818    let span = usize::try_from(span).expect("span bounded by max_dense_span");
4819
4820    let mut offsets = vec![0usize; span + 1];
4821    for &key in right_keys {
4822        offsets[(key - min_key) as usize + 1] += 1;
4823    }
4824    for i in 0..span {
4825        offsets[i + 1] += offsets[i];
4826    }
4827    let mut positions = vec![0usize; right_keys.len()];
4828    let mut cursor = offsets[..span].to_vec();
4829    for (pos, &key) in right_keys.iter().enumerate() {
4830        let bucket = (key - min_key) as usize;
4831        positions[cursor[bucket]] = pos;
4832        cursor[bucket] += 1;
4833    }
4834
4835    // Matched plan: (left_pos, bucket_start, run_len); bucket_start ==
4836    // usize::MAX marks an unmatched left row (one output row, null right).
4837    const UNMATCHED: usize = usize::MAX;
4838    let mut plan = Vec::<(usize, usize, usize)>::with_capacity(left_keys.len());
4839    let mut output_len = 0usize;
4840    for (left_pos, &key) in left_keys.iter().enumerate() {
4841        let offset = i128::from(key) - i128::from(min_key);
4842        let run = if offset >= 0 && offset < span as i128 {
4843            let bucket = offset as usize;
4844            let start = offsets[bucket];
4845            let len = offsets[bucket + 1] - start;
4846            if len == 0 {
4847                (left_pos, UNMATCHED, 1)
4848            } else {
4849                (left_pos, start, len)
4850            }
4851        } else {
4852            (left_pos, UNMATCHED, 1)
4853        };
4854        let Some(new_len) = output_len.checked_add(run.2) else {
4855            return Ok(None);
4856        };
4857        output_len = new_len;
4858        plan.push(run);
4859    }
4860    if plan.iter().any(|&(_, start, _)| start == UNMATCHED) {
4861        return Ok(None);
4862    }
4863
4864    // Shared right-lane segment descriptor (br-frankenpandas-yiqv5): the plan's
4865    // `(bucket_start, run_len)` pairs are exactly the nullable repeated-slices
4866    // segment format (`bucket_start == usize::MAX` == UNMATCHED ⇒ a null run), so
4867    // every right lane is emitted as a LAZY `LazyNullableRepeatedSlicesInt64`
4868    // over its bucket-order value tape instead of a materialized O(output_len)
4869    // buffer. The validity mask is rebuilt from these segments inside the column
4870    // ctor (matched runs valid, unmatched rows null) — identical to the prior
4871    // word-wise fill.
4872    let right_segments: Arc<[(usize, usize)]> = plan
4873        .iter()
4874        .map(|&(_, start, run_len)| (start, run_len))
4875        .collect();
4876
4877    // Left lanes as lazy repeat runs when the average fanout pays (3ad4n
4878    // gate); unmatched rows are singleton runs so the representation is
4879    // uniform.
4880    let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
4881
4882    // Only LOW-FANOUT LEFT lanes still materialize into O(output_len) buffers;
4883    // right lanes are always lazy (nullable repeated-slices) and high-fanout
4884    // left lanes are lazy repeat runs.
4885    let full_specs: Vec<usize> = specs
4886        .iter()
4887        .enumerate()
4888        .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Left) && !use_repeat_runs)
4889        .map(|(idx, _)| idx)
4890        .collect();
4891
4892    let mut full_data: Vec<Vec<i64>> = Vec::new();
4893    let thread_count = join_parallel_thread_count();
4894    if !full_specs.is_empty() {
4895        // Right value tapes in bucket order (muis1), shared read-only.
4896        let tapes: Vec<Option<Vec<i64>>> = full_specs
4897            .iter()
4898            .map(|&spec_idx| match specs[spec_idx].side {
4899                FusedInt64Side::Left => None,
4900                FusedInt64Side::Right => Some(
4901                    positions
4902                        .iter()
4903                        .map(|&right_pos| specs[spec_idx].values[right_pos])
4904                        .collect(),
4905                ),
4906            })
4907            .collect();
4908
4909        if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
4910            // Output-balanced chunk boundaries over the plan (6bsw3).
4911            let target = output_len.div_ceil(thread_count).max(1);
4912            let mut boundaries = vec![(0usize, 0usize)];
4913            let mut cumulative = 0usize;
4914            let mut next_target = target;
4915            for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
4916                cumulative += run_len;
4917                if cumulative >= next_target && plan_idx + 1 < plan.len() {
4918                    boundaries.push((plan_idx + 1, cumulative));
4919                    next_target = cumulative.saturating_add(target);
4920                }
4921            }
4922            boundaries.push((plan.len(), output_len));
4923            let chunk_count = boundaries.len() - 1;
4924
4925            let mut column_bufs: Vec<Vec<i64>> =
4926                full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4927            let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
4928                .map(|_| Vec::with_capacity(full_specs.len()))
4929                .collect();
4930            for buf in &mut column_bufs {
4931                let mut rest: &mut [i64] = buf.as_mut_slice();
4932                let mut prev = 0usize;
4933                for (chunk_idx, window) in boundaries.windows(2).enumerate() {
4934                    let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
4935                    prev = window[1].1;
4936                    rest = tail;
4937                    bundles[chunk_idx].push(chunk_slice);
4938                }
4939            }
4940
4941            let plan = &plan;
4942            let specs_ref = &specs;
4943            let full_specs_ref = &full_specs;
4944            std::thread::scope(|scope| {
4945                let mut handles = Vec::with_capacity(chunk_count);
4946                for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
4947                    let (plan_start, out_start) = boundaries[chunk_idx];
4948                    let (plan_end, out_end) = boundaries[chunk_idx + 1];
4949                    let tapes = &tapes;
4950                    handles.push(scope.spawn(move || {
4951                        let mut cursor = 0usize;
4952                        for &(left_pos, start, run_len) in &plan[plan_start..plan_end] {
4953                            for (slice, (&spec_idx, tape)) in bundle
4954                                .iter_mut()
4955                                .zip(full_specs_ref.iter().zip(tapes.iter()))
4956                            {
4957                                match specs_ref[spec_idx].side {
4958                                    FusedInt64Side::Left => {
4959                                        slice[cursor..cursor + run_len]
4960                                            .fill(specs_ref[spec_idx].values[left_pos]);
4961                                    }
4962                                    FusedInt64Side::Right => {
4963                                        if start != UNMATCHED {
4964                                            slice[cursor..cursor + run_len].copy_from_slice(
4965                                                &tape
4966                                                    .as_ref()
4967                                                    .expect("right spec must have a bucket tape")
4968                                                    [start..start + run_len],
4969                                            );
4970                                        }
4971                                        // Unmatched rows keep the zeroed
4972                                        // datum; the shared validity mask
4973                                        // marks them null.
4974                                    }
4975                                }
4976                            }
4977                            cursor += run_len;
4978                        }
4979                        debug_assert_eq!(cursor, out_end - out_start);
4980                    }));
4981                }
4982                for handle in handles {
4983                    handle
4984                        .join()
4985                        .expect("dense i64 left output worker must not panic");
4986                }
4987            });
4988            full_data = column_bufs;
4989        } else {
4990            full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4991            let mut cursor = 0usize;
4992            for &(left_pos, start, run_len) in &plan {
4993                for (buf, (&spec_idx, tape)) in full_data
4994                    .iter_mut()
4995                    .zip(full_specs.iter().zip(tapes.iter()))
4996                {
4997                    match specs[spec_idx].side {
4998                        FusedInt64Side::Left => {
4999                            buf[cursor..cursor + run_len].fill(specs[spec_idx].values[left_pos]);
5000                        }
5001                        FusedInt64Side::Right => {
5002                            if start != UNMATCHED {
5003                                buf[cursor..cursor + run_len].copy_from_slice(
5004                                    &tape.as_ref().expect("right spec must have a bucket tape")
5005                                        [start..start + run_len],
5006                                );
5007                            }
5008                        }
5009                    }
5010                }
5011                cursor += run_len;
5012            }
5013            debug_assert_eq!(cursor, output_len);
5014        }
5015    }
5016
5017    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5018    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5019    let mut columns = ColumnStore::new();
5020    let mut column_order = Vec::with_capacity(specs.len());
5021    let mut full_iter = full_data.into_iter();
5022    for spec in specs {
5023        let column = match spec.side {
5024            FusedInt64Side::Right => {
5025                // Lazy nullable repeated-slices over the bucket-order tape
5026                // (br-frankenpandas-yiqv5): O(matched) descriptor, no O(output)
5027                // materialization.
5028                let tape: Vec<i64> = positions
5029                    .iter()
5030                    .map(|&right_pos| spec.values[right_pos])
5031                    .collect();
5032                Column::from_i64_nullable_repeated_slices_shared(
5033                    tape,
5034                    Arc::clone(&right_segments),
5035                    output_len,
5036                )
5037            }
5038            FusedInt64Side::Left if use_repeat_runs => Column::from_i64_repeat_runs(
5039                plan.iter()
5040                    .map(|&(left_pos, _, run_len)| (spec.values[left_pos], run_len))
5041                    .collect(),
5042            ),
5043            FusedInt64Side::Left => {
5044                let data = full_iter
5045                    .next()
5046                    .expect("full lane buffer must exist for every non-run left spec");
5047                Column::from_i64_values(data)
5048            }
5049        };
5050        debug_assert_eq!(column.len(), output_len);
5051        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
5052    }
5053
5054    Ok(Some(MergedDataFrame {
5055        index,
5056        columns,
5057        column_order,
5058    }))
5059}
5060
5061/// Fused dense-i64 RIGHT merge builder (br-frankenpandas-4p3ie) — the
5062/// side-swapped mirror of [`build_single_key_dense_i64_left_merge_output`]:
5063/// the probe walks RIGHT keys in probe order against a dense CSR over the
5064/// LEFT key range, emitting `(right_pos, left_bucket_start, run_len)` plan
5065/// rows (`usize::MAX` sentinel = unmatched right row, one null-left output
5066/// row). Right lanes (including the shared key column, which pandas fills
5067/// from the RIGHT side under the LEFT name) are all-valid repeat runs; left
5068/// lanes fill from muis1-style left value tapes with ONE shared validity
5069/// mask and keep dtype Int64 with `Null(NullKind::Null)` at unmatched rows
5070/// (`reindex_by_positions` missing semantics — NOT Float64-promoted).
5071fn build_single_key_dense_i64_right_merge_output(
5072    left: &fp_frame::DataFrame,
5073    right: &fp_frame::DataFrame,
5074    left_on: &[&str],
5075    right_on: &[&str],
5076    left_key: &Column,
5077    right_key: &Column,
5078    suffixes: &ResolvedMergeSuffixes,
5079) -> Result<Option<MergedDataFrame>, JoinError> {
5080    debug_assert_eq!(left_on.len(), 1);
5081    debug_assert_eq!(right_on.len(), 1);
5082
5083    let Some(left_keys) = left_key.as_i64_slice() else {
5084        return Ok(None);
5085    };
5086    let Some(right_keys) = right_key.as_i64_slice() else {
5087        return Ok(None);
5088    };
5089    if left_keys.is_empty() || right_keys.is_empty() {
5090        return Ok(None);
5091    }
5092
5093    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5094    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5095    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5096    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5097    let shared_key_names = if left_on[0] == right_on[0] {
5098        [left_on[0]].into_iter().collect::<HashSet<&str>>()
5099    } else {
5100        HashSet::new()
5101    };
5102    let overlapping_names =
5103        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5104
5105    // Lane specs in output order. The shared key slot keeps the LEFT name
5106    // but carries RIGHT key values (all output rows have a right row), so it
5107    // is a Right-side lane on right_keys.
5108    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
5109    let mut sources = Vec::<Arc<[i64]>>::new();
5110    for name in left.column_names() {
5111        let col = left
5112            .columns()
5113            .get(name)
5114            .expect("left column listed in column_names must exist");
5115        let Some(values) = col.as_i64_slice() else {
5116            return Ok(None);
5117        };
5118        if left_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5119            let right_key_col = right
5120                .columns()
5121                .get(right_on[0])
5122                .expect("right key column must exist");
5123            let source = right_key_col
5124                .as_i64_arc()
5125                .unwrap_or_else(|| Arc::from(right_keys));
5126            specs.push(FusedInt64OutputColumn {
5127                name: name.clone(),
5128                side: FusedInt64Side::Right,
5129                values: right_keys,
5130            });
5131            sources.push(source);
5132            continue;
5133        }
5134        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
5135        let out_name = if left_key_name_set.contains(name.as_str()) {
5136            name.clone()
5137        } else if right_col_names.contains(name) {
5138            apply_merge_suffix(name, suffixes.left.as_deref())
5139        } else {
5140            name.clone()
5141        };
5142        specs.push(FusedInt64OutputColumn {
5143            name: out_name,
5144            side: FusedInt64Side::Left,
5145            values,
5146        });
5147        sources.push(source);
5148    }
5149    for name in right.column_names() {
5150        let col = right
5151            .columns()
5152            .get(name)
5153            .expect("right column listed in column_names must exist");
5154        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5155            continue;
5156        }
5157        let Some(values) = col.as_i64_slice() else {
5158            return Ok(None);
5159        };
5160        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
5161        let out_name = if left_col_names.contains(name) {
5162            apply_merge_suffix(name, suffixes.right.as_deref())
5163        } else {
5164            name.clone()
5165        };
5166        specs.push(FusedInt64OutputColumn {
5167            name: out_name,
5168            side: FusedInt64Side::Right,
5169            values,
5170        });
5171        sources.push(source);
5172    }
5173    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5174
5175    let row_count = left_keys.len().saturating_add(right_keys.len());
5176    let max_dense_span = row_count.saturating_mul(4).max(1024);
5177    let left_witness = left_key
5178        .int64_dense_cycle_witness()
5179        .filter(|witness| witness.len == left_keys.len());
5180    let right_witness = right_key
5181        .int64_dense_cycle_witness()
5182        .filter(|witness| witness.len == right_keys.len());
5183    if let (Some(left_witness), Some(right_witness), Some((left_min, left_max))) = (
5184        left_witness,
5185        right_witness,
5186        left_witness.and_then(dense_cycle_domain),
5187    ) {
5188        let left_span = i128::from(left_max) - i128::from(left_min) + 1;
5189        if left_span <= max_dense_span as i128
5190            && let Some((output_len, left_validity)) =
5191                dense_cycle_probe_output_len_and_validity(right_witness, left_witness)
5192        {
5193            if !left_validity.all() {
5194                // See the LEFT merge mirror: only the typed gather can
5195                // preserve pandas' Int64-to-Float64 widening for a new gap.
5196            } else {
5197                let index = Index::new_known_unique_int64_unit_range(0, output_len);
5198                let mut columns = ColumnStore::new();
5199                let mut column_order = Vec::with_capacity(specs.len());
5200                for (spec, source) in specs.into_iter().zip(sources) {
5201                    let column = match spec.side {
5202                        FusedInt64Side::Left => {
5203                            Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
5204                                source,
5205                                right_witness,
5206                                left_witness,
5207                                left_validity.clone(),
5208                                output_len,
5209                            )
5210                        }
5211                        FusedInt64Side::Right => Column::from_i64_dense_cycle_probe_repeat(
5212                            source,
5213                            right_witness,
5214                            left_witness,
5215                            output_len,
5216                        ),
5217                    };
5218                    debug_assert_eq!(column.len(), output_len);
5219                    insert_merged_output_column(
5220                        &mut columns,
5221                        &mut column_order,
5222                        spec.name,
5223                        column,
5224                    )?;
5225                }
5226                return Ok(Some(MergedDataFrame {
5227                    index,
5228                    columns,
5229                    column_order,
5230                }));
5231            }
5232        }
5233    }
5234
5235    // Dense CSR over the LEFT key range — same gate as
5236    // dense_int64_right_positions (span <= 4*rows+1024).
5237    let mut min_key = left_keys[0];
5238    let mut max_key = left_keys[0];
5239    for &key in left_keys {
5240        min_key = min_key.min(key);
5241        max_key = max_key.max(key);
5242    }
5243    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
5244    if span > max_dense_span as i128 {
5245        return Ok(None);
5246    }
5247    let span = usize::try_from(span).expect("span bounded by max_dense_span");
5248
5249    let mut offsets = vec![0usize; span + 1];
5250    for &key in left_keys {
5251        offsets[(key - min_key) as usize + 1] += 1;
5252    }
5253    for i in 0..span {
5254        offsets[i + 1] += offsets[i];
5255    }
5256    let mut positions = vec![0usize; left_keys.len()];
5257    let mut cursor = offsets[..span].to_vec();
5258    for (pos, &key) in left_keys.iter().enumerate() {
5259        let bucket = (key - min_key) as usize;
5260        positions[cursor[bucket]] = pos;
5261        cursor[bucket] += 1;
5262    }
5263
5264    // Plan over RIGHT probe order: (right_pos, left_bucket_start, run_len);
5265    // usize::MAX = unmatched right row (one null-left output row).
5266    const UNMATCHED: usize = usize::MAX;
5267    let mut plan = Vec::<(usize, usize, usize)>::with_capacity(right_keys.len());
5268    let mut output_len = 0usize;
5269    for (right_pos, &key) in right_keys.iter().enumerate() {
5270        let offset = i128::from(key) - i128::from(min_key);
5271        let run = if offset >= 0 && offset < span as i128 {
5272            let bucket = offset as usize;
5273            let start = offsets[bucket];
5274            let len = offsets[bucket + 1] - start;
5275            if len == 0 {
5276                (right_pos, UNMATCHED, 1)
5277            } else {
5278                (right_pos, start, len)
5279            }
5280        } else {
5281            (right_pos, UNMATCHED, 1)
5282        };
5283        let Some(new_len) = output_len.checked_add(run.2) else {
5284            return Ok(None);
5285        };
5286        output_len = new_len;
5287        plan.push(run);
5288    }
5289    if plan.iter().any(|&(_, start, _)| start == UNMATCHED) {
5290        return Ok(None);
5291    }
5292
5293    // One shared validity mask for every left lane.
5294    // Shared left-lane segment descriptor (br-frankenpandas-yiqv5): mirror of
5295    // the left builder — every null-introduced LEFT lane is a LAZY
5296    // `LazyNullableRepeatedSlicesInt64` over its bucket-order tape (plan's
5297    // `(bucket_start, run_len)`, `usize::MAX` ⇒ null run) instead of a
5298    // materialized O(output_len) buffer; validity rebuilt in the ctor.
5299    let left_segments: Arc<[(usize, usize)]> = plan
5300        .iter()
5301        .map(|&(_, start, run_len)| (start, run_len))
5302        .collect();
5303
5304    // Right lanes (all-valid) as lazy repeat runs when the fanout pays.
5305    let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
5306
5307    // Only LOW-FANOUT RIGHT lanes still materialize; left lanes are always lazy
5308    // (nullable repeated-slices) and high-fanout right lanes are lazy repeat runs.
5309    let full_specs: Vec<usize> = specs
5310        .iter()
5311        .enumerate()
5312        .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Right) && !use_repeat_runs)
5313        .map(|(idx, _)| idx)
5314        .collect();
5315
5316    let mut full_data: Vec<Vec<i64>> = Vec::new();
5317    let thread_count = join_parallel_thread_count();
5318    if !full_specs.is_empty() {
5319        // LEFT value tapes in bucket order, shared read-only.
5320        let tapes: Vec<Option<Vec<i64>>> = full_specs
5321            .iter()
5322            .map(|&spec_idx| match specs[spec_idx].side {
5323                FusedInt64Side::Right => None,
5324                FusedInt64Side::Left => Some(
5325                    positions
5326                        .iter()
5327                        .map(|&left_pos| specs[spec_idx].values[left_pos])
5328                        .collect(),
5329                ),
5330            })
5331            .collect();
5332
5333        if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
5334            let target = output_len.div_ceil(thread_count).max(1);
5335            let mut boundaries = vec![(0usize, 0usize)];
5336            let mut cumulative = 0usize;
5337            let mut next_target = target;
5338            for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
5339                cumulative += run_len;
5340                if cumulative >= next_target && plan_idx + 1 < plan.len() {
5341                    boundaries.push((plan_idx + 1, cumulative));
5342                    next_target = cumulative.saturating_add(target);
5343                }
5344            }
5345            boundaries.push((plan.len(), output_len));
5346            let chunk_count = boundaries.len() - 1;
5347
5348            let mut column_bufs: Vec<Vec<i64>> =
5349                full_specs.iter().map(|_| vec![0i64; output_len]).collect();
5350            let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
5351                .map(|_| Vec::with_capacity(full_specs.len()))
5352                .collect();
5353            for buf in &mut column_bufs {
5354                let mut rest: &mut [i64] = buf.as_mut_slice();
5355                let mut prev = 0usize;
5356                for (chunk_idx, window) in boundaries.windows(2).enumerate() {
5357                    let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
5358                    prev = window[1].1;
5359                    rest = tail;
5360                    bundles[chunk_idx].push(chunk_slice);
5361                }
5362            }
5363
5364            let plan = &plan;
5365            let specs_ref = &specs;
5366            let full_specs_ref = &full_specs;
5367            std::thread::scope(|scope| {
5368                let mut handles = Vec::with_capacity(chunk_count);
5369                for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
5370                    let (plan_start, out_start) = boundaries[chunk_idx];
5371                    let (plan_end, out_end) = boundaries[chunk_idx + 1];
5372                    let tapes = &tapes;
5373                    handles.push(scope.spawn(move || {
5374                        let mut cursor = 0usize;
5375                        for &(right_pos, start, run_len) in &plan[plan_start..plan_end] {
5376                            for (slice, (&spec_idx, tape)) in bundle
5377                                .iter_mut()
5378                                .zip(full_specs_ref.iter().zip(tapes.iter()))
5379                            {
5380                                match specs_ref[spec_idx].side {
5381                                    FusedInt64Side::Right => {
5382                                        slice[cursor..cursor + run_len]
5383                                            .fill(specs_ref[spec_idx].values[right_pos]);
5384                                    }
5385                                    FusedInt64Side::Left => {
5386                                        if start != UNMATCHED {
5387                                            slice[cursor..cursor + run_len].copy_from_slice(
5388                                                &tape
5389                                                    .as_ref()
5390                                                    .expect("left spec must have a bucket tape")
5391                                                    [start..start + run_len],
5392                                            );
5393                                        }
5394                                    }
5395                                }
5396                            }
5397                            cursor += run_len;
5398                        }
5399                        debug_assert_eq!(cursor, out_end - out_start);
5400                    }));
5401                }
5402                for handle in handles {
5403                    handle
5404                        .join()
5405                        .expect("dense i64 right output worker must not panic");
5406                }
5407            });
5408            full_data = column_bufs;
5409        } else {
5410            full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
5411            let mut cursor = 0usize;
5412            for &(right_pos, start, run_len) in &plan {
5413                for (buf, (&spec_idx, tape)) in full_data
5414                    .iter_mut()
5415                    .zip(full_specs.iter().zip(tapes.iter()))
5416                {
5417                    match specs[spec_idx].side {
5418                        FusedInt64Side::Right => {
5419                            buf[cursor..cursor + run_len].fill(specs[spec_idx].values[right_pos]);
5420                        }
5421                        FusedInt64Side::Left => {
5422                            if start != UNMATCHED {
5423                                buf[cursor..cursor + run_len].copy_from_slice(
5424                                    &tape.as_ref().expect("left spec must have a bucket tape")
5425                                        [start..start + run_len],
5426                                );
5427                            }
5428                        }
5429                    }
5430                }
5431                cursor += run_len;
5432            }
5433            debug_assert_eq!(cursor, output_len);
5434        }
5435    }
5436
5437    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5438    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5439    let mut columns = ColumnStore::new();
5440    let mut column_order = Vec::with_capacity(specs.len());
5441    let mut full_iter = full_data.into_iter();
5442    for spec in specs {
5443        let column = match spec.side {
5444            FusedInt64Side::Left => {
5445                // Lazy nullable repeated-slices over the left bucket-order tape
5446                // (br-frankenpandas-yiqv5). When no left row is missing the
5447                // segments carry no `usize::MAX` sentinel, so the ctor yields an
5448                // all-valid mask — identical to the prior `from_i64_values`.
5449                let tape: Vec<i64> = positions
5450                    .iter()
5451                    .map(|&left_pos| spec.values[left_pos])
5452                    .collect();
5453                Column::from_i64_nullable_repeated_slices_shared(
5454                    tape,
5455                    Arc::clone(&left_segments),
5456                    output_len,
5457                )
5458            }
5459            FusedInt64Side::Right if use_repeat_runs => Column::from_i64_repeat_runs(
5460                plan.iter()
5461                    .map(|&(right_pos, _, run_len)| (spec.values[right_pos], run_len))
5462                    .collect(),
5463            ),
5464            FusedInt64Side::Right => {
5465                let data = full_iter
5466                    .next()
5467                    .expect("full lane buffer must exist for every non-run right spec");
5468                Column::from_i64_values(data)
5469            }
5470        };
5471        debug_assert_eq!(column.len(), output_len);
5472        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
5473    }
5474
5475    Ok(Some(MergedDataFrame {
5476        index,
5477        columns,
5478        column_order,
5479    }))
5480}
5481
5482fn dense_cycle_domain(witness: Int64DenseCycleWitness) -> Option<(i64, i64)> {
5483    let last_offset = i64::try_from(witness.period.checked_sub(1)?).ok()?;
5484    Some((witness.start, witness.start.checked_add(last_offset)?))
5485}
5486
5487fn dense_cycle_probe_output_len_and_validity(
5488    probe_witness: Int64DenseCycleWitness,
5489    build_witness: Int64DenseCycleWitness,
5490) -> Option<(usize, ValidityMask)> {
5491    let mut output_len = 0usize;
5492    let mut invalid_ranges = Vec::<(usize, usize)>::new();
5493    for probe_pos in 0..probe_witness.len {
5494        let offset = i64::try_from(probe_pos % probe_witness.period).ok()?;
5495        let key = probe_witness.start.checked_add(offset)?;
5496        let run_len = build_witness
5497            .offset_count_for_key(key)
5498            .map_or(1, |(_, count)| count);
5499        if build_witness.offset_count_for_key(key).is_none() {
5500            push_dense_outer_invalid_range(&mut invalid_ranges, output_len, 1);
5501        }
5502        output_len = output_len.checked_add(run_len)?;
5503    }
5504    Some((
5505        output_len,
5506        ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len),
5507    ))
5508}
5509
5510struct DenseOuterRunTape {
5511    run_lens: Option<Arc<[usize]>>,
5512    left_run_valid: Option<Arc<[bool]>>,
5513    left_run_positions: Option<Arc<[usize]>>,
5514    right_positions_csr: Option<Arc<[usize]>>,
5515    right_segments: Option<Arc<[(usize, usize)]>>,
5516    key_runs: Vec<(i64, usize)>,
5517    left_sparse_validity: ValidityMask,
5518    right_sparse_validity: ValidityMask,
5519    output_len: usize,
5520    has_left_missing: bool,
5521    has_right_missing: bool,
5522}
5523
5524fn push_dense_outer_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
5525    if len == 0 {
5526        return;
5527    }
5528    if let Some((last_start, last_len)) = ranges.last_mut()
5529        && last_start.checked_add(*last_len) == Some(start)
5530    {
5531        *last_len += len;
5532        return;
5533    }
5534    ranges.push((start, len));
5535}
5536
5537fn append_dense_cycle_positions(
5538    positions: &mut Vec<usize>,
5539    witness: Int64DenseCycleWitness,
5540    key: i64,
5541) -> Option<usize> {
5542    let (mut pos, count) = witness.offset_count_for_key(key)?;
5543    for _ in 0..count {
5544        positions.push(pos);
5545        pos = pos.checked_add(witness.period)?;
5546    }
5547    Some(count)
5548}
5549
5550fn build_dense_cycle_outer_run_tape(
5551    left_witness: Int64DenseCycleWitness,
5552    right_witness: Int64DenseCycleWitness,
5553    min_key: i64,
5554    span: usize,
5555) -> Option<DenseOuterRunTape> {
5556    let mut run_count = 0usize;
5557    let mut active_key_count = 0usize;
5558    let mut output_len = 0usize;
5559    let mut has_left_missing = false;
5560    let mut has_right_missing = false;
5561    for bucket in 0..span {
5562        let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5563        let ll = left_witness
5564            .offset_count_for_key(key)
5565            .map_or(0, |(_, count)| count);
5566        let rl = right_witness
5567            .offset_count_for_key(key)
5568            .map_or(0, |(_, count)| count);
5569        let rows = match (ll > 0, rl > 0) {
5570            (true, true) => {
5571                run_count = run_count.checked_add(ll)?;
5572                ll.checked_mul(rl)?
5573            }
5574            (true, false) => {
5575                has_right_missing = true;
5576                run_count = run_count.checked_add(ll)?;
5577                ll
5578            }
5579            (false, true) => {
5580                has_left_missing = true;
5581                run_count = run_count.checked_add(1)?;
5582                rl
5583            }
5584            (false, false) => continue,
5585        };
5586        active_key_count = active_key_count.checked_add(1)?;
5587        output_len = output_len.checked_add(rows)?;
5588    }
5589
5590    let build_left_tape = !has_left_missing;
5591    let mut run_lens = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5592    let mut left_run_valid = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5593    let mut left_run_positions = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5594    let mut right_positions_csr = Vec::with_capacity(right_witness.len);
5595    let mut right_segments = Vec::with_capacity(run_count);
5596    let mut key_runs = Vec::with_capacity(active_key_count);
5597    let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
5598    let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
5599    let mut out_pos = 0usize;
5600    let build_right_tape = !has_right_missing;
5601    for bucket in 0..span {
5602        let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5603        let left_span = left_witness.offset_count_for_key(key);
5604        let right_span = right_witness.offset_count_for_key(key);
5605        let ll = left_span.map_or(0, |(_, count)| count);
5606        let rl = right_span.map_or(0, |(_, count)| count);
5607        if ll == 0 && rl == 0 {
5608            continue;
5609        }
5610
5611        let right_start = if rl > 0 {
5612            if build_right_tape {
5613                let start = right_positions_csr.len();
5614                let appended =
5615                    append_dense_cycle_positions(&mut right_positions_csr, right_witness, key)?;
5616                debug_assert_eq!(appended, rl);
5617                start
5618            } else {
5619                0
5620            }
5621        } else {
5622            usize::MAX
5623        };
5624
5625        let rows = match (left_span, right_span) {
5626            (Some((mut left_pos, left_count)), Some((_, right_count))) => {
5627                let rows = left_count.checked_mul(right_count)?;
5628                if build_left_tape {
5629                    run_lens.extend(std::iter::repeat_n(right_count, left_count));
5630                    left_run_valid.extend(std::iter::repeat_n(true, left_count));
5631                }
5632                if build_right_tape {
5633                    right_segments
5634                        .extend(std::iter::repeat_n((right_start, right_count), left_count));
5635                }
5636                if build_left_tape {
5637                    for _ in 0..left_count {
5638                        left_run_positions.push(left_pos);
5639                        left_pos = left_pos.checked_add(left_witness.period)?;
5640                    }
5641                }
5642                rows
5643            }
5644            (Some((mut left_pos, left_count)), None) => {
5645                push_dense_outer_invalid_range(&mut right_invalid_ranges, out_pos, left_count);
5646                if build_left_tape {
5647                    run_lens.extend(std::iter::repeat_n(1, left_count));
5648                    left_run_valid.extend(std::iter::repeat_n(true, left_count));
5649                }
5650                if build_right_tape {
5651                    right_segments.extend(std::iter::repeat_n((usize::MAX, 1), left_count));
5652                }
5653                if build_left_tape {
5654                    for _ in 0..left_count {
5655                        left_run_positions.push(left_pos);
5656                        left_pos = left_pos.checked_add(left_witness.period)?;
5657                    }
5658                }
5659                left_count
5660            }
5661            (None, Some((_, right_count))) => {
5662                push_dense_outer_invalid_range(&mut left_invalid_ranges, out_pos, right_count);
5663                if build_left_tape {
5664                    run_lens.push(right_count);
5665                    left_run_valid.push(false);
5666                    left_run_positions.push(0);
5667                }
5668                if build_right_tape {
5669                    right_segments.push((right_start, right_count));
5670                }
5671                right_count
5672            }
5673            (None, None) => unreachable!("empty buckets are skipped above"),
5674        };
5675        key_runs.push((key, rows));
5676        out_pos = out_pos.checked_add(rows)?;
5677    }
5678    if out_pos != output_len
5679        || (build_left_tape
5680            && (run_lens.len() != run_count
5681                || left_run_valid.len() != run_count
5682                || left_run_positions.len() != run_count))
5683        || (!build_left_tape
5684            && (!run_lens.is_empty()
5685                || !left_run_valid.is_empty()
5686                || !left_run_positions.is_empty()))
5687        || (build_right_tape
5688            && (right_segments.len() != run_count
5689                || right_positions_csr.len() != right_witness.len))
5690        || (!build_right_tape && (!right_segments.is_empty() || !right_positions_csr.is_empty()))
5691    {
5692        return None;
5693    }
5694
5695    Some(DenseOuterRunTape {
5696        run_lens: build_left_tape.then(|| Arc::from(run_lens)),
5697        left_run_valid: build_left_tape.then(|| Arc::from(left_run_valid)),
5698        left_run_positions: build_left_tape.then(|| Arc::from(left_run_positions)),
5699        right_positions_csr: build_right_tape.then(|| Arc::from(right_positions_csr)),
5700        right_segments: build_right_tape.then(|| Arc::from(right_segments)),
5701        key_runs,
5702        left_sparse_validity: ValidityMask::from_invalid_ranges(
5703            Arc::from(left_invalid_ranges),
5704            output_len,
5705        ),
5706        right_sparse_validity: ValidityMask::from_invalid_ranges(
5707            Arc::from(right_invalid_ranges),
5708            output_len,
5709        ),
5710        output_len,
5711        has_left_missing,
5712        has_right_missing,
5713    })
5714}
5715
5716/// Fused dense-i64 OUTER merge builder (br-frankenpandas-343ho).
5717///
5718/// `dense_int64_outer_positions` + the position-vector outer builder cost:
5719/// per-bucket `Vec<Vec<usize>>` heap allocs, two `Vec<Option<usize>>` of
5720/// output length, a per-row Scalar coalesce for the shared key column, and
5721/// per-column reindex walks. Here the bucket walk (ascending key order —
5722/// the dense outer output IS bucket order) emits a compact plan
5723/// (`(left_pos | MAX, right_bucket_start | MAX, run_len)`), and:
5724///
5725/// - the SHARED KEY lane is synthesized as `(min_key + bucket, bucket_rows)`
5726///   repeat runs — every row in a bucket has the bucket's key, whichever
5727///   side it came from, so the coalesce is a closed form (all-valid Int64);
5728/// - left lanes promote to nullable Float64 ONLY when right-only buckets
5729///   exist, right lanes ONLY when left-only rows exist — matching
5730///   `reindex_join_column_with_invented_gap`'s per-positions `has_missing` check (a
5731///   side with no missing rows keeps dtype Int64 via the all-present
5732///   take_positions path);
5733/// - per-side shared validity masks are word-filled once from the plan and
5734///   cloned per lane;
5735/// - lanes fill via the 6bsw3 row-chunked disjoint `split_at_mut` scheme
5736///   (an i64 group and an f64 group, sharing plan/boundaries), with muis1
5737///   right value tapes (i64, plus a once-cast f64 tape for promoted lanes).
5738///
5739/// Bit-identical: bucket walk order == `dense_int64_outer_positions`
5740/// (cross products left-major, then left-only rows, then right-only rows,
5741/// per ascending bucket); promoted slots use `v as f64` + the 0.0-datum
5742/// gap (`Null(NaN)`), preserved slots `Null(NullKind::Null)` — the exact
5743/// eager semantics per br-frankenpandas-1bvcl/lt5qx.
5744fn build_single_key_dense_i64_outer_merge_output(
5745    left: &fp_frame::DataFrame,
5746    right: &fp_frame::DataFrame,
5747    left_on: &[&str],
5748    right_on: &[&str],
5749    left_key: &Column,
5750    right_key: &Column,
5751    suffixes: &ResolvedMergeSuffixes,
5752) -> Result<Option<MergedDataFrame>, JoinError> {
5753    debug_assert_eq!(left_on.len(), 1);
5754    debug_assert_eq!(right_on.len(), 1);
5755
5756    // The closed-form key lane needs the coalesced shared-key shape; the
5757    // non-shared-name variant keeps the position-vector path.
5758    if left_on[0] != right_on[0] {
5759        return Ok(None);
5760    }
5761    let Some(left_keys) = left_key.as_i64_slice() else {
5762        return Ok(None);
5763    };
5764    let Some(right_keys) = right_key.as_i64_slice() else {
5765        return Ok(None);
5766    };
5767    if left_keys.is_empty() || right_keys.is_empty() {
5768        return Ok(None);
5769    }
5770
5771    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5772    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5773    let key_name = left_on[0];
5774    let shared_key_names = [key_name].into_iter().collect::<HashSet<&str>>();
5775    let overlapping_names =
5776        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5777
5778    // Lane specs in output order: left columns (the key slot handled as the
5779    // synthetic coalesced lane), then right non-key columns.
5780    enum OuterLaneKind {
5781        SharedKey,
5782        Lane(FusedInt64Side),
5783    }
5784    let mut spec_names = Vec::<String>::new();
5785    let mut spec_kinds = Vec::<OuterLaneKind>::new();
5786    let mut spec_values = Vec::<&[i64]>::new();
5787    let mut spec_sources = Vec::<Arc<[i64]>>::new();
5788    for name in left.column_names() {
5789        let col = left
5790            .columns()
5791            .get(name)
5792            .expect("left column listed in column_names must exist");
5793        let Some(values) = col.as_i64_slice() else {
5794            return Ok(None);
5795        };
5796        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
5797        if name.as_str() == key_name {
5798            spec_names.push(name.clone());
5799            spec_kinds.push(OuterLaneKind::SharedKey);
5800            spec_values.push(values);
5801            spec_sources.push(Arc::clone(&source));
5802            continue;
5803        }
5804        let out_name = if right_col_names.contains(name) {
5805            apply_merge_suffix(name, suffixes.left.as_deref())
5806        } else {
5807            name.clone()
5808        };
5809        spec_names.push(out_name);
5810        spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Left));
5811        spec_values.push(values);
5812        spec_sources.push(source);
5813    }
5814    for name in right.column_names() {
5815        let col = right
5816            .columns()
5817            .get(name)
5818            .expect("right column listed in column_names must exist");
5819        let Some(values) = col.as_i64_slice() else {
5820            return Ok(None);
5821        };
5822        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
5823        if name.as_str() == key_name {
5824            continue;
5825        }
5826        let out_name = if left_col_names.contains(name) {
5827            apply_merge_suffix(name, suffixes.right.as_deref())
5828        } else {
5829            name.clone()
5830        };
5831        spec_names.push(out_name);
5832        spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Right));
5833        spec_values.push(values);
5834        spec_sources.push(source);
5835    }
5836    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5837
5838    // Dense span over BOTH key sets (same gate as dense_int64_outer_positions
5839    // so fused/fallback routing matches).
5840    let left_witness = left_key
5841        .int64_dense_cycle_witness()
5842        .filter(|witness| witness.len == left_keys.len());
5843    let right_witness = right_key
5844        .int64_dense_cycle_witness()
5845        .filter(|witness| witness.len == right_keys.len());
5846    let (min_key, max_key) = match (
5847        left_witness.and_then(dense_cycle_domain),
5848        right_witness.and_then(dense_cycle_domain),
5849    ) {
5850        (Some((left_min, left_max)), Some((right_min, right_max))) => {
5851            (left_min.min(right_min), left_max.max(right_max))
5852        }
5853        _ => {
5854            let mut min_key = left_keys[0];
5855            let mut max_key = left_keys[0];
5856            for &key in left_keys.iter().chain(right_keys.iter()) {
5857                min_key = min_key.min(key);
5858                max_key = max_key.max(key);
5859            }
5860            (min_key, max_key)
5861        }
5862    };
5863    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
5864    let row_count = left_keys.len().saturating_add(right_keys.len());
5865    let max_dense_span = row_count.saturating_mul(4).max(1024);
5866    if span > max_dense_span as i128 {
5867        return Ok(None);
5868    }
5869    let span = usize::try_from(span).expect("span bounded by max_dense_span");
5870
5871    const NONE_POS: usize = usize::MAX;
5872    let Some(DenseOuterRunTape {
5873        run_lens,
5874        left_run_valid,
5875        left_run_positions,
5876        right_positions_csr,
5877        right_segments,
5878        key_runs,
5879        left_sparse_validity,
5880        right_sparse_validity,
5881        output_len,
5882        has_left_missing,
5883        has_right_missing,
5884    }) = (match (left_witness, right_witness) {
5885        (Some(left_witness), Some(right_witness)) => {
5886            build_dense_cycle_outer_run_tape(left_witness, right_witness, min_key, span)
5887        }
5888        _ => None,
5889    })
5890    .or_else(|| {
5891        // CSR layouts for both sides (replaces the per-bucket Vec<Vec<usize>>).
5892        let build_dense_cycle_csr =
5893            |witness: Int64DenseCycleWitness| -> Option<(Vec<usize>, Vec<usize>)> {
5894                let mut offsets = Vec::with_capacity(span + 1);
5895                offsets.push(0);
5896                let mut total = 0usize;
5897                for bucket in 0..span {
5898                    let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5899                    let count = witness
5900                        .offset_count_for_key(key)
5901                        .map_or(0, |(_, count)| count);
5902                    total = total.checked_add(count)?;
5903                    offsets.push(total);
5904                }
5905                if total != witness.len {
5906                    return None;
5907                }
5908                let mut positions = Vec::with_capacity(witness.len);
5909                for bucket in 0..span {
5910                    let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5911                    let appended =
5912                        append_dense_cycle_positions(&mut positions, witness, key).unwrap_or(0);
5913                    debug_assert_eq!(
5914                        appended,
5915                        witness
5916                            .offset_count_for_key(key)
5917                            .map_or(0, |(_, count)| count)
5918                    );
5919                }
5920                (positions.len() == witness.len).then_some((offsets, positions))
5921            };
5922        let build_csr = |keys: &[i64], witness: Option<Int64DenseCycleWitness>| {
5923            if let Some(csr) = witness
5924                .filter(|witness| witness.len == keys.len())
5925                .and_then(&build_dense_cycle_csr)
5926            {
5927                return csr;
5928            }
5929            let mut offsets = vec![0usize; span + 1];
5930            for &key in keys {
5931                offsets[(key - min_key) as usize + 1] += 1;
5932            }
5933            for i in 0..span {
5934                offsets[i + 1] += offsets[i];
5935            }
5936            let mut positions = vec![0usize; keys.len()];
5937            let mut cursor = offsets[..span].to_vec();
5938            for (pos, &key) in keys.iter().enumerate() {
5939                let bucket = (key - min_key) as usize;
5940                positions[cursor[bucket]] = pos;
5941                cursor[bucket] += 1;
5942            }
5943            (offsets, positions)
5944        };
5945        let (left_offsets, left_positions_csr) = build_csr(left_keys, left_witness);
5946        let (right_offsets, right_positions_csr) = build_csr(right_keys, right_witness);
5947
5948        // Bucket walk -> compact plan + closed-form key runs + output length.
5949        let mut plan = Vec::<(usize, usize, usize)>::new();
5950        let mut key_runs = Vec::<(i64, usize)>::new();
5951        let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
5952        let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
5953        let mut output_len = 0usize;
5954        let mut has_left_missing = false; // right-only buckets exist
5955        let mut has_right_missing = false; // left-only rows exist
5956        for bucket in 0..span {
5957            let ll = left_offsets[bucket + 1] - left_offsets[bucket];
5958            let rl = right_offsets[bucket + 1] - right_offsets[bucket];
5959            let bucket_rows = match (ll > 0, rl > 0) {
5960                (true, true) => {
5961                    let rows = ll.checked_mul(rl)?;
5962                    let rs = right_offsets[bucket];
5963                    for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
5964                        plan.push((lp, rs, rl));
5965                    }
5966                    rows
5967                }
5968                (true, false) => {
5969                    has_right_missing = true;
5970                    push_dense_outer_invalid_range(&mut right_invalid_ranges, output_len, ll);
5971                    for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
5972                        plan.push((lp, NONE_POS, 1));
5973                    }
5974                    ll
5975                }
5976                (false, true) => {
5977                    has_left_missing = true;
5978                    push_dense_outer_invalid_range(&mut left_invalid_ranges, output_len, rl);
5979                    plan.push((NONE_POS, right_offsets[bucket], rl));
5980                    rl
5981                }
5982                (false, false) => continue,
5983            };
5984            output_len = output_len.checked_add(bucket_rows)?;
5985            key_runs.push((min_key + bucket as i64, bucket_rows));
5986        }
5987
5988        // Shared lazy-lane descriptors (br-frankenpandas-yiqv5): the plan drives
5989        // every value lane as a LAZY column rather than an O(output_len)
5990        // materialized buffer. The kept side stays all-valid; the promoted
5991        // side becomes the matching nullable lazy lane.
5992        let run_lens: Arc<[usize]> = plan.iter().map(|&(_, _, run_len)| run_len).collect();
5993        let left_run_valid: Arc<[bool]> = plan.iter().map(|&(lp, _, _)| lp < NONE_POS).collect();
5994        let left_run_positions: Arc<[usize]> = plan
5995            .iter()
5996            .map(|&(lp, _, _)| if lp == NONE_POS { 0 } else { lp })
5997            .collect();
5998        let right_segments: Arc<[(usize, usize)]> =
5999            plan.iter().map(|&(_, rs, run_len)| (rs, run_len)).collect();
6000        Some(DenseOuterRunTape {
6001            run_lens: Some(run_lens),
6002            left_run_valid: Some(left_run_valid),
6003            left_run_positions: Some(left_run_positions),
6004            right_positions_csr: Some(Arc::from(right_positions_csr)),
6005            right_segments: Some(right_segments),
6006            key_runs,
6007            left_sparse_validity: ValidityMask::from_invalid_ranges(
6008                Arc::from(left_invalid_ranges),
6009                output_len,
6010            ),
6011            right_sparse_validity: ValidityMask::from_invalid_ranges(
6012                Arc::from(right_invalid_ranges),
6013                output_len,
6014            ),
6015            output_len,
6016            has_left_missing,
6017            has_right_missing,
6018        })
6019    })
6020    else {
6021        return Ok(None);
6022    };
6023
6024    // Promoted (nullable Float64) when that side has missing rows, preserved
6025    // (all-valid Int64) otherwise.
6026    let promoted = |side: FusedInt64Side| match side {
6027        FusedInt64Side::Left => has_left_missing,
6028        FusedInt64Side::Right => has_right_missing,
6029    };
6030
6031    // Left broadcast run values (one per run): i64 (preserved) or f64 (promoted).
6032    let left_run_values_i64 = |idx: usize| -> Option<Vec<i64>> {
6033        Some(
6034            left_run_positions
6035                .as_ref()?
6036                .iter()
6037                .zip(left_run_valid.as_ref()?.iter())
6038                .map(|(&lp, &valid)| if valid { spec_values[idx][lp] } else { 0 })
6039                .collect(),
6040        )
6041    };
6042    // Assemble columns in spec order, each a lazy lane.
6043    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6044    let mut columns = ColumnStore::new();
6045    let mut column_order = Vec::with_capacity(spec_names.len());
6046    for (idx, (name, kind)) in spec_names.into_iter().zip(spec_kinds.iter()).enumerate() {
6047        let column = match kind {
6048            OuterLaneKind::SharedKey => {
6049                // Closed-form coalesced key: all-valid, bucket key repeated in
6050                // ascending bucket order. Lazy repeat-runs when the fanout pays.
6051                if output_len >= key_runs.len().saturating_mul(2) {
6052                    Column::from_i64_repeat_runs(key_runs.clone())
6053                } else {
6054                    let mut data = Vec::with_capacity(output_len);
6055                    for &(key, run_len) in &key_runs {
6056                        data.resize(data.len() + run_len, key);
6057                    }
6058                    Column::from_i64_values(data)
6059                }
6060            }
6061            OuterLaneKind::Lane(side) => match (side, promoted(*side)) {
6062                (FusedInt64Side::Left, false) => {
6063                    let Some(run_lens) = run_lens.as_ref() else {
6064                        return Ok(None);
6065                    };
6066                    let Some(run_values) = left_run_values_i64(idx) else {
6067                        return Ok(None);
6068                    };
6069                    Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
6070                }
6071                (FusedInt64Side::Left, true) => {
6072                    if left_run_positions.is_none()
6073                        && let (Some(left_witness), Some(right_witness)) =
6074                            (left_witness, right_witness)
6075                    {
6076                        Column::from_i64_nullable_dense_cycle_left_as_f64_with_sparse_validity(
6077                            Arc::clone(&spec_sources[idx]),
6078                            left_witness,
6079                            right_witness,
6080                            min_key,
6081                            span,
6082                            left_sparse_validity.clone(),
6083                            output_len,
6084                        )
6085                    } else {
6086                        let Some(run_lens) = run_lens.as_ref() else {
6087                            return Ok(None);
6088                        };
6089                        let Some(left_run_positions) = left_run_positions.as_ref() else {
6090                            return Ok(None);
6091                        };
6092                        let Some(left_run_valid) = left_run_valid.as_ref() else {
6093                            return Ok(None);
6094                        };
6095                        Column::from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
6096                            Arc::clone(&spec_sources[idx]),
6097                            Arc::clone(left_run_positions),
6098                            Arc::clone(left_run_valid),
6099                            Arc::clone(run_lens),
6100                            left_sparse_validity.clone(),
6101                            output_len,
6102                        )
6103                    }
6104                }
6105                (FusedInt64Side::Right, false) => {
6106                    let Some(right_positions_csr) = right_positions_csr.as_ref() else {
6107                        return Ok(None);
6108                    };
6109                    let Some(right_segments) = right_segments.as_ref() else {
6110                        return Ok(None);
6111                    };
6112                    let tape_i64 = right_positions_csr
6113                        .iter()
6114                        .map(|&pos| spec_values[idx][pos])
6115                        .collect();
6116                    Column::from_i64_repeated_slices_shared(
6117                        tape_i64,
6118                        Arc::clone(right_segments),
6119                        output_len,
6120                    )
6121                }
6122                (FusedInt64Side::Right, true) => {
6123                    if right_positions_csr.is_none()
6124                        && let (Some(left_witness), Some(right_witness)) =
6125                            (left_witness, right_witness)
6126                    {
6127                        Column::from_i64_nullable_dense_cycle_right_as_f64_with_sparse_validity(
6128                            Arc::clone(&spec_sources[idx]),
6129                            left_witness,
6130                            right_witness,
6131                            min_key,
6132                            span,
6133                            right_sparse_validity.clone(),
6134                            output_len,
6135                        )
6136                    } else {
6137                        let Some(right_positions_csr) = right_positions_csr.as_ref() else {
6138                            return Ok(None);
6139                        };
6140                        let Some(right_segments) = right_segments.as_ref() else {
6141                            return Ok(None);
6142                        };
6143                        Column::from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
6144                            Arc::clone(&spec_sources[idx]),
6145                            Arc::clone(right_positions_csr),
6146                            Arc::clone(right_segments),
6147                            right_sparse_validity.clone(),
6148                            output_len,
6149                        )
6150                    }
6151                }
6152            },
6153        };
6154        debug_assert_eq!(column.len(), output_len);
6155        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
6156    }
6157
6158    Ok(Some(MergedDataFrame {
6159        index,
6160        columns,
6161        column_order,
6162    }))
6163}
6164
6165fn build_single_key_dense_i64_right_all_matched_merge_output(
6166    left: &fp_frame::DataFrame,
6167    right: &fp_frame::DataFrame,
6168    left_on: &[&str],
6169    right_on: &[&str],
6170    left_key: &Column,
6171    right_key: &Column,
6172    suffixes: &ResolvedMergeSuffixes,
6173) -> Result<Option<MergedDataFrame>, JoinError> {
6174    debug_assert_eq!(left_on.len(), 1);
6175    debug_assert_eq!(right_on.len(), 1);
6176
6177    let Some(left_keys) = left_key.as_i64_slice() else {
6178        return Ok(None);
6179    };
6180    let Some(right_keys) = right_key.as_i64_slice() else {
6181        return Ok(None);
6182    };
6183
6184    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6185    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6186    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6187    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6188    let shared_key_names = if left_on[0] == right_on[0] {
6189        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6190    } else {
6191        HashSet::new()
6192    };
6193    let overlapping_names =
6194        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6195
6196    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
6197    for name in left.column_names() {
6198        let col = left
6199            .columns()
6200            .get(name)
6201            .expect("left column listed in column_names must exist");
6202        let (values, side) = if left_key_name_set.contains(name.as_str())
6203            && shared_key_names.contains(name.as_str())
6204        {
6205            let right_key_col = right
6206                .columns()
6207                .get(right_on[0])
6208                .expect("right key column must exist");
6209            let Some(values) = right_key_col.as_i64_slice() else {
6210                return Ok(None);
6211            };
6212            (values, FusedInt64Side::Right)
6213        } else {
6214            let Some(values) = col.as_i64_slice() else {
6215                return Ok(None);
6216            };
6217            (values, FusedInt64Side::Left)
6218        };
6219        let out_name = if left_key_name_set.contains(name.as_str()) {
6220            name.clone()
6221        } else if right_col_names.contains(name) {
6222            apply_merge_suffix(name, suffixes.left.as_deref())
6223        } else {
6224            name.clone()
6225        };
6226        specs.push(FusedInt64OutputColumn {
6227            name: out_name,
6228            side,
6229            values,
6230        });
6231    }
6232
6233    for name in right.column_names() {
6234        let col = right
6235            .columns()
6236            .get(name)
6237            .expect("right column listed in column_names must exist");
6238        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6239            continue;
6240        }
6241        let Some(values) = col.as_i64_slice() else {
6242            return Ok(None);
6243        };
6244        let out_name = if left_col_names.contains(name) {
6245            apply_merge_suffix(name, suffixes.right.as_deref())
6246        } else {
6247            name.clone()
6248        };
6249        specs.push(FusedInt64OutputColumn {
6250            name: out_name,
6251            side: FusedInt64Side::Right,
6252            values,
6253        });
6254    }
6255
6256    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6257
6258    if right_keys.is_empty() {
6259        let mut columns = ColumnStore::new();
6260        let mut column_order = Vec::with_capacity(specs.len());
6261        for spec in specs {
6262            insert_merged_output_column(
6263                &mut columns,
6264                &mut column_order,
6265                spec.name,
6266                Column::from_i64_values(Vec::new()),
6267            )?;
6268        }
6269        return Ok(Some(MergedDataFrame {
6270            index: Index::new(Vec::new()),
6271            columns,
6272            column_order,
6273        }));
6274    }
6275    if left_keys.is_empty() {
6276        return Ok(None);
6277    }
6278
6279    let mut min = left_keys[0];
6280    let mut max = left_keys[0];
6281    for &v in left_keys {
6282        if v < min {
6283            min = v;
6284        }
6285        if v > max {
6286            max = v;
6287        }
6288    }
6289    let span = (max as i128) - (min as i128) + 1;
6290    if span > (1i128 << 24) || span > 16 * (left_keys.len() as i128) {
6291        return Ok(None);
6292    }
6293    let range = span as usize;
6294
6295    let mut offsets = vec![0usize; range + 1];
6296    for &v in left_keys {
6297        offsets[(v - min) as usize + 1] += 1;
6298    }
6299    for i in 0..range {
6300        offsets[i + 1] += offsets[i];
6301    }
6302    let mut positions = vec![0usize; left_keys.len()];
6303    let mut cursor = offsets.clone();
6304    for (pos, &v) in left_keys.iter().enumerate() {
6305        let bucket = (v - min) as usize;
6306        positions[cursor[bucket]] = pos;
6307        cursor[bucket] += 1;
6308    }
6309
6310    let mut output_len = 0usize;
6311    for &v in right_keys {
6312        if v < min || v > max {
6313            return Ok(None);
6314        }
6315        let bucket = (v - min) as usize;
6316        let bucket_len = offsets[bucket + 1] - offsets[bucket];
6317        if bucket_len == 0 {
6318            return Ok(None);
6319        }
6320        let Some(new_output_len) = output_len.checked_add(bucket_len) else {
6321            return Ok(None);
6322        };
6323        output_len = new_output_len;
6324    }
6325
6326    let mut output_data = specs
6327        .iter()
6328        .map(|_| Vec::<i64>::with_capacity(output_len))
6329        .collect::<Vec<_>>();
6330    for (right_pos, &v) in right_keys.iter().enumerate() {
6331        let bucket = (v - min) as usize;
6332        for &left_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
6333            for (out, spec) in output_data.iter_mut().zip(specs.iter()) {
6334                match spec.side {
6335                    FusedInt64Side::Left => out.push(spec.values[left_pos]),
6336                    FusedInt64Side::Right => out.push(spec.values[right_pos]),
6337                }
6338            }
6339        }
6340    }
6341
6342    // Lazy unit-range output index: identical labels (0..output_len as
6343    // IndexLabel::Int64, materialized on demand), pre-proven unique and
6344    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
6345    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6346    let mut columns = ColumnStore::new();
6347    let mut column_order = Vec::with_capacity(specs.len());
6348    for (spec, data) in specs.into_iter().zip(output_data) {
6349        debug_assert_eq!(data.len(), output_len);
6350        insert_merged_output_column(
6351            &mut columns,
6352            &mut column_order,
6353            spec.name,
6354            Column::from_i64_values(data),
6355        )?;
6356    }
6357
6358    Ok(Some(MergedDataFrame {
6359        index,
6360        columns,
6361        column_order,
6362    }))
6363}
6364
6365fn build_single_key_dense_i64_outer_all_matched_merge_output(
6366    left: &fp_frame::DataFrame,
6367    right: &fp_frame::DataFrame,
6368    left_on: &[&str],
6369    right_on: &[&str],
6370    left_key: &Column,
6371    right_key: &Column,
6372    suffixes: &ResolvedMergeSuffixes,
6373) -> Result<Option<MergedDataFrame>, JoinError> {
6374    debug_assert_eq!(left_on.len(), 1);
6375    debug_assert_eq!(right_on.len(), 1);
6376
6377    let Some(left_keys) = left_key.as_i64_slice() else {
6378        return Ok(None);
6379    };
6380    let Some(right_keys) = right_key.as_i64_slice() else {
6381        return Ok(None);
6382    };
6383
6384    if left_keys.is_empty() != right_keys.is_empty() {
6385        return Ok(None);
6386    }
6387    let dense_domain = if left_keys.is_empty() {
6388        None
6389    } else {
6390        let left_witness = left_key
6391            .int64_dense_cycle_witness()
6392            .filter(|witness| witness.len == left_keys.len());
6393        let right_witness = right_key
6394            .int64_dense_cycle_witness()
6395            .filter(|witness| witness.len == right_keys.len());
6396        match (
6397            left_witness.and_then(dense_cycle_domain),
6398            right_witness.and_then(dense_cycle_domain),
6399        ) {
6400            (Some(left_domain), Some(right_domain)) => {
6401                if left_domain != right_domain {
6402                    return Ok(None);
6403                }
6404                Some(left_domain)
6405            }
6406            _ => {
6407                let min_max = |keys: &[i64]| {
6408                    let mut min_key = keys[0];
6409                    let mut max_key = keys[0];
6410                    for &key in &keys[1..] {
6411                        min_key = min_key.min(key);
6412                        max_key = max_key.max(key);
6413                    }
6414                    (min_key, max_key)
6415                };
6416                let (left_min_key, left_max_key) = min_max(left_keys);
6417                let (right_min_key, right_max_key) = min_max(right_keys);
6418                if left_min_key != right_min_key || left_max_key != right_max_key {
6419                    return Ok(None);
6420                }
6421                Some((left_min_key, left_max_key))
6422            }
6423        }
6424    };
6425
6426    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6427    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6428    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6429    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6430    let shared_key_names = if left_on[0] == right_on[0] {
6431        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6432    } else {
6433        HashSet::new()
6434    };
6435    let overlapping_names =
6436        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6437
6438    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
6439    for name in left.column_names() {
6440        let col = left
6441            .columns()
6442            .get(name)
6443            .expect("left column listed in column_names must exist");
6444        let Some(values) = col.as_i64_slice() else {
6445            return Ok(None);
6446        };
6447        let out_name = if left_key_name_set.contains(name.as_str()) {
6448            name.clone()
6449        } else if right_col_names.contains(name) {
6450            apply_merge_suffix(name, suffixes.left.as_deref())
6451        } else {
6452            name.clone()
6453        };
6454        specs.push(FusedInt64OutputColumn {
6455            name: out_name,
6456            side: FusedInt64Side::Left,
6457            values,
6458        });
6459    }
6460
6461    for name in right.column_names() {
6462        let col = right
6463            .columns()
6464            .get(name)
6465            .expect("right column listed in column_names must exist");
6466        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6467            continue;
6468        }
6469        let Some(values) = col.as_i64_slice() else {
6470            return Ok(None);
6471        };
6472        let out_name = if left_col_names.contains(name) {
6473            apply_merge_suffix(name, suffixes.right.as_deref())
6474        } else {
6475            name.clone()
6476        };
6477        specs.push(FusedInt64OutputColumn {
6478            name: out_name,
6479            side: FusedInt64Side::Right,
6480            values,
6481        });
6482    }
6483
6484    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6485
6486    if left_keys.is_empty() || right_keys.is_empty() {
6487        if !left_keys.is_empty() || !right_keys.is_empty() {
6488            return Ok(None);
6489        }
6490        let mut columns = ColumnStore::new();
6491        let mut column_order = Vec::with_capacity(specs.len());
6492        for spec in specs {
6493            insert_merged_output_column(
6494                &mut columns,
6495                &mut column_order,
6496                spec.name,
6497                Column::from_i64_values(Vec::new()),
6498            )?;
6499        }
6500        return Ok(Some(MergedDataFrame {
6501            index: Index::new(Vec::new()),
6502            columns,
6503            column_order,
6504        }));
6505    }
6506
6507    let (min_key, max_key) = dense_domain.expect("empty dense outer case returned above");
6508
6509    let span = i128::from(max_key)
6510        .checked_sub(i128::from(min_key))
6511        .and_then(|span| span.checked_add(1));
6512    let Some(span) = span else {
6513        return Ok(None);
6514    };
6515    let row_count = left_keys.len().saturating_add(right_keys.len());
6516    let max_dense_span = row_count.saturating_mul(4).max(1024);
6517    if span > max_dense_span as i128 {
6518        return Ok(None);
6519    }
6520    let Ok(span) = usize::try_from(span) else {
6521        return Ok(None);
6522    };
6523
6524    let mut left_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
6525    let mut right_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
6526    for (pos, &key) in left_keys.iter().enumerate() {
6527        let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
6528            return Ok(None);
6529        };
6530        left_buckets[bucket].push(pos);
6531    }
6532    for (pos, &key) in right_keys.iter().enumerate() {
6533        let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
6534            return Ok(None);
6535        };
6536        right_buckets[bucket].push(pos);
6537    }
6538
6539    let mut output_len = 0usize;
6540    for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6541        match (left_bucket.is_empty(), right_bucket.is_empty()) {
6542            (false, false) => {
6543                let Some(bucket_rows) = left_bucket.len().checked_mul(right_bucket.len()) else {
6544                    return Ok(None);
6545                };
6546                let Some(new_output_len) = output_len.checked_add(bucket_rows) else {
6547                    return Ok(None);
6548                };
6549                output_len = new_output_len;
6550            }
6551            (false, true) | (true, false) => return Ok(None),
6552            (true, true) => {}
6553        }
6554    }
6555
6556    // Lazy unit-range output index: identical labels (0..output_len as
6557    // IndexLabel::Int64, materialized on demand), pre-proven unique and
6558    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
6559    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6560    let mut columns = ColumnStore::new();
6561    let mut column_order = Vec::with_capacity(specs.len());
6562    for spec in specs {
6563        let FusedInt64OutputColumn { name, side, values } = spec;
6564        let mut data = Vec::<i64>::with_capacity(output_len);
6565        match side {
6566            FusedInt64Side::Left => {
6567                for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6568                    if left_bucket.is_empty() {
6569                        continue;
6570                    }
6571                    let repeat_count = right_bucket.len();
6572                    for &left_pos in left_bucket {
6573                        let value = values[left_pos];
6574                        for _ in 0..repeat_count {
6575                            data.push(value);
6576                        }
6577                    }
6578                }
6579            }
6580            FusedInt64Side::Right => {
6581                for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6582                    if left_bucket.is_empty() {
6583                        continue;
6584                    }
6585                    for _ in left_bucket {
6586                        for &right_pos in right_bucket {
6587                            data.push(values[right_pos]);
6588                        }
6589                    }
6590                }
6591            }
6592        }
6593        debug_assert_eq!(data.len(), output_len);
6594        insert_merged_output_column(
6595            &mut columns,
6596            &mut column_order,
6597            name,
6598            Column::from_i64_values(data),
6599        )?;
6600    }
6601
6602    Ok(Some(MergedDataFrame {
6603        index,
6604        columns,
6605        column_order,
6606    }))
6607}
6608
6609struct FixedDecimalUtf8Domain {
6610    prefix: Vec<u8>,
6611    decimal_width: usize,
6612    start: u64,
6613    len: usize,
6614}
6615
6616impl FixedDecimalUtf8Domain {
6617    fn row_width(&self) -> usize {
6618        self.prefix.len() + self.decimal_width
6619    }
6620}
6621
6622fn trailing_decimal_width(bytes: &[u8]) -> Option<usize> {
6623    let width = bytes
6624        .iter()
6625        .rev()
6626        .take_while(|byte| byte.is_ascii_digit())
6627        .count();
6628    (width > 0).then_some(width)
6629}
6630
6631fn parse_decimal_u64(bytes: &[u8]) -> Option<u64> {
6632    let mut out = 0u64;
6633    for &byte in bytes {
6634        if !byte.is_ascii_digit() {
6635            return None;
6636        }
6637        out = out.checked_mul(10)?.checked_add(u64::from(byte - b'0'))?;
6638    }
6639    Some(out)
6640}
6641
6642fn fixed_decimal_utf8_domain(bytes: &[u8], offsets: &[usize]) -> Option<FixedDecimalUtf8Domain> {
6643    let len = offsets.len().checked_sub(1)?;
6644    if len == 0 {
6645        return None;
6646    }
6647
6648    let first = utf8_span(bytes, offsets, 0);
6649    let decimal_width = trailing_decimal_width(first)?;
6650    let prefix_len = first.len().checked_sub(decimal_width)?;
6651    let prefix = first[..prefix_len].to_vec();
6652    let start = parse_decimal_u64(&first[prefix_len..])?;
6653    let row_width = first.len();
6654
6655    for row in 0..len {
6656        let span = utf8_span(bytes, offsets, row);
6657        if span.len() != row_width || !span.starts_with(&prefix) {
6658            return None;
6659        }
6660        let value = parse_decimal_u64(&span[prefix_len..])?;
6661        if value != start.checked_add(row as u64)? {
6662            return None;
6663        }
6664    }
6665
6666    Some(FixedDecimalUtf8Domain {
6667        prefix,
6668        decimal_width,
6669        start,
6670        len,
6671    })
6672}
6673
6674fn fixed_decimal_utf8_bucket(span: &[u8], domain: &FixedDecimalUtf8Domain) -> Option<usize> {
6675    if span.len() != domain.row_width() || !span.starts_with(&domain.prefix) {
6676        return None;
6677    }
6678    let value = parse_decimal_u64(&span[domain.prefix.len()..])?;
6679    let relative = value.checked_sub(domain.start)?;
6680    let bucket = usize::try_from(relative).ok()?;
6681    (bucket < domain.len).then_some(bucket)
6682}
6683
6684enum FixedDecimalUtf8OuterLane<'a> {
6685    SharedKey,
6686    LeftF64(&'a [f64]),
6687    RightF64(&'a [f64]),
6688    LeftI64(&'a [i64]),
6689    RightI64(&'a [i64]),
6690}
6691
6692fn build_single_key_fixed_decimal_utf8_outer_all_matched_merge_output(
6693    left: &fp_frame::DataFrame,
6694    right: &fp_frame::DataFrame,
6695    left_on: &[&str],
6696    right_on: &[&str],
6697    left_key: &Column,
6698    right_key: &Column,
6699    suffixes: &ResolvedMergeSuffixes,
6700) -> Result<Option<MergedDataFrame>, JoinError> {
6701    debug_assert_eq!(left_on.len(), 1);
6702    debug_assert_eq!(right_on.len(), 1);
6703
6704    if left_on[0] != right_on[0] {
6705        return Ok(None);
6706    }
6707
6708    let Some((left_bytes, left_offsets)) = left_key.as_utf8_contiguous() else {
6709        return Ok(None);
6710    };
6711    let Some((right_bytes, right_offsets)) = right_key.as_utf8_contiguous() else {
6712        return Ok(None);
6713    };
6714    let left_len = left_offsets.len().saturating_sub(1);
6715    let right_len = right_offsets.len().saturating_sub(1);
6716    if left_len == 0 || right_len == 0 {
6717        return Ok(None);
6718    }
6719
6720    let Some(domain) = fixed_decimal_utf8_domain(right_bytes, right_offsets) else {
6721        return Ok(None);
6722    };
6723
6724    let mut counts = vec![0usize; right_len];
6725    let mut left_buckets = Vec::<usize>::with_capacity(left_len);
6726    for left_pos in 0..left_len {
6727        let span = utf8_span(left_bytes, left_offsets, left_pos);
6728        let Some(bucket) = fixed_decimal_utf8_bucket(span, &domain) else {
6729            return Ok(None);
6730        };
6731        counts[bucket] = counts[bucket].checked_add(1).ok_or_else(|| {
6732            JoinError::Frame(FrameError::CompatibilityRejected(
6733                "merge output row count overflowed".to_owned(),
6734            ))
6735        })?;
6736        left_buckets.push(bucket);
6737    }
6738    if counts.contains(&0) {
6739        return Ok(None);
6740    }
6741
6742    let mut offsets = Vec::with_capacity(right_len + 1);
6743    offsets.push(0usize);
6744    for &count in &counts {
6745        offsets.push(offsets.last().copied().unwrap_or(0) + count);
6746    }
6747    let output_len = offsets[right_len];
6748    let mut left_positions = vec![0usize; output_len];
6749    let mut cursor = offsets[..right_len].to_vec();
6750    for (left_pos, &bucket) in left_buckets.iter().enumerate() {
6751        let out = cursor[bucket];
6752        left_positions[out] = left_pos;
6753        cursor[bucket] += 1;
6754    }
6755
6756    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6757    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6758    let shared_key_names = [left_on[0]].into_iter().collect::<HashSet<&str>>();
6759    let overlapping_names =
6760        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6761    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6762
6763    let mut specs = Vec::<(String, FixedDecimalUtf8OuterLane<'_>)>::new();
6764    for name in left.column_names() {
6765        let col = left
6766            .columns()
6767            .get(name)
6768            .expect("left column listed in column_names must exist");
6769        let lane = if name.as_str() == left_on[0] {
6770            FixedDecimalUtf8OuterLane::SharedKey
6771        } else if let Some(values) = col.as_f64_slice() {
6772            FixedDecimalUtf8OuterLane::LeftF64(values)
6773        } else if let Some(values) = col.as_i64_slice() {
6774            FixedDecimalUtf8OuterLane::LeftI64(values)
6775        } else {
6776            return Ok(None);
6777        };
6778        let out_name = if name.as_str() == left_on[0] {
6779            name.clone()
6780        } else if right_col_names.contains(name) {
6781            apply_merge_suffix(name, suffixes.left.as_deref())
6782        } else {
6783            name.clone()
6784        };
6785        specs.push((out_name, lane));
6786    }
6787    for name in right.column_names() {
6788        if name.as_str() == right_on[0] {
6789            continue;
6790        }
6791        let col = right
6792            .columns()
6793            .get(name)
6794            .expect("right column listed in column_names must exist");
6795        let lane = if let Some(values) = col.as_f64_slice() {
6796            FixedDecimalUtf8OuterLane::RightF64(values)
6797        } else if let Some(values) = col.as_i64_slice() {
6798            FixedDecimalUtf8OuterLane::RightI64(values)
6799        } else {
6800            return Ok(None);
6801        };
6802        let out_name = if left_col_names.contains(name) {
6803            apply_merge_suffix(name, suffixes.right.as_deref())
6804        } else {
6805            name.clone()
6806        };
6807        specs.push((out_name, lane));
6808    }
6809
6810    let run_lens: Arc<[usize]> = Arc::from(counts.clone());
6811    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6812    let mut columns = ColumnStore::new();
6813    let mut column_order = Vec::with_capacity(specs.len());
6814    for (name, lane) in specs {
6815        let column = match lane {
6816            FixedDecimalUtf8OuterLane::SharedKey => {
6817                let row_width = domain.row_width();
6818                let mut bytes = Vec::with_capacity(output_len.saturating_mul(row_width));
6819                let mut out_offsets = Vec::with_capacity(output_len + 1);
6820                out_offsets.push(0);
6821                for (bucket, &count) in counts.iter().enumerate() {
6822                    let span = utf8_span(right_bytes, right_offsets, bucket);
6823                    for _ in 0..count {
6824                        bytes.extend_from_slice(span);
6825                        out_offsets.push(bytes.len());
6826                    }
6827                }
6828                Column::from_utf8_contiguous(bytes, out_offsets)
6829            }
6830            FixedDecimalUtf8OuterLane::LeftF64(values) => {
6831                let data = left_positions.iter().map(|&pos| values[pos]).collect();
6832                Column::from_f64_values_all_valid_unchecked(data)
6833            }
6834            FixedDecimalUtf8OuterLane::RightF64(values) => {
6835                let run_values = (0..right_len).map(|bucket| values[bucket]).collect();
6836                Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(&run_lens))
6837            }
6838            FixedDecimalUtf8OuterLane::LeftI64(values) => {
6839                let data = left_positions.iter().map(|&pos| values[pos]).collect();
6840                Column::from_i64_values(data)
6841            }
6842            FixedDecimalUtf8OuterLane::RightI64(values) => {
6843                let run_values = (0..right_len).map(|bucket| values[bucket]).collect();
6844                Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(&run_lens))
6845            }
6846        };
6847        debug_assert_eq!(column.len(), output_len);
6848        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
6849    }
6850
6851    Ok(Some(MergedDataFrame {
6852        index,
6853        columns,
6854        column_order,
6855    }))
6856}
6857
6858fn build_single_key_inner_merge_output(
6859    left: &fp_frame::DataFrame,
6860    right: &fp_frame::DataFrame,
6861    left_on: &[&str],
6862    right_on: &[&str],
6863    left_positions: &[usize],
6864    right_positions: &[usize],
6865    suffixes: &ResolvedMergeSuffixes,
6866) -> Result<MergedDataFrame, JoinError> {
6867    if left_on.len() == 1
6868        && left_positions.len() == left.len()
6869        && left.len() >= 2
6870        && left_positions.iter().enumerate().any(|(i, &l)| l != i)
6871        && let Some(left_key_col) = left.column(left_on[0])
6872    {
6873        let mut left_perm = left_positions.to_vec();
6874        let mut right_perm = right_positions.to_vec();
6875        permute_inner_merge_equal_left_len_positions(
6876            &[left_key_col],
6877            &mut left_perm,
6878            &mut right_perm,
6879        );
6880        return build_single_key_inner_merge_output_with_selections(
6881            left,
6882            right,
6883            left_on,
6884            right_on,
6885            PositionSelection::Positions(&left_perm),
6886            PositionSelection::Positions(&right_perm),
6887            suffixes,
6888        );
6889    }
6890    build_single_key_inner_merge_output_with_selections(
6891        left,
6892        right,
6893        left_on,
6894        right_on,
6895        PositionSelection::Positions(left_positions),
6896        PositionSelection::Positions(right_positions),
6897        suffixes,
6898    )
6899}
6900
6901fn build_single_key_inner_contiguous_no_overlap_output(
6902    left: &fp_frame::DataFrame,
6903    right: &fp_frame::DataFrame,
6904    left_on: &[&str],
6905    right_on: &[&str],
6906    left_positions: PositionSelection<'_>,
6907    right_positions: PositionSelection<'_>,
6908) -> Option<MergedDataFrame> {
6909    let (
6910        PositionSelection::ContiguousRange {
6911            start: left_start,
6912            len,
6913        },
6914        PositionSelection::ContiguousRange {
6915            start: right_start,
6916            len: right_len,
6917        },
6918    ) = (left_positions, right_positions)
6919    else {
6920        return None;
6921    };
6922    if left_on[0] != right_on[0] || len != right_len {
6923        return None;
6924    }
6925
6926    let left_col_names = left.column_names();
6927    let right_col_names = right.column_names();
6928    if left_col_names.iter().any(|left_name| {
6929        left_name.as_str() != left_on[0]
6930            && right_col_names
6931                .iter()
6932                .any(|right_name| right_name.as_str() == left_name.as_str())
6933    }) {
6934        return None;
6935    }
6936
6937    let mut columns = ColumnStore::new();
6938    let mut column_order =
6939        Vec::with_capacity(left_col_names.len() + right_col_names.len().saturating_sub(1));
6940    let left_selection = PositionSelection::ContiguousRange {
6941        start: left_start,
6942        len,
6943    };
6944    let right_selection = PositionSelection::ContiguousRange {
6945        start: right_start,
6946        len,
6947    };
6948
6949    for name in left_col_names.iter().copied() {
6950        let column = left
6951            .columns()
6952            .get(name)
6953            .expect("left column listed in column_names must exist");
6954        let output_column = if name.as_str() == left_on[0] {
6955            take_lower_hex_sequence_range(column, left_start, len)
6956                .unwrap_or_else(|| take_position_selection_typed(column, left_selection))
6957        } else {
6958            take_position_selection_typed(column, left_selection)
6959        };
6960        column_order.push(name.clone());
6961        let previous = columns.insert(name.clone(), output_column);
6962        debug_assert!(previous.is_none());
6963    }
6964    for name in right_col_names.iter().copied() {
6965        if name.as_str() == right_on[0] {
6966            continue;
6967        }
6968        let column = right
6969            .columns()
6970            .get(name)
6971            .expect("right column listed in column_names must exist");
6972        column_order.push(name.clone());
6973        let previous = columns.insert(
6974            name.clone(),
6975            take_position_selection_typed(column, right_selection),
6976        );
6977        debug_assert!(previous.is_none());
6978    }
6979
6980    Some(MergedDataFrame {
6981        index: Index::new_known_unique_int64_unit_range(0, len),
6982        columns,
6983        column_order,
6984    })
6985}
6986
6987fn build_single_key_inner_merge_output_with_selections(
6988    left: &fp_frame::DataFrame,
6989    right: &fp_frame::DataFrame,
6990    left_on: &[&str],
6991    right_on: &[&str],
6992    left_positions: PositionSelection<'_>,
6993    right_positions: PositionSelection<'_>,
6994    suffixes: &ResolvedMergeSuffixes,
6995) -> Result<MergedDataFrame, JoinError> {
6996    debug_assert_eq!(left_on.len(), 1);
6997    debug_assert_eq!(right_on.len(), 1);
6998    debug_assert_eq!(left_positions.len(), right_positions.len());
6999
7000    if let Some(merged) = build_single_key_inner_contiguous_no_overlap_output(
7001        left,
7002        right,
7003        left_on,
7004        right_on,
7005        left_positions,
7006        right_positions,
7007    ) {
7008        return Ok(merged);
7009    }
7010
7011    let n = left_positions.len();
7012    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7013    let index = Index::new_known_unique_int64_unit_range(0, n);
7014
7015    let left_col_names = left.column_names();
7016    let right_col_names = right.column_names();
7017    let use_linear_name_lookup =
7018        left_col_names.len() + right_col_names.len() <= SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT;
7019    let left_hashed_col_names = (!use_linear_name_lookup).then(|| {
7020        left_col_names
7021            .iter()
7022            .map(|name| name.as_str())
7023            .collect::<HashSet<_>>()
7024    });
7025    let right_hashed_col_names = (!use_linear_name_lookup).then(|| {
7026        right_col_names
7027            .iter()
7028            .map(|name| name.as_str())
7029            .collect::<HashSet<_>>()
7030    });
7031    let shared_key_name = (left_on[0] == right_on[0]).then_some(left_on[0]);
7032    let mut overlapping_names = left_col_names
7033        .iter()
7034        .filter_map(|name| {
7035            let name = name.as_str();
7036            (Some(name) != shared_key_name
7037                && column_name_lookup_contains(
7038                    &right_col_names,
7039                    right_hashed_col_names.as_ref(),
7040                    name,
7041                ))
7042            .then(|| name.to_owned())
7043        })
7044        .collect::<Vec<_>>();
7045    overlapping_names.sort();
7046    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7047
7048    // Resolve output column specs in order (name/suffix resolution is cheap),
7049    // then gather them. Each output column is an independent typed gather over
7050    // the position vector, so wide/large outputs build every column in parallel
7051    // (one column per worker) — the same disjoint-fill pattern as the dense-i64
7052    // fused builder (br-frankenpandas-j3jnd). Bit-identical to the serial loop:
7053    // identical per-column take_positions_typed result, inserted in spec order.
7054    let mut specs: Vec<(String, &Column, PositionSelection<'_>)> = Vec::new();
7055    for name in left_col_names.iter().copied() {
7056        let col = left
7057            .columns()
7058            .get(name)
7059            .expect("left column listed in column_names must exist");
7060        let out_name = if name.as_str() == left_on[0] {
7061            name.clone()
7062        } else if column_name_lookup_contains(
7063            &right_col_names,
7064            right_hashed_col_names.as_ref(),
7065            name.as_str(),
7066        ) {
7067            apply_merge_suffix(name, suffixes.left.as_deref())
7068        } else {
7069            name.clone()
7070        };
7071        specs.push((out_name, col, left_positions));
7072    }
7073    for name in right_col_names.iter().copied() {
7074        if name.as_str() == right_on[0] && shared_key_name == Some(name.as_str()) {
7075            continue;
7076        }
7077        let col = right
7078            .columns()
7079            .get(name)
7080            .expect("right column listed in column_names must exist");
7081        let out_name = if column_name_lookup_contains(
7082            &left_col_names,
7083            left_hashed_col_names.as_ref(),
7084            name.as_str(),
7085        ) {
7086            apply_merge_suffix(name, suffixes.right.as_deref())
7087        } else {
7088            name.clone()
7089        };
7090        specs.push((out_name, col, right_positions));
7091    }
7092
7093    let built: Vec<Column> = {
7094        let thread_count = join_parallel_thread_count();
7095        if specs.len() > 1 && n >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
7096            let mut slots: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
7097            let chunk = specs.len().div_ceil(thread_count).max(1);
7098            std::thread::scope(|scope| {
7099                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
7100                    scope.spawn(move || {
7101                        for ((_, col, positions), slot) in spec_chunk.iter().zip(slot_chunk) {
7102                            *slot = Some(take_position_selection_typed(col, *positions));
7103                        }
7104                    });
7105                }
7106            });
7107            slots
7108                .into_iter()
7109                .map(|c| c.expect("every spec column must be built"))
7110                .collect()
7111        } else {
7112            specs
7113                .iter()
7114                .map(|(_, col, positions)| take_position_selection_typed(col, *positions))
7115                .collect()
7116        }
7117    };
7118
7119    let mut columns = ColumnStore::new();
7120    let mut column_order: Vec<String> = Vec::with_capacity(specs.len());
7121    for ((out_name, _, _), column) in specs.into_iter().zip(built) {
7122        insert_merged_output_column(&mut columns, &mut column_order, out_name, column)?;
7123    }
7124
7125    Ok(MergedDataFrame {
7126        index,
7127        columns,
7128        column_order,
7129    })
7130}
7131
7132fn build_single_key_dense_left_merge_output(
7133    left: &fp_frame::DataFrame,
7134    right: &fp_frame::DataFrame,
7135    left_on: &[&str],
7136    right_on: &[&str],
7137    left_positions: &[Option<usize>],
7138    right_positions: &[Option<usize>],
7139    suffixes: &ResolvedMergeSuffixes,
7140) -> Result<MergedDataFrame, JoinError> {
7141    debug_assert_eq!(left_on.len(), 1);
7142    debug_assert_eq!(right_on.len(), 1);
7143    debug_assert_eq!(left_positions.len(), right_positions.len());
7144
7145    let n = left_positions.len();
7146    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7147    let index = Index::new_known_unique_int64_unit_range(0, n);
7148    let mut columns = ColumnStore::new();
7149    let mut column_order: Vec<String> = Vec::new();
7150
7151    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7152    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7153    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7154    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7155    let shared_key_names = if left_on[0] == right_on[0] {
7156        [left_on[0]].into_iter().collect::<HashSet<&str>>()
7157    } else {
7158        HashSet::new()
7159    };
7160    let overlapping_names =
7161        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7162    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7163    for name in left.column_names() {
7164        let col = left
7165            .columns()
7166            .get(name)
7167            .expect("left column listed in column_names must exist");
7168        let out_name = if left_key_name_set.contains(name.as_str()) {
7169            name.clone()
7170        } else if right_col_names.contains(name) {
7171            apply_merge_suffix(name, suffixes.left.as_deref())
7172        } else {
7173            name.clone()
7174        };
7175        let output = col.reindex_by_positions(left_positions)?;
7176        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7177    }
7178
7179    for name in right.column_names() {
7180        let col = right
7181            .columns()
7182            .get(name)
7183            .expect("right column listed in column_names must exist");
7184        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
7185            continue;
7186        }
7187
7188        let reindexed = reindex_join_column_with_invented_gap(col, right_positions)?;
7189        let out_name = if left_col_names.contains(name) {
7190            apply_merge_suffix(name, suffixes.right.as_deref())
7191        } else {
7192            name.clone()
7193        };
7194        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7195    }
7196
7197    Ok(MergedDataFrame {
7198        index,
7199        columns,
7200        column_order,
7201    })
7202}
7203
7204fn build_single_key_ordered_unique_left_merge_output(
7205    left: &fp_frame::DataFrame,
7206    right: &fp_frame::DataFrame,
7207    left_on: &[&str],
7208    right_on: &[&str],
7209    right_positions: &[Option<usize>],
7210    suffixes: &ResolvedMergeSuffixes,
7211) -> Result<MergedDataFrame, JoinError> {
7212    debug_assert_eq!(left_on.len(), 1);
7213    debug_assert_eq!(right_on.len(), 1);
7214    debug_assert_eq!(left.len(), right_positions.len());
7215
7216    let n = left.len();
7217    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7218    let index = Index::new_known_unique_int64_unit_range(0, n);
7219    let mut columns = ColumnStore::new();
7220    let mut column_order: Vec<String> = Vec::new();
7221    let mut identity_positions = None;
7222
7223    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7224    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7225    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7226    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7227    let shared_key_names = if left_on[0] == right_on[0] {
7228        [left_on[0]].into_iter().collect::<HashSet<&str>>()
7229    } else {
7230        HashSet::new()
7231    };
7232    let overlapping_names =
7233        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7234    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7235    // Building the shared Utf8 gather plan is O(output_rows): it scans every
7236    // optional position and, for a non-contiguous match pattern, allocates an
7237    // additional position tape plus validity bitmap. Most ordered Int64 joins
7238    // have only numeric payloads, where every column ignores that plan and uses
7239    // its typed reindexer. Defer the work until the first Utf8 payload actually
7240    // asks for it; subsequent Utf8 columns still share the single immutable
7241    // plan exactly as before.
7242    let right_utf8_plan: OnceLock<Option<SharedOptionalUtf8GatherPlan>> = OnceLock::new();
7243
7244    for name in left.column_names() {
7245        let col = left
7246            .columns()
7247            .get(name)
7248            .expect("left column listed in column_names must exist");
7249        let out_name = if left_key_name_set.contains(name.as_str()) {
7250            name.clone()
7251        } else if right_col_names.contains(name) {
7252            apply_merge_suffix(name, suffixes.left.as_deref())
7253        } else {
7254            name.clone()
7255        };
7256        let output = identity_merge_column(col, n, &mut identity_positions);
7257        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7258    }
7259
7260    for name in right.column_names() {
7261        let col = right
7262            .columns()
7263            .get(name)
7264            .expect("right column listed in column_names must exist");
7265        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
7266            continue;
7267        }
7268
7269        let reindexed = if col.dtype() == DType::Utf8 {
7270            let utf8_plan = right_utf8_plan
7271                .get_or_init(|| shared_optional_utf8_gather_plan(right_positions, right.len()))
7272                .as_ref();
7273            reindex_with_shared_utf8_plan(col, right_positions, utf8_plan)?
7274        } else {
7275            reindex_join_column_with_invented_gap(col, right_positions)?
7276        };
7277        let out_name = if left_col_names.contains(name) {
7278            apply_merge_suffix(name, suffixes.right.as_deref())
7279        } else {
7280            name.clone()
7281        };
7282        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7283    }
7284
7285    Ok(MergedDataFrame {
7286        index,
7287        columns,
7288        column_order,
7289    })
7290}
7291
7292fn build_single_key_ordered_unique_right_merge_output(
7293    left: &fp_frame::DataFrame,
7294    right: &fp_frame::DataFrame,
7295    left_on: &[&str],
7296    right_on: &[&str],
7297    left_positions: &[Option<usize>],
7298    suffixes: &ResolvedMergeSuffixes,
7299) -> Result<MergedDataFrame, JoinError> {
7300    debug_assert_eq!(left_on.len(), 1);
7301    debug_assert_eq!(right_on.len(), 1);
7302    debug_assert_eq!(right.len(), left_positions.len());
7303
7304    let n = right.len();
7305    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7306    let index = Index::new_known_unique_int64_unit_range(0, n);
7307    let mut columns = ColumnStore::new();
7308    let mut column_order: Vec<String> = Vec::new();
7309    let mut identity_positions = None;
7310
7311    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7312    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7313    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7314    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7315    let shared_key_names = if left_on[0] == right_on[0] {
7316        [left_on[0]].into_iter().collect::<HashSet<&str>>()
7317    } else {
7318        HashSet::new()
7319    };
7320    let overlapping_names =
7321        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7322    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7323
7324    for name in left.column_names() {
7325        let col = left
7326            .columns()
7327            .get(name)
7328            .expect("left column listed in column_names must exist");
7329        let out_name = if left_key_name_set.contains(name.as_str()) {
7330            name.clone()
7331        } else if right_col_names.contains(name) {
7332            apply_merge_suffix(name, suffixes.left.as_deref())
7333        } else {
7334            name.clone()
7335        };
7336        let output = if left_key_name_set.contains(name.as_str())
7337            && shared_key_names.contains(name.as_str())
7338        {
7339            let right_key_col = right
7340                .columns()
7341                .get(right_on[0])
7342                .expect("right key column must exist");
7343            identity_merge_column(right_key_col, n, &mut identity_positions)
7344        } else {
7345            reindex_join_column_with_invented_gap(col, left_positions)?
7346        };
7347        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7348    }
7349
7350    for name in right.column_names() {
7351        let col = right
7352            .columns()
7353            .get(name)
7354            .expect("right column listed in column_names must exist");
7355        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
7356            continue;
7357        }
7358
7359        let reindexed = identity_merge_column(col, n, &mut identity_positions);
7360        let out_name = if left_col_names.contains(name) {
7361            apply_merge_suffix(name, suffixes.right.as_deref())
7362        } else {
7363            name.clone()
7364        };
7365        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7366    }
7367
7368    Ok(MergedDataFrame {
7369        index,
7370        columns,
7371        column_order,
7372    })
7373}
7374
7375fn build_single_key_dense_right_merge_output(
7376    left: &fp_frame::DataFrame,
7377    right: &fp_frame::DataFrame,
7378    left_on: &[&str],
7379    right_on: &[&str],
7380    left_positions: &[Option<usize>],
7381    right_positions: &[Option<usize>],
7382    suffixes: &ResolvedMergeSuffixes,
7383) -> Result<MergedDataFrame, JoinError> {
7384    debug_assert_eq!(left_on.len(), 1);
7385    debug_assert_eq!(right_on.len(), 1);
7386    debug_assert_eq!(left_positions.len(), right_positions.len());
7387
7388    let n = left_positions.len();
7389    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7390    let index = Index::new_known_unique_int64_unit_range(0, n);
7391    let mut columns = ColumnStore::new();
7392    let mut column_order: Vec<String> = Vec::new();
7393
7394    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7395    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7396    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7397    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7398    let shared_key_names = if left_on[0] == right_on[0] {
7399        [left_on[0]].into_iter().collect::<HashSet<&str>>()
7400    } else {
7401        HashSet::new()
7402    };
7403    let overlapping_names =
7404        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7405    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7406
7407    for name in left.column_names() {
7408        let col = left
7409            .columns()
7410            .get(name)
7411            .expect("left column listed in column_names must exist");
7412        let out_name = if left_key_name_set.contains(name.as_str()) {
7413            name.clone()
7414        } else if right_col_names.contains(name) {
7415            apply_merge_suffix(name, suffixes.left.as_deref())
7416        } else {
7417            name.clone()
7418        };
7419        let output = if left_key_name_set.contains(name.as_str())
7420            && shared_key_names.contains(name.as_str())
7421        {
7422            let right_key_col = right
7423                .columns()
7424                .get(right_on[0])
7425                .expect("right key column must exist");
7426            right_key_col.reindex_by_positions(right_positions)?
7427        } else {
7428            reindex_join_column_with_invented_gap(col, left_positions)?
7429        };
7430        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7431    }
7432
7433    for name in right.column_names() {
7434        let col = right
7435            .columns()
7436            .get(name)
7437            .expect("right column listed in column_names must exist");
7438        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
7439            continue;
7440        }
7441
7442        let reindexed = col.reindex_by_positions(right_positions)?;
7443        let out_name = if left_col_names.contains(name) {
7444            apply_merge_suffix(name, suffixes.right.as_deref())
7445        } else {
7446            name.clone()
7447        };
7448        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7449    }
7450
7451    Ok(MergedDataFrame {
7452        index,
7453        columns,
7454        column_order,
7455    })
7456}
7457
7458fn build_single_key_ordered_unique_outer_merge_output(
7459    left: &fp_frame::DataFrame,
7460    right: &fp_frame::DataFrame,
7461    left_on: &[&str],
7462    right_on: &[&str],
7463    left_positions: &[Option<usize>],
7464    right_positions: &[Option<usize>],
7465    suffixes: &ResolvedMergeSuffixes,
7466) -> Result<MergedDataFrame, JoinError> {
7467    debug_assert_eq!(left_on.len(), 1);
7468    debug_assert_eq!(right_on.len(), 1);
7469    debug_assert_eq!(left_positions.len(), right_positions.len());
7470
7471    let n = left_positions.len();
7472    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7473    let index = Index::new_known_unique_int64_unit_range(0, n);
7474    let mut columns = ColumnStore::new();
7475    let mut column_order: Vec<String> = Vec::new();
7476
7477    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7478    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7479    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7480    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7481
7482    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
7483    if left_on[0] == right_on[0] {
7484        shared_name_positions.insert(left_on[0], (0, 0));
7485    }
7486    let shared_key_names = shared_name_positions
7487        .keys()
7488        .copied()
7489        .collect::<HashSet<&str>>();
7490    let overlapping_names =
7491        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7492    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7493
7494    let mut left_take_positions = Vec::with_capacity(n);
7495    let mut right_take_positions = Vec::with_capacity(n);
7496    let mut all_positions_present = true;
7497    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
7498        let (Some(left_pos), Some(right_pos)) = (*left_pos, *right_pos) else {
7499            all_positions_present = false;
7500            break;
7501        };
7502        left_take_positions.push(left_pos);
7503        right_take_positions.push(right_pos);
7504    }
7505    let all_present_take_positions =
7506        all_positions_present.then_some((left_take_positions, right_take_positions));
7507    let all_present_left_positions = all_present_take_positions
7508        .as_ref()
7509        .map(|(positions, _)| positions.as_slice());
7510    let all_present_right_positions = all_present_take_positions
7511        .as_ref()
7512        .map(|(_, positions)| positions.as_slice());
7513    let left_has_utf8 = left
7514        .columns()
7515        .values()
7516        .any(|column| column.dtype() == DType::Utf8);
7517    let right_has_utf8 = right
7518        .columns()
7519        .values()
7520        .any(|column| column.dtype() == DType::Utf8);
7521    let left_utf8_plan = (left_has_utf8 && all_present_left_positions.is_none())
7522        .then(|| shared_optional_utf8_gather_plan(left_positions, left.len()))
7523        .flatten();
7524    let right_utf8_plan = (right_has_utf8 && all_present_right_positions.is_none())
7525        .then(|| shared_optional_utf8_gather_plan(right_positions, right.len()))
7526        .flatten();
7527
7528    // Per-column output build is INDEPENDENT across columns and was the serial
7529    // hot phase of the join (~10.5ms of str_outer_join's reindex assembly at
7530    // n=150000, 12 Utf8 value columns). Build an ordered list of column specs
7531    // (cheap), compute each column — the O(output) `reindex_join_column_with_invented_gap`
7532    // gather / take / key-coalesce — across workers, then insert in the SAME
7533    // first-seen order (br-frankenpandas-uza04.102). Byte-identical: each output
7534    // column is the same values in the same row order, inserted in the same
7535    // left-then-right column order, so `columns`/`column_order` are unchanged.
7536    enum ColBuild<'a> {
7537        KeyCoalesce {
7538            left_key_col: &'a Column,
7539            right_key_col: &'a Column,
7540        },
7541        Reindex {
7542            col: &'a Column,
7543            positions: &'a [Option<usize>],
7544            utf8_plan: Option<&'a SharedOptionalUtf8GatherPlan>,
7545        },
7546        Take {
7547            col: &'a Column,
7548            present: &'a [usize],
7549        },
7550    }
7551    let mut jobs: Vec<(String, ColBuild<'_>)> = Vec::new();
7552    for name in left.column_names() {
7553        let col = left
7554            .columns()
7555            .get(name)
7556            .expect("left column listed in column_names must exist");
7557        if left_key_name_set.contains(name.as_str()) {
7558            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
7559                let left_key_col = left
7560                    .columns()
7561                    .get(left_on[*left_key_idx])
7562                    .expect("left key column must exist");
7563                let spec = if let Some(positions) = all_present_left_positions {
7564                    ColBuild::Take {
7565                        col: left_key_col,
7566                        present: positions,
7567                    }
7568                } else {
7569                    let right_key_col = right
7570                        .columns()
7571                        .get(right_on[*right_key_idx])
7572                        .expect("right key column must exist");
7573                    ColBuild::KeyCoalesce {
7574                        left_key_col,
7575                        right_key_col,
7576                    }
7577                };
7578                jobs.push((name.clone(), spec));
7579            } else {
7580                let spec = if let Some(positions) = all_present_left_positions {
7581                    ColBuild::Take {
7582                        col,
7583                        present: positions,
7584                    }
7585                } else {
7586                    ColBuild::Reindex {
7587                        col,
7588                        positions: left_positions,
7589                        utf8_plan: left_utf8_plan.as_ref(),
7590                    }
7591                };
7592                jobs.push((name.clone(), spec));
7593            }
7594            continue;
7595        }
7596        let spec = if let Some(positions) = all_present_left_positions {
7597            ColBuild::Take {
7598                col,
7599                present: positions,
7600            }
7601        } else {
7602            ColBuild::Reindex {
7603                col,
7604                positions: left_positions,
7605                utf8_plan: left_utf8_plan.as_ref(),
7606            }
7607        };
7608        let out_name = if right_col_names.contains(name) {
7609            apply_merge_suffix(name, suffixes.left.as_deref())
7610        } else {
7611            name.clone()
7612        };
7613        jobs.push((out_name, spec));
7614    }
7615    for name in right.column_names() {
7616        let col = right
7617            .columns()
7618            .get(name)
7619            .expect("right column listed in column_names must exist");
7620        if right_key_name_set.contains(name.as_str())
7621            && shared_name_positions.contains_key(name.as_str())
7622        {
7623            continue;
7624        }
7625        let spec = if let Some(positions) = all_present_right_positions {
7626            ColBuild::Take {
7627                col,
7628                present: positions,
7629            }
7630        } else {
7631            ColBuild::Reindex {
7632                col,
7633                positions: right_positions,
7634                utf8_plan: right_utf8_plan.as_ref(),
7635            }
7636        };
7637        let out_name = if left_col_names.contains(name) {
7638            apply_merge_suffix(name, suffixes.right.as_deref())
7639        } else {
7640            name.clone()
7641        };
7642        jobs.push((out_name, spec));
7643    }
7644
7645    let compute = |spec: &ColBuild<'_>| -> Result<Column, JoinError> {
7646        match spec {
7647            ColBuild::KeyCoalesce {
7648                left_key_col,
7649                right_key_col,
7650            } => {
7651                if let Some(column) = coalesce_temporal_i64_key_column(
7652                    left_key_col,
7653                    right_key_col,
7654                    left_positions,
7655                    right_positions,
7656                ) {
7657                    return Ok(column);
7658                }
7659                if let (Some(left_keys), Some(right_keys)) =
7660                    (left_key_col.as_i64_slice(), right_key_col.as_i64_slice())
7661                {
7662                    let mut data = Vec::with_capacity(left_positions.len());
7663                    let mut all_positions_valid = true;
7664                    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
7665                        match (*left_pos, *right_pos) {
7666                            (Some(pos), _) if pos < left_keys.len() => data.push(left_keys[pos]),
7667                            (None, Some(pos)) if pos < right_keys.len() => {
7668                                data.push(right_keys[pos])
7669                            }
7670                            _ => {
7671                                all_positions_valid = false;
7672                                break;
7673                            }
7674                        }
7675                    }
7676                    if all_positions_valid {
7677                        return Ok(Column::from_i64_values(data));
7678                    }
7679                }
7680
7681                let values = left_positions
7682                    .iter()
7683                    .zip(right_positions.iter())
7684                    .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
7685                        (Some(pos), _) => left_key_col.values()[*pos].clone(),
7686                        (None, Some(pos)) => right_key_col.values()[*pos].clone(),
7687                        (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
7688                    })
7689                    .collect::<Vec<_>>();
7690                Ok(Column::from_values(values)?)
7691            }
7692            ColBuild::Reindex {
7693                col,
7694                positions,
7695                utf8_plan,
7696            } => reindex_outer_with_shared_utf8_plan(col, positions, *utf8_plan),
7697            ColBuild::Take { col, present } => Ok(take_positions_typed(col, present)),
7698        }
7699    };
7700
7701    let worker_count = fp_columnar::cached_available_parallelism()
7702        .min(64)
7703        .min(jobs.len().max(1));
7704    let computed: Vec<Result<Column, JoinError>> = if worker_count >= 2 && jobs.len() >= 2 {
7705        let next = std::sync::atomic::AtomicUsize::new(0);
7706        let jobs_ref = &jobs;
7707        let compute_ref = &compute;
7708        let mut slots: Vec<Option<Result<Column, JoinError>>> =
7709            (0..jobs.len()).map(|_| None).collect();
7710        let parts = std::thread::scope(|scope| {
7711            let mut handles = Vec::with_capacity(worker_count);
7712            for _ in 0..worker_count {
7713                let next = &next;
7714                handles.push(scope.spawn(move || {
7715                    let mut out: Vec<(usize, Result<Column, JoinError>)> = Vec::new();
7716                    loop {
7717                        let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7718                        if i >= jobs_ref.len() {
7719                            break;
7720                        }
7721                        out.push((i, compute_ref(&jobs_ref[i].1)));
7722                    }
7723                    out
7724                }));
7725            }
7726            handles
7727                .into_iter()
7728                .map(|h| h.join().expect("join assembly worker panicked"))
7729                .collect::<Vec<_>>()
7730        });
7731        for part in parts {
7732            for (i, r) in part {
7733                slots[i] = Some(r);
7734            }
7735        }
7736        slots
7737            .into_iter()
7738            .map(|s| s.expect("every output column computed"))
7739            .collect()
7740    } else {
7741        jobs.iter().map(|(_, spec)| compute(spec)).collect()
7742    };
7743
7744    for ((out_name, _), col_res) in jobs.into_iter().zip(computed) {
7745        insert_merged_output_column(&mut columns, &mut column_order, out_name, col_res?)?;
7746    }
7747
7748    Ok(MergedDataFrame {
7749        index,
7750        columns,
7751        column_order,
7752    })
7753}
7754
7755fn build_single_key_ordered_identity_inner_merge_output(
7756    left: &fp_frame::DataFrame,
7757    right: &fp_frame::DataFrame,
7758    left_on: &[&str],
7759    right_on: &[&str],
7760    suffixes: &ResolvedMergeSuffixes,
7761) -> Result<MergedDataFrame, JoinError> {
7762    debug_assert_eq!(left_on.len(), 1);
7763    debug_assert_eq!(right_on.len(), 1);
7764    debug_assert_eq!(left_on[0], right_on[0]);
7765
7766    let n = left.len();
7767    debug_assert_eq!(n, right.len());
7768    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7769    let index = Index::new_known_unique_int64_unit_range(0, n);
7770    let mut columns = ColumnStore::new();
7771    let mut column_order: Vec<String> = Vec::new();
7772    let mut identity_positions = None;
7773
7774    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7775    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7776    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7777    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7778    let shared_key_names = left_on.iter().copied().collect::<HashSet<&str>>();
7779    let overlapping_names =
7780        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7781    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7782
7783    for name in left.column_names() {
7784        let col = left
7785            .columns()
7786            .get(name)
7787            .expect("left column listed in column_names must exist");
7788        let out_name = if left_key_name_set.contains(name.as_str()) {
7789            name.clone()
7790        } else if right_col_names.contains(name) {
7791            apply_merge_suffix(name, suffixes.left.as_deref())
7792        } else {
7793            name.clone()
7794        };
7795        let output = identity_merge_column(col, n, &mut identity_positions);
7796        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7797    }
7798
7799    for name in right.column_names() {
7800        if right_key_name_set.contains(name.as_str()) {
7801            continue;
7802        }
7803
7804        let col = right
7805            .columns()
7806            .get(name)
7807            .expect("right column listed in column_names must exist");
7808        let out_name = if left_col_names.contains(name) {
7809            apply_merge_suffix(name, suffixes.right.as_deref())
7810        } else {
7811            name.clone()
7812        };
7813        let output = identity_merge_column(col, n, &mut identity_positions);
7814        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7815    }
7816
7817    Ok(MergedDataFrame {
7818        index,
7819        columns,
7820        column_order,
7821    })
7822}
7823
7824/// Hash-free inner-join position build for two all-valid, bounded-range Int64
7825/// key columns. Replaces the `FxHashMap<&JoinKeyComponent, _>` build+probe with
7826/// a counting-sort / CSR direct-address table indexed by `key - min`.
7827///
7828/// Bit-identical to the hash path's emitted `(left_pos, right_pos)` pairs: the
7829/// hash path buckets right positions in *insertion* order (ascending position),
7830/// and this CSR fill also writes right positions in ascending-position order,
7831/// so for every left row the matched right rows are emitted in the same order;
7832/// left rows are still probed in ascending order. All-valid Int64 keys map to
7833/// `Present(IndexLabel::Int64(v))` in the hash path, whose equality is plain
7834/// `i64 ==`, so membership/equality semantics are identical. A left key outside
7835/// the right key span matches nothing in either path. Returns `None` (caller
7836/// falls back to the hash path) for non-Int64, any-missing, or wide-span keys.
7837fn dense_int64_inner_positions(
7838    left_key: &Column,
7839    right_key: &Column,
7840) -> Option<(Vec<usize>, Vec<usize>)> {
7841    let left = left_key.as_i64_slice()?;
7842    let right = right_key.as_i64_slice()?;
7843    dense_i64_inner_positions_slices(left, right)
7844}
7845
7846/// Typed single-key INNER positions for all-valid temporal columns. Datetime64
7847/// and Timedelta64 both store exact nanoseconds in `i64`; matching those raw
7848/// values is identical to matching their same-variant `IndexLabel` wrappers.
7849///
7850/// The fast path requires equal temporal dtypes and rejects NaT explicitly.
7851/// Ordered inputs validate each newly reached value while intersecting, instead
7852/// of pre-scanning both slices for NaT and strict ordering. Nullable keys
7853/// therefore fall through to the Scalar oracle, preserving its Missing-to-
7854/// Missing join behavior. Output construction still gathers the original
7855/// temporal key column, so dtype and value representation are kept.
7856fn temporal_i64_inner_positions(
7857    left_key: &Column,
7858    right_key: &Column,
7859) -> Option<(Vec<usize>, Vec<usize>)> {
7860    if !left_key.validity().all() || !right_key.validity().all() {
7861        return None;
7862    }
7863
7864    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7865        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7866            if left_tz == right_tz =>
7867        {
7868            (
7869                left_key.as_datetime64_slice()?,
7870                right_key.as_datetime64_slice()?,
7871                fp_types::Timestamp::NAT,
7872            )
7873        }
7874        (DType::Timedelta64, DType::Timedelta64) => (
7875            left_key.as_timedelta64_slice()?,
7876            right_key.as_timedelta64_slice()?,
7877            fp_types::Timedelta::NAT,
7878        ),
7879        _ => return None,
7880    };
7881    let mut left_positions = Vec::with_capacity(left.len().min(right.len()));
7882    let mut right_positions = Vec::with_capacity(left_positions.capacity());
7883    let (mut left_idx, mut right_idx) = (0usize, 0usize);
7884    let mut ordered = newly_reached_temporal_i64_value_is_strict(left, 0, nat)
7885        && newly_reached_temporal_i64_value_is_strict(right, 0, nat);
7886    while ordered && left_idx < left.len() && right_idx < right.len() {
7887        match left[left_idx].cmp(&right[right_idx]) {
7888            Ordering::Equal => {
7889                left_positions.push(left_idx);
7890                right_positions.push(right_idx);
7891                left_idx += 1;
7892                right_idx += 1;
7893                ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat)
7894                    && newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7895            }
7896            Ordering::Less => {
7897                left_idx += 1;
7898                ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat);
7899            }
7900            Ordering::Greater => {
7901                right_idx += 1;
7902                ordered = newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7903            }
7904        }
7905    }
7906    while ordered && left_idx < left.len() {
7907        left_idx += 1;
7908        ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat);
7909    }
7910    while ordered && right_idx < right.len() {
7911        right_idx += 1;
7912        ordered = newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7913    }
7914    if ordered {
7915        return Some((left_positions, right_positions));
7916    }
7917
7918    if left.contains(&nat) || right.contains(&nat) {
7919        return None;
7920    }
7921
7922    dense_i64_inner_positions_slices(left, right)
7923        .or_else(|| Some(hash_i64_inner_positions_slices(left, right)))
7924}
7925
7926/// Typed single-key LEFT positions for all-valid temporal columns. The ordered
7927/// unique case uses a two-pointer match scan; remaining shapes hash the raw
7928/// nanoseconds. Both emit left-major rows and ascending right positions per
7929/// key, exactly matching the generic Scalar planner. Nullable keys and NaT
7930/// retain that planner's Missing-key behavior by declining this path.
7931fn temporal_i64_left_positions(
7932    left_key: &Column,
7933    right_key: &Column,
7934) -> Option<OptionalJoinPositions> {
7935    if !left_key.validity().all() || !right_key.validity().all() {
7936        return None;
7937    }
7938
7939    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7940        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7941            if left_tz == right_tz =>
7942        {
7943            (
7944                left_key.as_datetime64_slice()?,
7945                right_key.as_datetime64_slice()?,
7946                fp_types::Timestamp::NAT,
7947            )
7948        }
7949        (DType::Timedelta64, DType::Timedelta64) => (
7950            left_key.as_timedelta64_slice()?,
7951            right_key.as_timedelta64_slice()?,
7952            fp_types::Timedelta::NAT,
7953        ),
7954        _ => return None,
7955    };
7956    if left.contains(&nat) || right.contains(&nat) {
7957        return None;
7958    }
7959
7960    if left.windows(2).all(|pair| pair[0] < pair[1])
7961        && right.windows(2).all(|pair| pair[0] < pair[1])
7962    {
7963        let left_positions = (0..left.len()).map(Some).collect::<Vec<_>>();
7964        let mut right_positions = Vec::with_capacity(left.len());
7965        let mut right_idx = 0usize;
7966        for &left_value in left {
7967            while right_idx < right.len() && right[right_idx] < left_value {
7968                right_idx += 1;
7969            }
7970            right_positions.push(
7971                (right_idx < right.len()
7972                    && matches!(right[right_idx].cmp(&left_value), Ordering::Equal))
7973                .then_some(right_idx),
7974            );
7975        }
7976        return Some((left_positions, right_positions));
7977    }
7978
7979    if right.is_empty() {
7980        return Some(((0..left.len()).map(Some).collect(), vec![None; left.len()]));
7981    }
7982    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
7983        right.len(),
7984        Default::default(),
7985    );
7986    for (pos, &key) in right.iter().enumerate() {
7987        right_map.entry(key).or_default().push(pos);
7988    }
7989    let mut left_positions = Vec::<Option<usize>>::with_capacity(left.len());
7990    let mut right_positions = Vec::<Option<usize>>::with_capacity(left.len());
7991    for (left_pos, &key) in left.iter().enumerate() {
7992        if let Some(matches) = right_map.get(&key) {
7993            for &right_pos in matches {
7994                left_positions.push(Some(left_pos));
7995                right_positions.push(Some(right_pos));
7996            }
7997        } else {
7998            left_positions.push(Some(left_pos));
7999            right_positions.push(None);
8000        }
8001    }
8002    Some((left_positions, right_positions))
8003}
8004
8005#[inline]
8006fn newly_reached_temporal_i64_value_is_strict(values: &[i64], idx: usize, nat: i64) -> bool {
8007    let Some(&value) = values.get(idx) else {
8008        return true;
8009    };
8010    value != nat && (idx == 0 || values[idx - 1] < value)
8011}
8012
8013/// Ordered-unique single-key RIGHT matches for all-valid temporal columns.
8014/// Datetime64 and Timedelta64 both store exact nanoseconds in `i64`, so a
8015/// monotone two-pointer scan produces the same optional left position per
8016/// right row as the generic Scalar planner without materializing either key.
8017/// Each newly reached value is validated for NaT and strict ordering during
8018/// that scan, avoiding separate input pre-scans. Nullable, NaT-bearing,
8019/// duplicate, unsorted, or mixed-dtype keys decline.
8020fn ordered_unique_temporal_i64_right_match_positions(
8021    left_key: &Column,
8022    right_key: &Column,
8023) -> Option<Vec<Option<usize>>> {
8024    if !left_key.validity().all() || !right_key.validity().all() {
8025        return None;
8026    }
8027
8028    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
8029        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
8030            if left_tz == right_tz =>
8031        {
8032            (
8033                left_key.as_datetime64_slice()?,
8034                right_key.as_datetime64_slice()?,
8035                fp_types::Timestamp::NAT,
8036            )
8037        }
8038        (DType::Timedelta64, DType::Timedelta64) => (
8039            left_key.as_timedelta64_slice()?,
8040            right_key.as_timedelta64_slice()?,
8041            fp_types::Timedelta::NAT,
8042        ),
8043        _ => return None,
8044    };
8045    if !newly_reached_temporal_i64_value_is_strict(left, 0, nat) {
8046        return None;
8047    }
8048
8049    let mut left_positions = Vec::with_capacity(right.len());
8050    let mut left_idx = 0usize;
8051    for (right_idx, &right_value) in right.iter().enumerate() {
8052        if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
8053            return None;
8054        }
8055        while left_idx < left.len() && left[left_idx] < right_value {
8056            left_idx += 1;
8057            if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
8058                return None;
8059            }
8060        }
8061        left_positions.push(
8062            (left_idx < left.len() && matches!(left[left_idx].cmp(&right_value), Ordering::Equal))
8063                .then_some(left_idx),
8064        );
8065    }
8066    while left_idx < left.len() {
8067        left_idx += 1;
8068        if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
8069            return None;
8070        }
8071    }
8072    Some(left_positions)
8073}
8074
8075/// Ordered-unique single-key OUTER union for all-valid temporal columns.
8076/// Datetime64 and Timedelta64 ordering is their raw nanosecond ordering, so a
8077/// three-way merge produces the same key-sorted optional position tapes as the
8078/// generic Scalar planner without materializing either input key for position
8079/// planning. Each newly reached value is validated for NaT and strict ordering
8080/// inside that merge, avoiding separate input pre-scans. Nullable, NaT-bearing,
8081/// duplicate, unsorted, or mixed-dtype keys decline.
8082fn ordered_unique_temporal_i64_outer_positions(
8083    left_key: &Column,
8084    right_key: &Column,
8085) -> Option<OptionalJoinPositions> {
8086    if !left_key.validity().all() || !right_key.validity().all() {
8087        return None;
8088    }
8089
8090    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
8091        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
8092            if left_tz == right_tz =>
8093        {
8094            (
8095                left_key.as_datetime64_slice()?,
8096                right_key.as_datetime64_slice()?,
8097                fp_types::Timestamp::NAT,
8098            )
8099        }
8100        (DType::Timedelta64, DType::Timedelta64) => (
8101            left_key.as_timedelta64_slice()?,
8102            right_key.as_timedelta64_slice()?,
8103            fp_types::Timedelta::NAT,
8104        ),
8105        _ => return None,
8106    };
8107    if !newly_reached_temporal_i64_value_is_strict(left, 0, nat)
8108        || !newly_reached_temporal_i64_value_is_strict(right, 0, nat)
8109    {
8110        return None;
8111    }
8112
8113    let capacity = left.len().saturating_add(right.len());
8114    let mut left_positions = Vec::<Option<usize>>::with_capacity(capacity);
8115    let mut right_positions = Vec::<Option<usize>>::with_capacity(capacity);
8116    let (mut left_idx, mut right_idx) = (0usize, 0usize);
8117    while left_idx < left.len() && right_idx < right.len() {
8118        match left[left_idx].cmp(&right[right_idx]) {
8119            Ordering::Equal => {
8120                left_positions.push(Some(left_idx));
8121                right_positions.push(Some(right_idx));
8122                left_idx += 1;
8123                right_idx += 1;
8124                if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat)
8125                    || !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat)
8126                {
8127                    return None;
8128                }
8129            }
8130            Ordering::Less => {
8131                left_positions.push(Some(left_idx));
8132                right_positions.push(None);
8133                left_idx += 1;
8134                if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
8135                    return None;
8136                }
8137            }
8138            Ordering::Greater => {
8139                left_positions.push(None);
8140                right_positions.push(Some(right_idx));
8141                right_idx += 1;
8142                if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
8143                    return None;
8144                }
8145            }
8146        }
8147    }
8148    while left_idx < left.len() {
8149        left_positions.push(Some(left_idx));
8150        right_positions.push(None);
8151        left_idx += 1;
8152        if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
8153            return None;
8154        }
8155    }
8156    while right_idx < right.len() {
8157        left_positions.push(None);
8158        right_positions.push(Some(right_idx));
8159        right_idx += 1;
8160        if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
8161            return None;
8162        }
8163    }
8164    Some((left_positions, right_positions))
8165}
8166
8167/// Core counting-sort/CSR inner-join over two `i64` key slices (see
8168/// [`dense_int64_inner_positions`]). Emits `(left_pos, right_pos)` pairs with
8169/// right positions ascending per left key, left probed ascending — matching the
8170/// hash path's bucket-insertion order. Returns `None` for a span wider than the
8171/// bounded direct-address gate so the caller falls back to hashing.
8172fn dense_i64_inner_positions_slices(
8173    left: &[i64],
8174    right: &[i64],
8175) -> Option<(Vec<usize>, Vec<usize>)> {
8176    if right.is_empty() || left.is_empty() {
8177        return Some((Vec::new(), Vec::new()));
8178    }
8179
8180    let mut min = right[0];
8181    let mut max = right[0];
8182    for &v in right {
8183        if v < min {
8184            min = v;
8185        }
8186        if v > max {
8187            max = v;
8188        }
8189    }
8190    // Bounded-span gate (mirrors the fp-columnar direct-address tally gates):
8191    // the dense table costs O(span) memory, so only take it when the span is
8192    // small in absolute terms AND relative to the build (right) side.
8193    let span = (max as i128) - (min as i128) + 1;
8194    if span > (1i128 << 24) || span > 16 * (right.len() as i128) {
8195        return None;
8196    }
8197    let range = span as usize;
8198
8199    // CSR build over the right side: counts -> exclusive-prefix offsets ->
8200    // positions filled in ascending right-position order.
8201    let mut offsets = vec![0usize; range + 1];
8202    for &v in right {
8203        offsets[(v - min) as usize + 1] += 1;
8204    }
8205    for i in 0..range {
8206        offsets[i + 1] += offsets[i];
8207    }
8208    let mut positions = vec![0usize; right.len()];
8209    let mut cursor = offsets.clone();
8210    for (pos, &v) in right.iter().enumerate() {
8211        let bucket = (v - min) as usize;
8212        positions[cursor[bucket]] = pos;
8213        cursor[bucket] += 1;
8214    }
8215
8216    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
8217    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8218    for (left_pos, &v) in left.iter().enumerate() {
8219        if v < min || v > max {
8220            continue;
8221        }
8222        let bucket = (v - min) as usize;
8223        for &right_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
8224            left_positions.push(left_pos);
8225            right_positions.push(right_pos);
8226        }
8227    }
8228    Some((left_positions, right_positions))
8229}
8230
8231/// Hash inner-join position build for the remaining all-valid Int64 single-key
8232/// shape after ordered/dense witnesses reject. This keeps the generic hash
8233/// path's left-major probe order and right-bucket insertion order, but hashes
8234/// raw `i64` keys instead of materializing `JoinKeyComponent::Present` wrappers.
8235fn hash_int64_inner_positions(
8236    left_key: &Column,
8237    right_key: &Column,
8238) -> Option<(Vec<usize>, Vec<usize>)> {
8239    let left = left_key.as_i64_slice()?;
8240    let right = right_key.as_i64_slice()?;
8241    Some(hash_i64_inner_positions_slices(left, right))
8242}
8243
8244/// LEFT-join positions via a typed `FxHashMap<i64>` build+probe for all-valid
8245/// Int64 keys — the wide/sparse sibling of `dense_int64_left_positions` (whose
8246/// direct-address table bails on a wide key span, dropping the join to the
8247/// generic `JoinKeyComponent` Scalar-materialization path: left merge on a
8248/// wide-i64 key was 0.65x pandas). Build the right key -> ascending-position
8249/// buckets, then emit one output row per (left row, matching right row) in left
8250/// order, or a single (left, None) for an unmatched left row (null-fill).
8251/// Bit-identical to the dense/generic left path: same left iteration order, same
8252/// ascending right positions per key bucket. `None` (falls back) unless BOTH keys
8253/// are all-valid Int64 (a null-bearing key keeps the generic null-matching path).
8254fn hash_int64_left_positions(
8255    left_key: &Column,
8256    right_key: &Column,
8257) -> Option<OptionalJoinPositions> {
8258    let left = left_key.as_i64_slice()?;
8259    let right = right_key.as_i64_slice()?;
8260    if right.is_empty() {
8261        let left_positions = (0..left.len()).map(Some).collect::<Vec<_>>();
8262        let right_positions = vec![None; left.len()];
8263        return Some((left_positions, right_positions));
8264    }
8265    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
8266        right.len(),
8267        Default::default(),
8268    );
8269    for (pos, &key) in right.iter().enumerate() {
8270        right_map.entry(key).or_default().push(pos);
8271    }
8272    let mut left_positions = Vec::<Option<usize>>::with_capacity(left.len());
8273    let mut right_positions = Vec::<Option<usize>>::with_capacity(left.len());
8274    for (left_pos, &key) in left.iter().enumerate() {
8275        if let Some(matches) = right_map.get(&key) {
8276            for &right_pos in matches {
8277                left_positions.push(Some(left_pos));
8278                right_positions.push(Some(right_pos));
8279            }
8280        } else {
8281            left_positions.push(Some(left_pos));
8282            right_positions.push(None);
8283        }
8284    }
8285    Some((left_positions, right_positions))
8286}
8287
8288/// OUTER positions for wide/sparse Int64 keys. Uses a LIGHT `FxHashMap<i64,u32>`
8289/// key -> gid (first-seen) plus CSR position lists per gid — far cheaper than a
8290/// `FxHashMap<i64,(SmallVec,SmallVec)>` (whose 40-byte value dominated the build
8291/// at ~270ms). Emits per key ASCENDING (gids argsorted by key), left×right cross
8292/// product per key, else unmatched-left/right — bit-identical to
8293/// `dense_int64_outer_positions` (its key-min buckets walk keys ascending with
8294/// the same per-bucket order; the CSR scatter preserves ascending row order per
8295/// key, matching the dense per-bucket push order).
8296fn hash_int64_outer_positions(
8297    left_key: &Column,
8298    right_key: &Column,
8299) -> Option<OptionalJoinPositions> {
8300    let left = left_key.as_i64_slice()?;
8301    let right = right_key.as_i64_slice()?;
8302    let mut gid_of: FxHashMap<i64, u32> = FxHashMap::with_capacity_and_hasher(
8303        left.len().saturating_add(right.len()),
8304        Default::default(),
8305    );
8306    let mut gid_keys: Vec<i64> = Vec::new();
8307    let mut left_gid: Vec<u32> = Vec::with_capacity(left.len());
8308    for &key in left {
8309        let g = *gid_of.entry(key).or_insert_with(|| {
8310            let x = gid_keys.len() as u32;
8311            gid_keys.push(key);
8312            x
8313        });
8314        left_gid.push(g);
8315    }
8316    let mut right_gid: Vec<u32> = Vec::with_capacity(right.len());
8317    for &key in right {
8318        let g = *gid_of.entry(key).or_insert_with(|| {
8319            let x = gid_keys.len() as u32;
8320            gid_keys.push(key);
8321            x
8322        });
8323        right_gid.push(g);
8324    }
8325    let ng = gid_keys.len();
8326    // CSR offsets from per-gid counts.
8327    let mut loff = vec![0u32; ng + 1];
8328    for &g in &left_gid {
8329        loff[g as usize + 1] += 1;
8330    }
8331    let mut roff = vec![0u32; ng + 1];
8332    for &g in &right_gid {
8333        roff[g as usize + 1] += 1;
8334    }
8335    for g in 0..ng {
8336        loff[g + 1] += loff[g];
8337        roff[g + 1] += roff[g];
8338    }
8339    let mut lpos = vec![0u32; left.len()];
8340    let mut lw = loff[..ng].to_vec();
8341    for (i, &g) in left_gid.iter().enumerate() {
8342        let g = g as usize;
8343        lpos[lw[g] as usize] = i as u32;
8344        lw[g] += 1;
8345    }
8346    let mut rpos = vec![0u32; right.len()];
8347    let mut rw = roff[..ng].to_vec();
8348    for (i, &g) in right_gid.iter().enumerate() {
8349        let g = g as usize;
8350        rpos[rw[g] as usize] = i as u32;
8351        rw[g] += 1;
8352    }
8353    let mut order: Vec<u32> = (0..ng as u32).collect();
8354    order.sort_unstable_by_key(|&g| gid_keys[g as usize]);
8355    let mut left_positions = Vec::<Option<usize>>::new();
8356    let mut right_positions = Vec::<Option<usize>>::new();
8357    for &g in &order {
8358        let g = g as usize;
8359        let ls = &lpos[loff[g] as usize..loff[g + 1] as usize];
8360        let rs = &rpos[roff[g] as usize..roff[g + 1] as usize];
8361        match (ls.is_empty(), rs.is_empty()) {
8362            (false, false) => {
8363                for &l in ls {
8364                    for &r in rs {
8365                        left_positions.push(Some(l as usize));
8366                        right_positions.push(Some(r as usize));
8367                    }
8368                }
8369            }
8370            (false, true) => {
8371                for &l in ls {
8372                    left_positions.push(Some(l as usize));
8373                    right_positions.push(None);
8374                }
8375            }
8376            (true, false) => {
8377                for &r in rs {
8378                    left_positions.push(None);
8379                    right_positions.push(Some(r as usize));
8380                }
8381            }
8382            (true, true) => {}
8383        }
8384    }
8385    Some((left_positions, right_positions))
8386}
8387
8388/// Hash build+probe over raw UTF-8 byte spans for all-valid contiguous-Utf8
8389/// keys (br-frankenpandas-i388q). Mirrors the generic `JoinKeyComponent` inner
8390/// path exactly — right positions pushed ascending per key bucket, left probed
8391/// in order — but hashes `&[u8]` spans directly instead of materializing each
8392/// key column to `Vec<Scalar>` and cloning every string into a
8393/// `JoinKeyComponent::Present(IndexLabel::Utf8)` wrapper. Returns `None` unless
8394/// BOTH keys are all-valid contiguous Utf8; null-bearing keys keep the generic
8395/// path (which matches null-to-null — a case `as_utf8_contiguous` excludes).
8396fn contiguous_utf8_inner_positions(
8397    left_key: &Column,
8398    right_key: &Column,
8399) -> Option<(Vec<usize>, Vec<usize>)> {
8400    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
8401    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
8402    let left_n = left_offsets.len() - 1;
8403    let right_n = right_offsets.len() - 1;
8404    if left_n == 0 || right_n == 0 {
8405        return Some((Vec::new(), Vec::new()));
8406    }
8407
8408    if let Some(positions) =
8409        sorted_contiguous_utf8_inner_positions(left_bytes, left_offsets, right_bytes, right_offsets)
8410    {
8411        return Some(positions);
8412    }
8413
8414    let mut right_map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
8415        right_n,
8416        Default::default(),
8417    );
8418    for pos in 0..right_n {
8419        let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
8420        right_map.entry(span).or_default().push(pos);
8421    }
8422
8423    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
8424    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8425    for left_pos in 0..left_n {
8426        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8427        if let Some(matches) = right_map.get(span) {
8428            for &right_pos in matches {
8429                left_positions.push(left_pos);
8430                right_positions.push(right_pos);
8431            }
8432        }
8433    }
8434    Some((left_positions, right_positions))
8435}
8436
8437fn collect_contiguous_utf8_position_map<'a>(
8438    bytes: &'a [u8],
8439    offsets: &[usize],
8440) -> FxHashMap<&'a [u8], JoinPositionBucket> {
8441    let n = offsets.len() - 1;
8442    let mut map =
8443        FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(n, Default::default());
8444    for pos in 0..n {
8445        let span = &bytes[offsets[pos]..offsets[pos + 1]];
8446        map.entry(span).or_default().push(pos);
8447    }
8448    map
8449}
8450
8451fn contiguous_utf8_left_positions(
8452    left_key: &Column,
8453    right_key: &Column,
8454) -> Option<OptionalJoinPositions> {
8455    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
8456    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
8457    let left_n = left_offsets.len() - 1;
8458    let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
8459
8460    let mut out_len = 0usize;
8461    for left_pos in 0..left_n {
8462        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8463        out_len += right_map.get(span).map_or(1, JoinPositionBucket::len);
8464    }
8465
8466    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8467    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8468    for left_pos in 0..left_n {
8469        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8470        if let Some(matches) = right_map.get(span) {
8471            for &right_pos in matches {
8472                left_positions.push(Some(left_pos));
8473                right_positions.push(Some(right_pos));
8474            }
8475        } else {
8476            left_positions.push(Some(left_pos));
8477            right_positions.push(None);
8478        }
8479    }
8480    Some((left_positions, right_positions))
8481}
8482
8483fn contiguous_utf8_outer_positions(
8484    left_key: &Column,
8485    right_key: &Column,
8486) -> Option<OptionalJoinPositions> {
8487    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
8488    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
8489    let left_n = left_offsets.len() - 1;
8490    let right_n = right_offsets.len() - 1;
8491
8492    let left_map = collect_contiguous_utf8_position_map(left_bytes, left_offsets);
8493    let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
8494    let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
8495        left_map.len() + right_map.len(),
8496        Default::default(),
8497    );
8498    let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
8499    for pos in 0..left_n {
8500        let span = &left_bytes[left_offsets[pos]..left_offsets[pos + 1]];
8501        if seen.insert(span) {
8502            keys.push(span);
8503        }
8504    }
8505    for pos in 0..right_n {
8506        let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
8507        if seen.insert(span) {
8508            keys.push(span);
8509        }
8510    }
8511    keys.sort_unstable();
8512
8513    let mut out_len = 0usize;
8514    for &key in &keys {
8515        out_len += match (left_map.get(key), right_map.get(key)) {
8516            (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
8517            (Some(lefts), None) => lefts.len(),
8518            (None, Some(rights)) => rights.len(),
8519            (None, None) => 0,
8520        };
8521    }
8522
8523    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8524    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8525    for key in keys {
8526        match (left_map.get(key), right_map.get(key)) {
8527            (Some(lefts), Some(rights)) => {
8528                for &left_pos in lefts {
8529                    for &right_pos in rights {
8530                        left_positions.push(Some(left_pos));
8531                        right_positions.push(Some(right_pos));
8532                    }
8533                }
8534            }
8535            (Some(lefts), None) => {
8536                for &left_pos in lefts {
8537                    left_positions.push(Some(left_pos));
8538                    right_positions.push(None);
8539                }
8540            }
8541            (None, Some(rights)) => {
8542                for &right_pos in rights {
8543                    left_positions.push(None);
8544                    right_positions.push(Some(right_pos));
8545                }
8546            }
8547            (None, None) => {}
8548        }
8549    }
8550    Some((left_positions, right_positions))
8551}
8552
8553fn scalar_utf8_values(column: &Column) -> Option<&[Scalar]> {
8554    if column.dtype() != DType::Utf8 || !column.validity().all() {
8555        return None;
8556    }
8557    let values = column.values();
8558    values
8559        .iter()
8560        .all(|value| matches!(value, Scalar::Utf8(_)))
8561        .then_some(values)
8562}
8563
8564fn scalar_utf8_span(value: &Scalar) -> Option<&[u8]> {
8565    match value {
8566        Scalar::Utf8(value) => Some(value.as_bytes()),
8567        _ => None,
8568    }
8569}
8570
8571fn collect_scalar_utf8_position_map(
8572    values: &[Scalar],
8573) -> Option<FxHashMap<&[u8], JoinPositionBucket>> {
8574    let mut map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
8575        values.len(),
8576        Default::default(),
8577    );
8578    for (pos, value) in values.iter().enumerate() {
8579        map.entry(scalar_utf8_span(value)?).or_default().push(pos);
8580    }
8581    Some(map)
8582}
8583
8584fn scalar_utf8_inner_positions(
8585    left_key: &Column,
8586    right_key: &Column,
8587) -> Option<(Vec<usize>, Vec<usize>)> {
8588    let left = scalar_utf8_values(left_key)?;
8589    let right = scalar_utf8_values(right_key)?;
8590    if left.is_empty() || right.is_empty() {
8591        return Some((Vec::new(), Vec::new()));
8592    }
8593
8594    let right_map = collect_scalar_utf8_position_map(right)?;
8595    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
8596    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8597    for (left_pos, value) in left.iter().enumerate() {
8598        if let Some(matches) = right_map.get(scalar_utf8_span(value)?) {
8599            for &right_pos in matches {
8600                left_positions.push(left_pos);
8601                right_positions.push(right_pos);
8602            }
8603        }
8604    }
8605    Some((left_positions, right_positions))
8606}
8607
8608fn scalar_utf8_left_positions(
8609    left_key: &Column,
8610    right_key: &Column,
8611) -> Option<OptionalJoinPositions> {
8612    let left = scalar_utf8_values(left_key)?;
8613    let right = scalar_utf8_values(right_key)?;
8614    let right_map = collect_scalar_utf8_position_map(right)?;
8615
8616    let mut out_len = 0usize;
8617    for value in left {
8618        out_len += right_map
8619            .get(scalar_utf8_span(value)?)
8620            .map_or(1, JoinPositionBucket::len);
8621    }
8622
8623    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8624    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8625    for (left_pos, value) in left.iter().enumerate() {
8626        if let Some(matches) = right_map.get(scalar_utf8_span(value)?) {
8627            for &right_pos in matches {
8628                left_positions.push(Some(left_pos));
8629                right_positions.push(Some(right_pos));
8630            }
8631        } else {
8632            left_positions.push(Some(left_pos));
8633            right_positions.push(None);
8634        }
8635    }
8636    Some((left_positions, right_positions))
8637}
8638
8639fn scalar_utf8_outer_positions(
8640    left_key: &Column,
8641    right_key: &Column,
8642) -> Option<OptionalJoinPositions> {
8643    let left = scalar_utf8_values(left_key)?;
8644    let right = scalar_utf8_values(right_key)?;
8645    let left_map = collect_scalar_utf8_position_map(left)?;
8646    let right_map = collect_scalar_utf8_position_map(right)?;
8647
8648    let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
8649        left_map.len() + right_map.len(),
8650        Default::default(),
8651    );
8652    let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
8653    for value in left {
8654        let span = scalar_utf8_span(value)?;
8655        if seen.insert(span) {
8656            keys.push(span);
8657        }
8658    }
8659    for value in right {
8660        let span = scalar_utf8_span(value)?;
8661        if seen.insert(span) {
8662            keys.push(span);
8663        }
8664    }
8665    keys.sort_unstable();
8666
8667    let mut out_len = 0usize;
8668    for &key in &keys {
8669        out_len += match (left_map.get(key), right_map.get(key)) {
8670            (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
8671            (Some(lefts), None) => lefts.len(),
8672            (None, Some(rights)) => rights.len(),
8673            (None, None) => 0,
8674        };
8675    }
8676
8677    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8678    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8679    for key in keys {
8680        match (left_map.get(key), right_map.get(key)) {
8681            (Some(lefts), Some(rights)) => {
8682                for &left_pos in lefts {
8683                    for &right_pos in rights {
8684                        left_positions.push(Some(left_pos));
8685                        right_positions.push(Some(right_pos));
8686                    }
8687                }
8688            }
8689            (Some(lefts), None) => {
8690                for &left_pos in lefts {
8691                    left_positions.push(Some(left_pos));
8692                    right_positions.push(None);
8693                }
8694            }
8695            (None, Some(rights)) => {
8696                for &right_pos in rights {
8697                    left_positions.push(None);
8698                    right_positions.push(Some(right_pos));
8699                }
8700            }
8701            (None, None) => {}
8702        }
8703    }
8704    Some((left_positions, right_positions))
8705}
8706
8707fn hash_i64_inner_positions_slices(left: &[i64], right: &[i64]) -> (Vec<usize>, Vec<usize>) {
8708    if right.is_empty() || left.is_empty() {
8709        return (Vec::new(), Vec::new());
8710    }
8711
8712    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
8713        right.len(),
8714        Default::default(),
8715    );
8716    for (pos, &key) in right.iter().enumerate() {
8717        right_map.entry(key).or_default().push(pos);
8718    }
8719
8720    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
8721    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8722    for (left_pos, &key) in left.iter().enumerate() {
8723        if let Some(matches) = right_map.get(&key) {
8724            for &right_pos in matches {
8725                left_positions.push(left_pos);
8726                right_positions.push(right_pos);
8727            }
8728        }
8729    }
8730    (left_positions, right_positions)
8731}
8732
8733/// Hash-free inner-join positions for a MULTI-column key whose every component
8734/// is an all-valid, bounded-range Int64 column. Packs each row's composite key
8735/// into a single `i64` via a mixed-radix code over the per-column spans
8736/// (`packed = Σ_c (val_c - min_c) · stride_c`, `stride_0 = 1`, `stride_c =
8737/// stride_{c-1}·range_{c-1}`), then runs the dense CSR core on the packed keys.
8738///
8739/// The packing is a bijection on the joint key box (mins/ranges computed over
8740/// BOTH sides so left- and right-side codes are comparable), so two composite
8741/// keys collide under packing IFF every component is equal — identical to the
8742/// `CompositeJoinKey` equality the FxHashMap path uses. Pair order is therefore
8743/// byte-for-byte the same as the hash path. Returns `None` (caller falls back to
8744/// the composite-hash path) for any non-Int64 / any-missing component or when
8745/// the packed span exceeds the bounded direct-address gate.
8746/// Typed INNER/LEFT positions for a 2-column all-valid Int64 composite key that's
8747/// too WIDE for `dense_packed_int64_inner_positions` (its packed mixed-radix span
8748/// exceeds the bounded gate on a high-cardinality component), which otherwise
8749/// dropped multi-key merge to the generic `collect_composite_keys` Scalar path
8750/// (2-i64-key merge was 0.65x inner / 0.69x left pandas). Packs each row's
8751/// `(k0, k1)` into a `u128` — a bijection, so key equality is exact — builds the
8752/// right key -> ascending-position map, and probes left in order: one row per
8753/// (left, matching right), or (for Left) a single `(Some, None)` null-fill for an
8754/// unmatched left row. Bit-identical to the generic `CompositeJoinKey` path (same
8755/// left iteration + ascending-right-per-key emit). Returns `None` for non-Inner/
8756/// Left, non-2-key, or any non-all-valid-Int64 component.
8757/// Each string of an all-valid text key column (a contiguous buffer or
8758/// `Scalar::Utf8` cells) in row order; `None` for any other column.
8759fn for_each_utf8_key<'a>(column: &'a Column, mut visit: impl FnMut(&'a [u8])) -> Option<()> {
8760    if let Some((bytes, offsets)) = column.as_utf8_contiguous() {
8761        for bounds in offsets.windows(2) {
8762            visit(&bytes[bounds[0]..bounds[1]]);
8763        }
8764        return Some(());
8765    }
8766    for value in scalar_utf8_values(column)? {
8767        visit(scalar_utf8_span(value)?);
8768    }
8769    Some(())
8770}
8771
8772/// A text key pair of a merge as int64 codes over one dictionary of both
8773/// sides' strings, a string numbered as its first row is met (the left's
8774/// rows first): two rows' strings are equal exactly when their codes are.
8775/// `None` unless both sides are all-valid text.
8776fn utf8_key_pair_codes<'a>(left: &'a Column, right: &'a Column) -> Option<(Column, Column)> {
8777    if left.dtype() != DType::Utf8 || right.dtype() != DType::Utf8 {
8778        return None;
8779    }
8780    let mut codes: FxHashMap<&'a [u8], i64> = FxHashMap::default();
8781    let mut code = |span: &'a [u8]| {
8782        let next = codes.len() as i64;
8783        *codes.entry(span).or_insert(next)
8784    };
8785    let mut left_codes = Vec::with_capacity(left.len());
8786    for_each_utf8_key(left, |span| left_codes.push(code(span)))?;
8787    let mut right_codes = Vec::with_capacity(right.len());
8788    for_each_utf8_key(right, |span| right_codes.push(code(span)))?;
8789    Some((
8790        Column::from_i64_values_owned(left_codes),
8791        Column::from_i64_values_owned(right_codes),
8792    ))
8793}
8794
8795fn typed_wide_two_i64_key_positions(
8796    join_type: JoinType,
8797    left_cols: &[&Column],
8798    right_cols: &[&Column],
8799) -> Option<MergeRowPositions> {
8800    if !matches!(
8801        join_type,
8802        JoinType::Inner | JoinType::Left | JoinType::Outer
8803    ) {
8804        return None;
8805    }
8806    if left_cols.len() != 2 || right_cols.len() != 2 {
8807        return None;
8808    }
8809    let l0 = left_cols[0].as_i64_slice()?;
8810    let l1 = left_cols[1].as_i64_slice()?;
8811    let r0 = right_cols[0].as_i64_slice()?;
8812    let r1 = right_cols[1].as_i64_slice()?;
8813    let pack = |a: i64, b: i64| -> u128 { (u128::from(a as u64) << 64) | u128::from(b as u64) };
8814
8815    if matches!(join_type, JoinType::Outer) {
8816        // OUTER: gid-factorize the u128 composite, CSR the per-gid positions, then
8817        // emit key-ASCENDING by the SEMANTIC (i64, i64) tuple (decoded from the
8818        // packed key — u128 order would mis-sort negatives). The typed branch
8819        // returns positions directly (the generic in-block sort is bypassed), so
8820        // they must arrive pre-sorted, matching sort_merge_rows_by_join_keys.
8821        let mut gid_of: FxHashMap<u128, u32> = FxHashMap::with_capacity_and_hasher(
8822            l0.len().saturating_add(r0.len()),
8823            Default::default(),
8824        );
8825        let mut gid_keys: Vec<u128> = Vec::new();
8826        let mut left_gid: Vec<u32> = Vec::with_capacity(l0.len());
8827        for pos in 0..l0.len() {
8828            let key = pack(l0[pos], l1[pos]);
8829            let g = *gid_of.entry(key).or_insert_with(|| {
8830                let x = gid_keys.len() as u32;
8831                gid_keys.push(key);
8832                x
8833            });
8834            left_gid.push(g);
8835        }
8836        let mut right_gid: Vec<u32> = Vec::with_capacity(r0.len());
8837        for pos in 0..r0.len() {
8838            let key = pack(r0[pos], r1[pos]);
8839            let g = *gid_of.entry(key).or_insert_with(|| {
8840                let x = gid_keys.len() as u32;
8841                gid_keys.push(key);
8842                x
8843            });
8844            right_gid.push(g);
8845        }
8846        let ng = gid_keys.len();
8847        let mut loff = vec![0u32; ng + 1];
8848        for &g in &left_gid {
8849            loff[g as usize + 1] += 1;
8850        }
8851        let mut roff = vec![0u32; ng + 1];
8852        for &g in &right_gid {
8853            roff[g as usize + 1] += 1;
8854        }
8855        for g in 0..ng {
8856            loff[g + 1] += loff[g];
8857            roff[g + 1] += roff[g];
8858        }
8859        let mut lpos = vec![0u32; l0.len()];
8860        let mut lw = loff[..ng].to_vec();
8861        for (i, &g) in left_gid.iter().enumerate() {
8862            let g = g as usize;
8863            lpos[lw[g] as usize] = i as u32;
8864            lw[g] += 1;
8865        }
8866        let mut rpos = vec![0u32; r0.len()];
8867        let mut rw = roff[..ng].to_vec();
8868        for (i, &g) in right_gid.iter().enumerate() {
8869            let g = g as usize;
8870            rpos[rw[g] as usize] = i as u32;
8871            rw[g] += 1;
8872        }
8873        // Argsort gids by the SEMANTIC (i64, i64) key (hi = k0, lo = k1).
8874        let decode = |packed: u128| -> (i64, i64) {
8875            (((packed >> 64) as u64) as i64, (packed as u64) as i64)
8876        };
8877        let mut order: Vec<u32> = (0..ng as u32).collect();
8878        order.sort_unstable_by_key(|&g| decode(gid_keys[g as usize]));
8879        let mut left_positions = Vec::<Option<usize>>::new();
8880        let mut right_positions = Vec::<Option<usize>>::new();
8881        for &g in &order {
8882            let g = g as usize;
8883            let ls = &lpos[loff[g] as usize..loff[g + 1] as usize];
8884            let rs = &rpos[roff[g] as usize..roff[g + 1] as usize];
8885            match (ls.is_empty(), rs.is_empty()) {
8886                (false, false) => {
8887                    for &l in ls {
8888                        for &r in rs {
8889                            left_positions.push(Some(l as usize));
8890                            right_positions.push(Some(r as usize));
8891                        }
8892                    }
8893                }
8894                (false, true) => {
8895                    for &l in ls {
8896                        left_positions.push(Some(l as usize));
8897                        right_positions.push(None);
8898                    }
8899                }
8900                (true, false) => {
8901                    for &r in rs {
8902                        left_positions.push(None);
8903                        right_positions.push(Some(r as usize));
8904                    }
8905                }
8906                (true, true) => {}
8907            }
8908        }
8909        return Some((left_positions, right_positions, None));
8910    }
8911
8912    // Inner / Left: right key -> ascending-position map, probe left in order.
8913    let mut right_map = FxHashMap::<u128, JoinPositionBucket>::with_capacity_and_hasher(
8914        r0.len(),
8915        Default::default(),
8916    );
8917    for pos in 0..r0.len() {
8918        right_map
8919            .entry(pack(r0[pos], r1[pos]))
8920            .or_default()
8921            .push(pos);
8922    }
8923    let is_left = matches!(join_type, JoinType::Left);
8924    let mut left_positions = Vec::<Option<usize>>::new();
8925    let mut right_positions = Vec::<Option<usize>>::new();
8926    for left_pos in 0..l0.len() {
8927        let key = pack(l0[left_pos], l1[left_pos]);
8928        if let Some(matches) = right_map.get(&key) {
8929            for &right_pos in matches {
8930                left_positions.push(Some(left_pos));
8931                right_positions.push(Some(right_pos));
8932            }
8933        } else if is_left {
8934            left_positions.push(Some(left_pos));
8935            right_positions.push(None);
8936        }
8937    }
8938    Some((left_positions, right_positions, None))
8939}
8940
8941/// General K-key (K >= 3) sibling of `typed_wide_two_i64_key_positions` for wide
8942/// Int64 key columns that overflow `dense_packed_int64_inner_positions` and exceed
8943/// the 2-key u128 packer. Factorizes each key column over left ∪ right into dense
8944/// gids (first-seen), then packs each row's per-column gids into a single u128
8945/// (column 0 most-significant) — a bijection whenever the summed gid bit-widths
8946/// fit 127 bits (else `None` → generic Scalar composite path). With the composite
8947/// as one integer, this reuses the exact same inner/left/outer emit as the 2-key
8948/// path. OUTER argsorts groups by the SEMANTIC original (i64,..,i64) tuple captured
8949/// at gid creation (packed-gid order is first-seen, not sorted). Bit-identical to
8950/// the `CompositeJoinKey` path (same left-order probe + ascending-right-per-key emit
8951/// for inner/left; same key-ascending group emit for outer). Returns `None` for
8952/// non-Inner/Left/Outer, K < 3, unequal K, any non-all-valid-Int64 component, or a
8953/// composite too wide for u128.
8954fn typed_wide_multi_i64_key_positions(
8955    join_type: JoinType,
8956    left_cols: &[&Column],
8957    right_cols: &[&Column],
8958) -> Option<MergeRowPositions> {
8959    if !matches!(
8960        join_type,
8961        JoinType::Inner | JoinType::Left | JoinType::Outer
8962    ) {
8963        return None;
8964    }
8965    let k = left_cols.len();
8966    if k < 3 || right_cols.len() != k {
8967        return None;
8968    }
8969    let mut ls: Vec<&[i64]> = Vec::with_capacity(k);
8970    let mut rs: Vec<&[i64]> = Vec::with_capacity(k);
8971    for c in 0..k {
8972        ls.push(left_cols[c].as_i64_slice()?);
8973        rs.push(right_cols[c].as_i64_slice()?);
8974    }
8975    let nl = ls[0].len();
8976    let nr = rs[0].len();
8977    if ls.iter().any(|s| s.len() != nl) || rs.iter().any(|s| s.len() != nr) {
8978        return None;
8979    }
8980
8981    // Factorize each key column over left ∪ right into dense first-seen gids.
8982    let mut lgid: Vec<Vec<u32>> = Vec::with_capacity(k);
8983    let mut rgid: Vec<Vec<u32>> = Vec::with_capacity(k);
8984    let mut cards: Vec<u64> = Vec::with_capacity(k);
8985    for c in 0..k {
8986        let mut m: FxHashMap<i64, u32> =
8987            FxHashMap::with_capacity_and_hasher(nl + nr, Default::default());
8988        let mut next: u32 = 0;
8989        let mut lg = Vec::with_capacity(nl);
8990        for &v in ls[c] {
8991            let g = *m.entry(v).or_insert_with(|| {
8992                let x = next;
8993                next += 1;
8994                x
8995            });
8996            lg.push(g);
8997        }
8998        let mut rg = Vec::with_capacity(nr);
8999        for &v in rs[c] {
9000            let g = *m.entry(v).or_insert_with(|| {
9001                let x = next;
9002                next += 1;
9003                x
9004            });
9005            rg.push(g);
9006        }
9007        cards.push(next as u64);
9008        lgid.push(lg);
9009        rgid.push(rg);
9010    }
9011
9012    // Per-column bit widths; bail if the packed composite exceeds u128.
9013    let mut bits: Vec<u32> = Vec::with_capacity(k);
9014    let mut total: u32 = 0;
9015    for &card in &cards {
9016        let b = if card <= 1 {
9017            0
9018        } else {
9019            64 - (card - 1).leading_zeros()
9020        };
9021        bits.push(b);
9022        total += b;
9023    }
9024    if total > 127 {
9025        return None;
9026    }
9027
9028    let pack = |gids: &[Vec<u32>], row: usize| -> u128 {
9029        let mut p: u128 = 0;
9030        for c in 0..k {
9031            p = (p << bits[c]) | u128::from(gids[c][row]);
9032        }
9033        p
9034    };
9035
9036    if matches!(join_type, JoinType::Outer) {
9037        let mut gid_of: FxHashMap<u128, u32> =
9038            FxHashMap::with_capacity_and_hasher(nl.saturating_add(nr), Default::default());
9039        // Semantic original tuple per composite gid (for the key-ascending sort).
9040        let mut gid_tuple: Vec<Vec<i64>> = Vec::new();
9041        let mut left_g: Vec<u32> = Vec::with_capacity(nl);
9042        for (row, _) in ls[0].iter().enumerate().take(nl) {
9043            let key = pack(&lgid, row);
9044            let g = *gid_of.entry(key).or_insert_with(|| {
9045                let x = gid_tuple.len() as u32;
9046                gid_tuple.push((0..k).map(|c| ls[c][row]).collect());
9047                x
9048            });
9049            left_g.push(g);
9050        }
9051        let mut right_g: Vec<u32> = Vec::with_capacity(nr);
9052        for (row, _) in rs[0].iter().enumerate().take(nr) {
9053            let key = pack(&rgid, row);
9054            let g = *gid_of.entry(key).or_insert_with(|| {
9055                let x = gid_tuple.len() as u32;
9056                gid_tuple.push((0..k).map(|c| rs[c][row]).collect());
9057                x
9058            });
9059            right_g.push(g);
9060        }
9061        let ng = gid_tuple.len();
9062        let mut loff = vec![0u32; ng + 1];
9063        for &g in &left_g {
9064            loff[g as usize + 1] += 1;
9065        }
9066        let mut roff = vec![0u32; ng + 1];
9067        for &g in &right_g {
9068            roff[g as usize + 1] += 1;
9069        }
9070        for g in 0..ng {
9071            loff[g + 1] += loff[g];
9072            roff[g + 1] += roff[g];
9073        }
9074        let mut lpos = vec![0u32; nl];
9075        let mut lw = loff[..ng].to_vec();
9076        for (i, &g) in left_g.iter().enumerate() {
9077            let g = g as usize;
9078            lpos[lw[g] as usize] = i as u32;
9079            lw[g] += 1;
9080        }
9081        let mut rpos = vec![0u32; nr];
9082        let mut rw = roff[..ng].to_vec();
9083        for (i, &g) in right_g.iter().enumerate() {
9084            let g = g as usize;
9085            rpos[rw[g] as usize] = i as u32;
9086            rw[g] += 1;
9087        }
9088        let mut order: Vec<u32> = (0..ng as u32).collect();
9089        order.sort_unstable_by(|&a, &b| gid_tuple[a as usize].cmp(&gid_tuple[b as usize]));
9090        let mut left_positions = Vec::<Option<usize>>::new();
9091        let mut right_positions = Vec::<Option<usize>>::new();
9092        for &g in &order {
9093            let g = g as usize;
9094            let lsl = &lpos[loff[g] as usize..loff[g + 1] as usize];
9095            let rsl = &rpos[roff[g] as usize..roff[g + 1] as usize];
9096            match (lsl.is_empty(), rsl.is_empty()) {
9097                (false, false) => {
9098                    for &l in lsl {
9099                        for &r in rsl {
9100                            left_positions.push(Some(l as usize));
9101                            right_positions.push(Some(r as usize));
9102                        }
9103                    }
9104                }
9105                (false, true) => {
9106                    for &l in lsl {
9107                        left_positions.push(Some(l as usize));
9108                        right_positions.push(None);
9109                    }
9110                }
9111                (true, false) => {
9112                    for &r in rsl {
9113                        left_positions.push(None);
9114                        right_positions.push(Some(r as usize));
9115                    }
9116                }
9117                (true, true) => {}
9118            }
9119        }
9120        return Some((left_positions, right_positions, None));
9121    }
9122
9123    // Inner / Left: right composite -> ascending-position map, probe left in order.
9124    let mut right_map =
9125        FxHashMap::<u128, JoinPositionBucket>::with_capacity_and_hasher(nr, Default::default());
9126    for pos in 0..nr {
9127        right_map.entry(pack(&rgid, pos)).or_default().push(pos);
9128    }
9129    let is_left = matches!(join_type, JoinType::Left);
9130    let mut left_positions = Vec::<Option<usize>>::new();
9131    let mut right_positions = Vec::<Option<usize>>::new();
9132    for left_pos in 0..nl {
9133        let key = pack(&lgid, left_pos);
9134        if let Some(matches) = right_map.get(&key) {
9135            for &right_pos in matches {
9136                left_positions.push(Some(left_pos));
9137                right_positions.push(Some(right_pos));
9138            }
9139        } else if is_left {
9140            left_positions.push(Some(left_pos));
9141            right_positions.push(None);
9142        }
9143    }
9144    Some((left_positions, right_positions, None))
9145}
9146
9147/// K-key (K >= 3) INNER/LEFT positions for all-valid BOUNDED-range Int64 keys
9148/// whose joint mixed-radix span fits an `i64` — even when that span exceeds the
9149/// direct-address gate of `dense_packed_int64_inner_positions` (2^24). Packs each
9150/// row's composite into one `i64` (`Σ_c (val_c - min_c)·stride_c`, `stride_0 = 1`,
9151/// `stride_c = stride_{c-1}·range_{c-1}`; a bijection on the joint key box, so
9152/// composite equality IFF every component equal) and runs the SINGLE-key i64 hash
9153/// merge on it — skipping the K per-column factorization `FxHashMap`s that
9154/// `typed_wide_multi_i64_key_positions` builds (the khash-floor cost that left
9155/// 3-key merge at 0.43-0.57x pandas). Bit-identical to that path / the generic
9156/// Scalar composite path: same left iteration order, same ascending right position
9157/// per composite bucket, same unmatched-left null-fill. Returns `None` (caller
9158/// falls back to the factorize path) unless every key is an all-valid Int64 slice
9159/// and the joint span fits `i64` — Outer bails (its key-ascending emit is handled
9160/// by the factorize path's semantic gid sort).
9161fn bounded_composite_multi_i64_key_positions(
9162    join_type: JoinType,
9163    left_cols: &[&Column],
9164    right_cols: &[&Column],
9165) -> Option<MergeRowPositions> {
9166    if !matches!(join_type, JoinType::Inner | JoinType::Left) {
9167        return None;
9168    }
9169    let k = left_cols.len();
9170    if k < 3 || right_cols.len() != k {
9171        return None;
9172    }
9173    let mut ls: Vec<&[i64]> = Vec::with_capacity(k);
9174    let mut rs: Vec<&[i64]> = Vec::with_capacity(k);
9175    for c in 0..k {
9176        ls.push(left_cols[c].as_i64_slice()?);
9177        rs.push(right_cols[c].as_i64_slice()?);
9178    }
9179    let nl = ls[0].len();
9180    let nr = rs[0].len();
9181    if ls.iter().any(|s| s.len() != nl) || rs.iter().any(|s| s.len() != nr) {
9182        return None;
9183    }
9184    if nl == 0 || nr == 0 {
9185        // Let the generic/factorize path handle degenerate empties (its
9186        // left-null-fill / empty-output shape is already validated there).
9187        return None;
9188    }
9189
9190    // Per-column min + span over left ∪ right; bail if the joint mixed-radix
9191    // product overflows i64 (a truly wide key keeps the factorize path).
9192    let mut mins = vec![0i64; k];
9193    let mut ranges = vec![0u128; k];
9194    for c in 0..k {
9195        let mut mn = i64::MAX;
9196        let mut mx = i64::MIN;
9197        for &v in ls[c] {
9198            if v < mn {
9199                mn = v;
9200            }
9201            if v > mx {
9202                mx = v;
9203            }
9204        }
9205        for &v in rs[c] {
9206            if v < mn {
9207                mn = v;
9208            }
9209            if v > mx {
9210                mx = v;
9211            }
9212        }
9213        mins[c] = mn;
9214        ranges[c] = (mx as i128 - mn as i128 + 1) as u128;
9215    }
9216    // strides[0] = 1, strides[c] = strides[c-1] * ranges[c-1]; bail on overflow.
9217    let mut strides = vec![1i64; k];
9218    let mut acc: u128 = 1;
9219    for c in 0..k {
9220        strides[c] = acc as i64;
9221        acc = acc.checked_mul(ranges[c])?;
9222        if acc > i64::MAX as u128 {
9223            return None;
9224        }
9225    }
9226    let comp = |s: &[&[i64]], row: usize| -> i64 {
9227        let mut p: i64 = 0;
9228        for c in 0..k {
9229            // (val - min) < range_c and range product fits i64 ⇒ no overflow.
9230            p += (s[c][row] - mins[c]) * strides[c];
9231        }
9232        p
9233    };
9234    let lcomp: Vec<i64> = (0..nl).map(|r| comp(&ls, r)).collect();
9235    let rcomp: Vec<i64> = (0..nr).map(|r| comp(&rs, r)).collect();
9236
9237    if matches!(join_type, JoinType::Inner) {
9238        let (lp, rp) = hash_i64_inner_positions_slices(&lcomp, &rcomp);
9239        return Some((
9240            lp.into_iter().map(Some).collect(),
9241            rp.into_iter().map(Some).collect(),
9242            None,
9243        ));
9244    }
9245
9246    // LEFT: right composite -> ascending-position buckets, probe left in order
9247    // (mirror of hash_int64_left_positions on the composite slices).
9248    let mut right_map =
9249        FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(nr, Default::default());
9250    for (pos, &key) in rcomp.iter().enumerate() {
9251        right_map.entry(key).or_default().push(pos);
9252    }
9253    let mut left_positions = Vec::<Option<usize>>::with_capacity(nl);
9254    let mut right_positions = Vec::<Option<usize>>::with_capacity(nl);
9255    for (left_pos, &key) in lcomp.iter().enumerate() {
9256        if let Some(matches) = right_map.get(&key) {
9257            for &right_pos in matches {
9258                left_positions.push(Some(left_pos));
9259                right_positions.push(Some(right_pos));
9260            }
9261        } else {
9262            left_positions.push(Some(left_pos));
9263            right_positions.push(None);
9264        }
9265    }
9266    Some((left_positions, right_positions, None))
9267}
9268
9269fn dense_packed_int64_inner_positions(
9270    left_cols: &[&Column],
9271    right_cols: &[&Column],
9272) -> Option<(Vec<usize>, Vec<usize>)> {
9273    let k = left_cols.len();
9274    if k == 0 || k != right_cols.len() {
9275        return None;
9276    }
9277
9278    let left_slices: Vec<&[i64]> = left_cols
9279        .iter()
9280        .map(|c| c.as_i64_slice())
9281        .collect::<Option<Vec<_>>>()?;
9282    let right_slices: Vec<&[i64]> = right_cols
9283        .iter()
9284        .map(|c| c.as_i64_slice())
9285        .collect::<Option<Vec<_>>>()?;
9286
9287    let n_left = left_slices[0].len();
9288    let n_right = right_slices[0].len();
9289    if n_left == 0 || n_right == 0 {
9290        return Some((Vec::new(), Vec::new()));
9291    }
9292
9293    // Per-column min and span over BOTH sides; product = joint packed span.
9294    let mut mins = vec![0i64; k];
9295    let mut strides = vec![1i128; k];
9296    let mut total: i128 = 1;
9297    for c in 0..k {
9298        let mut mn = right_slices[c][0];
9299        let mut mx = right_slices[c][0];
9300        for &v in left_slices[c].iter().chain(right_slices[c].iter()) {
9301            if v < mn {
9302                mn = v;
9303            }
9304            if v > mx {
9305                mx = v;
9306            }
9307        }
9308        mins[c] = mn;
9309        let range = (mx as i128) - (mn as i128) + 1;
9310        strides[c] = total;
9311        total = total.checked_mul(range)?;
9312        // Gate the packed span the same way the single-key core does, up front
9313        // (the product can overflow the bounded table for wide multi-keys).
9314        if total > (1i128 << 24) {
9315            return None;
9316        }
9317    }
9318    if total > 16 * ((n_left + n_right) as i128) {
9319        return None;
9320    }
9321
9322    let pack = |slices: &[&[i64]], n: usize| -> Vec<i64> {
9323        (0..n)
9324            .map(|row| {
9325                let mut acc: i128 = 0;
9326                for c in 0..k {
9327                    acc += ((slices[c][row] as i128) - (mins[c] as i128)) * strides[c];
9328                }
9329                acc as i64
9330            })
9331            .collect()
9332    };
9333    let packed_left = pack(&left_slices, n_left);
9334    let packed_right = pack(&right_slices, n_right);
9335
9336    dense_i64_inner_positions_slices(&packed_left, &packed_right)
9337}
9338
9339fn merge_single_key_inner_unsorted(
9340    left: &fp_frame::DataFrame,
9341    right: &fp_frame::DataFrame,
9342    left_on: &[&str],
9343    right_on: &[&str],
9344    left_key_columns: &[&Column],
9345    right_key_columns: &[&Column],
9346    suffixes: &ResolvedMergeSuffixes,
9347) -> Result<MergedDataFrame, JoinError> {
9348    debug_assert_eq!(left_key_columns.len(), 1);
9349    debug_assert_eq!(right_key_columns.len(), 1);
9350
9351    if left_on[0] == right_on[0]
9352        && ordered_identity_int64_keys_match(left_key_columns[0], right_key_columns[0])
9353    {
9354        return build_single_key_ordered_identity_inner_merge_output(
9355            left, right, left_on, right_on, suffixes,
9356        );
9357    }
9358    if let Some(merged) = build_single_key_affine_i64_inner_merge_output(
9359        left,
9360        right,
9361        left_on,
9362        right_on,
9363        left_key_columns[0],
9364        right_key_columns[0],
9365        suffixes,
9366    )? {
9367        return Ok(merged);
9368    }
9369    if let Some((left_positions, right_positions)) =
9370        ordered_unique_int64_inner_positions(left_key_columns[0], right_key_columns[0])
9371    {
9372        return build_single_key_inner_merge_output(
9373            left,
9374            right,
9375            left_on,
9376            right_on,
9377            &left_positions,
9378            &right_positions,
9379            suffixes,
9380        );
9381    }
9382
9383    if let Some(merged) = build_single_key_dense_i64_inner_merge_output(
9384        left,
9385        right,
9386        left_on,
9387        right_on,
9388        left_key_columns[0],
9389        right_key_columns[0],
9390        FusedInt64MergeOptions {
9391            suffixes,
9392            require_all_left_keys_matched: false,
9393        },
9394    )? {
9395        return Ok(merged);
9396    }
9397
9398    // Datetime64/Timedelta64 keys are physically i64 nanoseconds. For the
9399    // all-valid, same-dtype case, plan positions directly over that backing
9400    // instead of materializing one Scalar + JoinKeyComponent per row. Nullable
9401    // temporal keys deliberately keep the generic path below, where NaT joins
9402    // use the existing Missing-key semantics.
9403    if let Some((left_positions, right_positions)) =
9404        temporal_i64_inner_positions(left_key_columns[0], right_key_columns[0])
9405    {
9406        return build_single_key_inner_merge_output(
9407            left,
9408            right,
9409            left_on,
9410            right_on,
9411            &left_positions,
9412            &right_positions,
9413            suffixes,
9414        );
9415    }
9416
9417    // Hash-free dense direct-address build+probe for bounded all-valid Int64
9418    // keys (the common low-cardinality join-key shape). Bit-identical pairs.
9419    if let Some((left_positions, right_positions)) =
9420        dense_int64_inner_positions(left_key_columns[0], right_key_columns[0])
9421    {
9422        return build_single_key_inner_merge_output(
9423            left,
9424            right,
9425            left_on,
9426            right_on,
9427            &left_positions,
9428            &right_positions,
9429            suffixes,
9430        );
9431    }
9432    if let Some((left_positions, right_positions)) =
9433        hash_int64_inner_positions(left_key_columns[0], right_key_columns[0])
9434    {
9435        return build_single_key_inner_merge_output(
9436            left,
9437            right,
9438            left_on,
9439            right_on,
9440            &left_positions,
9441            &right_positions,
9442            suffixes,
9443        );
9444    }
9445
9446    if let Some(position_plan) =
9447        ordered_unique_utf8_inner_position_plan(left_key_columns[0], right_key_columns[0])
9448    {
9449        return match position_plan {
9450            InnerPositionPlan::Gather {
9451                left_positions,
9452                right_positions,
9453            } => build_single_key_inner_merge_output(
9454                left,
9455                right,
9456                left_on,
9457                right_on,
9458                &left_positions,
9459                &right_positions,
9460                suffixes,
9461            ),
9462            InnerPositionPlan::ContiguousRanges {
9463                left_start,
9464                right_start,
9465                len,
9466            } => build_single_key_inner_merge_output_with_selections(
9467                left,
9468                right,
9469                left_on,
9470                right_on,
9471                PositionSelection::ContiguousRange {
9472                    start: left_start,
9473                    len,
9474                },
9475                PositionSelection::ContiguousRange {
9476                    start: right_start,
9477                    len,
9478                },
9479                suffixes,
9480            ),
9481        };
9482    }
9483
9484    // Byte-span build+probe for all-valid contiguous-Utf8 string keys
9485    // (br-frankenpandas-i388q): skips the per-row String clone + Scalar
9486    // materialization of the JoinKeyComponent path. Same pairing -> same output.
9487    if let Some((left_positions, right_positions)) =
9488        contiguous_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
9489    {
9490        return build_single_key_inner_merge_output(
9491            left,
9492            right,
9493            left_on,
9494            right_on,
9495            &left_positions,
9496            &right_positions,
9497            suffixes,
9498        );
9499    }
9500    if let Some((left_positions, right_positions)) =
9501        scalar_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
9502    {
9503        return build_single_key_inner_merge_output(
9504            left,
9505            right,
9506            left_on,
9507            right_on,
9508            &left_positions,
9509            &right_positions,
9510            suffixes,
9511        );
9512    }
9513
9514    let left_keys = collect_single_join_keys(left_key_columns[0]);
9515    let right_keys = collect_single_join_keys(right_key_columns[0]);
9516    let mut right_map =
9517        FxHashMap::<&JoinKeyComponent, JoinPositionBucket>::with_capacity_and_hasher(
9518            right_keys.len(),
9519            Default::default(),
9520        );
9521    for (pos, key) in right_keys.iter().enumerate() {
9522        right_map.entry(key).or_default().push(pos);
9523    }
9524
9525    let mut left_positions = Vec::<usize>::with_capacity(left_keys.len().min(right_keys.len()));
9526    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
9527    for (left_pos, key) in left_keys.iter().enumerate() {
9528        if let Some(matches) = right_map.get(key) {
9529            for &right_pos in matches {
9530                left_positions.push(left_pos);
9531                right_positions.push(right_pos);
9532            }
9533        }
9534    }
9535
9536    build_single_key_inner_merge_output(
9537        left,
9538        right,
9539        left_on,
9540        right_on,
9541        &left_positions,
9542        &right_positions,
9543        suffixes,
9544    )
9545}
9546
9547/// Merge two DataFrames on one or more key columns.
9548///
9549/// Matches `pd.merge(left, right, left_on=left_keys, right_on=right_keys, how=join_type)`.
9550/// - Key columns are used for matching rows (hash join).
9551/// - Non-key columns are carried through and reindexed.
9552/// - Column name conflicts use configurable suffixes (default `_x`/`_y`).
9553/// - The output index is auto-generated (0..n RangeIndex-style).
9554pub fn merge_dataframes_on_with(
9555    left: &fp_frame::DataFrame,
9556    right: &fp_frame::DataFrame,
9557    left_on: &[&str],
9558    right_on: &[&str],
9559    join_type: JoinType,
9560) -> Result<MergedDataFrame, JoinError> {
9561    merge_dataframes_on_with_options(
9562        left,
9563        right,
9564        left_on,
9565        right_on,
9566        join_type,
9567        MergeExecutionOptions::default(),
9568    )
9569}
9570
9571/// Merge two DataFrames on one or more key columns with execution options.
9572pub fn merge_dataframes_on_with_options(
9573    left: &fp_frame::DataFrame,
9574    right: &fp_frame::DataFrame,
9575    left_on: &[&str],
9576    right_on: &[&str],
9577    join_type: JoinType,
9578    options: MergeExecutionOptions,
9579) -> Result<MergedDataFrame, JoinError> {
9580    merge_dataframes_on_with_fill(left, right, left_on, right_on, join_type, options, false)
9581}
9582
9583fn merge_dataframes_on_with_fill(
9584    left: &fp_frame::DataFrame,
9585    right: &fp_frame::DataFrame,
9586    left_on: &[&str],
9587    right_on: &[&str],
9588    join_type: JoinType,
9589    options: MergeExecutionOptions,
9590    forward_fill: bool,
9591) -> Result<MergedDataFrame, JoinError> {
9592    let suffixes = resolve_merge_suffixes(options.suffixes.clone());
9593    let indicator_name = resolve_merge_indicator_name(options.indicator_name.as_deref())?;
9594    // A column key a side repeats (['a', 'a']; not a join key) rides through
9595    // the merge under stand-in keys and comes back under its own name, each
9596    // column its own - by name every copy read the first column (i17d4). A
9597    // name the other side also has takes each side's suffix, as pandas'
9598    // (a_x, a_x beside a_y).
9599    let left_stand_in = stand_in_repeated_keys(left, left_on, 'l')?;
9600    let right_stand_in = stand_in_repeated_keys(right, right_on, 'r')?;
9601    let merged = merge_dataframes_on_with_options_storage(
9602        left_stand_in.as_ref().map_or(left, |(frame, _)| frame),
9603        right_stand_in.as_ref().map_or(right, |(frame, _)| frame),
9604        left_on,
9605        right_on,
9606        join_type,
9607        options,
9608        forward_fill,
9609    )?;
9610    let merged = keeping_source_widths(
9611        merged,
9612        left,
9613        right,
9614        left_on,
9615        right_on,
9616        join_type,
9617        indicator_name.as_deref(),
9618    )?;
9619    let suffixed = |name: &str, suffix: Option<&String>| {
9620        format!("{name}{}", suffix.map_or("", String::as_str))
9621    };
9622    let mut restored: FxHashMap<String, String> = FxHashMap::default();
9623    for (stand_in, own_suffix, other, other_on, other_suffix) in [
9624        (
9625            &left_stand_in,
9626            suffixes.left.as_ref(),
9627            right,
9628            right_on,
9629            suffixes.right.as_ref(),
9630        ),
9631        (
9632            &right_stand_in,
9633            suffixes.right.as_ref(),
9634            left,
9635            left_on,
9636            suffixes.left.as_ref(),
9637        ),
9638    ] {
9639        for (key, name) in stand_in.iter().flat_map(|(_, names)| names) {
9640            if other.column_occurrences(name) == 0 || other_on.contains(&name.as_str()) {
9641                restored.insert(key.clone(), name.clone());
9642                continue;
9643            }
9644            restored.insert(key.clone(), suffixed(name, own_suffix));
9645            // The other side's own (not stood-in) copy keeps its name in the
9646            // merge: it takes that side's suffix.
9647            restored
9648                .entry(name.clone())
9649                .or_insert_with(|| suffixed(name, other_suffix));
9650        }
9651    }
9652    let merged = if restored.is_empty() {
9653        merged
9654    } else {
9655        let restore = |name: &str| {
9656            restored
9657                .get(name)
9658                .map_or_else(|| name.to_owned(), Clone::clone)
9659        };
9660        MergedDataFrame {
9661            index: merged.index,
9662            columns: ColumnStore::from_pairs(
9663                merged
9664                    .columns
9665                    .iter_positional()
9666                    .map(|(name, column)| (restore(name), column.clone())),
9667            ),
9668            column_order: merged
9669                .column_order
9670                .iter()
9671                .map(|name| restore(name))
9672                .collect(),
9673        }
9674    };
9675    Ok(merged)
9676}
9677
9678/// A frame keyed by stand-ins and each stand-in with the name it stands for.
9679type StoodIn = (fp_frame::DataFrame, Vec<(String, String)>);
9680
9681/// `frame` with each column under a repeated key (not one of `on`) keyed by
9682/// a stand-in, and the stand-ins with their names; None when no key repeats
9683/// so.
9684fn stand_in_repeated_keys(
9685    frame: &fp_frame::DataFrame,
9686    on: &[&str],
9687    side: char,
9688) -> Result<Option<StoodIn>, JoinError> {
9689    let names = frame.column_names();
9690    let repeated = |name: &str| frame.column_occurrences(name) > 1 && !on.contains(&name);
9691    if !names.iter().any(|name| repeated(name)) {
9692        return Ok(None);
9693    }
9694    let mut stand_ins = Vec::new();
9695    let keys = names
9696        .iter()
9697        .enumerate()
9698        .map(|(position, name)| {
9699            if repeated(name) {
9700                let key = format!("\u{1}i17d4-{side}{position}");
9701                stand_ins.push((key.clone(), (*name).clone()));
9702                key
9703            } else {
9704                (*name).clone()
9705            }
9706        })
9707        .collect();
9708    Ok(Some((frame.with_column_keys(keys)?, stand_ins)))
9709}
9710
9711/// Restore widths by the output projection: all left positions followed by
9712/// right positions, excluding shared keys. Display names can repeat or
9713/// collide across suffixes and therefore cannot identify a source column.
9714/// Shared numeric keys retain the width of the rows supplying their values.
9715/// Only mixed-width right/outer keys need a complete-tuple origin scan.
9716fn keeping_source_widths(
9717    mut merged: MergedDataFrame,
9718    left: &fp_frame::DataFrame,
9719    right: &fp_frame::DataFrame,
9720    left_on: &[&str],
9721    right_on: &[&str],
9722    join_type: JoinType,
9723    indicator_name: Option<&str>,
9724) -> Result<MergedDataFrame, JoinError> {
9725    let shared = |name: &str| {
9726        !matches!(join_type, JoinType::Cross)
9727            && left_on
9728                .iter()
9729                .zip(right_on)
9730                .any(|(l, r)| l == r && *l == name)
9731    };
9732    let mut sources = Vec::with_capacity(left.num_columns() + right.num_columns());
9733    let fail = || {
9734        JoinError::Frame(FrameError::CompatibilityRejected(
9735            "merge output projection does not match source positions".to_owned(),
9736        ))
9737    };
9738    for position in 0..left.num_columns() {
9739        let name = left.column_name_at(position).ok_or_else(fail)?;
9740        let source = left.column_at(position).ok_or_else(fail)?;
9741        let partner = if shared(&name) {
9742            Some(right.column(&name).ok_or_else(fail)?)
9743        } else {
9744            None
9745        };
9746        sources.push((source, partner));
9747    }
9748    for position in 0..right.num_columns() {
9749        let name = right.column_name_at(position).ok_or_else(fail)?;
9750        if !shared(&name) {
9751            sources.push((right.column_at(position).ok_or_else(fail)?, None));
9752        }
9753    }
9754    if merged.columns.len() != sources.len() + usize::from(indicator_name.is_some()) {
9755        return Err(fail());
9756    }
9757    if let Some(indicator) = indicator_name
9758        && merged.columns.name_at(sources.len()) != Some(indicator)
9759    {
9760        return Err(fail());
9761    }
9762    let needs_origins = matches!(join_type, JoinType::Right | JoinType::Outer)
9763        && sources.iter().any(|(source, partner)| {
9764            partner.is_some_and(|partner| {
9765                source.width() != partner.width()
9766                    && fp_types::NumpyNumeric::of(&source.dtype(), source.width()).is_some()
9767                    && fp_types::NumpyNumeric::of(&partner.dtype(), partner.width()).is_some()
9768            })
9769        });
9770    let origins = if needs_origins {
9771        let left_keys = collect_composite_keys(&collect_join_key_columns(left, left_on, "left")?);
9772        let left_keys: FxHashSet<_> = left_keys.into_iter().collect();
9773        let right_keys =
9774            collect_composite_keys(&collect_join_key_columns(right, right_on, "right")?);
9775        let mut has_match = false;
9776        let mut has_right_only = false;
9777        for key in right_keys {
9778            if left_keys.contains(&key) {
9779                has_match = true;
9780            } else {
9781                has_right_only = true;
9782            }
9783        }
9784        let has_left = if matches!(join_type, JoinType::Outer) {
9785            !left.is_empty()
9786        } else {
9787            has_match
9788        };
9789        Some((has_left, has_right_only))
9790    } else {
9791        None
9792    };
9793    for (position, (source, partner)) in sources.into_iter().enumerate() {
9794        let column = merged.columns.column_at_mut(position).ok_or_else(fail)?;
9795        if let Some(partner) = partner {
9796            let numeric = fp_types::NumpyNumeric::of(&source.dtype(), source.width()).zip(
9797                fp_types::NumpyNumeric::of(&partner.dtype(), partner.width()),
9798            );
9799            let Some((left_numeric, right_numeric)) = numeric else {
9800                continue;
9801            };
9802            // Every inner/left shared key comes from a present left row.
9803            // Its width must not depend on an unmatched right payload row.
9804            if matches!(join_type, JoinType::Inner | JoinType::Left) {
9805                *column = column.clone().keeping_dtype_of(source);
9806                continue;
9807            }
9808            if let Some((has_left, has_right_only)) = origins {
9809                // No right-only tuples includes empty output: pandas keeps
9810                // the left dtype. Right-only output keeps the right dtype.
9811                if !has_right_only {
9812                    *column = column.clone().keeping_dtype_of(source);
9813                    continue;
9814                }
9815                if !has_left {
9816                    *column = column.clone().keeping_dtype_of(partner);
9817                    continue;
9818                }
9819            } else if column.width().is_some() {
9820                continue;
9821            }
9822            // Both origins require the common width, including clearing a
9823            // stale narrow tag on an already typed builder's output.
9824            if let Some(width) = left_numeric.result_type(right_numeric).width() {
9825                let nullable = column.dtype().is_nullable();
9826                if width.fits_storage(&column.dtype())
9827                    && (width.is_float() || nullable || !column.has_nulls())
9828                    && column.width() != Some(width)
9829                {
9830                    *column = column.cast_to_width(width, nullable)?;
9831                }
9832            } else if column.width().is_some() {
9833                *column = column.astype(column.dtype())?;
9834            }
9835        } else if source.width().is_some() {
9836            *column = column.clone().narrowed_like(source);
9837        }
9838    }
9839    Ok(merged)
9840}
9841
9842fn merge_dataframes_on_with_options_storage(
9843    left: &fp_frame::DataFrame,
9844    right: &fp_frame::DataFrame,
9845    left_on: &[&str],
9846    right_on: &[&str],
9847    join_type: JoinType,
9848    options: MergeExecutionOptions,
9849    forward_fill: bool,
9850) -> Result<MergedDataFrame, JoinError> {
9851    let MergeExecutionOptions {
9852        indicator_name,
9853        validate_mode,
9854        suffixes,
9855        sort,
9856    } = options;
9857    let indicator_name = resolve_merge_indicator_name(indicator_name.as_deref())?;
9858    let suffixes = resolve_merge_suffixes(suffixes);
9859
9860    if matches!(join_type, JoinType::Cross) {
9861        if let Some(validate_mode) = validate_mode
9862            && !matches!(validate_mode, MergeValidateMode::ManyToMany)
9863        {
9864            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9865                format!(
9866                    "merge validate='{}' is not supported for cross join",
9867                    validate_mode.as_str()
9868                ),
9869            )));
9870        }
9871        validate_merge_suffixes_intra_frame(
9872            &left.column_names(),
9873            &right.column_names(),
9874            &HashSet::new(),
9875            &suffixes,
9876        )?;
9877        return merge_dataframes_cross(left, right, indicator_name.as_deref(), &suffixes);
9878    }
9879
9880    if left_on.is_empty() || right_on.is_empty() {
9881        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9882            "merge requires at least one key column".to_owned(),
9883        )));
9884    }
9885    if left_on.len() != right_on.len() {
9886        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9887            "merge requires left_on and right_on key lists with equal length".to_owned(),
9888        )));
9889    }
9890
9891    let mut seen_left_keys = HashSet::new();
9892    for key_name in left_on {
9893        if !seen_left_keys.insert(*key_name) {
9894            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9895                format!("merge left key column '{key_name}' is duplicated"),
9896            )));
9897        }
9898    }
9899    let mut seen_right_keys = HashSet::new();
9900    for key_name in right_on {
9901        if !seen_right_keys.insert(*key_name) {
9902            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9903                format!("merge right key column '{key_name}' is duplicated"),
9904            )));
9905        }
9906    }
9907
9908    let left_key_columns = collect_join_key_columns(left, left_on, "left")?;
9909    let right_key_columns = collect_join_key_columns(right, right_on, "right")?;
9910
9911    let shared_key_names = if left_on == right_on {
9912        left_on.iter().copied().collect::<HashSet<&str>>()
9913    } else {
9914        HashSet::new()
9915    };
9916    validate_merge_suffixes_intra_frame(
9917        &left.column_names(),
9918        &right.column_names(),
9919        &shared_key_names,
9920        &suffixes,
9921    )?;
9922
9923    // br-frankenpandas-uza04: settle `validate=` HERE, off the raw typed key
9924    // buffer, instead of letting it drag the whole merge onto the generic
9925    // Scalar path.
9926    //
9927    // `validate_merge_cardinality` is called in exactly ONE place — the generic
9928    // `collect_composite_keys` branch at the bottom of this function — so
9929    // `validate_mode_allows_fast_positions` had to return false for every
9930    // enforcing mode purely to *route execution there*. The cost of asking for
9931    // a cardinality guarantee was therefore the entire fast-path family:
9932    // `dense_packed_int64_inner_positions`, `typed_wide_two_i64_key_positions`,
9933    // `bounded_composite_multi_i64_key_positions`,
9934    // `typed_wide_multi_i64_key_positions` and the single-key inner/left
9935    // shortcuts, all disabled, plus a `Vec<CompositeJoinKey>` built by reading
9936    // `column.values()[row]` — 32 B/elem of `Scalar` spine and a `SmallVec` per
9937    // row — on both sides.
9938    //
9939    // A single all-valid Int64 key needs none of that: duplicate detection is
9940    // an `FxHashSet<i64>` over `as_i64_slice`. When that check applies AND
9941    // passes, the merge is free to take exactly the path it would have taken
9942    // with no `validate=` at all, because a passing validation adds nothing to
9943    // the output — it only decides whether the merge is allowed to happen.
9944    //
9945    // Semantics preserved exactly: same messages, same left-before-right
9946    // precedence, same modes checked on the same sides. Moving the check
9947    // earlier is unobservable because nothing between this point and the old
9948    // call site can fail — every fast-path helper in between returns `Option`,
9949    // never `Err`.
9950    let typed_validation_settled = match validate_mode {
9951        Some(mode) => {
9952            typed_validate_merge_cardinality(mode, &left_key_columns, &right_key_columns)?
9953        }
9954        None => false,
9955    };
9956    let validate_allows_fast_positions =
9957        validate_mode_allows_fast_positions(validate_mode) || typed_validation_settled;
9958
9959    if matches!(join_type, JoinType::Inner)
9960        && left_on.len() == 1
9961        && right_on.len() == 1
9962        && !sort
9963        && indicator_name.is_none()
9964        && validate_allows_fast_positions
9965    {
9966        return merge_single_key_inner_unsorted(
9967            left,
9968            right,
9969            left_on,
9970            right_on,
9971            &left_key_columns,
9972            &right_key_columns,
9973            &suffixes,
9974        );
9975    }
9976    if matches!(join_type, JoinType::Left)
9977        && left_on.len() == 1
9978        && right_on.len() == 1
9979        && !sort
9980        && indicator_name.is_none()
9981        && validate_allows_fast_positions
9982        && let Some(right_positions) =
9983            ordered_unique_int64_left_match_positions(left_key_columns[0], right_key_columns[0])
9984    {
9985        return build_single_key_ordered_unique_left_merge_output(
9986            left,
9987            right,
9988            left_on,
9989            right_on,
9990            &right_positions,
9991            &suffixes,
9992        );
9993    }
9994    if matches!(join_type, JoinType::Left)
9995        && left_on.len() == 1
9996        && right_on.len() == 1
9997        && !sort
9998        && indicator_name.is_none()
9999        && validate_allows_fast_positions
10000        && let Some((left_positions, right_positions)) =
10001            temporal_i64_left_positions(left_key_columns[0], right_key_columns[0])
10002    {
10003        return build_single_key_dense_left_merge_output(
10004            left,
10005            right,
10006            left_on,
10007            right_on,
10008            &left_positions,
10009            &right_positions,
10010            &suffixes,
10011        );
10012    }
10013    if matches!(join_type, JoinType::Left)
10014        && left_on.len() == 1
10015        && right_on.len() == 1
10016        && !sort
10017        && indicator_name.is_none()
10018        && validate_allows_fast_positions
10019        && let Some(merged) = build_single_key_dense_cycle_i64_left_merge_output(
10020            left,
10021            right,
10022            left_on,
10023            right_on,
10024            left_key_columns[0],
10025            right_key_columns[0],
10026            &suffixes,
10027        )?
10028    {
10029        return Ok(merged);
10030    }
10031    if matches!(join_type, JoinType::Left)
10032        && left_on.len() == 1
10033        && right_on.len() == 1
10034        && !sort
10035        && indicator_name.is_none()
10036        && validate_allows_fast_positions
10037        && let Some(merged) = build_single_key_dense_i64_inner_merge_output(
10038            left,
10039            right,
10040            left_on,
10041            right_on,
10042            left_key_columns[0],
10043            right_key_columns[0],
10044            FusedInt64MergeOptions {
10045                suffixes: &suffixes,
10046                require_all_left_keys_matched: true,
10047            },
10048        )?
10049    {
10050        return Ok(merged);
10051    }
10052    if matches!(join_type, JoinType::Left)
10053        && left_on.len() == 1
10054        && right_on.len() == 1
10055        && !sort
10056        && indicator_name.is_none()
10057        && validate_allows_fast_positions
10058        && let Some(merged) = build_single_key_dense_i64_left_merge_output(
10059            left,
10060            right,
10061            left_on,
10062            right_on,
10063            left_key_columns[0],
10064            right_key_columns[0],
10065            &suffixes,
10066        )?
10067    {
10068        return Ok(merged);
10069    }
10070    if matches!(join_type, JoinType::Left)
10071        && left_on.len() == 1
10072        && right_on.len() == 1
10073        && !sort
10074        && indicator_name.is_none()
10075        && validate_allows_fast_positions
10076        && let Some((left_positions, right_positions)) =
10077            dense_int64_left_positions(left_key_columns[0], right_key_columns[0])
10078    {
10079        return build_single_key_dense_left_merge_output(
10080            left,
10081            right,
10082            left_on,
10083            right_on,
10084            &left_positions,
10085            &right_positions,
10086            &suffixes,
10087        );
10088    }
10089    if matches!(join_type, JoinType::Left)
10090        && left_on.len() == 1
10091        && right_on.len() == 1
10092        && !sort
10093        && indicator_name.is_none()
10094        && validate_allows_fast_positions
10095        && let Some((left_positions, right_positions)) =
10096            hash_int64_left_positions(left_key_columns[0], right_key_columns[0])
10097    {
10098        return build_single_key_dense_left_merge_output(
10099            left,
10100            right,
10101            left_on,
10102            right_on,
10103            &left_positions,
10104            &right_positions,
10105            &suffixes,
10106        );
10107    }
10108    if matches!(join_type, JoinType::Left)
10109        && left_on.len() == 1
10110        && right_on.len() == 1
10111        && !sort
10112        && indicator_name.is_none()
10113        && validate_allows_fast_positions
10114        && let Some((left_positions, right_positions)) =
10115            contiguous_utf8_left_positions(left_key_columns[0], right_key_columns[0])
10116    {
10117        return build_single_key_dense_left_merge_output(
10118            left,
10119            right,
10120            left_on,
10121            right_on,
10122            &left_positions,
10123            &right_positions,
10124            &suffixes,
10125        );
10126    }
10127    if matches!(join_type, JoinType::Left)
10128        && left_on.len() == 1
10129        && right_on.len() == 1
10130        && !sort
10131        && indicator_name.is_none()
10132        && validate_allows_fast_positions
10133        && let Some((left_positions, right_positions)) =
10134            scalar_utf8_left_positions(left_key_columns[0], right_key_columns[0])
10135    {
10136        return build_single_key_dense_left_merge_output(
10137            left,
10138            right,
10139            left_on,
10140            right_on,
10141            &left_positions,
10142            &right_positions,
10143            &suffixes,
10144        );
10145    }
10146    if matches!(join_type, JoinType::Right)
10147        && left_on.len() == 1
10148        && right_on.len() == 1
10149        && !sort
10150        && indicator_name.is_none()
10151        && validate_allows_fast_positions
10152        && let Some(left_positions) =
10153            ordered_unique_int64_right_match_positions(left_key_columns[0], right_key_columns[0])
10154    {
10155        return build_single_key_ordered_unique_right_merge_output(
10156            left,
10157            right,
10158            left_on,
10159            right_on,
10160            &left_positions,
10161            &suffixes,
10162        );
10163    }
10164    if matches!(join_type, JoinType::Right)
10165        && left_on.len() == 1
10166        && right_on.len() == 1
10167        && !sort
10168        && indicator_name.is_none()
10169        && validate_allows_fast_positions
10170        && let Some(left_positions) = ordered_unique_temporal_i64_right_match_positions(
10171            left_key_columns[0],
10172            right_key_columns[0],
10173        )
10174    {
10175        return build_single_key_ordered_unique_right_merge_output(
10176            left,
10177            right,
10178            left_on,
10179            right_on,
10180            &left_positions,
10181            &suffixes,
10182        );
10183    }
10184    if matches!(join_type, JoinType::Right)
10185        && left_on.len() == 1
10186        && right_on.len() == 1
10187        && !sort
10188        && indicator_name.is_none()
10189        && validate_allows_fast_positions
10190        && let Some(merged) = build_single_key_dense_i64_right_all_matched_merge_output(
10191            left,
10192            right,
10193            left_on,
10194            right_on,
10195            left_key_columns[0],
10196            right_key_columns[0],
10197            &suffixes,
10198        )?
10199    {
10200        return Ok(merged);
10201    }
10202    if matches!(join_type, JoinType::Right)
10203        && left_on.len() == 1
10204        && right_on.len() == 1
10205        && !sort
10206        && indicator_name.is_none()
10207        && validate_allows_fast_positions
10208        && let Some(merged) = build_single_key_dense_i64_right_merge_output(
10209            left,
10210            right,
10211            left_on,
10212            right_on,
10213            left_key_columns[0],
10214            right_key_columns[0],
10215            &suffixes,
10216        )?
10217    {
10218        return Ok(merged);
10219    }
10220    if matches!(join_type, JoinType::Right)
10221        && left_on.len() == 1
10222        && right_on.len() == 1
10223        && !sort
10224        && indicator_name.is_none()
10225        && validate_allows_fast_positions
10226        && let Some((left_positions, right_positions)) =
10227            dense_int64_right_positions(left_key_columns[0], right_key_columns[0])
10228    {
10229        return build_single_key_dense_right_merge_output(
10230            left,
10231            right,
10232            left_on,
10233            right_on,
10234            &left_positions,
10235            &right_positions,
10236            &suffixes,
10237        );
10238    }
10239    if matches!(join_type, JoinType::Outer)
10240        && left_on.len() == 1
10241        && right_on.len() == 1
10242        && !sort
10243        && indicator_name.is_none()
10244        && validate_allows_fast_positions
10245        && let Some((left_positions, right_positions)) =
10246            ordered_unique_temporal_i64_outer_positions(left_key_columns[0], right_key_columns[0])
10247    {
10248        return build_single_key_ordered_unique_outer_merge_output(
10249            left,
10250            right,
10251            left_on,
10252            right_on,
10253            &left_positions,
10254            &right_positions,
10255            &suffixes,
10256        );
10257    }
10258    if matches!(join_type, JoinType::Outer)
10259        && left_on.len() == 1
10260        && right_on.len() == 1
10261        && !sort
10262        && indicator_name.is_none()
10263        && validate_allows_fast_positions
10264        && let Some((left_positions, right_positions)) =
10265            ordered_unique_int64_outer_positions(left_key_columns[0], right_key_columns[0])
10266    {
10267        return build_single_key_ordered_unique_outer_merge_output(
10268            left,
10269            right,
10270            left_on,
10271            right_on,
10272            &left_positions,
10273            &right_positions,
10274            &suffixes,
10275        );
10276    }
10277    if matches!(join_type, JoinType::Outer)
10278        && left_on.len() == 1
10279        && right_on.len() == 1
10280        && !sort
10281        && indicator_name.is_none()
10282        && validate_allows_fast_positions
10283        && let Some(merged) = build_single_key_dense_i64_outer_all_matched_merge_output(
10284            left,
10285            right,
10286            left_on,
10287            right_on,
10288            left_key_columns[0],
10289            right_key_columns[0],
10290            &suffixes,
10291        )?
10292    {
10293        return Ok(merged);
10294    }
10295    if matches!(join_type, JoinType::Outer)
10296        && left_on.len() == 1
10297        && right_on.len() == 1
10298        && !sort
10299        && indicator_name.is_none()
10300        && validate_allows_fast_positions
10301        && let Some(merged) = build_single_key_dense_i64_outer_merge_output(
10302            left,
10303            right,
10304            left_on,
10305            right_on,
10306            left_key_columns[0],
10307            right_key_columns[0],
10308            &suffixes,
10309        )?
10310    {
10311        return Ok(merged);
10312    }
10313    if matches!(join_type, JoinType::Outer)
10314        && left_on.len() == 1
10315        && right_on.len() == 1
10316        && !sort
10317        && indicator_name.is_none()
10318        && validate_allows_fast_positions
10319        && let Some((left_positions, right_positions)) =
10320            dense_int64_outer_positions(left_key_columns[0], right_key_columns[0])
10321    {
10322        return build_single_key_ordered_unique_outer_merge_output(
10323            left,
10324            right,
10325            left_on,
10326            right_on,
10327            &left_positions,
10328            &right_positions,
10329            &suffixes,
10330        );
10331    }
10332    if matches!(join_type, JoinType::Outer)
10333        && left_on.len() == 1
10334        && right_on.len() == 1
10335        && !sort
10336        && indicator_name.is_none()
10337        && validate_allows_fast_positions
10338        && let Some((left_positions, right_positions)) =
10339            hash_int64_outer_positions(left_key_columns[0], right_key_columns[0])
10340    {
10341        return build_single_key_ordered_unique_outer_merge_output(
10342            left,
10343            right,
10344            left_on,
10345            right_on,
10346            &left_positions,
10347            &right_positions,
10348            &suffixes,
10349        );
10350    }
10351    if matches!(join_type, JoinType::Outer)
10352        && left_on.len() == 1
10353        && right_on.len() == 1
10354        && !sort
10355        && indicator_name.is_none()
10356        && validate_allows_fast_positions
10357        && let Some(merged) = build_single_key_fixed_decimal_utf8_outer_all_matched_merge_output(
10358            left,
10359            right,
10360            left_on,
10361            right_on,
10362            left_key_columns[0],
10363            right_key_columns[0],
10364            &suffixes,
10365        )?
10366    {
10367        return Ok(merged);
10368    }
10369    if matches!(join_type, JoinType::Outer)
10370        && left_on.len() == 1
10371        && right_on.len() == 1
10372        && !sort
10373        && indicator_name.is_none()
10374        && validate_allows_fast_positions
10375        && let Some((left_positions, right_positions)) =
10376            contiguous_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
10377    {
10378        return build_single_key_ordered_unique_outer_merge_output(
10379            left,
10380            right,
10381            left_on,
10382            right_on,
10383            &left_positions,
10384            &right_positions,
10385            &suffixes,
10386        );
10387    }
10388    if matches!(join_type, JoinType::Outer)
10389        && left_on.len() == 1
10390        && right_on.len() == 1
10391        && !sort
10392        && indicator_name.is_none()
10393        && validate_allows_fast_positions
10394        && let Some((left_positions, right_positions)) =
10395            scalar_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
10396    {
10397        return build_single_key_ordered_unique_outer_merge_output(
10398            left,
10399            right,
10400            left_on,
10401            right_on,
10402            &left_positions,
10403            &right_positions,
10404            &suffixes,
10405        );
10406    }
10407
10408    let needs_key_order = sort || matches!(join_type, JoinType::Outer);
10409
10410    // A text key of a multi-key INNER / LEFT merge whose other keys are
10411    // int64 joins as int64 codes over one dictionary of both sides' strings
10412    // (see [`utf8_key_pair_codes`]), so the typed int-key paths below take
10413    // it: their pairs follow equality and row order alone, never the keys'
10414    // order, which codes do not keep (an outer join's or sort's do). A (str,
10415    // int) key built a SmallVec of cloned labels a row and hashed it (merge
10416    // on ['g', 'z'] of 200k rows 22.5 ms, pandas 19.0;
10417    // br-frankenpandas-j4657). The key columns stay the output's.
10418    let coded_keys: Vec<Option<(Column, Column)>> = if left_key_columns.len() >= 2
10419        && matches!(join_type, JoinType::Inner | JoinType::Left)
10420        && !sort
10421        && indicator_name.is_none()
10422        && validate_allows_fast_positions
10423        && left_key_columns
10424            .iter()
10425            .any(|column| column.dtype() == DType::Utf8)
10426        && left_key_columns
10427            .iter()
10428            .zip(&right_key_columns)
10429            .all(|(left, right)| {
10430                (left.dtype() == DType::Utf8 && right.dtype() == DType::Utf8)
10431                    || (left.as_i64_slice().is_some() && right.as_i64_slice().is_some())
10432            }) {
10433        left_key_columns
10434            .iter()
10435            .zip(&right_key_columns)
10436            .map(|(left, right)| utf8_key_pair_codes(left, right))
10437            .collect()
10438    } else {
10439        Vec::new()
10440    };
10441    // Each key's column to match on: its codes, else itself.
10442    let match_left: Vec<&Column> = left_key_columns
10443        .iter()
10444        .enumerate()
10445        .map(|(key, &column)| {
10446            coded_keys
10447                .get(key)
10448                .and_then(Option::as_ref)
10449                .map_or(column, |(codes, _)| codes)
10450        })
10451        .collect();
10452    let match_right: Vec<&Column> = right_key_columns
10453        .iter()
10454        .enumerate()
10455        .map(|(key, &column)| {
10456            coded_keys
10457                .get(key)
10458                .and_then(Option::as_ref)
10459                .map_or(column, |(_, codes)| codes)
10460        })
10461        .collect();
10462
10463    // Hash-free fast path: a plain inner join on all-valid bounded-Int64 key
10464    // column(s) packs the composite key into one i64 and runs the dense CSR
10465    // core, skipping CompositeJoinKey materialization + FxHashMap build/probe.
10466    // Gated to inner joins with no sort/indicator/enforcing validate, where the
10467    // emitted (left,right) pairs are byte-for-byte identical to the hash path.
10468    let packed_inner = if matches!(join_type, JoinType::Inner)
10469        && !sort
10470        && validate_allows_fast_positions
10471        && indicator_name.is_none()
10472    {
10473        dense_packed_int64_inner_positions(&match_left, &match_right)
10474    } else {
10475        None
10476    };
10477
10478    // Typed wide 2-i64-key INNER/LEFT positions (bypasses the Scalar composite
10479    // path when a component is too wide for the packed dense gate). Same fast-path
10480    // gates as packed_inner (no sort/indicator, validate allows fast positions).
10481    let typed_two_key = if !sort
10482        && indicator_name.is_none()
10483        && validate_allows_fast_positions
10484        && packed_inner.is_none()
10485    {
10486        typed_wide_two_i64_key_positions(join_type, &match_left, &match_right)
10487    } else {
10488        None
10489    };
10490
10491    // Typed K-key (K >= 3) BOUNDED-Int64 INNER/LEFT positions: pack the composite
10492    // into one i64 + single-key i64 hash merge, skipping the K per-column
10493    // factorization maps the factorize path below builds (3-key merge was
10494    // 0.43-0.57x pandas — the khash floor of those maps). Same fast-path gates.
10495    let composite_multi_key = if !sort
10496        && indicator_name.is_none()
10497        && validate_allows_fast_positions
10498        && packed_inner.is_none()
10499        && typed_two_key.is_none()
10500    {
10501        bounded_composite_multi_i64_key_positions(join_type, &match_left, &match_right)
10502    } else {
10503        None
10504    };
10505
10506    // Typed general K-key (K >= 3) wide-Int64 positions: factorize-to-gid + u128
10507    // pack, bypassing the Scalar collect_composite_keys path. Same fast-path gates.
10508    let typed_multi_key = if !sort
10509        && indicator_name.is_none()
10510        && validate_allows_fast_positions
10511        && packed_inner.is_none()
10512        && typed_two_key.is_none()
10513        && composite_multi_key.is_none()
10514    {
10515        typed_wide_multi_i64_key_positions(join_type, &match_left, &match_right)
10516    } else {
10517        None
10518    };
10519
10520    let (left_positions, right_positions, _out_row_keys): MergeRowPositions =
10521        if let Some((lp, rp)) = packed_inner {
10522            (
10523                lp.into_iter().map(Some).collect(),
10524                rp.into_iter().map(Some).collect(),
10525                None,
10526            )
10527        } else if let Some(typed) = typed_two_key {
10528            typed
10529        } else if let Some(typed) = composite_multi_key {
10530            typed
10531        } else if let Some(typed) = typed_multi_key {
10532            typed
10533        } else {
10534            // Convert key columns to hashable composite keys.
10535            let left_keys = collect_composite_keys(&left_key_columns);
10536            let right_keys = collect_composite_keys(&right_key_columns);
10537            // Skip when the typed checker above already enforced this mode
10538            // (br-frankenpandas-uza04) — re-running it here would be a second
10539            // full pass over both key sides for an answer already known. A
10540            // shape the typed checker declined still lands here and is checked
10541            // exactly as before.
10542            if let Some(validate_mode) = validate_mode
10543                && !typed_validation_settled
10544            {
10545                validate_merge_cardinality(validate_mode, &left_keys, &right_keys)?;
10546            }
10547
10548            // Build only the probe maps required by the selected join direction.
10549            let right_map = if matches!(
10550                join_type,
10551                JoinType::Inner | JoinType::Left | JoinType::Outer | JoinType::Right
10552            ) {
10553                let mut m =
10554                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
10555                        right_keys.len(),
10556                        Default::default(),
10557                    );
10558                for (pos, key) in right_keys.iter().enumerate() {
10559                    m.entry(key).or_default().push(pos);
10560                }
10561                Some(m)
10562            } else {
10563                None
10564            };
10565
10566            // Right no longer needs a left_map: its branch below probes the small
10567            // right_map with a single left pass (O(right) build, not O(left)).
10568            let left_map = if matches!(join_type, JoinType::Outer) {
10569                let mut m =
10570                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
10571                        left_keys.len(),
10572                        Default::default(),
10573                    );
10574                for (pos, key) in left_keys.iter().enumerate() {
10575                    m.entry(key).or_default().push(pos);
10576                }
10577                Some(m)
10578            } else {
10579                None
10580            };
10581
10582            // Compute row position mappings.
10583            let row_capacity = match join_type {
10584                JoinType::Inner => left_keys.len().min(right_keys.len()),
10585                JoinType::Left => left_keys.len(),
10586                JoinType::Right => right_keys.len(),
10587                JoinType::Outer => left_keys.len().saturating_add(right_keys.len()),
10588                JoinType::Cross => left_keys.len().saturating_mul(right_keys.len()),
10589            };
10590            let mut left_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
10591            let mut right_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
10592            // No longer materialized: the post-position sort reads each row's key by
10593            // reference from left_keys/right_keys via its position, so the per-row
10594            // push_merge_row_key calls below no-op (no String-owning key clones).
10595            let mut out_row_keys: Option<Vec<CompositeJoinKey>> = None;
10596
10597            match join_type {
10598                JoinType::Inner | JoinType::Left | JoinType::Outer => {
10599                    let right_map = right_map
10600                        .as_ref()
10601                        .expect("right_map required for Inner, Left, and Outer joins");
10602                    for (left_pos, key) in left_keys.iter().enumerate() {
10603                        if let Some(matches) = right_map.get(key) {
10604                            for &right_pos in matches {
10605                                push_merge_row_key(&mut out_row_keys, key);
10606                                left_positions.push(Some(left_pos));
10607                                right_positions.push(Some(right_pos));
10608                            }
10609                            continue;
10610                        }
10611
10612                        if matches!(join_type, JoinType::Left | JoinType::Outer) {
10613                            push_merge_row_key(&mut out_row_keys, key);
10614                            left_positions.push(Some(left_pos));
10615                            right_positions.push(None);
10616                        }
10617                    }
10618
10619                    if matches!(join_type, JoinType::Outer) {
10620                        let left_map = left_map.as_ref().expect("left_map required for Outer join");
10621                        for (right_pos, key) in right_keys.iter().enumerate() {
10622                            if !left_map.contains_key(key) {
10623                                push_merge_row_key(&mut out_row_keys, key);
10624                                left_positions.push(None);
10625                                right_positions.push(Some(right_pos));
10626                            }
10627                        }
10628                    }
10629                }
10630                JoinType::Right => {
10631                    // Probe the SMALL right_map with a single left pass instead of
10632                    // building a left_map over every left row (the prior path —
10633                    // O(left) hash build; for a 1M⋈10k merge that was ~2.4x slower
10634                    // than the symmetric Left join). Bucket each matching left
10635                    // position under its right row; `left_by_right[r]` collects in
10636                    // left-iteration order, and we then emit right rows in order —
10637                    // byte-for-byte identical (left,right) pairs to the left_map
10638                    // path (right-row order outer, left-position order inner),
10639                    // including duplicate right keys and unmatched right rows.
10640                    let right_map = right_map
10641                        .as_ref()
10642                        .expect("right_map required for Right join");
10643                    let mut left_by_right: Vec<Vec<usize>> = vec![Vec::new(); right_keys.len()];
10644                    for (left_pos, key) in left_keys.iter().enumerate() {
10645                        if let Some(right_rows) = right_map.get(key) {
10646                            for &right_pos in right_rows {
10647                                left_by_right[right_pos].push(left_pos);
10648                            }
10649                        }
10650                    }
10651                    for (right_pos, key) in right_keys.iter().enumerate() {
10652                        let lefts = &left_by_right[right_pos];
10653                        if lefts.is_empty() {
10654                            push_merge_row_key(&mut out_row_keys, key);
10655                            left_positions.push(None);
10656                            right_positions.push(Some(right_pos));
10657                        } else {
10658                            for &left_pos in lefts {
10659                                push_merge_row_key(&mut out_row_keys, key);
10660                                left_positions.push(Some(left_pos));
10661                                right_positions.push(Some(right_pos));
10662                            }
10663                        }
10664                    }
10665                }
10666                JoinType::Cross => {
10667                    return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10668                        "cross join must be handled by merge_dataframes_cross".to_owned(),
10669                    )));
10670                }
10671            }
10672
10673            // Sort the output rows by join key in-place while left_keys/right_keys
10674            // are in scope (read by reference per row — no out_row_keys clone).
10675            if needs_key_order {
10676                sort_merge_rows_by_join_keys(
10677                    &left_keys,
10678                    &right_keys,
10679                    &left_key_columns,
10680                    &right_key_columns,
10681                    &mut left_positions,
10682                    &mut right_positions,
10683                );
10684            }
10685            (left_positions, right_positions, out_row_keys)
10686        };
10687
10688    let all_positions_present = matches!(join_type, JoinType::Inner)
10689        || (matches!(
10690            join_type,
10691            JoinType::Left | JoinType::Right | JoinType::Outer
10692        ) && left_positions.iter().all(Option::is_some)
10693            && right_positions.iter().all(Option::is_some));
10694    let all_present_take_positions = all_positions_present.then(|| {
10695        let mut left = left_positions
10696            .iter()
10697            .map(|position| position.expect("all-present join emits left positions for every row"))
10698            .collect::<Vec<_>>();
10699        let mut right = right_positions
10700            .iter()
10701            .map(|position| position.expect("all-present join emits right positions for every row"))
10702            .collect::<Vec<_>>();
10703        if matches!(join_type, JoinType::Inner) && !sort {
10704            permute_inner_merge_equal_left_len_positions(&left_key_columns, &mut left, &mut right);
10705        }
10706        (left, right)
10707    });
10708    let all_present_left_positions = all_present_take_positions
10709        .as_ref()
10710        .map(|(positions, _)| positions.as_slice());
10711    let all_present_right_positions = all_present_take_positions
10712        .as_ref()
10713        .map(|(_, positions)| positions.as_slice());
10714
10715    // Ordered merges carry the last matched SOURCE ROW forward. Filling
10716    // values would replace genuine nulls in that row and could combine cells
10717    // from different source rows. Shared join keys still use the unfilled
10718    // indexers so right-only keys retain their own values.
10719    let carry_rows = |positions: &[Option<usize>]| {
10720        let mut last = None;
10721        positions
10722            .iter()
10723            .map(|position| {
10724                if position.is_some() {
10725                    last = *position;
10726                }
10727                last
10728            })
10729            .collect::<Vec<_>>()
10730    };
10731    let filled_left = forward_fill.then(|| carry_rows(&left_positions));
10732    let filled_right = forward_fill.then(|| carry_rows(&right_positions));
10733    let left_data_positions = filled_left.as_deref().unwrap_or(&left_positions);
10734    let right_data_positions = filled_right.as_deref().unwrap_or(&right_positions);
10735
10736    // Build output columns by reindexing.
10737    let n = left_positions.len();
10738    // Lazy unit-range output index (see build_single_key_dense_i64 site).
10739    let index = Index::new_known_unique_int64_unit_range(0, n);
10740    let mut columns = ColumnStore::new();
10741    let mut column_order: Vec<String> = Vec::new();
10742
10743    // Collect column names to handle conflicts.
10744    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
10745    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
10746    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
10747    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
10748
10749    // Track positional pairs where left_on[i] and right_on[i] share the same key name.
10750    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
10751    for (idx, (left_key_name, right_key_name)) in left_on.iter().zip(right_on.iter()).enumerate() {
10752        if left_key_name == right_key_name {
10753            shared_name_positions.insert(*left_key_name, (idx, idx));
10754        }
10755    }
10756    let shared_key_names = shared_name_positions
10757        .keys()
10758        .copied()
10759        .collect::<HashSet<&str>>();
10760    let overlapping_names =
10761        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
10762    ensure_merge_suffixes_for_overlaps(&overlapping_names, &suffixes)?;
10763
10764    // Add left columns (including left key columns) in the left frame's own
10765    // column order (pandas preserves it; the BTreeMap would re-sort) — br-691lh.
10766    for name in left.column_names() {
10767        let col = left
10768            .columns()
10769            .get(name)
10770            .expect("left column listed in column_names must exist");
10771        if left_key_name_set.contains(name.as_str()) {
10772            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
10773                // Shared key name: for rows emitted from right-only keys, source key values from
10774                // the right frame instead of leaving them null.
10775                let left_key_col = left_key_columns[*left_key_idx];
10776                let key_column = if let Some(positions) = all_present_left_positions {
10777                    take_positions_typed(left_key_col, positions)
10778                } else {
10779                    let right_key_col = right_key_columns[*right_key_idx];
10780                    coalesce_utf8_contiguous_key_column(
10781                        left_key_col,
10782                        right_key_col,
10783                        &left_positions,
10784                        &right_positions,
10785                    )
10786                    .map(Ok)
10787                    .unwrap_or_else(|| {
10788                        let values = left_positions
10789                            .iter()
10790                            .zip(right_positions.iter())
10791                            .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
10792                                (Some(pos), _) => left_key_col.values()[*pos].clone(),
10793                                (None, Some(pos)) => right_key_col.values()[*pos].clone(),
10794                                (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
10795                            })
10796                            .collect::<Vec<_>>();
10797                        Column::from_values(values)
10798                    })?
10799                };
10800                insert_merged_output_column(
10801                    &mut columns,
10802                    &mut column_order,
10803                    name.clone(),
10804                    key_column,
10805                )?;
10806            } else {
10807                let key_column = if let Some(positions) = all_present_left_positions {
10808                    take_positions_typed(col, positions)
10809                } else {
10810                    reindex_join_column_with_invented_gap(col, left_data_positions)?
10811                };
10812                let out_name = if right_col_names.contains(name) {
10813                    apply_merge_suffix(name, suffixes.left.as_deref())
10814                } else {
10815                    name.clone()
10816                };
10817                insert_merged_output_column(&mut columns, &mut column_order, out_name, key_column)?;
10818            }
10819            continue;
10820        }
10821        let reindexed = if let Some(positions) = all_present_left_positions {
10822            take_positions_typed(col, positions)
10823        } else {
10824            reindex_join_column_with_invented_gap(col, left_data_positions)?
10825        };
10826        let out_name = if right_col_names.contains(name) {
10827            apply_merge_suffix(name, suffixes.left.as_deref())
10828        } else {
10829            name.clone()
10830        };
10831        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10832    }
10833
10834    // Add right non-key columns in the right frame's own column order — br-691lh.
10835    for name in right.column_names() {
10836        let col = right
10837            .columns()
10838            .get(name)
10839            .expect("right column listed in column_names must exist");
10840        if right_key_name_set.contains(name.as_str())
10841            && shared_name_positions.contains_key(name.as_str())
10842        {
10843            // Shared same-name key already emitted from the left side.
10844            continue;
10845        }
10846        let reindexed = if let Some(positions) = all_present_right_positions {
10847            take_positions_typed(col, positions)
10848        } else {
10849            reindex_join_column_with_invented_gap(col, right_data_positions)?
10850        };
10851        let out_name = if left_col_names.contains(name) {
10852            apply_merge_suffix(name, suffixes.right.as_deref())
10853        } else {
10854            name.clone()
10855        };
10856        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10857    }
10858
10859    if let Some(indicator_name) = indicator_name.as_deref() {
10860        ensure_indicator_name_available(
10861            indicator_name,
10862            &left_col_names,
10863            &right_col_names,
10864            &columns,
10865        )?;
10866        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions);
10867        insert_merged_output_column(
10868            &mut columns,
10869            &mut column_order,
10870            indicator_name.to_owned(),
10871            indicator_col,
10872        )?;
10873    }
10874
10875    Ok(MergedDataFrame {
10876        index,
10877        columns,
10878        column_order,
10879    })
10880}
10881
10882/// Merge two DataFrames on one or more key columns with identical key names.
10883///
10884/// Matches `pd.merge(left, right, on=keys, how=join_type)`.
10885pub fn merge_dataframes_on(
10886    left: &fp_frame::DataFrame,
10887    right: &fp_frame::DataFrame,
10888    on: &[&str],
10889    join_type: JoinType,
10890) -> Result<MergedDataFrame, JoinError> {
10891    merge_dataframes_on_with(left, right, on, on, join_type)
10892}
10893
10894/// Merge two DataFrames on a single key column.
10895pub fn merge_dataframes(
10896    left: &fp_frame::DataFrame,
10897    right: &fp_frame::DataFrame,
10898    on: &str,
10899    join_type: JoinType,
10900) -> Result<MergedDataFrame, JoinError> {
10901    if matches!(join_type, JoinType::Inner) {
10902        let left_key = left.column(on).ok_or_else(|| {
10903            JoinError::Frame(FrameError::CompatibilityRejected(format!(
10904                "left DataFrame missing key column '{on}'"
10905            )))
10906        })?;
10907        let right_key = right.column(on).ok_or_else(|| {
10908            JoinError::Frame(FrameError::CompatibilityRejected(format!(
10909                "right DataFrame missing key column '{on}'"
10910            )))
10911        })?;
10912        validate_object_join_keys(left_key)?;
10913        validate_object_join_keys(right_key)?;
10914        let suffixes = ResolvedMergeSuffixes::default();
10915        return merge_single_key_inner_unsorted(
10916            left,
10917            right,
10918            &[on],
10919            &[on],
10920            &[left_key],
10921            &[right_key],
10922            &suffixes,
10923        );
10924    }
10925    merge_dataframes_on(left, right, &[on], join_type)
10926}
10927
10928fn merge_dataframes_cross(
10929    left: &fp_frame::DataFrame,
10930    right: &fp_frame::DataFrame,
10931    indicator_name: Option<&str>,
10932    suffixes: &ResolvedMergeSuffixes,
10933) -> Result<MergedDataFrame, JoinError> {
10934    let left_rows = left.index().len();
10935    let right_rows = right.index().len();
10936    let out_rows = left_rows.saturating_mul(right_rows);
10937
10938    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_rows);
10939    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_rows);
10940    for left_pos in 0..left_rows {
10941        for right_pos in 0..right_rows {
10942            left_positions.push(Some(left_pos));
10943            right_positions.push(Some(right_pos));
10944        }
10945    }
10946
10947    let index = Index::new((0..out_rows as i64).map(IndexLabel::from).collect());
10948    let mut columns = ColumnStore::new();
10949    let mut column_order: Vec<String> = Vec::new();
10950
10951    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
10952    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
10953    let overlapping_names =
10954        collect_overlapping_column_names(&left_col_names, &right_col_names, &HashSet::new());
10955    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
10956
10957    // Each side's columns in its own order, as pandas (the store iterates
10958    // them by name, so the right side's came back sorted; buwrx).
10959    for position in 0..left.num_columns() {
10960        let (Some(name), Some(col)) = (left.column_name_at(position), left.column_at(position))
10961        else {
10962            continue;
10963        };
10964        let reindexed = col.reindex_by_positions(&left_positions)?;
10965        let out_name = if right_col_names.contains(&name) {
10966            apply_merge_suffix(&name, suffixes.left.as_deref())
10967        } else {
10968            name
10969        };
10970        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10971    }
10972
10973    for position in 0..right.num_columns() {
10974        let (Some(name), Some(col)) = (right.column_name_at(position), right.column_at(position))
10975        else {
10976            continue;
10977        };
10978        let reindexed = col.reindex_by_positions(&right_positions)?;
10979        let out_name = if left_col_names.contains(&name) {
10980            apply_merge_suffix(&name, suffixes.right.as_deref())
10981        } else {
10982            name
10983        };
10984        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10985    }
10986
10987    if let Some(indicator_name) = indicator_name {
10988        ensure_indicator_name_available(
10989            indicator_name,
10990            &left_col_names,
10991            &right_col_names,
10992            &columns,
10993        )?;
10994        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions);
10995        insert_merged_output_column(
10996            &mut columns,
10997            &mut column_order,
10998            indicator_name.to_owned(),
10999            indicator_col,
11000        )?;
11001    }
11002
11003    Ok(MergedDataFrame {
11004        index,
11005        columns,
11006        column_order,
11007    })
11008}
11009
11010/// Extension trait adding `.merge()` and `.join()` instance methods to `DataFrame`.
11011///
11012/// Import this trait to get pandas-style `df.merge(other, ...)` and `df.join(other, ...)`
11013/// as instance methods.
11014pub trait DataFrameMergeExt {
11015    /// Merge this DataFrame with another on shared key columns.
11016    ///
11017    /// Matches `pd.DataFrame.merge(other, on=keys, how=join_type)`.
11018    fn merge(
11019        &self,
11020        other: &fp_frame::DataFrame,
11021        on: &[&str],
11022        how: JoinType,
11023    ) -> Result<MergedDataFrame, JoinError>;
11024
11025    /// Merge with separate left/right key columns and execution options.
11026    ///
11027    /// Matches `pd.DataFrame.merge(other, left_on=..., right_on=..., how=...)`.
11028    fn merge_with_options(
11029        &self,
11030        other: &fp_frame::DataFrame,
11031        left_on: &[&str],
11032        right_on: &[&str],
11033        how: JoinType,
11034        options: MergeExecutionOptions,
11035    ) -> Result<MergedDataFrame, JoinError>;
11036
11037    /// Join another DataFrame on the index.
11038    ///
11039    /// Matches `pd.DataFrame.join(other, how=join_type)` (index-based join).
11040    fn join_on_index(
11041        &self,
11042        other: &fp_frame::DataFrame,
11043        how: JoinType,
11044    ) -> Result<MergedDataFrame, JoinError>;
11045
11046    /// pandas-named alias for [`Self::join_on_index`]. Matches
11047    /// `pd.DataFrame.join(other, how=...)` directly. Per br-frankenpandas-nk54a.
11048    ///
11049    /// Default impl delegates to `join_on_index`. Implementors that already
11050    /// have an optimized index-based join can leave this default.
11051    fn join(
11052        &self,
11053        other: &fp_frame::DataFrame,
11054        how: JoinType,
11055    ) -> Result<MergedDataFrame, JoinError> {
11056        self.join_on_index(other, how)
11057    }
11058
11059    /// Perform an asof merge (nearest-match join) on a sorted key column.
11060    ///
11061    /// Matches `pd.merge_asof(left, right, on=key)`. Both DataFrames must
11062    /// be sorted by the key column. For each row in `left`, finds the last
11063    /// row in `right` where `right[on] <= left[on]` (backward direction)
11064    /// or the nearest row in the specified direction.
11065    ///
11066    /// `direction`: "backward" (default), "forward", "nearest".
11067    fn merge_asof(
11068        &self,
11069        other: &fp_frame::DataFrame,
11070        on: &str,
11071        direction: &str,
11072    ) -> Result<MergedDataFrame, JoinError>;
11073
11074    /// Perform an asof merge with additional options.
11075    ///
11076    /// Matches `pd.merge_asof(left, right, on=key, direction=...,
11077    /// allow_exact_matches=..., tolerance=..., by=...)`.
11078    ///
11079    /// # Parameters
11080    /// - `other`: Right DataFrame to merge with
11081    /// - `on`: Column name to merge on (must be numeric and sorted)
11082    /// - `direction`: "backward", "forward", or "nearest"
11083    /// - `options`: Additional options (allow_exact_matches, tolerance, by)
11084    fn merge_asof_with_options(
11085        &self,
11086        other: &fp_frame::DataFrame,
11087        on: &str,
11088        direction: &str,
11089        options: MergeAsofOptions,
11090    ) -> Result<MergedDataFrame, JoinError>;
11091
11092    /// Perform an ordered merge (outer join + sort by keys).
11093    ///
11094    /// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
11095    fn merge_ordered(
11096        &self,
11097        other: &fp_frame::DataFrame,
11098        on: &[&str],
11099        fill_method: Option<&str>,
11100    ) -> Result<MergedDataFrame, JoinError>;
11101}
11102
11103/// Perform an ordered merge of two DataFrames.
11104///
11105/// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
11106/// Performs an outer join and ensures the result is sorted by the join keys.
11107pub fn merge_ordered(
11108    left: &fp_frame::DataFrame,
11109    right: &fp_frame::DataFrame,
11110    on: &[&str],
11111    fill_method: Option<&str>,
11112) -> Result<MergedDataFrame, JoinError> {
11113    merge_ordered_with_options(
11114        left,
11115        right,
11116        on,
11117        on,
11118        JoinType::Outer,
11119        fill_method,
11120        MergeExecutionOptions::default(),
11121    )
11122}
11123
11124/// Ordered merge with independent key names, join direction and suffixes.
11125///
11126/// Sorting is always by the complete join key. `ffill` propagates source
11127/// row positions before gathering columns, preserving actual missing cells
11128/// and the dtype of each side whenever no leading gap is introduced.
11129pub fn merge_ordered_with_options(
11130    left: &fp_frame::DataFrame,
11131    right: &fp_frame::DataFrame,
11132    left_on: &[&str],
11133    right_on: &[&str],
11134    how: JoinType,
11135    fill_method: Option<&str>,
11136    mut options: MergeExecutionOptions,
11137) -> Result<MergedDataFrame, JoinError> {
11138    validate_ordered_merge_options(how, fill_method)?;
11139    options.sort = true;
11140    merge_dataframes_on_with_fill(
11141        left,
11142        right,
11143        left_on,
11144        right_on,
11145        how,
11146        options,
11147        fill_method.is_some(),
11148    )
11149}
11150
11151fn validate_ordered_merge_options(
11152    how: JoinType,
11153    fill_method: Option<&str>,
11154) -> Result<(), JoinError> {
11155    if let Some(method) = fill_method
11156        && method != "ffill"
11157    {
11158        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11159            format!("merge_ordered: fill_method must be 'ffill' or None, got '{method}'"),
11160        )));
11161    }
11162    if how == JoinType::Cross {
11163        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11164            "merge_ordered: how must be 'left', 'right', 'inner' or 'outer'".to_owned(),
11165        )));
11166    }
11167    Ok(())
11168}
11169
11170/// The side whose groups drive an ordered merge (pandas' left_by or right_by).
11171///
11172/// Only one side may drive the operation. If the other frame also holds
11173/// every grouping column, only its corresponding group participates;
11174/// otherwise its entire frame participates in each group.
11175#[derive(Debug, Clone, PartialEq, Eq)]
11176pub enum MergeOrderedGroupBy {
11177    Left(Vec<String>),
11178    Right(Vec<String>),
11179}
11180
11181struct OrderedMergeGroup {
11182    key: CompositeJoinKey,
11183    labels: Vec<Scalar>,
11184    rows: Vec<usize>,
11185}
11186
11187/// Observed groups in first-appearance order, excluding rows with a missing
11188/// group key. A single categorical grouper also visits its unused categories
11189/// after the observed ones, as pandas' groupby(sort=False, observed=False).
11190fn ordered_merge_groups(
11191    frame: &fp_frame::DataFrame,
11192    by: &[String],
11193) -> Result<Vec<OrderedMergeGroup>, JoinError> {
11194    if by.is_empty() {
11195        return Err(FrameError::CompatibilityRejected("No group keys passed!".to_owned()).into());
11196    }
11197    let keys = build_group_keys(frame, by)?;
11198    let columns: Vec<&Column> = by
11199        .iter()
11200        .map(|name| frame.column(name).expect("group key was validated"))
11201        .collect();
11202    let mut groups: Vec<OrderedMergeGroup> = Vec::new();
11203    let mut positions: FxHashMap<CompositeJoinKey, usize> = FxHashMap::default();
11204    for (row, key) in keys.into_iter().enumerate() {
11205        if key
11206            .iter()
11207            .any(|value| matches!(value, JoinKeyComponent::Missing))
11208        {
11209            continue;
11210        }
11211        if let Some(&position) = positions.get(&key) {
11212            groups[position].rows.push(row);
11213        } else {
11214            positions.insert(key.clone(), groups.len());
11215            groups.push(OrderedMergeGroup {
11216                key,
11217                labels: columns
11218                    .iter()
11219                    .map(|column| column.scalar_at(row).expect("group row is in bounds"))
11220                    .collect(),
11221                rows: vec![row],
11222            });
11223        }
11224    }
11225    if let [column] = columns.as_slice()
11226        && let Some(meta) = column.categorical()
11227    {
11228        for value in &meta.categories {
11229            let key = CompositeJoinKey::from_vec(vec![scalar_to_key_component(value)]);
11230            if let std::collections::hash_map::Entry::Vacant(entry) = positions.entry(key.clone()) {
11231                entry.insert(groups.len());
11232                groups.push(OrderedMergeGroup {
11233                    key,
11234                    labels: vec![value.clone()],
11235                    rows: Vec::new(),
11236                });
11237            }
11238        }
11239    }
11240    Ok(groups)
11241}
11242
11243/// Merge each group's ordered rows independently, then concatenate the groups.
11244///
11245/// Matches pandas merge_ordered(left_by=...) / merge_ordered(right_by=...):
11246/// group order is first appearance on the selected side; sorting and forward
11247/// filling happen inside each group. Forward fill uses the same source-row
11248/// position kernel as an ungrouped ordered merge, so it neither crosses groups
11249/// nor fills an actual missing input cell. With grouping columns on both sides,
11250/// a group absent from the other side is kept in its source order (including
11251/// for how="inner"), following pandas' grouped-merge contract.
11252#[allow(clippy::too_many_arguments)]
11253pub fn merge_ordered_grouped_with_options(
11254    left: &fp_frame::DataFrame,
11255    right: &fp_frame::DataFrame,
11256    left_on: &[&str],
11257    right_on: &[&str],
11258    how: JoinType,
11259    fill_method: Option<&str>,
11260    by: &MergeOrderedGroupBy,
11261    options: MergeExecutionOptions,
11262) -> Result<MergedDataFrame, JoinError> {
11263    validate_ordered_merge_options(how, fill_method)?;
11264    let (grouped, other, names, on_left) = match by {
11265        MergeOrderedGroupBy::Left(names) => (left, right, names, true),
11266        MergeOrderedGroupBy::Right(names) => (right, left, names, false),
11267    };
11268    let groups = ordered_merge_groups(grouped, names)?;
11269    if groups.is_empty() {
11270        return Err(
11271            FrameError::CompatibilityRejected("No objects to concatenate".to_owned()).into(),
11272        );
11273    }
11274    let other_groups = if names.iter().all(|name| other.column(name).is_some()) {
11275        Some(
11276            ordered_merge_groups(other, names)?
11277                .into_iter()
11278                .map(|group| (group.key, group.rows))
11279                .collect::<FxHashMap<_, _>>(),
11280        )
11281    } else {
11282        None
11283    };
11284    let mut pieces = Vec::with_capacity(groups.len());
11285    for group in groups {
11286        let piece = grouped.take_rows(&group.rows)?;
11287        let counterpart = match &other_groups {
11288            Some(groups) => match groups.get(&group.key) {
11289                Some(rows) => Some(other.take_rows(rows)?),
11290                None => {
11291                    // pandas keeps an unmatched group's original columns,
11292                    // appending the other side's absent columns as NaN. The
11293                    // first piece determines the final output column axis.
11294                    let mut columns = piece.column_names();
11295                    columns.extend(
11296                        other
11297                            .column_names()
11298                            .into_iter()
11299                            .filter(|name| piece.column(name).is_none()),
11300                    );
11301                    let columns: Vec<&str> = columns.into_iter().map(String::as_str).collect();
11302                    pieces.push(piece.reindex_columns(&columns)?);
11303                    continue;
11304                }
11305            },
11306            None => None,
11307        };
11308        let counterpart = counterpart.as_ref().unwrap_or(other);
11309        let (left_piece, right_piece) = if on_left {
11310            (&piece, counterpart)
11311        } else {
11312            (counterpart, &piece)
11313        };
11314        let merged = merge_ordered_with_options(
11315            left_piece,
11316            right_piece,
11317            left_on,
11318            right_on,
11319            how,
11320            fill_method,
11321            options.clone(),
11322        )?;
11323        let mut merged = fp_frame::DataFrame::new_with_column_order(
11324            merged.index,
11325            merged.columns,
11326            merged.column_order,
11327        )?;
11328        for (name, label) in names.iter().zip(group.labels) {
11329            // Assigning the group label fills even leading outer-join gaps
11330            // and adds an unsuffixed column when both inputs carry this name.
11331            // A categorical / nullable key becomes the scalar's plain dtype;
11332            // zoned datetimes retain their zone.
11333            let dtype = label.dtype();
11334            let values = vec![label; merged.len()];
11335            let source = grouped.column(name).expect("group key was validated");
11336            let mut column = if matches!(source.dtype(), DType::Datetime64 { .. }) {
11337                Column::new(source.dtype(), values)?
11338            } else {
11339                Column::new(dtype, values)?
11340            };
11341            // Nullable numpy scalars retain their width when assigned as a
11342            // group label; numpy-backed group labels are ordinary Python
11343            // scalars and therefore use the default 64-bit width.
11344            if matches!(
11345                source.dtype(),
11346                DType::Int64Nullable | DType::Float64Nullable
11347            ) {
11348                column = column.keeping_dtype_of(source);
11349            }
11350            merged = merged.with_column(name, column)?;
11351        }
11352        pieces.push(merged);
11353    }
11354    let frames: Vec<&fp_frame::DataFrame> = pieces.iter().collect();
11355    let concatenated = fp_frame::concat_dataframes_with_ignore_index(&frames, true)?;
11356    // pandas fixes the schema to its first piece, including when that piece
11357    // is an unmatched group whose overlapping columns were not suffixed.
11358    let names: Vec<&str> = pieces[0]
11359        .column_names()
11360        .into_iter()
11361        .map(String::as_str)
11362        .collect();
11363    let result = concatenated.reindex_columns(&names)?;
11364    Ok(MergedDataFrame {
11365        index: result.index().clone(),
11366        columns: result.columns().clone(),
11367        column_order: result.column_names().into_iter().cloned().collect(),
11368    })
11369}
11370
11371/// Direction for asof merge matching.
11372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11373pub enum AsofDirection {
11374    Backward,
11375    Forward,
11376    Nearest,
11377}
11378
11379/// Options for asof merge operations.
11380///
11381/// Matches pandas `merge_asof` parameters:
11382/// - `allow_exact_matches`: If true (default), allow matching with same key value
11383/// - `tolerance`: Maximum distance between keys for a match
11384/// - `by`: Columns to match exactly before asof matching
11385#[derive(Debug, Clone)]
11386pub struct MergeAsofOptions {
11387    /// If true (default), allow matching with the same 'on' value.
11388    /// If false, don't match rows where left key == right key exactly.
11389    pub allow_exact_matches: bool,
11390    /// Maximum distance between left and right keys for a valid match.
11391    /// None means no tolerance limit.
11392    pub tolerance: Option<f64>,
11393    /// Columns to match exactly before performing asof merge.
11394    /// Acts like an equi-join on these columns first.
11395    pub by: Option<Vec<String>>,
11396    /// Left grouping columns when the two sides use different names.
11397    /// Must be paired with `right_by` and cannot be combined with `by`.
11398    pub left_by: Option<Vec<String>>,
11399    /// Right grouping columns, matched positionally to `left_by`.
11400    pub right_by: Option<Vec<String>>,
11401    /// Suffixes for overlapping non-shared-key columns, as in `merge`.
11402    /// `None` uses `("_x", "_y")`.
11403    pub suffixes: Option<[Option<String>; 2]>,
11404}
11405
11406impl Default for MergeAsofOptions {
11407    fn default() -> Self {
11408        Self::new()
11409    }
11410}
11411
11412impl MergeAsofOptions {
11413    /// Create options with defaults matching pandas behavior.
11414    pub fn new() -> Self {
11415        Self {
11416            allow_exact_matches: true,
11417            tolerance: None,
11418            by: None,
11419            left_by: None,
11420            right_by: None,
11421            suffixes: None,
11422        }
11423    }
11424
11425    /// Set whether exact matches are allowed.
11426    pub fn allow_exact_matches(mut self, allow: bool) -> Self {
11427        self.allow_exact_matches = allow;
11428        self
11429    }
11430
11431    /// Set the tolerance for matching.
11432    pub fn tolerance(mut self, tol: f64) -> Self {
11433        self.tolerance = Some(tol);
11434        self
11435    }
11436
11437    /// Set the columns to match exactly before asof merge.
11438    pub fn by(mut self, cols: Vec<String>) -> Self {
11439        self.by = Some(cols);
11440        self
11441    }
11442}
11443
11444/// When BOTH `on` keys are Datetime64, extract them as f64 SHIFTED by the global
11445/// minimum ns so the values fit f64's 2^53 integer precision exactly. A raw
11446/// Datetime64->ns->f64 cast collapses ns (~1.6e18) to garbage (>2^53), so
11447/// merge_asof previously REJECTED datetime keys ("must be numeric") — the primary
11448/// time-series asof case. Shifting is order- and difference-preserving (both sides
11449/// by the same min), so the f64 asof match + tolerance stay exact whenever the ns
11450/// RANGE fits 2^53 (~104 days). Returns:
11451/// - `None`: not both Datetime64 → caller uses the f64 numeric path unchanged.
11452/// - `Some(Err)`: range too wide for exact f64 → clean rejection (better than the
11453///   silently-wrong result a lossy cast would give).
11454/// - `Some(Ok((left,right)))`: shifted f64 keys, NaT/null → NaN.
11455type ShiftedDatetimeAsofKeys = (Vec<f64>, Vec<f64>);
11456
11457fn try_asof_datetime_shift(
11458    left_key: &Column,
11459    right_key: &Column,
11460    on: &str,
11461) -> Option<Result<ShiftedDatetimeAsofKeys, JoinError>> {
11462    if !matches!(
11463        (left_key.dtype(), right_key.dtype()),
11464        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz }) if left_tz == right_tz
11465    ) {
11466        return None;
11467    }
11468    let ld = left_key.as_datetime64_slice()?;
11469    let rd = right_key.as_datetime64_slice()?;
11470    let lv = left_key.validity();
11471    let rv = right_key.validity();
11472    // All-valid fast path: when a side has no null bits, the per-element
11473    // ValidityMask::get bit-test is skipped in both the min-scan and the shift
11474    // (only the cheap NaT sentinel compare remains, which vectorizes). NaT/null
11475    // are rare in an asof `on` key, so this is the hot path.
11476    let l_all = lv.all();
11477    let r_all = rv.all();
11478    let is_valid = |data: &[i64], v: &fp_columnar::ValidityMask, all: bool, i: usize| -> bool {
11479        (all || v.get(i)) && data[i] != fp_types::Timestamp::NAT
11480    };
11481    // Global min/max over the valid (non-NaT) ns of both sides.
11482    let mut lo = i64::MAX;
11483    let mut hi = i64::MIN;
11484    let mut any = false;
11485    for i in 0..ld.len() {
11486        if is_valid(ld, lv, l_all, i) {
11487            lo = lo.min(ld[i]);
11488            hi = hi.max(ld[i]);
11489            any = true;
11490        }
11491    }
11492    for i in 0..rd.len() {
11493        if is_valid(rd, rv, r_all, i) {
11494            lo = lo.min(rd[i]);
11495            hi = hi.max(rd[i]);
11496            any = true;
11497        }
11498    }
11499    if !any {
11500        // All-NaT/empty: every shifted value is NaN; produce that directly.
11501        return Some(Ok((vec![f64::NAN; ld.len()], vec![f64::NAN; rd.len()])));
11502    }
11503    if (hi as i128 - lo as i128) >= (1i128 << 53) {
11504        return Some(Err(JoinError::Frame(FrameError::CompatibilityRejected(
11505            format!(
11506                "merge_asof: Datetime64 key '{on}' spans more than ~104 days of nanoseconds, \
11507             which exceeds f64 asof precision; not yet supported"
11508            ),
11509        ))));
11510    }
11511    let shift = |data: &[i64], v: &fp_columnar::ValidityMask, all: bool| -> Vec<f64> {
11512        (0..data.len())
11513            .map(|i| {
11514                if is_valid(data, v, all, i) {
11515                    (data[i] - lo) as f64
11516                } else {
11517                    f64::NAN
11518                }
11519            })
11520            .collect()
11521    };
11522    Some(Ok((shift(ld, lv, l_all), shift(rd, rv, r_all))))
11523}
11524
11525#[derive(Clone, Copy)]
11526struct Datetime64AsofKey<'a> {
11527    data: &'a [i64],
11528    validity: &'a ValidityMask,
11529    all_valid: bool,
11530    nat_is_missing: bool,
11531}
11532
11533impl Datetime64AsofKey<'_> {
11534    #[inline]
11535    fn is_valid(self, i: usize) -> bool {
11536        (self.all_valid || self.validity.get(i))
11537            && (!self.nat_is_missing || self.data[i] != fp_types::Timestamp::NAT)
11538    }
11539}
11540
11541fn datetime64_key_parts(column: &Column) -> Option<Datetime64AsofKey<'_>> {
11542    let data = column.as_datetime64_slice()?;
11543    let validity = column.validity();
11544    Some(Datetime64AsofKey {
11545        data,
11546        validity,
11547        all_valid: validity.all(),
11548        nat_is_missing: true,
11549    })
11550}
11551
11552/// The exact integer representation of integer, datetime and timedelta keys.
11553/// Numeric i64::MIN is a value; only temporal keys use it as the NaT sentinel.
11554/// Keeping these keys out of f64 prevents adjacent IDs/nanoseconds above 2^53
11555/// from becoming false exact matches, including within grouped asof joins.
11556fn integer_asof_key_parts(column: &Column) -> Option<Datetime64AsofKey<'_>> {
11557    if matches!(column.dtype(), DType::Datetime64 { .. }) {
11558        return datetime64_key_parts(column);
11559    }
11560    let (data, validity, nat_is_missing) = match column.dtype() {
11561        DType::Int64 => {
11562            let (data, validity) = column.as_i64_slice_with_validity()?;
11563            (data, validity, false)
11564        }
11565        DType::Int64Nullable => {
11566            let (data, validity) = column.as_masked_i64_slice()?;
11567            (data, validity, false)
11568        }
11569        DType::Timedelta64 => (column.as_timedelta64_slice()?, column.validity(), true),
11570        _ => return None,
11571    };
11572    Some(Datetime64AsofKey {
11573        data,
11574        validity,
11575        all_valid: validity.all(),
11576        nat_is_missing,
11577    })
11578}
11579
11580fn ensure_sorted_non_decreasing_datetime64(
11581    key: Datetime64AsofKey<'_>,
11582    side: &str,
11583    on: &str,
11584) -> Result<(), JoinError> {
11585    let mut prev: Option<i64> = None;
11586    let mut unsorted = false;
11587    for i in 0..key.data.len() {
11588        if !key.is_valid(i) {
11589            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11590                format!("Merge keys contain null values on {side} side"),
11591            )));
11592        }
11593        let value = key.data[i];
11594        unsorted |= prev.is_some_and(|previous| value < previous);
11595        prev = Some(value);
11596    }
11597    if unsorted {
11598        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11599            format!("merge_asof: {side} column '{on}' must be sorted"),
11600        )));
11601    }
11602    Ok(())
11603}
11604
11605fn within_datetime64_tolerance(left: i64, right: i64, tolerance: Option<f64>) -> bool {
11606    match tolerance {
11607        Some(tol) => ((left as i128 - right as i128).abs() as f64) <= tol,
11608        None => true,
11609    }
11610}
11611
11612fn compute_asof_matches_datetime64(
11613    left: Datetime64AsofKey<'_>,
11614    right: Datetime64AsofKey<'_>,
11615    direction: AsofDirection,
11616    allow_exact_matches: bool,
11617    tolerance: Option<f64>,
11618) -> Vec<Option<usize>> {
11619    let mut filtered_values = Vec::new();
11620    let mut filtered_positions = Vec::new();
11621    let (right_valid_values, right_valid_positions) = if right.all_valid
11622        && (!right.nat_is_missing || !right.data.contains(&fp_types::Timestamp::NAT))
11623    {
11624        (right.data, None)
11625    } else {
11626        for i in 0..right.data.len() {
11627            if right.is_valid(i) {
11628                filtered_values.push(right.data[i]);
11629                filtered_positions.push(i);
11630            }
11631        }
11632        (
11633            filtered_values.as_slice(),
11634            Some(filtered_positions.as_slice()),
11635        )
11636    };
11637
11638    compute_asof_matches_datetime64_prepared(
11639        left,
11640        right_valid_values,
11641        right_valid_positions,
11642        direction,
11643        allow_exact_matches,
11644        tolerance,
11645    )
11646}
11647
11648fn compute_asof_matches_datetime64_prepared(
11649    left: Datetime64AsofKey<'_>,
11650    right_valid_values: &[i64],
11651    right_valid_positions: Option<&[usize]>,
11652    direction: AsofDirection,
11653    allow_exact_matches: bool,
11654    tolerance: Option<f64>,
11655) -> Vec<Option<usize>> {
11656    let right_source_position =
11657        |position: usize| right_valid_positions.map_or(position, |positions| positions[position]);
11658
11659    let mut right_matches = Vec::with_capacity(left.data.len());
11660
11661    match direction {
11662        AsofDirection::Backward => {
11663            let mut best: Option<usize> = None;
11664            let mut best_val: Option<i64> = None;
11665            let mut j = 0usize;
11666            for i in 0..left.data.len() {
11667                if !left.is_valid(i) {
11668                    right_matches.push(None);
11669                    continue;
11670                }
11671                let lv = left.data[i];
11672                while j < right_valid_values.len() {
11673                    let rv = right_valid_values[j];
11674                    let should_include = if allow_exact_matches {
11675                        rv <= lv
11676                    } else {
11677                        rv < lv
11678                    };
11679                    if !should_include {
11680                        break;
11681                    }
11682                    best = Some(right_source_position(j));
11683                    best_val = Some(rv);
11684                    j += 1;
11685                }
11686
11687                let matched = match (best, best_val) {
11688                    (Some(idx), Some(rv)) if within_datetime64_tolerance(lv, rv, tolerance) => {
11689                        Some(idx)
11690                    }
11691                    _ => None,
11692                };
11693                right_matches.push(matched);
11694            }
11695        }
11696        AsofDirection::Forward => {
11697            let mut j = 0usize;
11698            for i in 0..left.data.len() {
11699                if !left.is_valid(i) {
11700                    right_matches.push(None);
11701                    continue;
11702                }
11703                let lv = left.data[i];
11704                while j < right_valid_values.len() {
11705                    let rv = right_valid_values[j];
11706                    let should_skip = if allow_exact_matches {
11707                        rv < lv
11708                    } else {
11709                        rv <= lv
11710                    };
11711                    if !should_skip {
11712                        break;
11713                    }
11714                    j += 1;
11715                }
11716
11717                if j < right_valid_values.len() {
11718                    let rv = right_valid_values[j];
11719                    if within_datetime64_tolerance(lv, rv, tolerance) {
11720                        right_matches.push(Some(right_source_position(j)));
11721                    } else {
11722                        right_matches.push(None);
11723                    }
11724                } else {
11725                    right_matches.push(None);
11726                }
11727            }
11728        }
11729        AsofDirection::Nearest => {
11730            for i in 0..left.data.len() {
11731                if !left.is_valid(i) {
11732                    right_matches.push(None);
11733                    continue;
11734                }
11735                if right_valid_values.is_empty() {
11736                    right_matches.push(None);
11737                    continue;
11738                }
11739
11740                let lv = left.data[i];
11741                let (lower, upper) = if allow_exact_matches {
11742                    let lo = right_valid_values.partition_point(|rv| *rv <= lv);
11743                    let up = right_valid_values.partition_point(|rv| *rv < lv);
11744                    (
11745                        if lo > 0 { Some(lo - 1) } else { None },
11746                        if up < right_valid_values.len() {
11747                            Some(up)
11748                        } else {
11749                            None
11750                        },
11751                    )
11752                } else {
11753                    let lo = right_valid_values.partition_point(|rv| *rv < lv);
11754                    let up = right_valid_values.partition_point(|rv| *rv <= lv);
11755                    (
11756                        if lo > 0 { Some(lo - 1) } else { None },
11757                        if up < right_valid_values.len() {
11758                            Some(up)
11759                        } else {
11760                            None
11761                        },
11762                    )
11763                };
11764
11765                let chosen = match (lower, upper) {
11766                    (Some(l), Some(u)) => {
11767                        let lower_dist = (right_valid_values[l] as i128 - lv as i128).abs();
11768                        let upper_dist = (right_valid_values[u] as i128 - lv as i128).abs();
11769                        if upper_dist < lower_dist {
11770                            Some(u)
11771                        } else {
11772                            Some(l)
11773                        }
11774                    }
11775                    (Some(l), None) => Some(l),
11776                    (None, Some(u)) => Some(u),
11777                    (None, None) => None,
11778                };
11779
11780                let matched = match chosen {
11781                    Some(idx)
11782                        if within_datetime64_tolerance(lv, right_valid_values[idx], tolerance) =>
11783                    {
11784                        Some(right_source_position(idx))
11785                    }
11786                    _ => None,
11787                };
11788                right_matches.push(matched);
11789            }
11790        }
11791    }
11792
11793    right_matches
11794}
11795
11796fn try_asof_integer_matches(
11797    left_key: &Column,
11798    right_key: &Column,
11799    on: &str,
11800    direction: AsofDirection,
11801    allow_exact_matches: bool,
11802    tolerance: Option<f64>,
11803) -> Option<Result<Vec<Option<usize>>, JoinError>> {
11804    let left = integer_asof_key_parts(left_key)?;
11805    let right = integer_asof_key_parts(right_key)?;
11806
11807    Some((|| {
11808        ensure_sorted_non_decreasing_datetime64(left, "left", on)?;
11809        ensure_sorted_non_decreasing_datetime64(right, "right", on)?;
11810
11811        Ok(compute_asof_matches_datetime64(
11812            left,
11813            right,
11814            direction,
11815            allow_exact_matches,
11816            tolerance,
11817        ))
11818    })())
11819}
11820
11821fn asof_numeric_values(column: &Column, side: &str, on: &str) -> Result<Vec<f64>, JoinError> {
11822    // Typed fast path: an all-valid Int64/Float64 key column reads the raw slice
11823    // directly, skipping the per-cell values() Scalar materialization + to_f64
11824    // dispatch (merge_asof key extraction was ~0.83x pandas). Bit-identical:
11825    // as_i64_slice/as_f64_slice are all-valid (no missing → no NaN-fill branch),
11826    // and Scalar::Int64(v).to_f64() == v as f64, Scalar::Float64(v).to_f64() == v.
11827    // Nullable / Timedelta64 / Datetime64 keys fall through to the Scalar loop.
11828    if let Some(data) = column.as_i64_slice() {
11829        return Ok(data.iter().map(|&v| v as f64).collect());
11830    }
11831    if let Some(data) = column.as_f64_slice() {
11832        return Ok(data.to_vec());
11833    }
11834    let mut out = Vec::with_capacity(column.len());
11835    for value in column.values() {
11836        // pandas merge_asof accepts Timedelta64 (and datetime) `on` columns
11837        // and orders them by ns count. Scalar::Timedelta64.to_f64() returns
11838        // NonNumericValue, so the default branch would reject the join.
11839        // Extract ns directly for non-NaT Timedelta values; treat NaT as NaN
11840        // (matches the ValueIsMissing arm below).
11841        if let Scalar::Timedelta64(ns) = value {
11842            if *ns == fp_types::Timedelta::NAT {
11843                out.push(f64::NAN);
11844            } else {
11845                out.push(*ns as f64);
11846            }
11847            continue;
11848        }
11849        match value.to_f64() {
11850            Ok(v) => out.push(v),
11851            Err(TypeError::ValueIsMissing { .. }) => out.push(f64::NAN),
11852            Err(_) => {
11853                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11854                    format!("merge_asof: {side} column '{on}' must be numeric"),
11855                )));
11856            }
11857        }
11858    }
11859    Ok(out)
11860}
11861
11862/// `merge_asof` compares ordering keys rather than coercing them to a common
11863/// numeric representation.  Converting both sides to `f64` before validating
11864/// their dtypes makes an `int64` key appear compatible with a `float64` key,
11865/// which pandas rejects even when every finite value is exactly representable.
11866fn ensure_matching_asof_key_dtypes(
11867    left_key: &Column,
11868    right_key: &Column,
11869    on: &str,
11870) -> Result<(), JoinError> {
11871    if left_key.dtype() != right_key.dtype() || left_key.width() != right_key.width() {
11872        let dtype_name = |column: &Column| {
11873            let dtype = column.dtype();
11874            column.width().map_or_else(
11875                || dtype.display_name(),
11876                |width| width.name(dtype.is_nullable()).to_owned(),
11877            )
11878        };
11879        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11880            format!(
11881                "merge_asof: incompatible merge keys [0] for '{on}': left dtype('{}'), right dtype('{}'), must be the same type",
11882                dtype_name(left_key),
11883                dtype_name(right_key),
11884            ),
11885        )));
11886    }
11887    Ok(())
11888}
11889
11890fn ensure_sorted_non_decreasing(values: &[f64], side: &str, on: &str) -> Result<(), JoinError> {
11891    let mut prev: Option<f64> = None;
11892    let mut unsorted = false;
11893    for &value in values {
11894        if value.is_nan() {
11895            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11896                format!("Merge keys contain null values on {side} side"),
11897            )));
11898        }
11899        unsorted |= prev.is_some_and(|previous| value < previous);
11900        prev = Some(value);
11901    }
11902    if unsorted {
11903        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11904            format!("merge_asof: {side} column '{on}' must be sorted"),
11905        )));
11906    }
11907    Ok(())
11908}
11909
11910/// Perform an asof merge between two DataFrames.
11911pub fn merge_asof(
11912    left: &fp_frame::DataFrame,
11913    right: &fp_frame::DataFrame,
11914    on: &str,
11915    direction: AsofDirection,
11916) -> Result<MergedDataFrame, JoinError> {
11917    merge_asof_with_options(left, right, on, direction, MergeAsofOptions::new())
11918}
11919
11920/// Perform an asof merge between two DataFrames with additional options.
11921///
11922/// # Parameters
11923/// - `left`: Left DataFrame
11924/// - `right`: Right DataFrame
11925/// - `on`: Column name to merge on (must be numeric and sorted)
11926/// - `direction`: Match direction (Backward, Forward, Nearest)
11927/// - `options`: Additional merge options (allow_exact_matches, tolerance, by)
11928pub fn merge_asof_with_options(
11929    left: &fp_frame::DataFrame,
11930    right: &fp_frame::DataFrame,
11931    on: &str,
11932    direction: AsofDirection,
11933    options: MergeAsofOptions,
11934) -> Result<MergedDataFrame, JoinError> {
11935    merge_asof_on_with_options(left, right, on, on, direction, options)
11936}
11937
11938/// Perform an asof merge with independently named ordering and grouping keys.
11939///
11940/// Unlike a shared `on` key, distinct `left_on` / `right_on` columns both
11941/// appear in the output. Grouping key pairs follow the same rule: only a
11942/// pair whose names are equal is emitted once. `options.by` selects common
11943/// grouping columns; `left_by` and `right_by` select paired side-specific
11944/// columns instead. Both frames must be globally sorted by their ordering key.
11945pub fn merge_asof_on_with_options(
11946    left: &fp_frame::DataFrame,
11947    right: &fp_frame::DataFrame,
11948    left_on: &str,
11949    right_on: &str,
11950    direction: AsofDirection,
11951    options: MergeAsofOptions,
11952) -> Result<MergedDataFrame, JoinError> {
11953    merge_asof_on_with_indexer(left, right, left_on, right_on, direction, options)
11954        .map(|(merged, _)| merged)
11955}
11956
11957/// An asof merge together with the source right-row position for every result row.
11958///
11959/// The indexer is produced by the same matching pass as the merged columns;
11960/// `None` identifies an unmatched left row. Index/column adapters can use it
11961/// to preserve the exact source key dtype and fill an unmatched key from the
11962/// left index, without re-running the join or round-tripping integers through
11963/// a float-promoted output column.
11964pub fn merge_asof_on_with_indexer(
11965    left: &fp_frame::DataFrame,
11966    right: &fp_frame::DataFrame,
11967    left_on: &str,
11968    right_on: &str,
11969    direction: AsofDirection,
11970    options: MergeAsofOptions,
11971) -> Result<(MergedDataFrame, Vec<Option<usize>>), JoinError> {
11972    let invalid =
11973        |message: &str| JoinError::Frame(FrameError::CompatibilityRejected(message.to_owned()));
11974    let (left_by, right_by) = match (&options.by, &options.left_by, &options.right_by) {
11975        (Some(by), None, None) => (by.as_slice(), by.as_slice()),
11976        (None, Some(left_by), Some(right_by)) => (left_by.as_slice(), right_by.as_slice()),
11977        (None, None, None) => (&[][..], &[][..]),
11978        (Some(_), _, _) => return Err(invalid("Can only pass by OR left_by and right_by")),
11979        (None, Some(_), None) => return Err(invalid("missing right_by")),
11980        (None, None, Some(_)) => return Err(invalid("missing left_by")),
11981    };
11982    if left_by.len() != right_by.len() {
11983        return Err(invalid("left_by and right_by must be the same length"));
11984    }
11985    let keys = AsofKeys {
11986        left_on,
11987        right_on,
11988        left_by,
11989        right_by,
11990    };
11991    let right_matches = if left_by.is_empty() {
11992        asof_simple_matches(left, right, keys, direction, &options)?
11993    } else {
11994        asof_grouped_matches(left, right, keys, direction, &options)?
11995    };
11996    let merged = build_asof_output(left, right, keys, &right_matches, &options)?;
11997    Ok((merged, right_matches))
11998}
11999
12000#[derive(Clone, Copy)]
12001struct AsofKeys<'a> {
12002    left_on: &'a str,
12003    right_on: &'a str,
12004    left_by: &'a [String],
12005    right_by: &'a [String],
12006}
12007
12008/// Simple asof merge without grouping.
12009fn asof_simple_matches(
12010    left: &fp_frame::DataFrame,
12011    right: &fp_frame::DataFrame,
12012    keys: AsofKeys<'_>,
12013    direction: AsofDirection,
12014    options: &MergeAsofOptions,
12015) -> Result<Vec<Option<usize>>, JoinError> {
12016    let on = keys.left_on;
12017    let right_on = keys.right_on;
12018    let left_key = left.columns().get(on).ok_or_else(|| {
12019        JoinError::Frame(FrameError::CompatibilityRejected(format!(
12020            "merge_asof: column '{on}' not found in left"
12021        )))
12022    })?;
12023    let right_key = right.columns().get(right_on).ok_or_else(|| {
12024        JoinError::Frame(FrameError::CompatibilityRejected(format!(
12025            "merge_asof: column '{right_on}' not found in right"
12026        )))
12027    })?;
12028
12029    ensure_matching_asof_key_dtypes(left_key, right_key, on)?;
12030
12031    if let Some(integer_matches) = try_asof_integer_matches(
12032        left_key,
12033        right_key,
12034        on,
12035        direction,
12036        options.allow_exact_matches,
12037        options.tolerance,
12038    ) {
12039        return integer_matches;
12040    }
12041
12042    // Float keys retain their native f64 ordering. The datetime shift is a
12043    // fallback only for a temporal column without an accessible typed backing.
12044    let (left_vals, right_vals) = match try_asof_datetime_shift(left_key, right_key, on) {
12045        Some(shifted) => shifted?,
12046        None => (
12047            asof_numeric_values(left_key, "left", on)?,
12048            asof_numeric_values(right_key, "right", right_on)?,
12049        ),
12050    };
12051
12052    // Matching dtypes are necessary but not sufficient: pandas rejects
12053    // missing ordering keys on either side, including NaT. Validation runs
12054    // before matching so a missing row cannot silently disappear.
12055    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
12056    ensure_sorted_non_decreasing(&right_vals, "right", right_on)?;
12057
12058    let right_matches = compute_asof_matches(
12059        &left_vals,
12060        &right_vals,
12061        direction,
12062        options.allow_exact_matches,
12063        options.tolerance,
12064    );
12065
12066    Ok(right_matches)
12067}
12068
12069/// Grouped asof merge: match on `by` columns first, then asof within groups.
12070fn asof_grouped_matches(
12071    left: &fp_frame::DataFrame,
12072    right: &fp_frame::DataFrame,
12073    keys: AsofKeys<'_>,
12074    direction: AsofDirection,
12075    options: &MergeAsofOptions,
12076) -> Result<Vec<Option<usize>>, JoinError> {
12077    let on = keys.left_on;
12078    let right_on = keys.right_on;
12079    // Validate by columns exist
12080    for (col, right_col) in keys.left_by.iter().zip(keys.right_by) {
12081        let left_column = left.columns().get(col).ok_or_else(|| {
12082            JoinError::Frame(FrameError::CompatibilityRejected(format!(
12083                "merge_asof: 'by' column '{col}' not found in left"
12084            )))
12085        })?;
12086        let right_column = right.columns().get(right_col).ok_or_else(|| {
12087            JoinError::Frame(FrameError::CompatibilityRejected(format!(
12088                "merge_asof: 'by' column '{right_col}' not found in right"
12089            )))
12090        })?;
12091        ensure_matching_asof_key_dtypes(left_column, right_column, col)?;
12092        validate_object_join_keys(left_column)?;
12093        validate_object_join_keys(right_column)?;
12094    }
12095
12096    let left_key = left.columns().get(on).ok_or_else(|| {
12097        JoinError::Frame(FrameError::CompatibilityRejected(format!(
12098            "merge_asof: column '{on}' not found in left"
12099        )))
12100    })?;
12101    let right_key = right.columns().get(right_on).ok_or_else(|| {
12102        JoinError::Frame(FrameError::CompatibilityRejected(format!(
12103            "merge_asof: column '{right_on}' not found in right"
12104        )))
12105    })?;
12106
12107    ensure_matching_asof_key_dtypes(left_key, right_key, on)?;
12108
12109    let integer_keys = integer_asof_key_parts(left_key).zip(integer_asof_key_parts(right_key));
12110    let (left_vals, right_vals) = if let Some((left_key, right_key)) = integer_keys {
12111        ensure_sorted_non_decreasing_datetime64(left_key, "left", on)?;
12112        ensure_sorted_non_decreasing_datetime64(right_key, "right", right_on)?;
12113        (Vec::new(), Vec::new())
12114    } else {
12115        let (left_vals, right_vals) = match try_asof_datetime_shift(left_key, right_key, on) {
12116            Some(shifted) => shifted?,
12117            None => (
12118                asof_numeric_values(left_key, "left", on)?,
12119                asof_numeric_values(right_key, "right", right_on)?,
12120            ),
12121        };
12122        ensure_sorted_non_decreasing(&left_vals, "left", on)?;
12123        ensure_sorted_non_decreasing(&right_vals, "right", right_on)?;
12124        (left_vals, right_vals)
12125    };
12126
12127    // Factorize both sides in a shared group-id space. The borrowed
12128    // single-key path avoids string allocation; the generic path uses the
12129    // same canonical equality as ordinary joins, including signed zero and
12130    // missing grouping values.
12131    let (left_ids, right_ids) = build_group_ids(left, right, keys.left_by, keys.right_by)?;
12132
12133    // Group right rows by their `by` group id for asof matching (looked up by
12134    // `.get()` per left group below). No per-group sort validation is needed:
12135    // the global `ensure_sorted_non_decreasing` checks above already require the
12136    // `on` column to be non-decreasing over the whole frame, and every
12137    // per-group subsequence of a sorted column is itself sorted — so the old
12138    // per-group checks were unreachable (the global check fires first on any
12139    // unsorted input). FxHashMap (vs std SipHash) speeds the build.
12140    let mut right_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
12141    for (idx, &id) in right_ids.iter().enumerate() {
12142        right_groups.entry(id).or_default().push(idx);
12143    }
12144
12145    // Group LEFT rows by their `by` group id (preserving the globally-sorted
12146    // order within each group), then run the monotonic two-pointer asof sweep
12147    // ONCE per group over all of the group's left values — instead of rebuilding
12148    // the group's right-value vector and re-scanning it from scratch for every
12149    // individual left row (the old O(L·R) per group). compute_asof_matches
12150    // already drives a single left array with a monotonic cursor and handles
12151    // NaN left keys (→ None, cursor unchanged); because every per-group left
12152    // subsequence is sorted (the global `on` column is non-decreasing), the
12153    // grouped sweep yields the identical match for each left row as the old
12154    // fresh-per-row scan. Results are scattered by absolute left index, so the
12155    // output order is independent of group-iteration order.
12156    let mut left_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
12157    for (left_idx, &id) in left_ids.iter().enumerate() {
12158        left_groups.entry(id).or_default().push(left_idx);
12159    }
12160
12161    let mut right_matches: Vec<Option<usize>> = vec![None; left.len()];
12162    for (group_id, left_positions) in &left_groups {
12163        let Some(group_indices) = right_groups.get(group_id) else {
12164            continue; // no right rows for this group -> all matches stay None
12165        };
12166        let group_matches = if let Some((left_key, right_key)) = integer_keys {
12167            let take_group = |key: Datetime64AsofKey<'_>, positions: &[usize]| {
12168                let mut validity = ValidityMask::all_valid(positions.len());
12169                let data: Vec<i64> = positions
12170                    .iter()
12171                    .enumerate()
12172                    .map(|(out, &source)| {
12173                        if !key.is_valid(source) {
12174                            validity.set(out, false);
12175                        }
12176                        key.data[source]
12177                    })
12178                    .collect();
12179                (data, validity)
12180            };
12181            let (left_data, left_validity) = take_group(left_key, left_positions);
12182            let (right_data, right_validity) = take_group(right_key, group_indices);
12183            compute_asof_matches_datetime64(
12184                Datetime64AsofKey {
12185                    data: &left_data,
12186                    validity: &left_validity,
12187                    all_valid: left_validity.all(),
12188                    nat_is_missing: left_key.nat_is_missing,
12189                },
12190                Datetime64AsofKey {
12191                    data: &right_data,
12192                    validity: &right_validity,
12193                    all_valid: right_validity.all(),
12194                    nat_is_missing: right_key.nat_is_missing,
12195                },
12196                direction,
12197                options.allow_exact_matches,
12198                options.tolerance,
12199            )
12200        } else {
12201            let group_right_vals: Vec<f64> = group_indices.iter().map(|&i| right_vals[i]).collect();
12202            let group_left_vals: Vec<f64> = left_positions.iter().map(|&i| left_vals[i]).collect();
12203            compute_asof_matches(
12204                &group_left_vals,
12205                &group_right_vals,
12206                direction,
12207                options.allow_exact_matches,
12208                options.tolerance,
12209            )
12210        };
12211
12212        for (k, &left_idx) in left_positions.iter().enumerate() {
12213            if let Some(Some(group_idx)) = group_matches.get(k) {
12214                right_matches[left_idx] = Some(group_indices[*group_idx]);
12215            }
12216        }
12217    }
12218
12219    Ok(right_matches)
12220}
12221
12222/// Borrowed, allocation-free grouping keys for the single-column path.
12223/// Missing representations share one group, booleans share their integer
12224/// value, and periods retain their frequency. Nonmissing floats, intervals
12225/// and object values use the ordinary join engine's canonical key path.
12226#[derive(PartialEq, Eq, Hash)]
12227enum ByKey<'a> {
12228    Missing,
12229    Int(i64),
12230    Str(&'a str),
12231    Timedelta(i64),
12232    Datetime(i64),
12233    Period(fp_types::Period),
12234}
12235
12236impl<'a> ByKey<'a> {
12237    fn from_scalar(s: &'a Scalar) -> Option<Self> {
12238        if s.is_missing() {
12239            return Some(ByKey::Missing);
12240        }
12241        Some(match s {
12242            Scalar::Null(_) => ByKey::Missing,
12243            Scalar::Bool(b) => ByKey::Int(i64::from(*b)),
12244            Scalar::Int64(v) => ByKey::Int(*v),
12245            Scalar::Utf8(s) => ByKey::Str(s.as_str()),
12246            Scalar::Timedelta64(v) => ByKey::Timedelta(*v),
12247            Scalar::Datetime64(v) => ByKey::Datetime(*v),
12248            Scalar::Period(v) => ByKey::Period(*v),
12249            Scalar::Float64(_) | Scalar::Interval(_) | Scalar::Object(_) => return None,
12250        })
12251    }
12252}
12253
12254/// Factorize a single grouping column over both frames into a shared id space.
12255/// Unsupported borrowed keys fall back to canonical composite join keys.
12256fn try_factorize_typed<'a>(
12257    left: &'a [Scalar],
12258    right: &'a [Scalar],
12259) -> Option<(Vec<u32>, Vec<u32>)> {
12260    let mut codes: FxHashMap<ByKey<'a>, u32> = FxHashMap::default();
12261    let mut next = 0u32;
12262    let mut left_ids = Vec::with_capacity(left.len());
12263    for v in left {
12264        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
12265            let i = next;
12266            next += 1;
12267            i
12268        });
12269        left_ids.push(id);
12270    }
12271    let mut right_ids = Vec::with_capacity(right.len());
12272    for v in right {
12273        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
12274            let i = next;
12275            next += 1;
12276            i
12277        });
12278        right_ids.push(id);
12279    }
12280    Some((left_ids, right_ids))
12281}
12282
12283/// Build dense u32 group ids for the left and right frames over the `by`
12284/// columns, sharing one id space. Returns `(left_ids, right_ids)`.
12285///
12286/// The single-key fast path borrows its scalar payloads. Other shapes use
12287/// canonical composite keys shared with equality joins, so float signed
12288/// zeros and different missing representations cannot split a group.
12289fn build_group_ids(
12290    left: &fp_frame::DataFrame,
12291    right: &fp_frame::DataFrame,
12292    by_cols: &[String],
12293    right_by_cols: &[String],
12294) -> Result<(Vec<u32>, Vec<u32>), JoinError> {
12295    if by_cols.len() == 1
12296        && let (Some(lcol), Some(rcol)) = (
12297            left.columns().get(&by_cols[0]),
12298            right.columns().get(&right_by_cols[0]),
12299        )
12300        && let Some(ids) = try_factorize_typed(lcol.values(), rcol.values())
12301    {
12302        return Ok(ids);
12303    }
12304
12305    let left_keys = build_group_keys(left, by_cols)?;
12306    let right_keys = build_group_keys(right, right_by_cols)?;
12307    let mut codes: FxHashMap<CompositeJoinKey, u32> = FxHashMap::default();
12308    let mut next = 0u32;
12309    let mut intern = |k: &CompositeJoinKey, codes: &mut FxHashMap<CompositeJoinKey, u32>| {
12310        if let Some(&id) = codes.get(k) {
12311            id
12312        } else {
12313            let id = next;
12314            next += 1;
12315            codes.insert(k.clone(), id);
12316            id
12317        }
12318    };
12319    let left_ids = left_keys.iter().map(|k| intern(k, &mut codes)).collect();
12320    let right_ids = right_keys.iter().map(|k| intern(k, &mut codes)).collect();
12321    Ok((left_ids, right_ids))
12322}
12323
12324/// Build grouping keys with the same equality semantics as an equi-join.
12325fn build_group_keys(
12326    df: &fp_frame::DataFrame,
12327    by_cols: &[String],
12328) -> Result<Vec<CompositeJoinKey>, JoinError> {
12329    let names: Vec<&str> = by_cols.iter().map(String::as_str).collect();
12330    let columns = collect_join_key_columns(df, &names, "grouping")?;
12331    Ok(collect_composite_keys(&columns))
12332}
12333
12334/// Compute asof matches for a single group or the whole dataset.
12335fn compute_asof_matches(
12336    left_vals: &[f64],
12337    right_vals: &[f64],
12338    direction: AsofDirection,
12339    allow_exact_matches: bool,
12340    tolerance: Option<f64>,
12341) -> Vec<Option<usize>> {
12342    let mut right_non_nan_values = Vec::new();
12343    let mut right_non_nan_positions = Vec::new();
12344    for (pos, &rv) in right_vals.iter().enumerate() {
12345        if !rv.is_nan() {
12346            right_non_nan_values.push(rv);
12347            right_non_nan_positions.push(pos);
12348        }
12349    }
12350
12351    let mut right_matches: Vec<Option<usize>> = Vec::with_capacity(left_vals.len());
12352
12353    match direction {
12354        AsofDirection::Backward => {
12355            let mut best: Option<usize> = None;
12356            let mut best_val: Option<f64> = None;
12357            let mut j = 0usize;
12358            for &lv in left_vals {
12359                if lv.is_nan() {
12360                    right_matches.push(None);
12361                    continue;
12362                }
12363                // Advance while right <= left (or right < left if !allow_exact_matches)
12364                while j < right_non_nan_values.len() {
12365                    let rv = right_non_nan_values[j];
12366                    let should_include = if allow_exact_matches {
12367                        rv <= lv
12368                    } else {
12369                        rv < lv
12370                    };
12371                    if !should_include {
12372                        break;
12373                    }
12374                    best = Some(right_non_nan_positions[j]);
12375                    best_val = Some(rv);
12376                    j += 1;
12377                }
12378
12379                // Check tolerance
12380                let matched = match (best, best_val, tolerance) {
12381                    (Some(idx), Some(rv), Some(tol)) if (lv - rv).abs() <= tol => Some(idx),
12382                    (Some(idx), _, None) => Some(idx),
12383                    _ => None,
12384                };
12385                right_matches.push(matched);
12386            }
12387        }
12388        AsofDirection::Forward => {
12389            let mut j = 0usize;
12390            for &lv in left_vals {
12391                if lv.is_nan() {
12392                    right_matches.push(None);
12393                    continue;
12394                }
12395                // Advance while right < left (or right <= left if !allow_exact_matches)
12396                while j < right_non_nan_values.len() {
12397                    let rv = right_non_nan_values[j];
12398                    let should_skip = if allow_exact_matches {
12399                        rv < lv
12400                    } else {
12401                        rv <= lv
12402                    };
12403                    if !should_skip {
12404                        break;
12405                    }
12406                    j += 1;
12407                }
12408
12409                if j < right_non_nan_values.len() {
12410                    let rv = right_non_nan_values[j];
12411                    // Check tolerance
12412                    let matched = match tolerance {
12413                        Some(tol) if (rv - lv).abs() <= tol => Some(right_non_nan_positions[j]),
12414                        None => Some(right_non_nan_positions[j]),
12415                        _ => None,
12416                    };
12417                    right_matches.push(matched);
12418                } else {
12419                    right_matches.push(None);
12420                }
12421            }
12422        }
12423        AsofDirection::Nearest => {
12424            for &lv in left_vals {
12425                if lv.is_nan() {
12426                    right_matches.push(None);
12427                    continue;
12428                }
12429                if right_non_nan_values.is_empty() {
12430                    right_matches.push(None);
12431                    continue;
12432                }
12433
12434                // For nearest, pick the closest neighbor on each side. The
12435                // candidate window depends on whether exact (equal) keys may
12436                // match:
12437                //   allow_exact:  lower = last value <= lv, upper = first value >= lv
12438                //   !allow_exact: lower = last value <  lv, upper = first value >  lv
12439                // Selecting the window up front (rather than excluding exact
12440                // matches after the fact) skips over runs of exact-equal keys
12441                // when they are disallowed, so a nearer non-equal key beyond
12442                // the run is still found — matching pandas merge_asof.
12443                let (lower, upper) = if allow_exact_matches {
12444                    let lo = right_non_nan_values.partition_point(|rv| *rv <= lv);
12445                    let up = right_non_nan_values.partition_point(|rv| *rv < lv);
12446                    (
12447                        if lo > 0 { Some(lo - 1) } else { None },
12448                        if up < right_non_nan_values.len() {
12449                            Some(up)
12450                        } else {
12451                            None
12452                        },
12453                    )
12454                } else {
12455                    let lo = right_non_nan_values.partition_point(|rv| *rv < lv);
12456                    let up = right_non_nan_values.partition_point(|rv| *rv <= lv);
12457                    (
12458                        if lo > 0 { Some(lo - 1) } else { None },
12459                        if up < right_non_nan_values.len() {
12460                            Some(up)
12461                        } else {
12462                            None
12463                        },
12464                    )
12465                };
12466
12467                let chosen = match (lower, upper) {
12468                    (Some(l), Some(u)) => {
12469                        let lower_dist = (right_non_nan_values[l] - lv).abs();
12470                        let upper_dist = (right_non_nan_values[u] - lv).abs();
12471                        // Ties go to the lower (backward) neighbor, like pandas.
12472                        if upper_dist < lower_dist {
12473                            Some(u)
12474                        } else {
12475                            Some(l)
12476                        }
12477                    }
12478                    (Some(l), None) => Some(l),
12479                    (None, Some(u)) => Some(u),
12480                    (None, None) => None,
12481                };
12482
12483                // Apply tolerance check
12484                let matched = match chosen {
12485                    Some(idx) => {
12486                        let rv = right_non_nan_values[idx];
12487                        match tolerance {
12488                            Some(tol) if (lv - rv).abs() <= tol => {
12489                                Some(right_non_nan_positions[idx])
12490                            }
12491                            None => Some(right_non_nan_positions[idx]),
12492                            _ => None,
12493                        }
12494                    }
12495                    None => None,
12496                };
12497                right_matches.push(matched);
12498            }
12499        }
12500    }
12501
12502    right_matches
12503}
12504
12505/// Build the output DataFrame from computed matches.
12506/// One output column of `build_asof_output`: left columns are present for every
12507/// row (clone), right columns are gathered by the asof match positions.
12508enum AsofOutputTask<'a> {
12509    LeftClone(&'a Column),
12510    RightGather(&'a Column),
12511}
12512
12513fn build_asof_output(
12514    left: &fp_frame::DataFrame,
12515    right: &fp_frame::DataFrame,
12516    keys: AsofKeys<'_>,
12517    right_matches: &[Option<usize>],
12518    options: &MergeAsofOptions,
12519) -> Result<MergedDataFrame, JoinError> {
12520    let right_n = right.len();
12521
12522    let left_col_names: Vec<String> = left.column_names().iter().map(|s| s.to_string()).collect();
12523    let right_col_names_all: Vec<String> =
12524        right.column_names().iter().map(|s| s.to_string()).collect();
12525
12526    // Only identically named pairs are shared output keys. Distinct keys
12527    // remain separate columns, even when a key also names the other side's
12528    // payload column (which then receives the usual overlap suffix).
12529    let excluded_cols: HashSet<&str> = {
12530        let mut s = HashSet::new();
12531        if keys.left_on == keys.right_on {
12532            s.insert(keys.left_on);
12533        }
12534        for (left_by, right_by) in keys.left_by.iter().zip(keys.right_by) {
12535            if left_by == right_by {
12536                s.insert(left_by.as_str());
12537            }
12538        }
12539        s
12540    };
12541
12542    let right_col_names: Vec<String> = right_col_names_all
12543        .iter()
12544        .filter(|c| !excluded_cols.contains(c.as_str()))
12545        .cloned()
12546        .collect();
12547
12548    let left_name_set: HashSet<&String> = left_col_names.iter().collect();
12549    let right_name_set: HashSet<&String> = right_col_names_all.iter().collect();
12550    let overlap_names =
12551        collect_overlapping_column_names(&left_name_set, &right_name_set, &excluded_cols);
12552    let overlap_set: HashSet<String> = overlap_names.iter().cloned().collect();
12553    let suffixes = resolve_merge_suffixes(options.suffixes.clone());
12554    ensure_merge_suffixes_for_overlaps(&overlap_names, &suffixes)?;
12555
12556    let n_out = left.len();
12557    let mut out_columns = ColumnStore::new();
12558    let mut column_order: Vec<String> = Vec::new();
12559
12560    // Resolve every output column (name + build task) in order, then build the
12561    // columns — left columns clone all rows, right columns gather matched-or-null
12562    // values. Each output column is independent, so wide/large outputs build all
12563    // columns across a worker pool (br-frankenpandas-fu8f5; same disjoint-fill
12564    // pattern as the dense-i64/inner-merge builders). Bit-identical to the serial
12565    // loops: identical per-column result (left clone; right Scalar gather with
12566    // Null(NullKind::NaN) on unmatched, then Column::new with the source dtype),
12567    // inserted in the same order.
12568    let mut specs: Vec<(String, AsofOutputTask<'_>)> = Vec::new();
12569    for col_name in &left_col_names {
12570        let col = left.columns().get(col_name).ok_or_else(|| {
12571            JoinError::Frame(FrameError::CompatibilityRejected(format!(
12572                "merge_asof: left column '{col_name}' not found"
12573            )))
12574        })?;
12575        let output_name = if overlap_set.contains(col_name) {
12576            apply_merge_suffix(col_name, suffixes.left.as_deref())
12577        } else {
12578            col_name.clone()
12579        };
12580        specs.push((output_name, AsofOutputTask::LeftClone(col)));
12581    }
12582    for col_name in &right_col_names {
12583        let right_col = right.columns().get(col_name).ok_or_else(|| {
12584            JoinError::Frame(FrameError::CompatibilityRejected(format!(
12585                "merge_asof: right column '{col_name}' not found"
12586            )))
12587        })?;
12588        let output_name = if overlap_set.contains(col_name) {
12589            apply_merge_suffix(col_name, suffixes.right.as_deref())
12590        } else {
12591            col_name.clone()
12592        };
12593        specs.push((output_name, AsofOutputTask::RightGather(right_col)));
12594    }
12595
12596    let build_one = |task: &AsofOutputTask<'_>| -> Result<Column, JoinError> {
12597        match task {
12598            AsofOutputTask::LeftClone(col) => Ok((*col).clone()),
12599            AsofOutputTask::RightGather(right_col) => {
12600                // Typed all-valid-Float64 gather (br-frankenpandas asof typed
12601                // output): an `as_f64_slice` source is all-valid, so it carries
12602                // NO NaN values (Float64 validity marks NaN invalid, and the
12603                // slice is gated on `validity.all()`). Gather matched data into a
12604                // contiguous f64 buffer + validity bitset instead of cloning a
12605                // 32 B Scalar per row and re-validating in Column::new. Bit-
12606                // identical to the Scalar path: a matched slot is a finite
12607                // `Float64(src[j])` (valid bit), an unmatched slot is
12608                // `Null(NullKind::NaN)` (cleared bit) — exactly what the Scalar
12609                // gather + Column::new produce, with no matched-NaN ambiguity
12610                // because the source has none.
12611                if let Some(src) = right_col.as_f64_slice() {
12612                    let mut data = Vec::with_capacity(n_out);
12613                    let mut validity = fp_columnar::ValidityMask::all_valid(n_out);
12614                    for (i, m) in right_matches.iter().enumerate() {
12615                        match m {
12616                            Some(j) if *j < right_n => data.push(src[*j]),
12617                            _ => {
12618                                // 0.0 datum + cleared bit is the gap convention:
12619                                // LazyNullableFloat64 materializes Null(NaN) only
12620                                // when the datum is NOT NaN, so an unmatched slot
12621                                // must use 0.0 (a NaN datum would materialize a
12622                                // present Float64(NaN) instead).
12623                                data.push(0.0);
12624                                validity.set(i, false);
12625                            }
12626                        }
12627                    }
12628                    return Ok(Column::from_f64_values_with_validity(data, validity)
12629                        .keeping_dtype_of(right_col));
12630                }
12631                // A right column that gains an UNMATCHED row gains a gap, and an
12632                // all-valid numpy int64 cannot hold one — pandas widens it to
12633                // float64, exactly as it does for the join family. This used to
12634                // be a hand-rolled gather ending in
12635                // `Column::new(right_col.dtype(), vals)`, which kept Int64 and
12636                // left the present values pinned as ints beside a NaN.
12637                //
12638                // MEASURED, live pandas 2.2.3:
12639                //   L = DataFrame({'time':[1,5,10], 'left_val':[10,50,100]})
12640                //   R = DataFrame({'time':[2,6],    'right_val':[20,60]})
12641                //   pd.merge_asof(L, R, on='time', direction='forward')
12642                //     right_val -> [20.0, 60.0, NaN]   dtype float64
12643                //     time and left_val stay int64 — they gain no gap
12644                //   with every left row matched, right_val stays int64
12645                //
12646                // Note the rule here is PER COLUMN, unlike Series.unstack where
12647                // a gap widens the whole frame: merge builds each output column
12648                // independently, so only the column that gains the gap moves.
12649                //
12650                // reindex_join_column_with_invented_gap is the helper the nywa8
12651                // join sweep already built for this, including the guard that a
12652                // source ALREADY carrying a missing value is nullable and keeps
12653                // its dtype. merge_asof was the sibling that sweep did not
12654                // reach; calling it rather than re-deriving the rule here.
12655                Ok(reindex_join_column_with_invented_gap(
12656                    right_col,
12657                    right_matches,
12658                )?)
12659            }
12660        }
12661    };
12662
12663    let built: Vec<Result<Column, JoinError>> = {
12664        let thread_count = join_parallel_thread_count();
12665        if specs.len() > 1 && n_out >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
12666            let mut slots: Vec<Option<Result<Column, JoinError>>> =
12667                (0..specs.len()).map(|_| None).collect();
12668            let chunk = specs.len().div_ceil(thread_count).max(1);
12669            let build_one = &build_one;
12670            std::thread::scope(|scope| {
12671                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
12672                    scope.spawn(move || {
12673                        for ((_, task), slot) in spec_chunk.iter().zip(slot_chunk) {
12674                            *slot = Some(build_one(task));
12675                        }
12676                    });
12677                }
12678            });
12679            slots
12680                .into_iter()
12681                .map(|c| c.expect("every asof output column must be built"))
12682                .collect()
12683        } else {
12684            specs.iter().map(|(_, task)| build_one(task)).collect()
12685        }
12686    };
12687
12688    for ((output_name, _), column) in specs.into_iter().zip(built) {
12689        insert_merged_output_column(&mut out_columns, &mut column_order, output_name, column?)?;
12690    }
12691
12692    Ok(MergedDataFrame {
12693        index: left.index().clone(),
12694        columns: out_columns,
12695        column_order,
12696    })
12697}
12698
12699impl DataFrameMergeExt for fp_frame::DataFrame {
12700    fn merge(
12701        &self,
12702        other: &fp_frame::DataFrame,
12703        on: &[&str],
12704        how: JoinType,
12705    ) -> Result<MergedDataFrame, JoinError> {
12706        merge_dataframes_on(self, other, on, how)
12707    }
12708
12709    fn merge_with_options(
12710        &self,
12711        other: &fp_frame::DataFrame,
12712        left_on: &[&str],
12713        right_on: &[&str],
12714        how: JoinType,
12715        options: MergeExecutionOptions,
12716    ) -> Result<MergedDataFrame, JoinError> {
12717        merge_dataframes_on_with_options(self, other, left_on, right_on, how, options)
12718    }
12719
12720    fn join_on_index(
12721        &self,
12722        other: &fp_frame::DataFrame,
12723        how: JoinType,
12724    ) -> Result<MergedDataFrame, JoinError> {
12725        let left = self.reset_index(false)?;
12726        let right = other.reset_index(false)?;
12727        merge_dataframes_on(&left, &right, &["index"], how)
12728    }
12729
12730    fn merge_asof(
12731        &self,
12732        other: &fp_frame::DataFrame,
12733        on: &str,
12734        direction: &str,
12735    ) -> Result<MergedDataFrame, JoinError> {
12736        self.merge_asof_with_options(other, on, direction, MergeAsofOptions::new())
12737    }
12738
12739    fn merge_asof_with_options(
12740        &self,
12741        other: &fp_frame::DataFrame,
12742        on: &str,
12743        direction: &str,
12744        options: MergeAsofOptions,
12745    ) -> Result<MergedDataFrame, JoinError> {
12746        let dir = match direction {
12747            "backward" => AsofDirection::Backward,
12748            "forward" => AsofDirection::Forward,
12749            "nearest" => AsofDirection::Nearest,
12750            _ => {
12751                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
12752                    format!("merge_asof: invalid direction '{direction}'"),
12753                )));
12754            }
12755        };
12756        crate::merge_asof_with_options(self, other, on, dir, options)
12757    }
12758
12759    fn merge_ordered(
12760        &self,
12761        other: &fp_frame::DataFrame,
12762        on: &[&str],
12763        fill_method: Option<&str>,
12764    ) -> Result<MergedDataFrame, JoinError> {
12765        crate::merge_ordered(self, other, on, fill_method)
12766    }
12767}
12768
12769#[cfg(test)]
12770mod tests {
12771    use fp_columnar::{Column, ValidityMask};
12772    use fp_frame::{ColumnStore, Series};
12773    use fp_index::{Index, IndexLabel};
12774    use fp_types::{DType, NullKind, Scalar};
12775
12776    use super::{
12777        DataFrameMergeExt, DenseI64InnerOutputPlan, DenseI64LaneData, FusedInt64OutputColumn,
12778        FusedInt64Side, InnerPositionPlan, JoinExecutionOptions, JoinType, PositionSelection,
12779        ResolvedMergeSuffixes, build_dense_i64_inner_output_data,
12780        build_single_key_dense_cycle_i64_left_merge_output,
12781        build_single_key_dense_i64_left_merge_output,
12782        build_single_key_dense_i64_right_merge_output,
12783        build_single_key_inner_contiguous_no_overlap_output, dense_int64_outer_positions,
12784        join_series, join_series_with_options, join_series_with_trace,
12785        lower_hex_overlap_plan_from_certificates, ordered_unique_int64_outer_positions,
12786        ordered_unique_utf8_inner_position_plan, ordered_unique_utf8_inner_positions,
12787        ordered_utf8_lower_hex_overlap_len, scalar_utf8_left_positions,
12788        scalar_utf8_outer_positions, sorted_contiguous_utf8_inner_positions,
12789        strictly_increasing_utf8_key_spans, utf8_span_lower_bound,
12790    };
12791
12792    fn contiguous_utf8_column(values: &[&str]) -> Column {
12793        let mut bytes = Vec::new();
12794        let mut offsets = Vec::with_capacity(values.len() + 1);
12795        offsets.push(0);
12796        for value in values {
12797            bytes.extend_from_slice(value.as_bytes());
12798            offsets.push(bytes.len());
12799        }
12800        Column::from_utf8_contiguous(bytes, offsets)
12801    }
12802
12803    fn utf8_key_merge_frame(keys: &[&str], value_name: &str, base: i64) -> DataFrame {
12804        let index = Index::new(
12805            (0..keys.len())
12806                .map(|row| IndexLabel::Int64(row as i64))
12807                .collect(),
12808        );
12809        let mut columns = ColumnStore::new();
12810        columns.insert("id".to_owned(), contiguous_utf8_column(keys));
12811        columns.insert(
12812            value_name.to_owned(),
12813            Column::from_i64_values((0..keys.len()).map(|row| base + row as i64).collect()),
12814        );
12815        DataFrame::new_with_column_order(
12816            index,
12817            columns,
12818            vec!["id".to_owned(), value_name.to_owned()],
12819        )
12820        .expect("utf8 key frame")
12821    }
12822
12823    fn scalar_utf8_column(values: &[&str]) -> Column {
12824        Column::from_values(
12825            values
12826                .iter()
12827                .map(|value| Scalar::Utf8((*value).to_owned()))
12828                .collect(),
12829        )
12830        .expect("scalar utf8 column")
12831    }
12832
12833    #[test]
12834    fn scalar_utf8_left_positions_preserve_duplicate_order_blackthrush() {
12835        let left = scalar_utf8_column(&["b", "a", "b", "x"]);
12836        let right = scalar_utf8_column(&["a", "b", "b"]);
12837
12838        let (left_positions, right_positions) =
12839            scalar_utf8_left_positions(&left, &right).expect("scalar utf8 left positions");
12840
12841        assert_eq!(
12842            left_positions,
12843            vec![Some(0), Some(0), Some(1), Some(2), Some(2), Some(3)]
12844        );
12845        assert_eq!(
12846            right_positions,
12847            vec![Some(1), Some(2), Some(0), Some(1), Some(2), None]
12848        );
12849    }
12850
12851    #[test]
12852    fn scalar_utf8_outer_positions_sort_keys_and_keep_unmatched_blackthrush() {
12853        let left = scalar_utf8_column(&["b", "a", "b", "x"]);
12854        let right = scalar_utf8_column(&["a", "b", "b", "z"]);
12855
12856        let (left_positions, right_positions) =
12857            scalar_utf8_outer_positions(&left, &right).expect("scalar utf8 outer positions");
12858
12859        assert_eq!(
12860            left_positions,
12861            vec![Some(1), Some(0), Some(0), Some(2), Some(2), Some(3), None,]
12862        );
12863        assert_eq!(
12864            right_positions,
12865            vec![Some(0), Some(1), Some(2), Some(1), Some(2), None, Some(3),]
12866        );
12867    }
12868
12869    #[test]
12870    fn dense_outer_positions_group_repeated_keys_e186m() {
12871        // Each side's rows grouped by key in one counting pass: keys
12872        // ascending, a key's left rows in order, each with its right rows
12873        // in order, a one-sided key with None opposite (br-frankenpandas-e186m).
12874        let left = Column::from_i64_values(vec![3, 1, 3, 2]);
12875        let right = Column::from_i64_values(vec![1, 3, 3, 5]);
12876        let (left_positions, right_positions) =
12877            dense_int64_outer_positions(&left, &right).expect("dense outer positions");
12878        assert_eq!(
12879            left_positions,
12880            vec![Some(1), Some(3), Some(0), Some(0), Some(2), Some(2), None]
12881        );
12882        assert_eq!(
12883            right_positions,
12884            vec![Some(0), None, Some(1), Some(2), Some(1), Some(2), Some(3)]
12885        );
12886        // A key holding a missing value, or keys spread past the dense table,
12887        // decline (NEGATIVE).
12888        let gappy = Column::new(
12889            DType::Int64,
12890            vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)],
12891        )
12892        .expect("int column with a gap");
12893        assert!(dense_int64_outer_positions(&gappy, &right).is_none());
12894        let sparse = Column::from_i64_values(vec![0, 1_000_000_000, 0]);
12895        assert!(dense_int64_outer_positions(&sparse, &right).is_none());
12896    }
12897
12898    #[test]
12899    fn inner_join_multiplies_cardinality_for_duplicates() {
12900        let left = Series::from_values(
12901            "left",
12902            vec!["k".into(), "k".into(), "x".into()],
12903            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12904        )
12905        .expect("left");
12906
12907        let right = Series::from_values(
12908            "right",
12909            vec!["k".into(), "k".into()],
12910            vec![Scalar::Int64(10), Scalar::Int64(20)],
12911        )
12912        .expect("right");
12913
12914        let out = join_series(&left, &right, JoinType::Inner).expect("join");
12915        assert_eq!(out.index.labels().len(), 4);
12916        assert_eq!(
12917            out.left_values.values(),
12918            &[
12919                Scalar::Int64(1),
12920                Scalar::Int64(1),
12921                Scalar::Int64(2),
12922                Scalar::Int64(2)
12923            ]
12924        );
12925    }
12926
12927    #[test]
12928    fn left_join_injects_missing_for_unmatched_right_rows() {
12929        let left = Series::from_values(
12930            "left",
12931            vec!["a".into(), "b".into()],
12932            vec![Scalar::Int64(1), Scalar::Int64(2)],
12933        )
12934        .expect("left");
12935        let right =
12936            Series::from_values("right", vec!["a".into()], vec![Scalar::Int64(10)]).expect("right");
12937
12938        let out = join_series(&left, &right, JoinType::Left).expect("join");
12939        // The right side gains a gap, so pandas widens it to float64 and the
12940        // gap is a NaN — on a LEFT join exactly as on an outer one. MEASURED,
12941        // live pandas 2.2.3, l=[10,20,30]@[1,2,3] joined with r=[200]@[2]:
12942        //   how='left'  -> l int64 [10,20,30]   r float64 [nan, 200.0, nan]
12943        //   how='outer' -> same
12944        // This assertion previously pinned Int64 + Null(Null), which was
12945        // FrankenPandas' own pre-fix answer. (br-frankenpandas-nywa8)
12946        assert_eq!(
12947            out.right_values.values(),
12948            &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
12949        );
12950    }
12951
12952    #[test]
12953    fn arena_join_matches_global_allocator_behavior() {
12954        let left = Series::from_values(
12955            "left",
12956            vec!["k".into(), "k".into(), "x".into()],
12957            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12958        )
12959        .expect("left");
12960
12961        let right = Series::from_values(
12962            "right",
12963            vec!["k".into(), "k".into()],
12964            vec![Scalar::Int64(10), Scalar::Int64(20)],
12965        )
12966        .expect("right");
12967
12968        let global = join_series_with_options(
12969            &left,
12970            &right,
12971            JoinType::Inner,
12972            JoinExecutionOptions {
12973                use_arena: false,
12974                arena_budget_bytes: 0,
12975            },
12976        )
12977        .expect("global join");
12978
12979        let arena = join_series_with_options(
12980            &left,
12981            &right,
12982            JoinType::Inner,
12983            JoinExecutionOptions::default(),
12984        )
12985        .expect("arena join");
12986
12987        assert_eq!(arena, global);
12988    }
12989
12990    #[test]
12991    fn arena_join_falls_back_when_budget_is_too_small() {
12992        let left = Series::from_values(
12993            "left",
12994            vec!["a".into(), "a".into(), "a".into()],
12995            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12996        )
12997        .expect("left");
12998        let right = Series::from_values(
12999            "right",
13000            vec!["a".into(), "a".into()],
13001            vec![Scalar::Int64(10), Scalar::Int64(20)],
13002        )
13003        .expect("right");
13004
13005        let options = JoinExecutionOptions {
13006            use_arena: true,
13007            arena_budget_bytes: 1,
13008        };
13009        let (fallback_out, trace) =
13010            join_series_with_trace(&left, &right, JoinType::Inner, options).expect("fallback join");
13011        let global_out = join_series_with_options(
13012            &left,
13013            &right,
13014            JoinType::Inner,
13015            JoinExecutionOptions {
13016                use_arena: false,
13017                arena_budget_bytes: 0,
13018            },
13019        )
13020        .expect("global join");
13021
13022        assert_eq!(fallback_out, global_out);
13023        assert!(!trace.used_arena);
13024        assert!(trace.estimated_bytes > options.arena_budget_bytes);
13025    }
13026
13027    #[test]
13028    fn arena_join_is_stable_across_many_small_operations() {
13029        let left = Series::from_values(
13030            "left",
13031            vec!["a".into(), "b".into()],
13032            vec![Scalar::Int64(1), Scalar::Int64(2)],
13033        )
13034        .expect("left");
13035        let right = Series::from_values(
13036            "right",
13037            vec!["a".into(), "b".into()],
13038            vec![Scalar::Int64(10), Scalar::Int64(20)],
13039        )
13040        .expect("right");
13041
13042        let options = JoinExecutionOptions::default();
13043        for _ in 0..1_000 {
13044            let out = join_series_with_options(&left, &right, JoinType::Inner, options)
13045                .expect("arena join");
13046            assert_eq!(out.index.labels().len(), 2);
13047            assert_eq!(
13048                out.right_values.values(),
13049                &[Scalar::Int64(10), Scalar::Int64(20)]
13050            );
13051        }
13052    }
13053
13054    /// AG-06-T test #8: 100K-row inner join with arena -> correct output, no OOM.
13055    #[test]
13056    fn arena_large_join_100k_rows() {
13057        let n = 100_000;
13058        let labels: Vec<IndexLabel> = (0..n).map(|i| IndexLabel::Int64(i as i64 % 1000)).collect();
13059        let values: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
13060
13061        let left = Series::from_values("left", labels.clone(), values.clone()).expect("left");
13062        let right = Series::from_values("right", labels, values).expect("right");
13063
13064        let out = join_series_with_options(
13065            &left,
13066            &right,
13067            JoinType::Inner,
13068            JoinExecutionOptions::default(),
13069        )
13070        .expect("100K arena join");
13071
13072        // With 1000 distinct keys, each appearing 100 times on each side,
13073        // inner join produces 100 * 100 * 1000 = 10M rows.
13074        // But that's too large; use a budget that forces fallback.
13075        let out_fallback = join_series_with_options(
13076            &left,
13077            &right,
13078            JoinType::Inner,
13079            JoinExecutionOptions {
13080                use_arena: true,
13081                arena_budget_bytes: 1,
13082            },
13083        )
13084        .expect("100K fallback join");
13085
13086        assert_eq!(out.index.labels().len(), out_fallback.index.labels().len());
13087    }
13088
13089    #[test]
13090    fn right_join_contains_all_right_labels() {
13091        let left = Series::from_values(
13092            "left",
13093            vec!["a".into(), "b".into()],
13094            vec![Scalar::Int64(1), Scalar::Int64(2)],
13095        )
13096        .expect("left");
13097        let right = Series::from_values(
13098            "right",
13099            vec!["b".into(), "c".into()],
13100            vec![Scalar::Int64(20), Scalar::Int64(30)],
13101        )
13102        .expect("right");
13103
13104        let out = join_series(&left, &right, JoinType::Right).expect("join");
13105        // Right join: all right labels preserved. "b" matches, "c" unmatched.
13106        assert_eq!(out.index.labels().len(), 2);
13107        assert_eq!(
13108            out.index.labels(),
13109            &[IndexLabel::Utf8("b".into()), IndexLabel::Utf8("c".into())]
13110        );
13111        // "b" matched -> left=2, right=20. "c" unmatched -> left is a gap, so
13112        // the LEFT lane widens to float64 with a NaN (br-frankenpandas-nywa8;
13113        // the widening follows the invented gap, not the join type).
13114        assert_eq!(
13115            out.left_values.values(),
13116            &[Scalar::Float64(2.0), Scalar::Null(NullKind::NaN)]
13117        );
13118        assert_eq!(
13119            out.right_values.values(),
13120            &[Scalar::Int64(20), Scalar::Int64(30)]
13121        );
13122    }
13123
13124    #[test]
13125    fn right_join_multiplies_cardinality_for_duplicates() {
13126        let left = Series::from_values(
13127            "left",
13128            vec!["k".into(), "k".into()],
13129            vec![Scalar::Int64(1), Scalar::Int64(2)],
13130        )
13131        .expect("left");
13132        let right = Series::from_values(
13133            "right",
13134            vec!["k".into(), "x".into()],
13135            vec![Scalar::Int64(10), Scalar::Int64(30)],
13136        )
13137        .expect("right");
13138
13139        let out = join_series(&left, &right, JoinType::Right).expect("join");
13140        // "k" in right matches 2 left rows -> 2 output rows for "k", plus 1 for "x" unmatched.
13141        assert_eq!(out.index.labels().len(), 3);
13142        assert_eq!(
13143            out.right_values.values(),
13144            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(30)]
13145        );
13146    }
13147
13148    #[test]
13149    fn outer_join_contains_all_labels_from_both_sides() {
13150        let left = Series::from_values(
13151            "left",
13152            vec!["a".into(), "b".into()],
13153            vec![Scalar::Int64(1), Scalar::Int64(2)],
13154        )
13155        .expect("left");
13156        let right = Series::from_values(
13157            "right",
13158            vec!["b".into(), "c".into()],
13159            vec![Scalar::Int64(20), Scalar::Int64(30)],
13160        )
13161        .expect("right");
13162
13163        let out = join_series(&left, &right, JoinType::Outer).expect("join");
13164        // Outer: "a" (left only), "b" (both), "c" (right only) -> 3 rows
13165        assert_eq!(out.index.labels().len(), 3);
13166        assert_eq!(
13167            out.left_values.values(),
13168            &[
13169                Scalar::Float64(1.0),
13170                Scalar::Float64(2.0),
13171                Scalar::Null(NullKind::NaN)
13172            ]
13173        );
13174        assert_eq!(
13175            out.right_values.values(),
13176            &[
13177                Scalar::Null(NullKind::NaN),
13178                Scalar::Float64(20.0),
13179                Scalar::Float64(30.0)
13180            ]
13181        );
13182    }
13183
13184    #[test]
13185    fn outer_join_sorts_union_labels_like_pandas() {
13186        let left = Series::from_values(
13187            "left",
13188            vec!["a".into(), "c".into()],
13189            vec![Scalar::Int64(1), Scalar::Int64(3)],
13190        )
13191        .expect("left");
13192        let right = Series::from_values(
13193            "right",
13194            vec!["b".into(), "c".into()],
13195            vec![Scalar::Int64(20), Scalar::Int64(30)],
13196        )
13197        .expect("right");
13198
13199        let out = join_series(&left, &right, JoinType::Outer).expect("join");
13200        assert_eq!(
13201            out.index.labels(),
13202            &[
13203                IndexLabel::Utf8("a".into()),
13204                IndexLabel::Utf8("b".into()),
13205                IndexLabel::Utf8("c".into())
13206            ]
13207        );
13208        assert_eq!(
13209            out.left_values.values(),
13210            &[
13211                Scalar::Float64(1.0),
13212                Scalar::Null(NullKind::NaN),
13213                Scalar::Float64(3.0)
13214            ]
13215        );
13216        assert_eq!(
13217            out.right_values.values(),
13218            &[
13219                Scalar::Null(NullKind::NaN),
13220                Scalar::Float64(20.0),
13221                Scalar::Float64(30.0)
13222            ]
13223        );
13224    }
13225
13226    #[test]
13227    fn outer_join_with_duplicates() {
13228        let left = Series::from_values(
13229            "left",
13230            vec!["k".into(), "k".into(), "a".into()],
13231            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13232        )
13233        .expect("left");
13234        let right = Series::from_values(
13235            "right",
13236            vec!["k".into(), "z".into()],
13237            vec![Scalar::Int64(10), Scalar::Int64(99)],
13238        )
13239        .expect("right");
13240
13241        let out = join_series(&left, &right, JoinType::Outer).expect("join");
13242        // "k" x "k": 2 matched rows. "a": left-only (1 row). "z": right-only (1 row).
13243        assert_eq!(out.index.labels().len(), 4);
13244    }
13245
13246    #[test]
13247    fn arena_right_join_matches_global() {
13248        let left = Series::from_values(
13249            "left",
13250            vec!["a".into(), "b".into()],
13251            vec![Scalar::Int64(1), Scalar::Int64(2)],
13252        )
13253        .expect("left");
13254        let right = Series::from_values(
13255            "right",
13256            vec!["b".into(), "c".into()],
13257            vec![Scalar::Int64(20), Scalar::Int64(30)],
13258        )
13259        .expect("right");
13260
13261        let global = join_series_with_options(
13262            &left,
13263            &right,
13264            JoinType::Right,
13265            JoinExecutionOptions {
13266                use_arena: false,
13267                arena_budget_bytes: 0,
13268            },
13269        )
13270        .expect("global");
13271        let arena = join_series_with_options(
13272            &left,
13273            &right,
13274            JoinType::Right,
13275            JoinExecutionOptions::default(),
13276        )
13277        .expect("arena");
13278        assert_eq!(arena, global);
13279    }
13280
13281    #[test]
13282    fn arena_outer_join_matches_global() {
13283        let left = Series::from_values(
13284            "left",
13285            vec!["a".into(), "b".into()],
13286            vec![Scalar::Int64(1), Scalar::Int64(2)],
13287        )
13288        .expect("left");
13289        let right = Series::from_values(
13290            "right",
13291            vec!["b".into(), "c".into()],
13292            vec![Scalar::Int64(20), Scalar::Int64(30)],
13293        )
13294        .expect("right");
13295
13296        let global = join_series_with_options(
13297            &left,
13298            &right,
13299            JoinType::Outer,
13300            JoinExecutionOptions {
13301                use_arena: false,
13302                arena_budget_bytes: 0,
13303            },
13304        )
13305        .expect("global");
13306        let arena = join_series_with_options(
13307            &left,
13308            &right,
13309            JoinType::Outer,
13310            JoinExecutionOptions::default(),
13311        )
13312        .expect("arena");
13313        assert_eq!(arena, global);
13314    }
13315
13316    /// AG-06-T test #6: arena is scoped per-operation. Two sequential
13317    /// operations each get their own arena (verified by both succeeding).
13318    #[test]
13319    fn arena_reset_between_operations() {
13320        let left = Series::from_values(
13321            "left",
13322            vec!["a".into(), "b".into()],
13323            vec![Scalar::Int64(1), Scalar::Int64(2)],
13324        )
13325        .expect("left");
13326        let right = Series::from_values(
13327            "right",
13328            vec!["a".into(), "c".into()],
13329            vec![Scalar::Int64(10), Scalar::Int64(30)],
13330        )
13331        .expect("right");
13332
13333        // Operation 1: inner join
13334        let out1 = join_series_with_options(
13335            &left,
13336            &right,
13337            JoinType::Inner,
13338            JoinExecutionOptions::default(),
13339        )
13340        .expect("op1");
13341        assert_eq!(out1.index.labels().len(), 1);
13342
13343        // Operation 2: left join (arena from op1 was freed)
13344        let out2 = join_series_with_options(
13345            &left,
13346            &right,
13347            JoinType::Left,
13348            JoinExecutionOptions::default(),
13349        )
13350        .expect("op2");
13351        assert_eq!(out2.index.labels().len(), 2);
13352    }
13353
13354    // ---- DataFrame merge tests (bd-2gi.17) ----
13355
13356    use fp_frame::{DataFrame, FrameError};
13357
13358    use super::{
13359        JoinError, MergeExecutionOptions, MergeValidateMode, MergedDataFrame,
13360        build_single_key_dense_right_merge_output, dense_int64_right_positions, merge_dataframes,
13361        merge_dataframes_on, merge_dataframes_on_with, merge_dataframes_on_with_options,
13362        ordered_identity_int64_keys_match, resolve_merge_suffixes,
13363    };
13364
13365    fn make_left_df() -> DataFrame {
13366        DataFrame::from_dict(
13367            &["id", "val_a"],
13368            vec![
13369                (
13370                    "id",
13371                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13372                ),
13373                (
13374                    "val_a",
13375                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
13376                ),
13377            ],
13378        )
13379        .unwrap()
13380    }
13381
13382    fn make_right_df() -> DataFrame {
13383        DataFrame::from_dict(
13384            &["id", "val_b"],
13385            vec![
13386                (
13387                    "id",
13388                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
13389                ),
13390                (
13391                    "val_b",
13392                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
13393                ),
13394            ],
13395        )
13396        .unwrap()
13397    }
13398
13399    #[test]
13400    fn merge_preserves_pandas_column_order_for_nonalphabetical_names() {
13401        // br-frankenpandas-691lh: output columns follow pandas order — key/left
13402        // columns in the LEFT frame's source order, then right non-key columns —
13403        // not alphabetical (the columns map is a BTreeMap). Verified vs pandas
13404        // 2.2.3: merge(left[k,zebra,apple], right[k,mango], on=k)
13405        //   -> [k, zebra, apple, mango].
13406        let left = DataFrame::from_dict(
13407            &["k", "zebra", "apple"],
13408            vec![
13409                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13410                ("zebra", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13411                ("apple", vec![Scalar::Int64(30), Scalar::Int64(40)]),
13412            ],
13413        )
13414        .unwrap();
13415        let right = DataFrame::from_dict(
13416            &["k", "mango"],
13417            vec![
13418                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13419                ("mango", vec![Scalar::Int64(50), Scalar::Int64(60)]),
13420            ],
13421        )
13422        .unwrap();
13423        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
13424        let order: Vec<&str> = merged.column_order.iter().map(String::as_str).collect();
13425        assert_eq!(order, ["k", "zebra", "apple", "mango"]);
13426    }
13427
13428    #[test]
13429    fn merge_outer_gap_widens_int64_and_keeps_int64_nullable_4qg5w_11() {
13430        // DISC-011's merge row (pandas 2.2.3): the row an outer merge invents
13431        // is float64 NaN in a numpy int64 column and NA in a nullable Int64.
13432        let frame = |key: &str, keys: &[i64], name: &str, dtype: DType, values: &[i64]| {
13433            let ints = |xs: &[i64]| xs.iter().map(|x| Scalar::Int64(*x)).collect::<Vec<_>>();
13434            let labels = (0..keys.len() as i64).map(IndexLabel::Int64).collect();
13435            let columns = std::collections::BTreeMap::from([
13436                (
13437                    key.to_owned(),
13438                    Column::new(DType::Int64, ints(keys)).unwrap(),
13439                ),
13440                (name.to_owned(), Column::new(dtype, ints(values)).unwrap()),
13441            ]);
13442            DataFrame::new_with_column_order(
13443                Index::new(labels),
13444                columns,
13445                vec![key.to_owned(), name.to_owned()],
13446            )
13447            .unwrap()
13448        };
13449        for (dtype, widened) in [
13450            (DType::Int64, DType::Float64),
13451            (DType::Int64Nullable, DType::Int64Nullable),
13452        ] {
13453            let left = frame("k", &[1, 2], "v", dtype.clone(), &[7, 8]);
13454            let right = frame("k", &[2, 3], "w", dtype.clone(), &[5, 6]);
13455            let merged = merge_dataframes(&left, &right, "k", JoinType::Outer).unwrap();
13456            let v = merged.columns.get("v").unwrap();
13457            assert_eq!(v.dtype(), widened, "{dtype:?}");
13458            match widened {
13459                DType::Float64 => {
13460                    assert_eq!(v.values()[0], Scalar::Float64(7.0));
13461                    assert_eq!(v.values()[2], Scalar::Null(NullKind::NaN));
13462                }
13463                _ => {
13464                    assert_eq!(v.values()[0], Scalar::Int64(7));
13465                    assert!(v.values()[2].is_missing(), "{dtype:?}: {:?}", v.values());
13466                }
13467            }
13468        }
13469    }
13470
13471    #[test]
13472    fn join_row_count_lattice_n8npw() {
13473        // Invariant (br-frankenpandas-n8npw): inner<=left<=outer and inner<=right<=outer
13474        // by row count. Seeded LCG, no mocks.
13475        let mut s: u64 = 0x4e57_0b1c_2d3e_4f55;
13476        let mut next = || {
13477            s = s
13478                .wrapping_mul(6_364_136_223_846_793_005)
13479                .wrapping_add(1_442_695_040_888_963_407);
13480            (s >> 33) as u32
13481        };
13482        for iter in 0..300u32 {
13483            let ln = (next() % 6) as usize + 1;
13484            let rn = (next() % 6) as usize + 1;
13485            let lk: Vec<Scalar> = (0..ln)
13486                .map(|_| Scalar::Int64((next() % 4) as i64))
13487                .collect();
13488            let rk: Vec<Scalar> = (0..rn)
13489                .map(|_| Scalar::Int64((next() % 4) as i64))
13490                .collect();
13491            let left = DataFrame::from_dict(
13492                &["k", "lv"],
13493                vec![
13494                    ("k", lk),
13495                    ("lv", (0..ln).map(|i| Scalar::Int64(i as i64)).collect()),
13496                ],
13497            )
13498            .unwrap();
13499            let right = DataFrame::from_dict(
13500                &["k", "rv"],
13501                vec![
13502                    ("k", rk),
13503                    ("rv", (0..rn).map(|i| Scalar::Int64(i as i64)).collect()),
13504                ],
13505            )
13506            .unwrap();
13507            let rows = |jt| {
13508                let m = merge_dataframes(&left, &right, "k", jt).unwrap();
13509                merged_values(&m, "k").unwrap().len()
13510            };
13511            let inner = rows(JoinType::Inner);
13512            let lj = rows(JoinType::Left);
13513            let rj = rows(JoinType::Right);
13514            let outer = rows(JoinType::Outer);
13515            assert!(
13516                inner <= lj && lj <= outer,
13517                "inner<=left<=outer iter={iter}: {inner} {lj} {outer}"
13518            );
13519            assert!(
13520                inner <= rj && rj <= outer,
13521                "inner<=right<=outer iter={iter}: {inner} {rj} {outer}"
13522            );
13523        }
13524    }
13525
13526    #[test]
13527    fn right_join_null_fill_multiset_7je8m() {
13528        use std::collections::HashMap;
13529        // Differential (br-frankenpandas-7je8m): RIGHT join preserves every right row;
13530        // matched left payload cross-product else null. (key, lv-or-None, rv) multiset
13531        // vs oracle. Seeded LCG, no mocks.
13532        let mut s: u64 = 0x4e57_0b1c_2d3e_4f54;
13533        let mut next = || {
13534            s = s
13535                .wrapping_mul(6_364_136_223_846_793_005)
13536                .wrapping_add(1_442_695_040_888_963_407);
13537            (s >> 33) as u32
13538        };
13539        for iter in 0..300u32 {
13540            let ln = (next() % 6) as usize + 1;
13541            let rn = (next() % 6) as usize + 1;
13542            let lk: Vec<i64> = (0..ln).map(|_| (next() % 4) as i64).collect();
13543            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
13544            let rk: Vec<i64> = (0..rn).map(|_| (next() % 4) as i64).collect();
13545            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
13546            let left = DataFrame::from_dict(
13547                &["k", "lv"],
13548                vec![
13549                    ("k", lk.iter().map(|&x| Scalar::Int64(x)).collect()),
13550                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
13551                ],
13552            )
13553            .unwrap();
13554            let right = DataFrame::from_dict(
13555                &["k", "rv"],
13556                vec![
13557                    ("k", rk.iter().map(|&x| Scalar::Int64(x)).collect()),
13558                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
13559                ],
13560            )
13561            .unwrap();
13562            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).unwrap();
13563
13564            let ks = merged_values(&merged, "k").unwrap();
13565            let lvs = merged_values(&merged, "lv").unwrap();
13566            let rvs = merged_values(&merged, "rv").unwrap();
13567            let ki = |v: &Scalar| -> i64 {
13568                match v {
13569                    Scalar::Int64(x) => *x,
13570                    Scalar::Float64(x) => *x as i64,
13571                    _ => i64::MIN,
13572                }
13573            };
13574            let kopt =
13575                |v: &Scalar| -> Option<i64> { if v.is_missing() { None } else { Some(ki(v)) } };
13576            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
13577                .map(|i| (ki(&ks[i]), kopt(&lvs[i]), ki(&rvs[i])))
13578                .collect();
13579            // Oracle.
13580            let mut lby: HashMap<i64, Vec<i64>> = HashMap::new();
13581            for i in 0..ln {
13582                lby.entry(lk[i]).or_default().push(lv[i]);
13583            }
13584            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
13585            for i in 0..rn {
13586                match lby.get(&rk[i]) {
13587                    Some(lvals) => {
13588                        for &a in lvals {
13589                            exp.push((rk[i], Some(a), rv[i]));
13590                        }
13591                    }
13592                    None => exp.push((rk[i], None, rv[i])),
13593                }
13594            }
13595            got.sort();
13596            exp.sort();
13597            assert_eq!(got, exp, "right join multiset iter={iter}");
13598        }
13599    }
13600
13601    #[test]
13602    fn inner_join_utf8_value_multiset_fr4ns() {
13603        use std::collections::HashMap;
13604        // Differential (br-frankenpandas-fr4ns): inner join on Utf8 keys; the (key,
13605        // lv, rv) multiset == per-key cross-product (5foyp was int/dense; jlf8d a
13606        // single case). Seeded LCG, no mocks.
13607        let mut s: u64 = 0x4e57_0b1c_2d3e_4f51;
13608        let mut next = || {
13609            s = s
13610                .wrapping_mul(6_364_136_223_846_793_005)
13611                .wrapping_add(1_442_695_040_888_963_407);
13612            (s >> 33) as u32
13613        };
13614        let key = |n: u32| Scalar::Utf8(format!("{}", (b'a' + (n % 4) as u8) as char));
13615        for iter in 0..300u32 {
13616            let ln = (next() % 6) as usize + 1;
13617            let rn = (next() % 6) as usize + 1;
13618            let lk: Vec<Scalar> = (0..ln).map(|_| key(next())).collect();
13619            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
13620            let rk: Vec<Scalar> = (0..rn).map(|_| key(next())).collect();
13621            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
13622            let left = DataFrame::from_dict(
13623                &["k", "lv"],
13624                vec![
13625                    ("k", lk.clone()),
13626                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
13627                ],
13628            )
13629            .unwrap();
13630            let right = DataFrame::from_dict(
13631                &["k", "rv"],
13632                vec![
13633                    ("k", rk.clone()),
13634                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
13635                ],
13636            )
13637            .unwrap();
13638            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
13639
13640            let ks = merged_values(&merged, "k").unwrap();
13641            let lvs = merged_values(&merged, "lv").unwrap();
13642            let rvs = merged_values(&merged, "rv").unwrap();
13643            let kstr = |v: &Scalar| -> String {
13644                match v {
13645                    Scalar::Utf8(x) => x.clone(),
13646                    _ => String::new(),
13647                }
13648            };
13649            let ki = |v: &Scalar| -> i64 {
13650                match v {
13651                    Scalar::Int64(x) => *x,
13652                    _ => i64::MIN,
13653                }
13654            };
13655            let mut got: Vec<(String, i64, i64)> = (0..ks.len())
13656                .map(|i| (kstr(&ks[i]), ki(&lvs[i]), ki(&rvs[i])))
13657                .collect();
13658            // Oracle: per-key cross product.
13659            let mut lby: HashMap<String, Vec<i64>> = HashMap::new();
13660            for i in 0..ln {
13661                lby.entry(kstr(&lk[i])).or_default().push(lv[i]);
13662            }
13663            let mut rby: HashMap<String, Vec<i64>> = HashMap::new();
13664            for i in 0..rn {
13665                rby.entry(kstr(&rk[i])).or_default().push(rv[i]);
13666            }
13667            let mut exp: Vec<(String, i64, i64)> = Vec::new();
13668            for (k, lvals) in &lby {
13669                if let Some(rvals) = rby.get(k) {
13670                    for &a in lvals {
13671                        for &b in rvals {
13672                            exp.push((k.clone(), a, b));
13673                        }
13674                    }
13675                }
13676            }
13677            got.sort();
13678            exp.sort();
13679            assert_eq!(got, exp, "inner Utf8 multiset iter={iter}");
13680        }
13681    }
13682
13683    #[test]
13684    fn inner_join_utf8_keys_jlf8d() {
13685        use std::collections::HashMap;
13686        // br-frankenpandas-jlf8d: inner join on Utf8 keys (general/hash path).
13687        let s = |v: &str| Scalar::Utf8(v.to_owned());
13688        let left = DataFrame::from_dict(
13689            &["k", "lv"],
13690            vec![
13691                ("k", vec![s("a"), s("b"), s("c")]),
13692                (
13693                    "lv",
13694                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13695                ),
13696            ],
13697        )
13698        .expect("left");
13699        let right = DataFrame::from_dict(
13700            &["k", "rv"],
13701            vec![
13702                ("k", vec![s("b"), s("c"), s("d")]),
13703                (
13704                    "rv",
13705                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
13706                ),
13707            ],
13708        )
13709        .expect("right");
13710        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
13711
13712        let keys = merged_values(&merged, "k").expect("k");
13713        let lv = merged_values(&merged, "lv").expect("lv");
13714        let rv = merged_values(&merged, "rv").expect("rv");
13715        let exp_lv: HashMap<&str, i64> = [("b", 2), ("c", 3)].into_iter().collect();
13716        let exp_rv: HashMap<&str, i64> = [("b", 10), ("c", 20)].into_iter().collect();
13717        assert_eq!(keys.len(), 2, "inner keys = {{b,c}}");
13718        for i in 0..keys.len() {
13719            let k = match &keys[i] {
13720                Scalar::Utf8(x) => x.as_str(),
13721                _ => "?",
13722            };
13723            let geti = |s: &Scalar| match s {
13724                Scalar::Int64(v) => *v,
13725                _ => i64::MIN,
13726            };
13727            assert_eq!(geti(&lv[i]), exp_lv[k], "lv at {k}");
13728            assert_eq!(geti(&rv[i]), exp_rv[k], "rv at {k}");
13729        }
13730    }
13731
13732    #[test]
13733    fn merge_indicator_is_held_as_codes_fl3f0() {
13734        // br-frankenpandas-fl3f0: `_merge` is each row's code into the fixed
13735        // categories [left_only, right_only, both] (0 / 1 / 2), as pandas'
13736        // Categorical - a String a row was made into a Scalar-backed
13737        // categorical - and reads back as those categories. NEGATIVE: a row
13738        // in neither side would be missing (-1), never a category.
13739        let left_positions = [Some(0), Some(1), None, Some(2)];
13740        let right_positions = [None, Some(0), Some(1), Some(1)];
13741        let column = super::build_merge_indicator_column(&left_positions, &right_positions);
13742        assert_eq!(column.dtype(), fp_types::DType::Categorical);
13743        assert_eq!(column.categorical_codes(), Some(&[0, 2, 1, 2][..]));
13744        let categories: Vec<Scalar> = ["left_only", "right_only", "both"]
13745            .map(|category| Scalar::Utf8(category.to_owned()))
13746            .to_vec();
13747        assert_eq!(
13748            column.categorical().map(|meta| meta.categories.clone()),
13749            Some(categories)
13750        );
13751        let shown: Vec<Scalar> = ["left_only", "both", "right_only", "both"]
13752            .map(|value| Scalar::Utf8(value.to_owned()))
13753            .to_vec();
13754        assert_eq!(column.values(), shown.as_slice());
13755        let neither = super::build_merge_indicator_column(&[None], &[None]);
13756        assert_eq!(neither.categorical_codes(), Some(&[-1][..]));
13757        assert!(neither.values()[0].is_missing());
13758    }
13759
13760    #[test]
13761    fn merge_indicator_column_d3ec6() {
13762        use std::collections::BTreeSet;
13763        // br-frankenpandas-d3ec6: outer-join indicator marks left_only/both/right_only.
13764        let left = DataFrame::from_dict(
13765            &["k"],
13766            vec![(
13767                "k",
13768                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13769            )],
13770        )
13771        .expect("left");
13772        let right = DataFrame::from_dict(
13773            &["k"],
13774            vec![(
13775                "k",
13776                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
13777            )],
13778        )
13779        .expect("right");
13780        let opts = super::MergeExecutionOptions {
13781            indicator_name: Some("_merge".to_owned()),
13782            ..Default::default()
13783        };
13784        let m = super::merge_dataframes_on_with_options(
13785            &left,
13786            &right,
13787            &["k"],
13788            &["k"],
13789            JoinType::Outer,
13790            opts,
13791        )
13792        .expect("merge");
13793
13794        let keys = merged_values(&m, "k").expect("k");
13795        let ind = merged_values(&m, "_merge").expect("_merge present");
13796        let lset: BTreeSet<i64> = [1, 2, 3].into_iter().collect();
13797        let rset: BTreeSet<i64> = [2, 3, 4].into_iter().collect();
13798        assert_eq!(keys.len(), 4, "outer keys = union");
13799        for i in 0..keys.len() {
13800            let k = match &keys[i] {
13801                Scalar::Int64(v) => *v,
13802                _ => i64::MIN,
13803            };
13804            let exp = match (lset.contains(&k), rset.contains(&k)) {
13805                (true, true) => "both",
13806                (true, false) => "left_only",
13807                (false, true) => "right_only",
13808                (false, false) => "??",
13809            };
13810            assert_eq!(ind[i], Scalar::Utf8(exp.to_owned()), "indicator at key {k}");
13811        }
13812    }
13813
13814    #[test]
13815    fn merge_overlapping_columns_suffixed_vb10q() {
13816        // br-frankenpandas-vb10q: a non-key column present in both frames is
13817        // suffixed _x (left) / _y (right) on merge.
13818        let mk = |vfactor: i64| {
13819            DataFrame::from_dict(
13820                &["k", "v"],
13821                vec![
13822                    (
13823                        "k",
13824                        vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13825                    ),
13826                    (
13827                        "v",
13828                        vec![
13829                            Scalar::Int64(vfactor),
13830                            Scalar::Int64(2 * vfactor),
13831                            Scalar::Int64(3 * vfactor),
13832                        ],
13833                    ),
13834                ],
13835            )
13836            .expect("frame")
13837        };
13838        let left = mk(10); // v = k*10
13839        let right = mk(100); // v = k*100
13840        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
13841
13842        let keys = merged_values(&merged, "k").expect("k");
13843        let vx = merged_values(&merged, "v_x").expect("v_x present");
13844        let vy = merged_values(&merged, "v_y").expect("v_y present");
13845        assert_eq!(keys.len(), 3);
13846        for i in 0..keys.len() {
13847            let k = match &keys[i] {
13848                Scalar::Int64(x) => *x,
13849                _ => i64::MIN,
13850            };
13851            assert_eq!(vx[i], Scalar::Int64(k * 10), "v_x at key {k}");
13852            assert_eq!(vy[i], Scalar::Int64(k * 100), "v_y at key {k}");
13853        }
13854    }
13855
13856    #[test]
13857    fn int64_join_row_count_matches_cardinality_invariant_ya1po() {
13858        use std::collections::BTreeMap;
13859
13860        // Metamorphic harness (br-frankenpandas-ya1po): merge_dataframes row count
13861        // must equal the pandas-standard cardinality per join type — an
13862        // ordering-independent invariant guarding the dense/direct-address Int64
13863        // join fast paths. Deterministic seeded LCG — no rand crate, no mocks.
13864        let mut state: u64 = 0xa5a5_5a5a_dead_beef;
13865        let mut next = || {
13866            state = state
13867                .wrapping_mul(6_364_136_223_846_793_005)
13868                .wrapping_add(1_442_695_040_888_963_407);
13869            (state >> 33) as u32
13870        };
13871
13872        let build = |keys: &[i64], payload_name: &str| {
13873            let n = keys.len();
13874            DataFrame::from_dict(
13875                &["k", payload_name],
13876                vec![
13877                    (
13878                        "k",
13879                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13880                    ),
13881                    (
13882                        payload_name,
13883                        (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>(),
13884                    ),
13885                ],
13886            )
13887            .expect("frame")
13888        };
13889
13890        for iter in 0..1500u32 {
13891            let nl = (next() % 9) as usize + 1;
13892            let nr = (next() % 9) as usize + 1;
13893            // Small key range so many-to-many (duplicate-key) joins are common.
13894            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
13895            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
13896            let left = build(&lk, "lv");
13897            let right = build(&rk, "rv");
13898
13899            let mut lc: BTreeMap<i64, i64> = BTreeMap::new();
13900            let mut rc: BTreeMap<i64, i64> = BTreeMap::new();
13901            for &k in &lk {
13902                *lc.entry(k).or_default() += 1;
13903            }
13904            for &k in &rk {
13905                *rc.entry(k).or_default() += 1;
13906            }
13907            let mut all_keys: Vec<i64> = lc.keys().chain(rc.keys()).copied().collect();
13908            all_keys.sort_unstable();
13909            all_keys.dedup();
13910
13911            let g = |k: i64, m: &BTreeMap<i64, i64>| m.get(&k).copied().unwrap_or(0);
13912            let inner: i64 = all_keys.iter().map(|&k| g(k, &lc) * g(k, &rc)).sum();
13913            let left_exp: i64 = lc.iter().map(|(&k, &l)| l * g(k, &rc).max(1)).sum();
13914            let right_exp: i64 = rc.iter().map(|(&k, &r)| r * g(k, &lc).max(1)).sum();
13915            let outer: i64 = all_keys
13916                .iter()
13917                .map(|&k| {
13918                    let (l, r) = (g(k, &lc), g(k, &rc));
13919                    if l > 0 && r > 0 { l * r } else { l + r }
13920                })
13921                .sum();
13922
13923            let ctx = format!("iter={iter} lk={lk:?} rk={rk:?}");
13924            for (jt, exp) in [
13925                (JoinType::Inner, inner),
13926                (JoinType::Left, left_exp),
13927                (JoinType::Right, right_exp),
13928                (JoinType::Outer, outer),
13929            ] {
13930                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
13931                let rows = merged_values(&merged, "k").expect("key col").len() as i64;
13932                assert_eq!(rows, exp, "{jt:?} row count {ctx}");
13933            }
13934        }
13935    }
13936
13937    #[test]
13938    fn inner_join_value_multiset_matches_crossproduct_oracle_5foyp() {
13939        use std::collections::BTreeMap;
13940
13941        // Value-level oracle (br-frankenpandas-5foyp): an inner join must pair the
13942        // CORRECT rows, not merely produce the right count. Assert the multiset of
13943        // output (key, left_payload, right_payload) triples equals the
13944        // independently-computed per-key cross product. Ordering-independent
13945        // (sorted-vector compare). Deterministic seeded LCG — no rand, no mocks.
13946        let mut state: u64 = 0x0ddc_0ffe_e0dd_f00d;
13947        let mut next = || {
13948            state = state
13949                .wrapping_mul(6_364_136_223_846_793_005)
13950                .wrapping_add(1_442_695_040_888_963_407);
13951            (state >> 33) as u32
13952        };
13953
13954        let build = |keys: &[i64], pname: &str| {
13955            let n = keys.len();
13956            DataFrame::from_dict(
13957                &["k", pname],
13958                vec![
13959                    (
13960                        "k",
13961                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13962                    ),
13963                    // Distinct per-row payload (= row index) so mis-pairings are visible.
13964                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
13965                ],
13966            )
13967            .expect("frame")
13968        };
13969        // Extract i64; a non-Int64 maps to a sentinel that will never equal a
13970        // real row index/key, so any dtype regression still fails the multiset
13971        // assert below (no panic — keeps the helper side-effect-free).
13972        let geti = |s: &Scalar| match s {
13973            Scalar::Int64(v) => *v,
13974            _ => i64::MIN,
13975        };
13976
13977        for iter in 0..1500u32 {
13978            let nl = (next() % 9) as usize + 1;
13979            let nr = (next() % 9) as usize + 1;
13980            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
13981            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
13982            let left = build(&lk, "lv");
13983            let right = build(&rk, "rv");
13984
13985            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
13986            let ks = merged_values(&merged, "k").expect("k");
13987            let lvs = merged_values(&merged, "lv").expect("lv");
13988            let rvs = merged_values(&merged, "rv").expect("rv");
13989            let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
13990                .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
13991                .collect();
13992            got.sort_unstable();
13993
13994            // Independent oracle: per-key cross product of left/right row payloads.
13995            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13996            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13997            for (i, &k) in lk.iter().enumerate() {
13998                lg.entry(k).or_default().push(i as i64);
13999            }
14000            for (i, &k) in rk.iter().enumerate() {
14001                rg.entry(k).or_default().push(i as i64);
14002            }
14003            let mut exp: Vec<(i64, i64, i64)> = Vec::new();
14004            for (&k, lps) in &lg {
14005                if let Some(rps) = rg.get(&k) {
14006                    for &a in lps {
14007                        for &b in rps {
14008                            exp.push((k, a, b));
14009                        }
14010                    }
14011                }
14012            }
14013            exp.sort_unstable();
14014
14015            assert_eq!(
14016                got, exp,
14017                "inner join value multiset iter={iter} lk={lk:?} rk={rk:?}"
14018            );
14019        }
14020    }
14021
14022    #[test]
14023    fn left_outer_join_nullfill_value_oracle_kaj3t() {
14024        use std::collections::BTreeMap;
14025
14026        // Value oracle for LEFT/OUTER null-fill (br-frankenpandas-kaj3t): unmatched
14027        // rows get NULL-filled on the absent side — the subtlest join behavior.
14028        // NULL is represented by the i64::MIN sentinel (payloads are 0..n and keys
14029        // 0..3, so a sentinel never collides with a real value). Deterministic
14030        // seeded LCG — no rand crate, no mocks.
14031        const NUL: i64 = i64::MIN;
14032        let mut state: u64 = 0xfeed_face_cafe_b0ba;
14033        let mut next = || {
14034            state = state
14035                .wrapping_mul(6_364_136_223_846_793_005)
14036                .wrapping_add(1_442_695_040_888_963_407);
14037            (state >> 33) as u32
14038        };
14039
14040        let build = |keys: &[i64], pname: &str| {
14041            let n = keys.len();
14042            DataFrame::from_dict(
14043                &["k", pname],
14044                vec![
14045                    (
14046                        "k",
14047                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
14048                    ),
14049                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
14050                ],
14051            )
14052            .expect("frame")
14053        };
14054        // Int64 -> value. Left/outer joins upcast Int64 payload columns to
14055        // Float64 when null-fill introduces missing values (pandas parity: Int64
14056        // can't hold NaN), so accept finite Float64 too. NULL / NaN -> NUL
14057        // sentinel. Payloads are small whole numbers, so f64 -> i64 is exact.
14058        let geti = |s: &Scalar| match s {
14059            Scalar::Int64(v) => *v,
14060            Scalar::Float64(v) if v.is_finite() => *v as i64,
14061            _ => NUL,
14062        };
14063
14064        for iter in 0..1500u32 {
14065            let nl = (next() % 9) as usize + 1;
14066            let nr = (next() % 9) as usize + 1;
14067            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
14068            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
14069            let left = build(&lk, "lv");
14070            let right = build(&rk, "rv");
14071
14072            // Right rows grouped by key (payload = row index).
14073            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
14074            for (j, &k) in rk.iter().enumerate() {
14075                rg.entry(k).or_default().push(j as i64);
14076            }
14077            let lkeys: std::collections::BTreeSet<i64> = lk.iter().copied().collect();
14078
14079            let read = |jt: JoinType| -> Vec<(i64, i64, i64)> {
14080                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
14081                let ks = merged_values(&merged, "k").expect("k");
14082                let lvs = merged_values(&merged, "lv").expect("lv");
14083                let rvs = merged_values(&merged, "rv").expect("rv");
14084                let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
14085                    .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
14086                    .collect();
14087                got.sort_unstable();
14088                got
14089            };
14090
14091            // LEFT oracle: every left row appears; matched -> one row per right
14092            // match, unmatched -> NULL right payload (key still the left key).
14093            let mut exp_left: Vec<(i64, i64, i64)> = Vec::new();
14094            for (i, &k) in lk.iter().enumerate() {
14095                match rg.get(&k) {
14096                    Some(rps) => {
14097                        for &j in rps {
14098                            exp_left.push((k, i as i64, j));
14099                        }
14100                    }
14101                    None => exp_left.push((k, i as i64, NUL)),
14102                }
14103            }
14104            exp_left.sort_unstable();
14105            assert_eq!(
14106                read(JoinType::Left),
14107                exp_left,
14108                "left join value oracle iter={iter} lk={lk:?} rk={rk:?}"
14109            );
14110
14111            // OUTER oracle: LEFT plus right-only rows (no left match) with NULL
14112            // left payload and the coalesced key.
14113            let mut exp_outer = exp_left.clone();
14114            for (j, &k) in rk.iter().enumerate() {
14115                if !lkeys.contains(&k) {
14116                    exp_outer.push((k, NUL, j as i64));
14117                }
14118            }
14119            exp_outer.sort_unstable();
14120            assert_eq!(
14121                read(JoinType::Outer),
14122                exp_outer,
14123                "outer join value oracle iter={iter} lk={lk:?} rk={rk:?}"
14124            );
14125        }
14126    }
14127
14128    #[test]
14129    fn left_join_value_multiset_matches_unmatched_oracle_gp0ik() {
14130        use std::collections::BTreeMap;
14131
14132        // Value-level LEFT join oracle (br-frankenpandas-gp0ik): matched keys
14133        // emit the left/right cross product; unmatched left rows emit exactly one
14134        // row with a missing right payload. Ordering-independent sorted multiset.
14135        let mut state: u64 = 0x51de_cafe_2026_0618;
14136        let mut next = || {
14137            state = state
14138                .wrapping_mul(6_364_136_223_846_793_005)
14139                .wrapping_add(1_442_695_040_888_963_407);
14140            (state >> 33) as u32
14141        };
14142
14143        let build = |keys: &[i64], pname: &str| {
14144            let n = keys.len();
14145            DataFrame::from_dict(
14146                &["k", pname],
14147                vec![
14148                    (
14149                        "k",
14150                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
14151                    ),
14152                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
14153                ],
14154            )
14155            .expect("frame")
14156        };
14157        let geti = |s: &Scalar| match s {
14158            Scalar::Int64(v) => *v,
14159            _ => i64::MIN,
14160        };
14161        let get_optional_i64 = |s: &Scalar| match s {
14162            Scalar::Int64(v) => Some(*v),
14163            Scalar::Float64(v) if v.is_finite() && v.fract() == 0.0 => Some(*v as i64),
14164            value if value.is_missing() => None,
14165            _ => Some(i64::MIN),
14166        };
14167
14168        for iter in 0..1500u32 {
14169            let nl = (next() % 9) as usize + 1;
14170            let nr = (next() % 9) as usize + 1;
14171            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64).collect();
14172            let rk: Vec<i64> = (0..nr).map(|_| (next() % 3) as i64).collect();
14173            let left = build(&lk, "lv");
14174            let right = build(&rk, "rv");
14175
14176            let merged = merge_dataframes(&left, &right, "k", JoinType::Left).expect("merge");
14177            let ks = merged_values(&merged, "k").expect("k");
14178            let lvs = merged_values(&merged, "lv").expect("lv");
14179            let rvs = merged_values(&merged, "rv").expect("rv");
14180            let mut got: Vec<(i64, i64, Option<i64>)> = (0..ks.len())
14181                .map(|i| (geti(&ks[i]), geti(&lvs[i]), get_optional_i64(&rvs[i])))
14182                .collect();
14183            got.sort_unstable();
14184
14185            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
14186            for (i, &k) in rk.iter().enumerate() {
14187                rg.entry(k).or_default().push(i as i64);
14188            }
14189            let mut exp: Vec<(i64, i64, Option<i64>)> = Vec::new();
14190            for (left_pos, &k) in lk.iter().enumerate() {
14191                if let Some(right_positions) = rg.get(&k) {
14192                    for &right_pos in right_positions {
14193                        exp.push((k, left_pos as i64, Some(right_pos)));
14194                    }
14195                } else {
14196                    exp.push((k, left_pos as i64, None));
14197                }
14198            }
14199            exp.sort_unstable();
14200
14201            assert_eq!(
14202                got, exp,
14203                "left join value multiset iter={iter} lk={lk:?} rk={rk:?}"
14204            );
14205        }
14206    }
14207
14208    #[test]
14209    fn right_join_value_multiset_matches_unmatched_oracle_pd1h5() {
14210        use std::collections::BTreeMap;
14211
14212        // Value-level RIGHT join oracle (br-frankenpandas-pd1h5): matched keys
14213        // emit the left/right cross product; unmatched right rows emit exactly one
14214        // row with a missing left payload. Ordering-independent sorted multiset.
14215        let mut state: u64 = 0x7191_2026_0618_a015;
14216        let mut next = || {
14217            state = state
14218                .wrapping_mul(6_364_136_223_846_793_005)
14219                .wrapping_add(1_442_695_040_888_963_407);
14220            (state >> 33) as u32
14221        };
14222
14223        let build = |keys: &[i64], pname: &str| {
14224            let n = keys.len();
14225            DataFrame::from_dict(
14226                &["k", pname],
14227                vec![
14228                    (
14229                        "k",
14230                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
14231                    ),
14232                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
14233                ],
14234            )
14235            .expect("frame")
14236        };
14237        let geti = |s: &Scalar| match s {
14238            Scalar::Int64(v) => *v,
14239            Scalar::Float64(v) if v.is_finite() => *v as i64,
14240            _ => i64::MIN,
14241        };
14242        let get_optional_i64 = |s: &Scalar| match s {
14243            Scalar::Int64(v) => Some(*v),
14244            Scalar::Float64(v) if v.is_finite() => Some(*v as i64),
14245            value if value.is_missing() => None,
14246            _ => Some(i64::MIN),
14247        };
14248
14249        for iter in 0..1500u32 {
14250            let nl = (next() % 9) as usize + 1;
14251            let nr = (next() % 9) as usize + 1;
14252            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
14253            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64).collect();
14254            let left = build(&lk, "lv");
14255            let right = build(&rk, "rv");
14256
14257            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).expect("merge");
14258            let ks = merged_values(&merged, "k").expect("k");
14259            let lvs = merged_values(&merged, "lv").expect("lv");
14260            let rvs = merged_values(&merged, "rv").expect("rv");
14261            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
14262                .map(|i| (geti(&ks[i]), get_optional_i64(&lvs[i]), geti(&rvs[i])))
14263                .collect();
14264            got.sort_unstable();
14265
14266            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
14267            for (i, &k) in lk.iter().enumerate() {
14268                lg.entry(k).or_default().push(i as i64);
14269            }
14270            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
14271            for (right_pos, &k) in rk.iter().enumerate() {
14272                if let Some(left_positions) = lg.get(&k) {
14273                    for &left_pos in left_positions {
14274                        exp.push((k, Some(left_pos), right_pos as i64));
14275                    }
14276                } else {
14277                    exp.push((k, None, right_pos as i64));
14278                }
14279            }
14280            exp.sort_unstable();
14281
14282            assert_eq!(
14283                got, exp,
14284                "right join value multiset iter={iter} lk={lk:?} rk={rk:?}"
14285            );
14286        }
14287    }
14288
14289    fn merged_values<'a>(
14290        merged: &'a MergedDataFrame,
14291        name: &str,
14292    ) -> Result<&'a [Scalar], JoinError> {
14293        Ok(merged
14294            .columns
14295            .get(name)
14296            .ok_or_else(|| {
14297                JoinError::Frame(FrameError::CompatibilityRejected(format!(
14298                    "missing merged column '{name}'"
14299                )))
14300            })?
14301            .values())
14302    }
14303
14304    #[test]
14305    fn temporal_i64_inner_positions_match_scalar_oracle_with_duplicates_b2hwb() {
14306        let build_positions_from_scalar_oracle = |left: &Column, right: &Column| {
14307            let left_keys = super::collect_single_join_keys(left);
14308            let right_keys = super::collect_single_join_keys(right);
14309            let mut left_positions = Vec::new();
14310            let mut right_positions = Vec::new();
14311            for (left_pos, left_key) in left_keys.iter().enumerate() {
14312                for (right_pos, right_key) in right_keys.iter().enumerate() {
14313                    if left_key == right_key {
14314                        left_positions.push(left_pos);
14315                        right_positions.push(right_pos);
14316                    }
14317                }
14318            }
14319            (left_positions, right_positions)
14320        };
14321
14322        let left_ns = [30, 10, 20, 10];
14323        let right_ns = [10, 30, 10, 40];
14324        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14325            let scalar = |ns| match &temporal {
14326                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
14327                DType::Timedelta64 => Scalar::Timedelta64(ns),
14328                _ => unreachable!("test iterates only temporal dtypes"),
14329            };
14330            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
14331                .expect("left temporal key");
14332            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
14333                .expect("right temporal key");
14334
14335            assert_eq!(
14336                super::temporal_i64_inner_positions(&left, &right),
14337                Some(build_positions_from_scalar_oracle(&left, &right)),
14338                "raw-nanosecond planner must preserve scalar-oracle pair order for {temporal:?}"
14339            );
14340        }
14341
14342        let nat = fp_types::Timestamp::NAT;
14343        let ordered = Column::from_datetime64_values(vec![1, 2, 3, 4]);
14344        let nat_middle = Column::from_datetime64_values(vec![1, 2, nat, 4]);
14345        let nat_tail = Column::from_datetime64_values(vec![1, 2, 3, nat]);
14346        let single_nat = Column::from_datetime64_values(vec![nat]);
14347        for (left, right) in [
14348            (&nat_middle, &ordered),
14349            (&ordered, &nat_tail),
14350            (&single_nat, &ordered),
14351        ] {
14352            assert!(
14353                super::temporal_i64_inner_positions(left, right).is_none(),
14354                "NaT anywhere must retain the scalar INNER fallback",
14355            );
14356        }
14357    }
14358
14359    #[test]
14360    #[ignore = "foreground performance probe"]
14361    fn bench_temporal_i64_inner_validation_fusion_71kgc() {
14362        let n = 400_000_i64;
14363        let input_len = usize::try_from(n).expect("positive benchmark length");
14364        let left = Column::from_datetime64_values_with_validity(
14365            (0..n).collect(),
14366            ValidityMask::all_valid(input_len),
14367        );
14368        let right = Column::from_datetime64_values_with_validity(
14369            (0..n).map(|value| value * 2).collect(),
14370            ValidityMask::all_valid(input_len),
14371        );
14372
14373        // Exact pre-71kgc ordered body: separate NaT and strict-order scans
14374        // followed by the same two-pointer intersection.
14375        let former = || {
14376            if !left.validity().all() || !right.validity().all() {
14377                return None;
14378            }
14379            let left_raw = left.as_datetime64_slice()?;
14380            let right_raw = right.as_datetime64_slice()?;
14381            let nat = fp_types::Timestamp::NAT;
14382            if left_raw.contains(&nat) || right_raw.contains(&nat) {
14383                return None;
14384            }
14385            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
14386                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
14387            {
14388                return None;
14389            }
14390
14391            let mut left_positions = Vec::with_capacity(left_raw.len().min(right_raw.len()));
14392            let mut right_positions = Vec::with_capacity(left_positions.capacity());
14393            let (mut left_idx, mut right_idx) = (0usize, 0usize);
14394            while left_idx < left_raw.len() && right_idx < right_raw.len() {
14395                match left_raw[left_idx].cmp(&right_raw[right_idx]) {
14396                    std::cmp::Ordering::Equal => {
14397                        left_positions.push(left_idx);
14398                        right_positions.push(right_idx);
14399                        left_idx += 1;
14400                        right_idx += 1;
14401                    }
14402                    std::cmp::Ordering::Less => left_idx += 1,
14403                    std::cmp::Ordering::Greater => right_idx += 1,
14404                }
14405            }
14406            Some((left_positions, right_positions))
14407        };
14408        let candidate = || super::temporal_i64_inner_positions(&left, &right);
14409
14410        let former_output = former().expect("former temporal INNER positions");
14411        let candidate_output = candidate().expect("temporal INNER positions");
14412        assert_eq!(candidate_output, former_output);
14413        assert_eq!(candidate_output.0.len(), input_len.div_ceil(2));
14414        drop((former_output, candidate_output));
14415        for _ in 0..2 {
14416            std::hint::black_box(former());
14417            std::hint::black_box(candidate());
14418        }
14419
14420        type InnerPositions = Option<(Vec<usize>, Vec<usize>)>;
14421        let sample = |plan: &dyn Fn() -> InnerPositions| {
14422            let start = std::time::Instant::now();
14423            let output = std::hint::black_box(plan()).expect("supported temporal INNER plan");
14424            assert_eq!(std::hint::black_box(output.0.len()), input_len.div_ceil(2));
14425            drop(output);
14426            start.elapsed().as_secs_f64() * 1_000.0
14427        };
14428        let mut former_a = Vec::with_capacity(15);
14429        let mut former_b = Vec::with_capacity(15);
14430        let mut candidate_a = Vec::with_capacity(15);
14431        let mut candidate_b = Vec::with_capacity(15);
14432        for round in 0..15 {
14433            if round % 2 == 0 {
14434                former_a.push(sample(&former));
14435                candidate_a.push(sample(&candidate));
14436                candidate_b.push(sample(&candidate));
14437                former_b.push(sample(&former));
14438            } else {
14439                former_b.push(sample(&former));
14440                candidate_b.push(sample(&candidate));
14441                candidate_a.push(sample(&candidate));
14442                former_a.push(sample(&former));
14443            }
14444        }
14445
14446        let report = |label: &str, mut samples: Vec<f64>| {
14447            samples.sort_by(f64::total_cmp);
14448            let p50 = samples[samples.len() / 2];
14449            let p95_idx = samples
14450                .len()
14451                .saturating_mul(95)
14452                .div_ceil(100)
14453                .saturating_sub(1);
14454            println!(
14455                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
14456                samples[p95_idx],
14457                samples[samples.len() - 1],
14458            );
14459        };
14460        report("inner_plan_three_pass_former_a", former_a);
14461        report("inner_plan_three_pass_former_b", former_b);
14462        report("inner_plan_fused_candidate_a", candidate_a);
14463        report("inner_plan_fused_candidate_b", candidate_b);
14464    }
14465
14466    #[test]
14467    fn merge_datetime_inner_preserves_dtype_order_and_nat_fallback_b2hwb() -> Result<(), JoinError>
14468    {
14469        let left = DataFrame::from_dict(
14470            &["key", "lv"],
14471            vec![
14472                (
14473                    "key",
14474                    vec![
14475                        Scalar::Datetime64(30),
14476                        Scalar::Datetime64(10),
14477                        Scalar::Datetime64(20),
14478                        Scalar::Datetime64(10),
14479                    ],
14480                ),
14481                (
14482                    "lv",
14483                    vec![
14484                        Scalar::Int64(0),
14485                        Scalar::Int64(1),
14486                        Scalar::Int64(2),
14487                        Scalar::Int64(3),
14488                    ],
14489                ),
14490            ],
14491        )?;
14492        let right = DataFrame::from_dict(
14493            &["key", "rv"],
14494            vec![
14495                (
14496                    "key",
14497                    vec![
14498                        Scalar::Datetime64(10),
14499                        Scalar::Datetime64(30),
14500                        Scalar::Datetime64(10),
14501                        Scalar::Datetime64(40),
14502                    ],
14503                ),
14504                (
14505                    "rv",
14506                    vec![
14507                        Scalar::Int64(100),
14508                        Scalar::Int64(101),
14509                        Scalar::Int64(102),
14510                        Scalar::Int64(103),
14511                    ],
14512                ),
14513            ],
14514        )?;
14515        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner)?;
14516        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
14517        assert_eq!(
14518            merged_values(&merged, "key")?,
14519            &[
14520                Scalar::Datetime64(30),
14521                Scalar::Datetime64(10),
14522                Scalar::Datetime64(10),
14523                Scalar::Datetime64(10),
14524                Scalar::Datetime64(10),
14525            ]
14526        );
14527        assert_eq!(
14528            merged_values(&merged, "lv")?,
14529            &[
14530                Scalar::Int64(0),
14531                Scalar::Int64(1),
14532                Scalar::Int64(1),
14533                Scalar::Int64(3),
14534                Scalar::Int64(3),
14535            ]
14536        );
14537        assert_eq!(
14538            merged_values(&merged, "rv")?,
14539            &[
14540                Scalar::Int64(101),
14541                Scalar::Int64(100),
14542                Scalar::Int64(102),
14543                Scalar::Int64(100),
14544                Scalar::Int64(102),
14545            ]
14546        );
14547
14548        let nat = fp_types::Timestamp::NAT;
14549        let nat_left = DataFrame::from_dict(
14550            &["key", "lv"],
14551            vec![
14552                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
14553                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
14554            ],
14555        )?;
14556        let nat_right = DataFrame::from_dict(
14557            &["key", "rv"],
14558            vec![
14559                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
14560                ("rv", vec![Scalar::Int64(10), Scalar::Int64(11)]),
14561            ],
14562        )?;
14563        assert!(
14564            super::temporal_i64_inner_positions(
14565                nat_left.column("key").expect("left NaT key"),
14566                nat_right.column("key").expect("right NaT key")
14567            )
14568            .is_none(),
14569            "NaT must retain the scalar Missing-key fallback"
14570        );
14571        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Inner)?;
14572        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
14573        assert_eq!(nat_merged.index.len(), 2);
14574        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
14575        assert_eq!(
14576            &merged_values(&nat_merged, "key")?[1..],
14577            &[Scalar::Datetime64(5)]
14578        );
14579
14580        Ok(())
14581    }
14582
14583    #[test]
14584    fn temporal_i64_left_positions_match_scalar_oracle_with_duplicates_lw0qg() {
14585        let build_positions_from_scalar_oracle = |left: &Column, right: &Column| {
14586            let left_keys = super::collect_single_join_keys(left);
14587            let right_keys = super::collect_single_join_keys(right);
14588            let mut left_positions = Vec::new();
14589            let mut right_positions = Vec::new();
14590            for (left_pos, left_key) in left_keys.iter().enumerate() {
14591                let mut matched = false;
14592                for (right_pos, right_key) in right_keys.iter().enumerate() {
14593                    if left_key == right_key {
14594                        left_positions.push(Some(left_pos));
14595                        right_positions.push(Some(right_pos));
14596                        matched = true;
14597                    }
14598                }
14599                if !matched {
14600                    left_positions.push(Some(left_pos));
14601                    right_positions.push(None);
14602                }
14603            }
14604            (left_positions, right_positions)
14605        };
14606
14607        let left_ns = [30, 10, 20, 10, 50];
14608        let right_ns = [10, 30, 10, 40];
14609        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14610            let scalar = |ns| match &temporal {
14611                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
14612                DType::Timedelta64 => Scalar::Timedelta64(ns),
14613                _ => unreachable!("test iterates only temporal dtypes"),
14614            };
14615            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
14616                .expect("left temporal key");
14617            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
14618                .expect("right temporal key");
14619
14620            assert_eq!(
14621                super::temporal_i64_left_positions(&left, &right),
14622                Some(build_positions_from_scalar_oracle(&left, &right)),
14623                "raw-nanosecond LEFT planner must preserve scalar-oracle row order for {temporal:?}"
14624            );
14625        }
14626    }
14627
14628    #[test]
14629    fn merge_datetime_left_preserves_dtype_order_and_nat_fallback_lw0qg() -> Result<(), JoinError> {
14630        let left = DataFrame::from_dict(
14631            &["key", "lv"],
14632            vec![
14633                (
14634                    "key",
14635                    vec![
14636                        Scalar::Datetime64(30),
14637                        Scalar::Datetime64(10),
14638                        Scalar::Datetime64(20),
14639                        Scalar::Datetime64(10),
14640                        Scalar::Datetime64(50),
14641                    ],
14642                ),
14643                (
14644                    "lv",
14645                    vec![
14646                        Scalar::Int64(0),
14647                        Scalar::Int64(1),
14648                        Scalar::Int64(2),
14649                        Scalar::Int64(3),
14650                        Scalar::Int64(4),
14651                    ],
14652                ),
14653            ],
14654        )?;
14655        let right = DataFrame::from_dict(
14656            &["key", "rv"],
14657            vec![
14658                (
14659                    "key",
14660                    vec![
14661                        Scalar::Datetime64(10),
14662                        Scalar::Datetime64(30),
14663                        Scalar::Datetime64(10),
14664                        Scalar::Datetime64(40),
14665                    ],
14666                ),
14667                (
14668                    "rv",
14669                    vec![
14670                        Scalar::Int64(100),
14671                        Scalar::Int64(101),
14672                        Scalar::Int64(102),
14673                        Scalar::Int64(103),
14674                    ],
14675                ),
14676            ],
14677        )?;
14678        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Left)?;
14679        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
14680        assert_eq!(
14681            merged_values(&merged, "key")?,
14682            &[
14683                Scalar::Datetime64(30),
14684                Scalar::Datetime64(10),
14685                Scalar::Datetime64(10),
14686                Scalar::Datetime64(20),
14687                Scalar::Datetime64(10),
14688                Scalar::Datetime64(10),
14689                Scalar::Datetime64(50),
14690            ]
14691        );
14692        assert_eq!(
14693            merged_values(&merged, "lv")?,
14694            &[
14695                Scalar::Int64(0),
14696                Scalar::Int64(1),
14697                Scalar::Int64(1),
14698                Scalar::Int64(2),
14699                Scalar::Int64(3),
14700                Scalar::Int64(3),
14701                Scalar::Int64(4),
14702            ]
14703        );
14704        let right_values = merged_values(&merged, "rv")?;
14705        assert_eq!(right_values.len(), 7);
14706        assert_eq!(right_values[0], Scalar::Float64(101.0));
14707        assert_eq!(
14708            &right_values[1..3],
14709            &[Scalar::Float64(100.0), Scalar::Float64(102.0)]
14710        );
14711        assert!(right_values[3].is_missing());
14712        assert_eq!(
14713            &right_values[4..6],
14714            &[Scalar::Float64(100.0), Scalar::Float64(102.0)]
14715        );
14716        assert!(right_values[6].is_missing());
14717
14718        let nat = fp_types::Timestamp::NAT;
14719        let nat_left = DataFrame::from_dict(
14720            &["key", "lv"],
14721            vec![
14722                (
14723                    "key",
14724                    vec![
14725                        Scalar::Datetime64(nat),
14726                        Scalar::Datetime64(5),
14727                        Scalar::Datetime64(7),
14728                    ],
14729                ),
14730                (
14731                    "lv",
14732                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
14733                ),
14734            ],
14735        )?;
14736        let nat_right = DataFrame::from_dict(
14737            &["key", "rv"],
14738            vec![
14739                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
14740                ("rv", vec![Scalar::Int64(10), Scalar::Int64(11)]),
14741            ],
14742        )?;
14743        assert!(
14744            super::temporal_i64_left_positions(
14745                nat_left.column("key").expect("left NaT key"),
14746                nat_right.column("key").expect("right NaT key")
14747            )
14748            .is_none(),
14749            "NaT must retain the scalar Missing-key fallback"
14750        );
14751        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Left)?;
14752        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
14753        assert_eq!(nat_merged.index.len(), 3);
14754        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
14755        assert_eq!(
14756            &merged_values(&nat_merged, "key")?[1..],
14757            &[Scalar::Datetime64(5), Scalar::Datetime64(7)]
14758        );
14759        let nat_right_values = merged_values(&nat_merged, "rv")?;
14760        assert_eq!(
14761            &nat_right_values[..2],
14762            &[Scalar::Float64(10.0), Scalar::Float64(11.0)]
14763        );
14764        assert!(nat_right_values[2].is_missing());
14765
14766        Ok(())
14767    }
14768
14769    #[test]
14770    fn temporal_i64_right_positions_match_scalar_oracle_and_reject_unsupported_8tf5c() {
14771        let scalar_oracle = |left: &Column, right: &Column| {
14772            let left_keys = super::collect_single_join_keys(left);
14773            let right_keys = super::collect_single_join_keys(right);
14774            right_keys
14775                .iter()
14776                .map(|right_key| left_keys.iter().position(|left_key| left_key == right_key))
14777                .collect::<Vec<_>>()
14778        };
14779
14780        let left_ns = [-20, 10, 30, 50];
14781        let right_ns = [-30, -20, 20, 30, 60];
14782        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14783            let scalar = |ns| match &temporal {
14784                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
14785                DType::Timedelta64 => Scalar::Timedelta64(ns),
14786                _ => unreachable!("test iterates only temporal dtypes"),
14787            };
14788            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
14789                .expect("left temporal key");
14790            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
14791                .expect("right temporal key");
14792            assert_eq!(
14793                super::ordered_unique_temporal_i64_right_match_positions(&left, &right),
14794                Some(scalar_oracle(&left, &right)),
14795                "raw-nanosecond RIGHT planner must preserve right-major scalar matches for {temporal:?}",
14796            );
14797        }
14798
14799        let empty_left = Column::from_datetime64_values(Vec::new());
14800        let ordered_right = Column::from_datetime64_values(vec![1, 2, 3]);
14801        assert_eq!(
14802            super::ordered_unique_temporal_i64_right_match_positions(&empty_left, &ordered_right,),
14803            Some(vec![None; 3]),
14804        );
14805
14806        let nat = fp_types::Timestamp::NAT;
14807        let nat_left = Column::from_datetime64_values(vec![nat, 1, 2]);
14808        let nat_middle_left = Column::from_datetime64_values(vec![1, nat, 3]);
14809        let nat_tail_right = Column::from_datetime64_values(vec![1, 2, nat]);
14810        let single_nat = Column::from_datetime64_values(vec![nat]);
14811        let duplicate_left = Column::from_datetime64_values(vec![1, 1, 2]);
14812        let late_duplicate_left = Column::from_datetime64_values(vec![1, 2, 3, 3]);
14813        let unsorted_right = Column::from_datetime64_values(vec![2, 1, 3]);
14814        let late_unsorted_right = Column::from_datetime64_values(vec![1, 2, 4, 3]);
14815        let mixed_right =
14816            Column::from_values([1, 2, 3].into_iter().map(Scalar::Timedelta64).collect())
14817                .expect("mixed timedelta key");
14818        let mut validity = ValidityMask::all_valid(3);
14819        validity.set(1, false);
14820        let nullable_left = Column::from_datetime64_values_with_validity(vec![1, 2, 3], validity);
14821        for (left, right) in [
14822            (&nat_left, &ordered_right),
14823            (&nat_middle_left, &ordered_right),
14824            (&ordered_right, &nat_tail_right),
14825            (&single_nat, &ordered_right),
14826            (&duplicate_left, &ordered_right),
14827            (&late_duplicate_left, &ordered_right),
14828            (&ordered_right, &unsorted_right),
14829            (&ordered_right, &late_unsorted_right),
14830            (&ordered_right, &mixed_right),
14831            (&nullable_left, &ordered_right),
14832        ] {
14833            assert!(
14834                super::ordered_unique_temporal_i64_right_match_positions(left, right).is_none(),
14835                "unsupported temporal RIGHT shape must retain the scalar fallback",
14836            );
14837        }
14838    }
14839
14840    #[test]
14841    #[ignore = "foreground performance probe"]
14842    fn bench_temporal_i64_right_validation_fusion_69e0m() {
14843        let n = 400_000_i64;
14844        let input_len = usize::try_from(n).expect("positive benchmark length");
14845        let left = Column::from_datetime64_values_with_validity(
14846            (0..n).collect(),
14847            ValidityMask::all_valid(input_len),
14848        );
14849        let right = Column::from_datetime64_values_with_validity(
14850            (0..n).map(|value| value * 2).collect(),
14851            ValidityMask::all_valid(input_len),
14852        );
14853
14854        // Exact pre-69e0m body: separate NaT and strict-order scans followed
14855        // by the same right-major two-pointer match.
14856        let former = || {
14857            if !left.validity().all() || !right.validity().all() {
14858                return None;
14859            }
14860            let left_raw = left.as_datetime64_slice()?;
14861            let right_raw = right.as_datetime64_slice()?;
14862            let nat = fp_types::Timestamp::NAT;
14863            if left_raw.contains(&nat) || right_raw.contains(&nat) {
14864                return None;
14865            }
14866            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
14867                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
14868            {
14869                return None;
14870            }
14871
14872            let mut left_positions = Vec::with_capacity(right_raw.len());
14873            let mut left_idx = 0usize;
14874            for &right_value in right_raw {
14875                while left_idx < left_raw.len() && left_raw[left_idx] < right_value {
14876                    left_idx += 1;
14877                }
14878                left_positions.push(
14879                    (left_idx < left_raw.len()
14880                        && matches!(
14881                            left_raw[left_idx].cmp(&right_value),
14882                            std::cmp::Ordering::Equal
14883                        ))
14884                    .then_some(left_idx),
14885                );
14886            }
14887            Some(left_positions)
14888        };
14889        let candidate = || super::ordered_unique_temporal_i64_right_match_positions(&left, &right);
14890
14891        let former_output = former().expect("former temporal RIGHT positions");
14892        let candidate_output = candidate().expect("fused temporal RIGHT positions");
14893        assert_eq!(candidate_output, former_output);
14894        assert_eq!(candidate_output.len(), input_len);
14895        drop((former_output, candidate_output));
14896        for _ in 0..2 {
14897            std::hint::black_box(former());
14898            std::hint::black_box(candidate());
14899        }
14900
14901        let sample = |plan: &dyn Fn() -> Option<Vec<Option<usize>>>| {
14902            let start = std::time::Instant::now();
14903            let output = std::hint::black_box(plan()).expect("supported temporal RIGHT plan");
14904            assert_eq!(std::hint::black_box(output.len()), input_len);
14905            drop(output);
14906            start.elapsed().as_secs_f64() * 1_000.0
14907        };
14908        let mut former_a = Vec::with_capacity(15);
14909        let mut former_b = Vec::with_capacity(15);
14910        let mut candidate_a = Vec::with_capacity(15);
14911        let mut candidate_b = Vec::with_capacity(15);
14912        for round in 0..15 {
14913            if round % 2 == 0 {
14914                former_a.push(sample(&former));
14915                candidate_a.push(sample(&candidate));
14916                candidate_b.push(sample(&candidate));
14917                former_b.push(sample(&former));
14918            } else {
14919                former_b.push(sample(&former));
14920                candidate_b.push(sample(&candidate));
14921                candidate_a.push(sample(&candidate));
14922                former_a.push(sample(&former));
14923            }
14924        }
14925
14926        let report = |label: &str, mut samples: Vec<f64>| {
14927            samples.sort_by(f64::total_cmp);
14928            let p50 = samples[samples.len() / 2];
14929            let p95_idx = samples
14930                .len()
14931                .saturating_mul(95)
14932                .div_ceil(100)
14933                .saturating_sub(1);
14934            println!(
14935                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
14936                samples[p95_idx],
14937                samples[samples.len() - 1],
14938            );
14939        };
14940        report("right_plan_three_pass_former_a", former_a);
14941        report("right_plan_three_pass_former_b", former_b);
14942        report("right_plan_fused_candidate_a", candidate_a);
14943        report("right_plan_fused_candidate_b", candidate_b);
14944    }
14945
14946    #[test]
14947    fn merge_datetime_right_preserves_dtype_order_and_nat_fallback_8tf5c() -> Result<(), JoinError>
14948    {
14949        let left = DataFrame::from_dict(
14950            &["key", "lv"],
14951            vec![
14952                (
14953                    "key",
14954                    vec![
14955                        Scalar::Datetime64(10),
14956                        Scalar::Datetime64(30),
14957                        Scalar::Datetime64(50),
14958                    ],
14959                ),
14960                (
14961                    "lv",
14962                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
14963                ),
14964            ],
14965        )?;
14966        let right = DataFrame::from_dict(
14967            &["key", "rv"],
14968            vec![
14969                (
14970                    "key",
14971                    vec![
14972                        Scalar::Datetime64(0),
14973                        Scalar::Datetime64(10),
14974                        Scalar::Datetime64(40),
14975                        Scalar::Datetime64(50),
14976                        Scalar::Datetime64(60),
14977                    ],
14978                ),
14979                (
14980                    "rv",
14981                    vec![
14982                        Scalar::Int64(100),
14983                        Scalar::Int64(101),
14984                        Scalar::Int64(102),
14985                        Scalar::Int64(103),
14986                        Scalar::Int64(104),
14987                    ],
14988                ),
14989            ],
14990        )?;
14991        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Right)?;
14992        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
14993        assert_eq!(
14994            merged_values(&merged, "key")?,
14995            &[
14996                Scalar::Datetime64(0),
14997                Scalar::Datetime64(10),
14998                Scalar::Datetime64(40),
14999                Scalar::Datetime64(50),
15000                Scalar::Datetime64(60),
15001            ],
15002        );
15003        assert_eq!(
15004            merged_values(&merged, "rv")?,
15005            &[
15006                Scalar::Int64(100),
15007                Scalar::Int64(101),
15008                Scalar::Int64(102),
15009                Scalar::Int64(103),
15010                Scalar::Int64(104),
15011            ],
15012        );
15013        let left_values = merged_values(&merged, "lv")?;
15014        assert_eq!(left_values.len(), 5);
15015        assert!(left_values[0].is_missing());
15016        assert_eq!(left_values[1], Scalar::Float64(0.0));
15017        assert!(left_values[2].is_missing());
15018        assert_eq!(left_values[3], Scalar::Float64(2.0));
15019        assert!(left_values[4].is_missing());
15020
15021        let nat = fp_types::Timestamp::NAT;
15022        let nat_left = DataFrame::from_dict(
15023            &["key", "lv"],
15024            vec![
15025                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
15026                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
15027            ],
15028        )?;
15029        let nat_right = DataFrame::from_dict(
15030            &["key", "rv"],
15031            vec![
15032                (
15033                    "key",
15034                    vec![
15035                        Scalar::Datetime64(nat),
15036                        Scalar::Datetime64(5),
15037                        Scalar::Datetime64(7),
15038                    ],
15039                ),
15040                (
15041                    "rv",
15042                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(12)],
15043                ),
15044            ],
15045        )?;
15046        assert!(
15047            super::ordered_unique_temporal_i64_right_match_positions(
15048                nat_left.column("key").expect("left NaT key"),
15049                nat_right.column("key").expect("right NaT key"),
15050            )
15051            .is_none(),
15052            "NaT must retain the scalar Missing-key fallback",
15053        );
15054        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Right)?;
15055        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
15056        assert_eq!(nat_merged.index.len(), 3);
15057        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
15058        assert_eq!(
15059            &merged_values(&nat_merged, "key")?[1..],
15060            &[Scalar::Datetime64(5), Scalar::Datetime64(7)],
15061        );
15062        let nat_left_values = merged_values(&nat_merged, "lv")?;
15063        assert_eq!(
15064            &nat_left_values[..2],
15065            &[Scalar::Float64(0.0), Scalar::Float64(1.0)]
15066        );
15067        assert!(nat_left_values[2].is_missing());
15068
15069        Ok(())
15070    }
15071
15072    #[test]
15073    fn temporal_i64_outer_key_coalesce_matches_scalar_and_declines_unsupported_i4gzc() {
15074        let left_positions = [None, Some(0), Some(1), None, Some(2), Some(3), None];
15075        let right_positions = [Some(0), Some(1), None, Some(2), Some(3), None, Some(4)];
15076        let left_ns = vec![-20, 10, 30, 50];
15077        let right_ns = vec![-30, -20, 20, 30, 60];
15078        let union_ns = [-30, -20, 10, 20, 30, 50, 60];
15079        let temporal_column = |dtype: &DType, values: Vec<i64>| {
15080            let len = values.len();
15081            match dtype {
15082                DType::Datetime64 { .. } => Column::from_datetime64_values_with_validity(
15083                    values,
15084                    ValidityMask::all_valid(len),
15085                ),
15086                DType::Timedelta64 => Column::from_timedelta64_values_with_validity(
15087                    values,
15088                    ValidityMask::all_valid(len),
15089                ),
15090                _ => unreachable!("test iterates only temporal dtypes"),
15091            }
15092        };
15093
15094        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
15095            let left = temporal_column(&temporal, left_ns.clone());
15096            let right = temporal_column(&temporal, right_ns.clone());
15097            let candidate = super::coalesce_temporal_i64_key_column(
15098                &left,
15099                &right,
15100                &left_positions,
15101                &right_positions,
15102            )
15103            .expect("supported temporal key coalesce");
15104            assert_eq!(candidate.dtype(), temporal);
15105            assert!(candidate.validity().all());
15106            let candidate_ns = match &temporal {
15107                DType::Datetime64 { .. } => candidate.as_datetime64_slice(),
15108                DType::Timedelta64 => candidate.as_timedelta64_slice(),
15109                _ => unreachable!("test iterates only temporal dtypes"),
15110            };
15111            assert_eq!(candidate_ns, Some(union_ns.as_slice()));
15112
15113            let reference_values = left_positions
15114                .iter()
15115                .zip(right_positions.iter())
15116                .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
15117                    (Some(pos), _) => left.values()[*pos].clone(),
15118                    (None, Some(pos)) => right.values()[*pos].clone(),
15119                    (None, None) => Scalar::Null(NullKind::Null),
15120                })
15121                .collect::<Vec<_>>();
15122            let reference = Column::from_values(reference_values).expect("scalar reference");
15123            assert_eq!(candidate, reference);
15124        }
15125
15126        let naive_datetime = DType::datetime64_naive();
15127        let datetime_left = temporal_column(&naive_datetime, left_ns);
15128        let datetime_right = temporal_column(&naive_datetime, right_ns);
15129        let timedelta_right = temporal_column(&DType::Timedelta64, vec![-30, -20, 20, 30, 60]);
15130        let mut nullable_validity = ValidityMask::all_valid(datetime_left.len());
15131        nullable_validity.set(1, false);
15132        let nullable_left =
15133            Column::from_datetime64_values_with_validity(vec![-20, 10, 30, 50], nullable_validity);
15134        let nat_left = Column::from_datetime64_values_with_validity(
15135            vec![fp_types::Timestamp::NAT, 10, 30, 50],
15136            ValidityMask::all_valid(4),
15137        );
15138        for (left, right, left_tape, right_tape) in [
15139            (
15140                &nullable_left,
15141                &datetime_right,
15142                left_positions.as_slice(),
15143                right_positions.as_slice(),
15144            ),
15145            (
15146                &datetime_left,
15147                &timedelta_right,
15148                left_positions.as_slice(),
15149                right_positions.as_slice(),
15150            ),
15151            (&nat_left, &datetime_right, &[Some(0)], &[Some(0)]),
15152            (&datetime_left, &datetime_right, &[Some(0)], &[]),
15153            (&datetime_left, &datetime_right, &[Some(99)], &[None]),
15154            (&datetime_left, &datetime_right, &[None], &[None]),
15155        ] {
15156            assert!(
15157                super::coalesce_temporal_i64_key_column(left, right, left_tape, right_tape,)
15158                    .is_none(),
15159                "unsupported temporal key coalesce must retain Scalar fallback",
15160            );
15161        }
15162    }
15163
15164    #[test]
15165    #[ignore = "foreground performance probe"]
15166    fn bench_temporal_i64_outer_key_coalesce_i4gzc() {
15167        let n = 200_000_i64;
15168        let input_len = usize::try_from(n).expect("positive benchmark length");
15169        let left = Column::from_datetime64_values_with_validity(
15170            (0..n).collect(),
15171            ValidityMask::all_valid(input_len),
15172        );
15173        let right = Column::from_datetime64_values_with_validity(
15174            (0..n).map(|value| value * 2).collect(),
15175            ValidityMask::all_valid(input_len),
15176        );
15177        let (left_positions, right_positions) =
15178            super::ordered_unique_temporal_i64_outer_positions(&left, &right)
15179                .expect("ordered temporal position tapes");
15180        let expected_rows = 300_000usize;
15181        assert_eq!(left_positions.len(), expected_rows);
15182
15183        let former = || {
15184            let values = left_positions
15185                .iter()
15186                .zip(right_positions.iter())
15187                .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
15188                    (Some(pos), _) => left.values()[*pos].clone(),
15189                    (None, Some(pos)) => right.values()[*pos].clone(),
15190                    (None, None) => Scalar::Null(NullKind::Null),
15191                })
15192                .collect::<Vec<_>>();
15193            Column::from_values(values).expect("former Scalar key coalesce")
15194        };
15195        let candidate = || {
15196            super::coalesce_temporal_i64_key_column(
15197                &left,
15198                &right,
15199                &left_positions,
15200                &right_positions,
15201            )
15202            .expect("typed temporal key coalesce")
15203        };
15204
15205        let former_output = former();
15206        let candidate_output = candidate();
15207        assert_eq!(candidate_output, former_output);
15208        drop((former_output, candidate_output));
15209        for _ in 0..2 {
15210            std::hint::black_box(former());
15211            std::hint::black_box(candidate());
15212        }
15213
15214        let sample = |build: &dyn Fn() -> Column| {
15215            let start = std::time::Instant::now();
15216            let output = std::hint::black_box(build());
15217            assert_eq!(std::hint::black_box(output.len()), expected_rows);
15218            drop(output);
15219            start.elapsed().as_secs_f64() * 1_000.0
15220        };
15221        let mut former_a = Vec::with_capacity(15);
15222        let mut former_b = Vec::with_capacity(15);
15223        let mut candidate_a = Vec::with_capacity(15);
15224        let mut candidate_b = Vec::with_capacity(15);
15225        for round in 0..15 {
15226            if round % 2 == 0 {
15227                former_a.push(sample(&former));
15228                candidate_a.push(sample(&candidate));
15229                candidate_b.push(sample(&candidate));
15230                former_b.push(sample(&former));
15231            } else {
15232                former_b.push(sample(&former));
15233                candidate_b.push(sample(&candidate));
15234                candidate_a.push(sample(&candidate));
15235                former_a.push(sample(&former));
15236            }
15237        }
15238
15239        let report = |label: &str, mut samples: Vec<f64>| {
15240            samples.sort_by(f64::total_cmp);
15241            let p50 = samples[samples.len() / 2];
15242            let p95_idx = samples
15243                .len()
15244                .saturating_mul(95)
15245                .div_ceil(100)
15246                .saturating_sub(1);
15247            println!(
15248                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
15249                samples[p95_idx],
15250                samples[samples.len() - 1],
15251            );
15252        };
15253        report("outer_key_scalar_former_a", former_a);
15254        report("outer_key_scalar_former_b", former_b);
15255        report("outer_key_typed_candidate_a", candidate_a);
15256        report("outer_key_typed_candidate_b", candidate_b);
15257    }
15258
15259    #[test]
15260    fn temporal_i64_outer_positions_match_ordered_union_and_reject_unsupported_rvb6u() {
15261        let left_ns = [-20, 10, 30, 50];
15262        let right_ns = [-30, -20, 20, 30, 60];
15263        let expected = (
15264            vec![None, Some(0), Some(1), None, Some(2), Some(3), None],
15265            vec![Some(0), Some(1), None, Some(2), Some(3), None, Some(4)],
15266        );
15267        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
15268            let scalar = |ns| match &temporal {
15269                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
15270                DType::Timedelta64 => Scalar::Timedelta64(ns),
15271                _ => unreachable!("test iterates only temporal dtypes"),
15272            };
15273            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
15274                .expect("left temporal key");
15275            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
15276                .expect("right temporal key");
15277            assert_eq!(
15278                super::ordered_unique_temporal_i64_outer_positions(&left, &right),
15279                Some(expected.clone()),
15280                "raw-nanosecond OUTER planner must preserve key-sorted optional positions for {temporal:?}",
15281            );
15282        }
15283
15284        let empty_left = Column::from_datetime64_values(Vec::new());
15285        let ordered_right = Column::from_datetime64_values(vec![1, 2, 3]);
15286        assert_eq!(
15287            super::ordered_unique_temporal_i64_outer_positions(&empty_left, &ordered_right),
15288            Some((vec![None; 3], vec![Some(0), Some(1), Some(2)])),
15289        );
15290
15291        let nat = fp_types::Timestamp::NAT;
15292        let nat_left = Column::from_datetime64_values(vec![nat, 1, 2]);
15293        let duplicate_left = Column::from_datetime64_values(vec![1, 1, 2]);
15294        let unsorted_right = Column::from_datetime64_values(vec![2, 1, 3]);
15295        let mixed_right =
15296            Column::from_values([1, 2, 3].into_iter().map(Scalar::Timedelta64).collect())
15297                .expect("mixed timedelta key");
15298        let mut validity = ValidityMask::all_valid(3);
15299        validity.set(1, false);
15300        let nullable_left = Column::from_datetime64_values_with_validity(vec![1, 2, 3], validity);
15301        for (left, right) in [
15302            (&nat_left, &ordered_right),
15303            (&duplicate_left, &ordered_right),
15304            (&ordered_right, &unsorted_right),
15305            (&ordered_right, &mixed_right),
15306            (&nullable_left, &ordered_right),
15307        ] {
15308            assert!(
15309                super::ordered_unique_temporal_i64_outer_positions(left, right).is_none(),
15310                "unsupported temporal OUTER shape must retain the scalar fallback",
15311            );
15312        }
15313    }
15314
15315    #[test]
15316    #[ignore = "foreground performance probe"]
15317    fn bench_temporal_i64_outer_validation_fusion_pizud() {
15318        let n = 400_000_i64;
15319        let input_len = usize::try_from(n).expect("positive benchmark length");
15320        let left = Column::from_datetime64_values_with_validity(
15321            (0..n).collect(),
15322            ValidityMask::all_valid(input_len),
15323        );
15324        let right = Column::from_datetime64_values_with_validity(
15325            (0..n).map(|value| value * 2).collect(),
15326            ValidityMask::all_valid(input_len),
15327        );
15328        let expected_rows = 600_000usize;
15329
15330        // Exact pre-pizud body: separate NaT and strict-order scans followed by
15331        // the same three-way optional-position union.
15332        let former = || {
15333            if !left.validity().all() || !right.validity().all() {
15334                return None;
15335            }
15336            let left_raw = left.as_datetime64_slice()?;
15337            let right_raw = right.as_datetime64_slice()?;
15338            let nat = fp_types::Timestamp::NAT;
15339            if left_raw.contains(&nat) || right_raw.contains(&nat) {
15340                return None;
15341            }
15342            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
15343                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
15344            {
15345                return None;
15346            }
15347
15348            let capacity = left_raw.len().saturating_add(right_raw.len());
15349            let mut left_positions = Vec::<Option<usize>>::with_capacity(capacity);
15350            let mut right_positions = Vec::<Option<usize>>::with_capacity(capacity);
15351            let (mut left_idx, mut right_idx) = (0usize, 0usize);
15352            while left_idx < left_raw.len() && right_idx < right_raw.len() {
15353                match left_raw[left_idx].cmp(&right_raw[right_idx]) {
15354                    std::cmp::Ordering::Equal => {
15355                        left_positions.push(Some(left_idx));
15356                        right_positions.push(Some(right_idx));
15357                        left_idx += 1;
15358                        right_idx += 1;
15359                    }
15360                    std::cmp::Ordering::Less => {
15361                        left_positions.push(Some(left_idx));
15362                        right_positions.push(None);
15363                        left_idx += 1;
15364                    }
15365                    std::cmp::Ordering::Greater => {
15366                        left_positions.push(None);
15367                        right_positions.push(Some(right_idx));
15368                        right_idx += 1;
15369                    }
15370                }
15371            }
15372            while left_idx < left_raw.len() {
15373                left_positions.push(Some(left_idx));
15374                right_positions.push(None);
15375                left_idx += 1;
15376            }
15377            while right_idx < right_raw.len() {
15378                left_positions.push(None);
15379                right_positions.push(Some(right_idx));
15380                right_idx += 1;
15381            }
15382            Some((left_positions, right_positions))
15383        };
15384        let candidate = || super::ordered_unique_temporal_i64_outer_positions(&left, &right);
15385
15386        let former_output = former().expect("former temporal union");
15387        let candidate_output = candidate().expect("fused temporal union");
15388        assert_eq!(candidate_output, former_output);
15389        assert_eq!(candidate_output.0.len(), expected_rows);
15390        drop((former_output, candidate_output));
15391        for _ in 0..2 {
15392            std::hint::black_box(former());
15393            std::hint::black_box(candidate());
15394        }
15395
15396        let sample = |plan: &dyn Fn() -> Option<super::OptionalJoinPositions>| {
15397            let start = std::time::Instant::now();
15398            let output = std::hint::black_box(plan()).expect("supported temporal union");
15399            assert_eq!(std::hint::black_box(output.0.len()), expected_rows);
15400            drop(output);
15401            start.elapsed().as_secs_f64() * 1_000.0
15402        };
15403        let mut former_a = Vec::with_capacity(15);
15404        let mut former_b = Vec::with_capacity(15);
15405        let mut candidate_a = Vec::with_capacity(15);
15406        let mut candidate_b = Vec::with_capacity(15);
15407        for round in 0..15 {
15408            if round % 2 == 0 {
15409                former_a.push(sample(&former));
15410                candidate_a.push(sample(&candidate));
15411                candidate_b.push(sample(&candidate));
15412                former_b.push(sample(&former));
15413            } else {
15414                former_b.push(sample(&former));
15415                candidate_b.push(sample(&candidate));
15416                candidate_a.push(sample(&candidate));
15417                former_a.push(sample(&former));
15418            }
15419        }
15420
15421        let report = |label: &str, mut samples: Vec<f64>| {
15422            samples.sort_by(f64::total_cmp);
15423            let p50 = samples[samples.len() / 2];
15424            let p95_idx = samples
15425                .len()
15426                .saturating_mul(95)
15427                .div_ceil(100)
15428                .saturating_sub(1);
15429            println!(
15430                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
15431                samples[p95_idx],
15432                samples[samples.len() - 1],
15433            );
15434        };
15435        report("outer_plan_three_pass_former_a", former_a);
15436        report("outer_plan_three_pass_former_b", former_b);
15437        report("outer_plan_fused_candidate_a", candidate_a);
15438        report("outer_plan_fused_candidate_b", candidate_b);
15439    }
15440
15441    #[test]
15442    fn merge_temporal_outer_matches_generic_dtype_order_and_null_fill_rvb6u()
15443    -> Result<(), JoinError> {
15444        let left_ns = [-20, 10, 30, 50];
15445        let right_ns = [-30, -20, 20, 30, 60];
15446        let union_ns = [-30, -20, 10, 20, 30, 50, 60];
15447        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
15448            let scalar = |ns| match &temporal {
15449                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
15450                DType::Timedelta64 => Scalar::Timedelta64(ns),
15451                _ => unreachable!("test iterates only temporal dtypes"),
15452            };
15453            let left = DataFrame::from_dict(
15454                &["key", "lv"],
15455                vec![
15456                    ("key", left_ns.into_iter().map(scalar).collect()),
15457                    (
15458                        "lv",
15459                        vec![
15460                            Scalar::Int64(100),
15461                            Scalar::Int64(101),
15462                            Scalar::Int64(102),
15463                            Scalar::Int64(103),
15464                        ],
15465                    ),
15466                ],
15467            )?;
15468            let right = DataFrame::from_dict(
15469                &["key", "rv"],
15470                vec![
15471                    ("key", right_ns.into_iter().map(scalar).collect()),
15472                    (
15473                        "rv",
15474                        vec![
15475                            Scalar::Int64(200),
15476                            Scalar::Int64(201),
15477                            Scalar::Int64(202),
15478                            Scalar::Int64(203),
15479                            Scalar::Int64(204),
15480                        ],
15481                    ),
15482                ],
15483            )?;
15484            let candidate = merge_dataframes_on(&left, &right, &["key"], JoinType::Outer)?;
15485            let generic = merge_dataframes_on_with_options(
15486                &left,
15487                &right,
15488                &["key"],
15489                &["key"],
15490                JoinType::Outer,
15491                MergeExecutionOptions {
15492                    sort: true,
15493                    ..MergeExecutionOptions::default()
15494                },
15495            )?;
15496            assert_eq!(candidate, generic, "{temporal:?} OUTER output parity");
15497            assert_eq!(candidate.columns["key"].dtype(), temporal);
15498            assert_eq!(
15499                merged_values(&candidate, "key")?,
15500                union_ns
15501                    .into_iter()
15502                    .map(scalar)
15503                    .collect::<Vec<_>>()
15504                    .as_slice(),
15505            );
15506
15507            let left_values = merged_values(&candidate, "lv")?;
15508            assert!(left_values[0].is_missing());
15509            assert_eq!(left_values[1], Scalar::Float64(100.0));
15510            assert_eq!(left_values[2], Scalar::Float64(101.0));
15511            assert!(left_values[3].is_missing());
15512            assert_eq!(left_values[4], Scalar::Float64(102.0));
15513            assert_eq!(left_values[5], Scalar::Float64(103.0));
15514            assert!(left_values[6].is_missing());
15515
15516            let right_values = merged_values(&candidate, "rv")?;
15517            assert_eq!(right_values[0], Scalar::Float64(200.0));
15518            assert_eq!(right_values[1], Scalar::Float64(201.0));
15519            assert!(right_values[2].is_missing());
15520            assert_eq!(right_values[3], Scalar::Float64(202.0));
15521            assert_eq!(right_values[4], Scalar::Float64(203.0));
15522            assert!(right_values[5].is_missing());
15523            assert_eq!(right_values[6], Scalar::Float64(204.0));
15524        }
15525
15526        let nat = fp_types::Timestamp::NAT;
15527        let nat_left = DataFrame::from_dict(
15528            &["key", "lv"],
15529            vec![
15530                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
15531                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
15532            ],
15533        )?;
15534        let nat_right = DataFrame::from_dict(
15535            &["key", "rv"],
15536            vec![
15537                (
15538                    "key",
15539                    vec![
15540                        Scalar::Datetime64(nat),
15541                        Scalar::Datetime64(5),
15542                        Scalar::Datetime64(7),
15543                    ],
15544                ),
15545                (
15546                    "rv",
15547                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(12)],
15548                ),
15549            ],
15550        )?;
15551        assert!(
15552            super::ordered_unique_temporal_i64_outer_positions(
15553                nat_left.column("key").expect("left NaT key"),
15554                nat_right.column("key").expect("right NaT key"),
15555            )
15556            .is_none(),
15557            "NaT must retain the scalar Missing-key fallback",
15558        );
15559        let nat_candidate = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Outer)?;
15560        let nat_generic = merge_dataframes_on_with_options(
15561            &nat_left,
15562            &nat_right,
15563            &["key"],
15564            &["key"],
15565            JoinType::Outer,
15566            MergeExecutionOptions {
15567                sort: true,
15568                ..MergeExecutionOptions::default()
15569            },
15570        )?;
15571        assert_eq!(nat_candidate, nat_generic);
15572        assert_eq!(
15573            nat_candidate.columns["key"].dtype(),
15574            DType::datetime64_naive()
15575        );
15576        assert!(
15577            merged_values(&nat_candidate, "key")?
15578                .iter()
15579                .any(Scalar::is_missing),
15580        );
15581
15582        Ok(())
15583    }
15584
15585    #[test]
15586    fn merge_composite_datetime_component_is_honored_not_missing_j0in7() -> Result<(), JoinError> {
15587        // A COMPOSITE join key [Utf8, Datetime64] declines the single-key temporal
15588        // fast path (`temporal_i64_inner_positions`) and routes through the generic
15589        // Scalar/`scalar_to_key_component` path. The Datetime64 (and Timedelta64)
15590        // component must map to a Present key by value — NOT collapse to `Missing`.
15591        // If it collapsed to Missing, rows sharing the Utf8 component would match
15592        // regardless of timestamp (Missing == Missing), over-matching. Left has two
15593        // "a" rows at ts=10/20; right has "a" at ts=10/99. Honoring the datetime,
15594        // the only equal composite keys are ("a",10) and ("b",10) => exactly 2 rows.
15595        // Under the old Missing-collapse this would be 5 rows.
15596        let left = DataFrame::from_dict(
15597            &["region", "ts", "lv"],
15598            vec![
15599                (
15600                    "region",
15601                    vec![
15602                        Scalar::Utf8("a".to_owned()),
15603                        Scalar::Utf8("a".to_owned()),
15604                        Scalar::Utf8("b".to_owned()),
15605                    ],
15606                ),
15607                (
15608                    "ts",
15609                    vec![
15610                        Scalar::Datetime64(10),
15611                        Scalar::Datetime64(20),
15612                        Scalar::Datetime64(10),
15613                    ],
15614                ),
15615                (
15616                    "lv",
15617                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
15618                ),
15619            ],
15620        )?;
15621        let right = DataFrame::from_dict(
15622            &["region", "ts", "rv"],
15623            vec![
15624                (
15625                    "region",
15626                    vec![
15627                        Scalar::Utf8("a".to_owned()),
15628                        Scalar::Utf8("a".to_owned()),
15629                        Scalar::Utf8("b".to_owned()),
15630                    ],
15631                ),
15632                (
15633                    "ts",
15634                    vec![
15635                        Scalar::Datetime64(10),
15636                        Scalar::Datetime64(99),
15637                        Scalar::Datetime64(10),
15638                    ],
15639                ),
15640                (
15641                    "rv",
15642                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(102)],
15643                ),
15644            ],
15645        )?;
15646        let merged = merge_dataframes_on(&left, &right, &["region", "ts"], JoinType::Inner)?;
15647        assert_eq!(
15648            merged.index.len(),
15649            2,
15650            "datetime composite component must discriminate, not collapse to Missing"
15651        );
15652        assert_eq!(merged.columns["ts"].dtype(), DType::datetime64_naive());
15653        // Pair (lv, rv) up per output row, order-independently.
15654        let mut pairs: Vec<(i64, i64)> = merged_values(&merged, "lv")?
15655            .iter()
15656            .zip(merged_values(&merged, "rv")?)
15657            .map(|(l, r)| match (l, r) {
15658                (Scalar::Int64(a), Scalar::Int64(b)) => (*a, *b),
15659                _ => panic!("unexpected non-Int64 value column"),
15660            })
15661            .collect();
15662        pairs.sort_unstable();
15663        assert_eq!(pairs, vec![(0, 100), (2, 102)]);
15664
15665        // The Timedelta64 sibling arm must behave identically.
15666        let ltd = DataFrame::from_dict(
15667            &["region", "td", "lv"],
15668            vec![
15669                (
15670                    "region",
15671                    vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("a".to_owned())],
15672                ),
15673                ("td", vec![Scalar::Timedelta64(10), Scalar::Timedelta64(20)]),
15674                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
15675            ],
15676        )?;
15677        let rtd = DataFrame::from_dict(
15678            &["region", "td", "rv"],
15679            vec![
15680                (
15681                    "region",
15682                    vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("a".to_owned())],
15683                ),
15684                ("td", vec![Scalar::Timedelta64(10), Scalar::Timedelta64(99)]),
15685                ("rv", vec![Scalar::Int64(100), Scalar::Int64(101)]),
15686            ],
15687        )?;
15688        let merged_td = merge_dataframes_on(&ltd, &rtd, &["region", "td"], JoinType::Inner)?;
15689        assert_eq!(
15690            merged_td.index.len(),
15691            1,
15692            "timedelta composite component must discriminate, not collapse to Missing"
15693        );
15694        assert_eq!(merged_values(&merged_td, "lv")?, &[Scalar::Int64(0)]);
15695        assert_eq!(merged_values(&merged_td, "rv")?, &[Scalar::Int64(100)]);
15696
15697        Ok(())
15698    }
15699
15700    fn merged_values_where_indicator(
15701        merged: &MergedDataFrame,
15702        column_name: &str,
15703        indicator_name: &str,
15704        indicator_value: &str,
15705    ) -> Result<Vec<Scalar>, JoinError> {
15706        let values = merged_values(merged, column_name)?;
15707        let indicators = merged_values(merged, indicator_name)?;
15708        Ok(values
15709            .iter()
15710            .zip(indicators.iter())
15711            .filter_map(|(value, indicator)| {
15712                if matches!(indicator, Scalar::Utf8(v) if v == indicator_value) {
15713                    Some(value.clone())
15714                } else {
15715                    None
15716                }
15717            })
15718            .collect())
15719    }
15720
15721    #[test]
15722    fn merge_inner_basic() {
15723        let left = make_left_df();
15724        let right = make_right_df();
15725        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15726
15727        assert_eq!(merged.columns.get("id").unwrap().len(), 2);
15728        assert_eq!(
15729            merged.columns.get("id").unwrap().values(),
15730            &[Scalar::Int64(2), Scalar::Int64(3)]
15731        );
15732        assert_eq!(
15733            merged.columns.get("val_a").unwrap().values(),
15734            &[Scalar::Int64(20), Scalar::Int64(30)]
15735        );
15736        assert_eq!(
15737            merged.columns.get("val_b").unwrap().values(),
15738            &[Scalar::Int64(200), Scalar::Int64(300)]
15739        );
15740    }
15741
15742    #[test]
15743    fn merge_inner_single_key_preserves_duplicate_probe_order() {
15744        let left = DataFrame::from_dict(
15745            &["id", "left_value"],
15746            vec![
15747                (
15748                    "id",
15749                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
15750                ),
15751                (
15752                    "left_value",
15753                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
15754                ),
15755            ],
15756        )
15757        .unwrap();
15758        let right = DataFrame::from_dict(
15759            &["id", "right_value"],
15760            vec![
15761                (
15762                    "id",
15763                    vec![Scalar::Int64(2), Scalar::Int64(2), Scalar::Int64(1)],
15764                ),
15765                (
15766                    "right_value",
15767                    vec![Scalar::Int64(200), Scalar::Int64(201), Scalar::Int64(100)],
15768                ),
15769            ],
15770        )
15771        .unwrap();
15772
15773        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15774
15775        assert_eq!(
15776            merged.columns.get("id").unwrap().values(),
15777            &[
15778                Scalar::Int64(2),
15779                Scalar::Int64(2),
15780                Scalar::Int64(1),
15781                Scalar::Int64(2),
15782                Scalar::Int64(2),
15783            ]
15784        );
15785        assert_eq!(
15786            merged.columns.get("left_value").unwrap().values(),
15787            &[
15788                Scalar::Int64(20),
15789                Scalar::Int64(20),
15790                Scalar::Int64(10),
15791                Scalar::Int64(21),
15792                Scalar::Int64(21),
15793            ]
15794        );
15795        assert_eq!(
15796            merged.columns.get("right_value").unwrap().values(),
15797            &[
15798                Scalar::Int64(200),
15799                Scalar::Int64(201),
15800                Scalar::Int64(100),
15801                Scalar::Int64(200),
15802                Scalar::Int64(201),
15803            ]
15804        );
15805    }
15806
15807    #[test]
15808    fn merge_inner_wide_sparse_int64_hash_matches_generic_validated_route() {
15809        let stride = 1_i64 << 30;
15810        let left = DataFrame::from_dict(
15811            &["id", "left_value"],
15812            vec![
15813                (
15814                    "id",
15815                    vec![3, 1, 3, 0, 2]
15816                        .into_iter()
15817                        .map(|v| Scalar::Int64(v * stride))
15818                        .collect(),
15819                ),
15820                (
15821                    "left_value",
15822                    vec![
15823                        Scalar::Int64(10),
15824                        Scalar::Int64(11),
15825                        Scalar::Int64(12),
15826                        Scalar::Int64(13),
15827                        Scalar::Int64(14),
15828                    ],
15829                ),
15830            ],
15831        )
15832        .unwrap();
15833        let right = DataFrame::from_dict(
15834            &["id", "right_value"],
15835            vec![
15836                (
15837                    "id",
15838                    vec![3, 2, 3, 1]
15839                        .into_iter()
15840                        .map(|v| Scalar::Int64(v * stride))
15841                        .collect(),
15842                ),
15843                (
15844                    "right_value",
15845                    vec![
15846                        Scalar::Int64(100),
15847                        Scalar::Int64(101),
15848                        Scalar::Int64(102),
15849                        Scalar::Int64(103),
15850                    ],
15851                ),
15852            ],
15853        )
15854        .unwrap();
15855
15856        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15857        let generic = merge_dataframes_on_with_options(
15858            &left,
15859            &right,
15860            &["id"],
15861            &["id"],
15862            JoinType::Inner,
15863            MergeExecutionOptions {
15864                validate_mode: Some(MergeValidateMode::ManyToMany),
15865                ..MergeExecutionOptions::default()
15866            },
15867        )
15868        .unwrap();
15869
15870        assert_eq!(fast.index, generic.index);
15871        assert_eq!(fast.column_order, generic.column_order);
15872        assert_eq!(fast.columns, generic.columns);
15873        assert_eq!(
15874            fast.columns.get("id").unwrap().values(),
15875            &[
15876                Scalar::Int64(3 * stride),
15877                Scalar::Int64(3 * stride),
15878                Scalar::Int64(stride),
15879                Scalar::Int64(3 * stride),
15880                Scalar::Int64(3 * stride),
15881                Scalar::Int64(2 * stride),
15882            ]
15883        );
15884        assert_eq!(
15885            fast.columns.get("left_value").unwrap().values(),
15886            &[
15887                Scalar::Int64(10),
15888                Scalar::Int64(10),
15889                Scalar::Int64(11),
15890                Scalar::Int64(12),
15891                Scalar::Int64(12),
15892                Scalar::Int64(14),
15893            ]
15894        );
15895        assert_eq!(
15896            fast.columns.get("right_value").unwrap().values(),
15897            &[
15898                Scalar::Int64(100),
15899                Scalar::Int64(102),
15900                Scalar::Int64(103),
15901                Scalar::Int64(100),
15902                Scalar::Int64(102),
15903                Scalar::Int64(101),
15904            ]
15905        );
15906    }
15907
15908    #[test]
15909    fn dense_i64_inner_parallel_output_data_preserves_row_major_order() {
15910        let left_keys = vec![-1, 2, 1, 2, 3, 9];
15911        let min = 1;
15912        let max = 3;
15913        let offsets = vec![0, 2, 3, 5];
15914        let positions = vec![1usize, 4, 0, 2, 3];
15915        let left_values = vec![10, 20, 30, 40, 50, 60];
15916        let right_values = vec![100, 101, 102, 103, 104];
15917        let specs = vec![
15918            FusedInt64OutputColumn {
15919                name: "left".to_string(),
15920                side: FusedInt64Side::Left,
15921                values: &left_values,
15922            },
15923            FusedInt64OutputColumn {
15924                name: "right".to_string(),
15925                side: FusedInt64Side::Right,
15926                values: &right_values,
15927            },
15928        ];
15929
15930        let plan = DenseI64InnerOutputPlan {
15931            left_keys: &left_keys,
15932            min,
15933            max,
15934            offsets: &offsets,
15935            positions: &positions,
15936            output_len: 6,
15937        };
15938        let actual = build_dense_i64_inner_output_data(&specs, &plan);
15939
15940        // 4 matched left rows -> 6 output rows: avg fanout < 2, so the left
15941        // lane stays fully materialized alongside the right lane.
15942        assert_eq!(lane_expanded(&actual[0]), vec![20, 30, 30, 40, 50, 50]);
15943        assert_eq!(
15944            lane_expanded(&actual[1]),
15945            vec![100, 101, 104, 100, 102, 103]
15946        );
15947        assert!(matches!(actual[0], DenseI64LaneData::Full(_)));
15948        assert!(matches!(actual[1], DenseI64LaneData::Full(_)));
15949    }
15950
15951    fn lane_expanded(lane: &DenseI64LaneData) -> Vec<i64> {
15952        match lane {
15953            DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
15954                let mut out = Vec::new();
15955                for (&value, &run_len) in values.iter().zip(run_lens.iter()) {
15956                    out.resize(out.len() + run_len, value);
15957                }
15958                out
15959            }
15960            DenseI64LaneData::RepeatedSlices { data, segments } => {
15961                let mut out = Vec::new();
15962                for &(start, len) in segments.iter() {
15963                    out.extend_from_slice(&data[start..start + len]);
15964                }
15965                out
15966            }
15967            DenseI64LaneData::Full(data) => data.clone(),
15968        }
15969    }
15970
15971    #[test]
15972    fn dense_i64_inner_high_fanout_emits_repeat_run_left_lanes() {
15973        // 2 matched left rows, each matching 3 right rows -> avg fanout 3:
15974        // left lane must come back as repeat runs and the right lane as
15975        // repeated slices. Their expansion equals the old full fill.
15976        let left_keys = vec![1, 7, 2];
15977        let min = 1;
15978        let max = 2;
15979        let offsets = vec![0, 3, 6];
15980        let positions = vec![0usize, 2, 4, 1, 3, 5];
15981        let left_values = vec![10, 20, 30];
15982        let right_values = vec![100, 101, 102, 103, 104, 105];
15983        let specs = vec![
15984            FusedInt64OutputColumn {
15985                name: "left".to_string(),
15986                side: FusedInt64Side::Left,
15987                values: &left_values,
15988            },
15989            FusedInt64OutputColumn {
15990                name: "right".to_string(),
15991                side: FusedInt64Side::Right,
15992                values: &right_values,
15993            },
15994        ];
15995
15996        let plan = DenseI64InnerOutputPlan {
15997            left_keys: &left_keys,
15998            min,
15999            max,
16000            offsets: &offsets,
16001            positions: &positions,
16002            output_len: 6,
16003        };
16004        let actual = build_dense_i64_inner_output_data(&specs, &plan);
16005
16006        assert!(matches!(
16007            actual[0],
16008            DenseI64LaneData::RepeatRunLengths { .. }
16009        ));
16010        assert!(matches!(actual[1], DenseI64LaneData::RepeatedSlices { .. }));
16011        assert_eq!(lane_expanded(&actual[0]), vec![10, 10, 10, 30, 30, 30]);
16012        assert_eq!(
16013            lane_expanded(&actual[1]),
16014            vec![100, 102, 104, 101, 103, 105]
16015        );
16016
16017        // The lazy Column built from shared run lengths is indistinguishable
16018        // from the eagerly materialized one (values, slice view, length,
16019        // equality).
16020        let lazy = fp_columnar::Column::from_i64_repeat_values_run_lengths(
16021            vec![10, 30],
16022            std::sync::Arc::from([3usize, 3]),
16023        );
16024        let eager = fp_columnar::Column::from_i64_values(vec![10, 10, 10, 30, 30, 30]);
16025        assert_eq!(lazy.len(), eager.len());
16026        assert_eq!(lazy.as_i64_slice(), eager.as_i64_slice());
16027        assert_eq!(lazy.values(), eager.values());
16028        assert_eq!(lazy, eager);
16029    }
16030
16031    #[test]
16032    fn dense_cycle_left_join_declines_invented_gaps_66wab() {
16033        let left = DataFrame::from_dict(
16034            &["id", "v"],
16035            vec![
16036                (
16037                    "id",
16038                    vec![
16039                        Scalar::Int64(0),
16040                        Scalar::Int64(1),
16041                        Scalar::Int64(2),
16042                        Scalar::Int64(0),
16043                        Scalar::Int64(1),
16044                        Scalar::Int64(2),
16045                        Scalar::Int64(0),
16046                    ],
16047                ),
16048                (
16049                    "v",
16050                    vec![
16051                        Scalar::Int64(10),
16052                        Scalar::Int64(11),
16053                        Scalar::Int64(12),
16054                        Scalar::Int64(13),
16055                        Scalar::Int64(14),
16056                        Scalar::Int64(15),
16057                        Scalar::Int64(16),
16058                    ],
16059                ),
16060            ],
16061        )
16062        .unwrap();
16063        let right = DataFrame::from_dict(
16064            &["id", "rv"],
16065            vec![
16066                (
16067                    "id",
16068                    vec![
16069                        Scalar::Int64(1),
16070                        Scalar::Int64(2),
16071                        Scalar::Int64(1),
16072                        Scalar::Int64(2),
16073                    ],
16074                ),
16075                (
16076                    "rv",
16077                    vec![
16078                        Scalar::Int64(100),
16079                        Scalar::Int64(200),
16080                        Scalar::Int64(101),
16081                        Scalar::Int64(201),
16082                    ],
16083                ),
16084            ],
16085        )
16086        .unwrap();
16087        let suffixes = ResolvedMergeSuffixes::default();
16088        let left_key = left.column("id").unwrap();
16089        let right_key = right.column("id").unwrap();
16090
16091        let dense_cycle = build_single_key_dense_cycle_i64_left_merge_output(
16092            &left,
16093            &right,
16094            &["id"],
16095            &["id"],
16096            left_key,
16097            right_key,
16098            &suffixes,
16099        )
16100        .unwrap();
16101        assert!(dense_cycle.is_none());
16102        assert!(
16103            build_single_key_dense_i64_left_merge_output(
16104                &left,
16105                &right,
16106                &["id"],
16107                &["id"],
16108                left_key,
16109                right_key,
16110                &suffixes,
16111            )
16112            .unwrap()
16113            .is_none()
16114        );
16115    }
16116
16117    #[test]
16118    fn merge_inner_ordered_identity_matches_generic_validated_route() {
16119        let left = DataFrame::from_dict(
16120            &["id", "v"],
16121            vec![
16122                (
16123                    "id",
16124                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16125                ),
16126                (
16127                    "v",
16128                    vec![
16129                        Scalar::Int64(10),
16130                        Scalar::Null(NullKind::Null),
16131                        Scalar::Int64(30),
16132                    ],
16133                ),
16134            ],
16135        )
16136        .unwrap();
16137        let right = DataFrame::from_dict(
16138            &["id", "w"],
16139            vec![
16140                (
16141                    "id",
16142                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16143                ),
16144                (
16145                    "w",
16146                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
16147                ),
16148            ],
16149        )
16150        .unwrap();
16151
16152        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
16153        let generic = merge_dataframes_on_with_options(
16154            &left,
16155            &right,
16156            &["id"],
16157            &["id"],
16158            JoinType::Inner,
16159            MergeExecutionOptions {
16160                validate_mode: Some(MergeValidateMode::OneToOne),
16161                ..MergeExecutionOptions::default()
16162            },
16163        )
16164        .unwrap();
16165
16166        assert_eq!(fast.index, generic.index);
16167        assert_eq!(fast.column_order, generic.column_order);
16168        assert_eq!(fast.columns, generic.columns);
16169    }
16170
16171    #[test]
16172    fn merge_inner_dense_int64_fused_materialization_matches_generic_route() {
16173        let left = DataFrame::from_dict(
16174            &["id", "v", "overlap"],
16175            vec![
16176                (
16177                    "id",
16178                    vec![
16179                        Scalar::Int64(2),
16180                        Scalar::Int64(1),
16181                        Scalar::Int64(2),
16182                        Scalar::Int64(3),
16183                    ],
16184                ),
16185                (
16186                    "v",
16187                    vec![
16188                        Scalar::Int64(20),
16189                        Scalar::Int64(10),
16190                        Scalar::Int64(21),
16191                        Scalar::Int64(30),
16192                    ],
16193                ),
16194                (
16195                    "overlap",
16196                    vec![
16197                        Scalar::Int64(200),
16198                        Scalar::Int64(100),
16199                        Scalar::Int64(201),
16200                        Scalar::Int64(300),
16201                    ],
16202                ),
16203            ],
16204        )
16205        .unwrap();
16206        let right = DataFrame::from_dict(
16207            &["id", "w", "overlap"],
16208            vec![
16209                (
16210                    "id",
16211                    vec![
16212                        Scalar::Int64(2),
16213                        Scalar::Int64(2),
16214                        Scalar::Int64(1),
16215                        Scalar::Int64(4),
16216                    ],
16217                ),
16218                (
16219                    "w",
16220                    vec![
16221                        Scalar::Int64(2000),
16222                        Scalar::Int64(2001),
16223                        Scalar::Int64(1000),
16224                        Scalar::Int64(4000),
16225                    ],
16226                ),
16227                (
16228                    "overlap",
16229                    vec![
16230                        Scalar::Int64(20_000),
16231                        Scalar::Int64(20_001),
16232                        Scalar::Int64(10_000),
16233                        Scalar::Int64(40_000),
16234                    ],
16235                ),
16236            ],
16237        )
16238        .unwrap();
16239
16240        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
16241        let generic = merge_dataframes_on_with_options(
16242            &left,
16243            &right,
16244            &["id"],
16245            &["id"],
16246            JoinType::Inner,
16247            MergeExecutionOptions {
16248                validate_mode: Some(MergeValidateMode::ManyToMany),
16249                ..MergeExecutionOptions::default()
16250            },
16251        )
16252        .unwrap();
16253
16254        assert_eq!(fast.index, generic.index);
16255        assert_eq!(fast.column_order, generic.column_order);
16256        assert_eq!(fast.columns, generic.columns);
16257        assert_eq!(
16258            fast.column_order,
16259            ["id", "v", "overlap_x", "w", "overlap_y"]
16260        );
16261        assert_eq!(
16262            fast.columns.get("id").unwrap().values(),
16263            &[
16264                Scalar::Int64(2),
16265                Scalar::Int64(2),
16266                Scalar::Int64(1),
16267                Scalar::Int64(2),
16268                Scalar::Int64(2),
16269            ]
16270        );
16271        assert_eq!(
16272            fast.columns.get("w").unwrap().values(),
16273            &[
16274                Scalar::Int64(2000),
16275                Scalar::Int64(2001),
16276                Scalar::Int64(1000),
16277                Scalar::Int64(2000),
16278                Scalar::Int64(2001),
16279            ]
16280        );
16281        assert!(
16282            fast.columns
16283                .values()
16284                .all(|column| column.as_i64_slice().is_some())
16285        );
16286    }
16287
16288    #[test]
16289    fn merge_inner_ordered_unique_int64_subset_matches_generic_validated_route() {
16290        let left = DataFrame::from_dict(
16291            &["id", "v"],
16292            vec![
16293                (
16294                    "id",
16295                    vec![
16296                        Scalar::Int64(0),
16297                        Scalar::Int64(1),
16298                        Scalar::Int64(2),
16299                        Scalar::Int64(3),
16300                        Scalar::Int64(4),
16301                    ],
16302                ),
16303                (
16304                    "v",
16305                    vec![
16306                        Scalar::Int64(10),
16307                        Scalar::Int64(11),
16308                        Scalar::Int64(12),
16309                        Scalar::Int64(13),
16310                        Scalar::Int64(14),
16311                    ],
16312                ),
16313            ],
16314        )
16315        .unwrap();
16316        let right = DataFrame::from_dict(
16317            &["id", "w"],
16318            vec![
16319                (
16320                    "id",
16321                    vec![
16322                        Scalar::Int64(0),
16323                        Scalar::Int64(2),
16324                        Scalar::Int64(4),
16325                        Scalar::Int64(6),
16326                    ],
16327                ),
16328                (
16329                    "w",
16330                    vec![
16331                        Scalar::Int64(100),
16332                        Scalar::Int64(200),
16333                        Scalar::Int64(300),
16334                        Scalar::Int64(400),
16335                    ],
16336                ),
16337            ],
16338        )
16339        .unwrap();
16340
16341        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
16342        let generic = merge_dataframes_on_with_options(
16343            &left,
16344            &right,
16345            &["id"],
16346            &["id"],
16347            JoinType::Inner,
16348            MergeExecutionOptions {
16349                validate_mode: Some(MergeValidateMode::OneToOne),
16350                ..MergeExecutionOptions::default()
16351            },
16352        )
16353        .unwrap();
16354
16355        assert_eq!(fast.index, generic.index);
16356        assert_eq!(fast.column_order, generic.column_order);
16357        assert_eq!(fast.columns, generic.columns);
16358        assert_eq!(
16359            fast.columns.get("id").unwrap().values(),
16360            &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(4)]
16361        );
16362        assert_eq!(
16363            fast.columns.get("v").unwrap().values(),
16364            &[Scalar::Int64(10), Scalar::Int64(12), Scalar::Int64(14)]
16365        );
16366        assert_eq!(
16367            fast.columns.get("w").unwrap().values(),
16368            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
16369        );
16370    }
16371
16372    #[test]
16373    fn merge_inner_ordered_identity_falls_back_for_non_identity_keys() {
16374        let cases = [
16375            (
16376                vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(4)],
16377                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16378            ),
16379            (
16380                vec![
16381                    Scalar::Int64(1),
16382                    Scalar::Null(NullKind::Null),
16383                    Scalar::Int64(3),
16384                ],
16385                vec![
16386                    Scalar::Int64(1),
16387                    Scalar::Null(NullKind::Null),
16388                    Scalar::Int64(3),
16389                ],
16390            ),
16391        ];
16392
16393        for (left_keys, right_keys) in cases {
16394            let left = DataFrame::from_dict(
16395                &["id", "v"],
16396                vec![
16397                    ("id", left_keys),
16398                    (
16399                        "v",
16400                        vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
16401                    ),
16402                ],
16403            )
16404            .unwrap();
16405            let right = DataFrame::from_dict(
16406                &["id", "w"],
16407                vec![
16408                    ("id", right_keys),
16409                    (
16410                        "w",
16411                        vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
16412                    ),
16413                ],
16414            )
16415            .unwrap();
16416
16417            let maybe_fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
16418            let generic = merge_dataframes_on_with_options(
16419                &left,
16420                &right,
16421                &["id"],
16422                &["id"],
16423                JoinType::Inner,
16424                MergeExecutionOptions {
16425                    validate_mode: Some(MergeValidateMode::OneToOne),
16426                    ..MergeExecutionOptions::default()
16427                },
16428            )
16429            .unwrap();
16430
16431            assert_eq!(maybe_fast.index, generic.index);
16432            assert_eq!(maybe_fast.column_order, generic.column_order);
16433            assert_eq!(maybe_fast.columns, generic.columns);
16434        }
16435    }
16436
16437    #[test]
16438    fn merge_default_suffixes_match_pandas() {
16439        // Overlapping non-key column "v" gets pandas default _x/_y suffixes.
16440        // Verified vs pandas 2.2.3: left{k:[1,2,3],v:[10,20,30]} merged inner on
16441        // k with right{k:[2,3,4],v:[200,300,400]} -> cols [k,v_x,v_y],
16442        // k=[2,3], v_x=[20,30], v_y=[200,300].
16443        let idx: Vec<_> = (0..3).map(|i| (i as i64).into()).collect();
16444        let left = fp_frame::DataFrame::from_series(vec![
16445            fp_frame::Series::from_values(
16446                "k",
16447                idx.clone(),
16448                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16449            )
16450            .unwrap(),
16451            fp_frame::Series::from_values(
16452                "v",
16453                idx.clone(),
16454                vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
16455            )
16456            .unwrap(),
16457        ])
16458        .unwrap();
16459        let right = fp_frame::DataFrame::from_series(vec![
16460            fp_frame::Series::from_values(
16461                "k",
16462                idx.clone(),
16463                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
16464            )
16465            .unwrap(),
16466            fp_frame::Series::from_values(
16467                "v",
16468                idx,
16469                vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
16470            )
16471            .unwrap(),
16472        ])
16473        .unwrap();
16474        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
16475
16476        assert_eq!(
16477            merged.columns.get("k").unwrap().values(),
16478            &[Scalar::Int64(2), Scalar::Int64(3)],
16479            "k"
16480        );
16481        assert_eq!(
16482            merged.columns.get("v_x").unwrap().values(),
16483            &[Scalar::Int64(20), Scalar::Int64(30)],
16484            "v_x"
16485        );
16486        assert_eq!(
16487            merged.columns.get("v_y").unwrap().values(),
16488            &[Scalar::Int64(200), Scalar::Int64(300)],
16489            "v_y"
16490        );
16491        assert!(
16492            !merged.columns.contains_key("v"),
16493            "bare 'v' should be suffixed away"
16494        );
16495    }
16496
16497    #[test]
16498    fn merge_left_preserves_all_left_rows() {
16499        let left = make_left_df();
16500        let right = make_right_df();
16501        let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16502
16503        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
16504        assert_eq!(
16505            merged.columns.get("val_a").unwrap().values(),
16506            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
16507        );
16508        // val_b widens to Float64 because id=1 invents a missing value.
16509        assert_eq!(merged.columns.get("val_b").unwrap().dtype(), DType::Float64);
16510        assert_eq!(
16511            merged.columns.get("val_b").unwrap().values()[0],
16512            Scalar::Null(NullKind::NaN)
16513        );
16514        assert_eq!(
16515            merged.columns.get("val_b").unwrap().values()[1],
16516            Scalar::Float64(200.0)
16517        );
16518        assert_eq!(
16519            merged.columns.get("val_b").unwrap().values()[2],
16520            Scalar::Float64(300.0)
16521        );
16522    }
16523
16524    #[test]
16525    fn merge_left_ordered_unique_int64_subset_matches_generic_validated_route() {
16526        let left = DataFrame::from_dict(
16527            &["id", "v"],
16528            vec![
16529                (
16530                    "id",
16531                    vec![
16532                        Scalar::Int64(0),
16533                        Scalar::Int64(1),
16534                        Scalar::Int64(2),
16535                        Scalar::Int64(3),
16536                        Scalar::Int64(4),
16537                    ],
16538                ),
16539                (
16540                    "v",
16541                    vec![
16542                        Scalar::Int64(10),
16543                        Scalar::Int64(11),
16544                        Scalar::Int64(12),
16545                        Scalar::Int64(13),
16546                        Scalar::Int64(14),
16547                    ],
16548                ),
16549            ],
16550        )
16551        .unwrap();
16552        let right = DataFrame::from_dict(
16553            &["id", "w"],
16554            vec![
16555                (
16556                    "id",
16557                    vec![
16558                        Scalar::Int64(0),
16559                        Scalar::Int64(2),
16560                        Scalar::Int64(4),
16561                        Scalar::Int64(6),
16562                    ],
16563                ),
16564                (
16565                    "w",
16566                    vec![
16567                        Scalar::Int64(100),
16568                        Scalar::Int64(200),
16569                        Scalar::Int64(300),
16570                        Scalar::Int64(400),
16571                    ],
16572                ),
16573            ],
16574        )
16575        .unwrap();
16576
16577        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16578        let generic = merge_dataframes_on_with_options(
16579            &left,
16580            &right,
16581            &["id"],
16582            &["id"],
16583            JoinType::Left,
16584            MergeExecutionOptions {
16585                validate_mode: Some(MergeValidateMode::OneToOne),
16586                ..MergeExecutionOptions::default()
16587            },
16588        )
16589        .unwrap();
16590
16591        assert_eq!(fast.index, generic.index);
16592        assert_eq!(fast.column_order, generic.column_order);
16593        assert_eq!(fast.columns, generic.columns);
16594        assert_eq!(
16595            fast.columns.get("id").unwrap().values(),
16596            &[
16597                Scalar::Int64(0),
16598                Scalar::Int64(1),
16599                Scalar::Int64(2),
16600                Scalar::Int64(3),
16601                Scalar::Int64(4)
16602            ]
16603        );
16604        let right_values = fast.columns.get("w").unwrap().values();
16605        assert_eq!(right_values[0], Scalar::Float64(100.0));
16606        assert!(right_values[1].is_missing());
16607        assert_eq!(right_values[2], Scalar::Float64(200.0));
16608        assert!(right_values[3].is_missing());
16609        assert_eq!(right_values[4], Scalar::Float64(300.0));
16610    }
16611
16612    #[test]
16613    fn merge_left_ordered_unique_int64_retains_lazy_utf8_payload_plan() {
16614        let left = DataFrame::from_dict(
16615            &["id", "v"],
16616            vec![
16617                ("id", (0..5_i64).map(Scalar::Int64).collect::<Vec<_>>()),
16618                ("v", (10..15_i64).map(Scalar::Int64).collect::<Vec<_>>()),
16619            ],
16620        )
16621        .unwrap();
16622        let right = DataFrame::from_dict(
16623            &["id", "tag"],
16624            vec![
16625                (
16626                    "id",
16627                    [0_i64, 2, 4, 6].into_iter().map(Scalar::Int64).collect(),
16628                ),
16629                (
16630                    "tag",
16631                    ["zero", "two", "four", "six"]
16632                        .into_iter()
16633                        .map(|value| Scalar::Utf8(value.to_owned()))
16634                        .collect(),
16635                ),
16636            ],
16637        )
16638        .unwrap();
16639
16640        let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16641        let tags = merged.columns.get("tag").unwrap().values();
16642        assert_eq!(tags[0], Scalar::Utf8("zero".to_owned()));
16643        assert!(tags[1].is_missing());
16644        assert_eq!(tags[2], Scalar::Utf8("two".to_owned()));
16645        assert!(tags[3].is_missing());
16646        assert_eq!(tags[4], Scalar::Utf8("four".to_owned()));
16647    }
16648
16649    #[test]
16650    fn merge_left_dense_int64_duplicates_matches_generic_validated_route() {
16651        let left = DataFrame::from_dict(
16652            &["id", "v"],
16653            vec![
16654                (
16655                    "id",
16656                    vec![
16657                        Scalar::Int64(2),
16658                        Scalar::Int64(0),
16659                        Scalar::Int64(2),
16660                        Scalar::Int64(1),
16661                        Scalar::Int64(5),
16662                    ],
16663                ),
16664                (
16665                    "v",
16666                    vec![
16667                        Scalar::Int64(10),
16668                        Scalar::Int64(11),
16669                        Scalar::Int64(12),
16670                        Scalar::Int64(13),
16671                        Scalar::Int64(15),
16672                    ],
16673                ),
16674            ],
16675        )
16676        .unwrap();
16677        let right = DataFrame::from_dict(
16678            &["id", "w"],
16679            vec![
16680                (
16681                    "id",
16682                    vec![
16683                        Scalar::Int64(2),
16684                        Scalar::Int64(2),
16685                        Scalar::Int64(3),
16686                        Scalar::Int64(0),
16687                    ],
16688                ),
16689                (
16690                    "w",
16691                    vec![
16692                        Scalar::Int64(200),
16693                        Scalar::Int64(201),
16694                        Scalar::Int64(300),
16695                        Scalar::Int64(400),
16696                    ],
16697                ),
16698            ],
16699        )
16700        .unwrap();
16701
16702        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16703        let generic = merge_dataframes_on_with_options(
16704            &left,
16705            &right,
16706            &["id"],
16707            &["id"],
16708            JoinType::Left,
16709            MergeExecutionOptions {
16710                validate_mode: Some(MergeValidateMode::ManyToMany),
16711                ..MergeExecutionOptions::default()
16712            },
16713        )
16714        .unwrap();
16715
16716        assert_eq!(fast.index, generic.index);
16717        assert_eq!(fast.column_order, generic.column_order);
16718        assert_eq!(fast.columns, generic.columns);
16719        assert_eq!(
16720            fast.columns.get("id").unwrap().values(),
16721            &[
16722                Scalar::Int64(2),
16723                Scalar::Int64(2),
16724                Scalar::Int64(0),
16725                Scalar::Int64(2),
16726                Scalar::Int64(2),
16727                Scalar::Int64(1),
16728                Scalar::Int64(5),
16729            ]
16730        );
16731        let left_values = fast.columns.get("v").unwrap().values();
16732        assert_eq!(left_values[0], Scalar::Int64(10));
16733        assert_eq!(left_values[1], Scalar::Int64(10));
16734        assert_eq!(left_values[2], Scalar::Int64(11));
16735        assert_eq!(left_values[4], Scalar::Int64(12));
16736        assert_eq!(left_values[6], Scalar::Int64(15));
16737        let right_values = fast.columns.get("w").unwrap().values();
16738        assert_eq!(right_values[0], Scalar::Float64(200.0));
16739        assert_eq!(right_values[1], Scalar::Float64(201.0));
16740        assert_eq!(right_values[2], Scalar::Float64(400.0));
16741        assert!(right_values[5].is_missing());
16742        assert!(right_values[6].is_missing());
16743    }
16744
16745    #[test]
16746    fn merge_left_dense_cycle_probe_declines_invented_gaps_66wab() {
16747        let left = DataFrame::from_dict(
16748            &["id", "v"],
16749            vec![
16750                (
16751                    "id",
16752                    vec![
16753                        Scalar::Int64(0),
16754                        Scalar::Int64(1),
16755                        Scalar::Int64(2),
16756                        Scalar::Int64(0),
16757                        Scalar::Int64(1),
16758                    ],
16759                ),
16760                (
16761                    "v",
16762                    vec![
16763                        Scalar::Int64(10),
16764                        Scalar::Int64(11),
16765                        Scalar::Int64(12),
16766                        Scalar::Int64(13),
16767                        Scalar::Int64(14),
16768                    ],
16769                ),
16770            ],
16771        )
16772        .unwrap();
16773        let right = DataFrame::from_dict(
16774            &["id", "w"],
16775            vec![
16776                (
16777                    "id",
16778                    vec![
16779                        Scalar::Int64(1),
16780                        Scalar::Int64(2),
16781                        Scalar::Int64(1),
16782                        Scalar::Int64(2),
16783                    ],
16784                ),
16785                (
16786                    "w",
16787                    vec![
16788                        Scalar::Int64(100),
16789                        Scalar::Int64(200),
16790                        Scalar::Int64(101),
16791                        Scalar::Int64(201),
16792                    ],
16793                ),
16794            ],
16795        )
16796        .unwrap();
16797        let left_key = left.columns().get("id").unwrap();
16798        let right_key = right.columns().get("id").unwrap();
16799        assert!(left_key.int64_dense_cycle_witness().is_some());
16800        assert!(right_key.int64_dense_cycle_witness().is_some());
16801        let suffixes = resolve_merge_suffixes(None);
16802
16803        let fused = build_single_key_dense_i64_left_merge_output(
16804            &left,
16805            &right,
16806            &["id"],
16807            &["id"],
16808            left_key,
16809            right_key,
16810            &suffixes,
16811        )
16812        .unwrap();
16813        assert!(fused.is_none());
16814    }
16815
16816    #[test]
16817    fn partial_int64_merges_promote_invented_gaps_66wab() {
16818        let left = DataFrame::from_dict(
16819            &["id", "v"],
16820            vec![
16821                (
16822                    "id",
16823                    vec![
16824                        Scalar::Int64(0),
16825                        Scalar::Int64(1),
16826                        Scalar::Int64(2),
16827                        Scalar::Int64(0),
16828                        Scalar::Int64(1),
16829                    ],
16830                ),
16831                (
16832                    "v",
16833                    vec![
16834                        Scalar::Int64(10),
16835                        Scalar::Int64(11),
16836                        Scalar::Int64(12),
16837                        Scalar::Int64(13),
16838                        Scalar::Int64(14),
16839                    ],
16840                ),
16841            ],
16842        )
16843        .unwrap();
16844        let right = DataFrame::from_dict(
16845            &["id", "w"],
16846            vec![
16847                (
16848                    "id",
16849                    vec![
16850                        Scalar::Int64(1),
16851                        Scalar::Int64(2),
16852                        Scalar::Int64(1),
16853                        Scalar::Int64(2),
16854                    ],
16855                ),
16856                (
16857                    "w",
16858                    vec![
16859                        Scalar::Int64(100),
16860                        Scalar::Int64(200),
16861                        Scalar::Int64(101),
16862                        Scalar::Int64(201),
16863                    ],
16864                ),
16865            ],
16866        )
16867        .unwrap();
16868
16869        let left_join = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16870        let left_gap_column = left_join.columns.get("w").unwrap();
16871        assert_eq!(left_gap_column.dtype(), DType::Float64);
16872        assert_eq!(left_gap_column.values()[0], Scalar::Null(NullKind::NaN));
16873        assert_eq!(left_gap_column.values()[1], Scalar::Float64(100.0));
16874
16875        let right_join = merge_dataframes(&right, &left, "id", JoinType::Right).unwrap();
16876        let right_gap_column = right_join.columns.get("w").unwrap();
16877        assert_eq!(right_gap_column.dtype(), DType::Float64);
16878        assert_eq!(right_gap_column.values()[0], Scalar::Null(NullKind::NaN));
16879        assert_eq!(right_gap_column.values()[1], Scalar::Float64(100.0));
16880    }
16881
16882    /// A missing value FrankenPandas spells two ways on a float lane: the
16883    /// `Null(NaN)` marker, and a present `Float64` whose bits are NaN (typed
16884    /// kernels emit the latter directly). pandas has ONE representation — the
16885    /// NaN bit pattern in the float64 array — and the fixture format writes
16886    /// either as `na_n`, so a null-kind assertion on a float lane must accept
16887    /// both or it fails on a legitimate representation change. What it must
16888    /// still reject is a carried-over generic `Null(Null)` or a `NaT`.
16889    ///
16890    /// br-frankenpandas-nywa8; the trap is WindyHare's window/derived slice.
16891    fn assert_nan_flavoured(value: &Scalar, what: &str) {
16892        let ok = match value {
16893            Scalar::Null(NullKind::NaN) => true,
16894            Scalar::Float64(v) => v.is_nan(),
16895            _ => false,
16896        };
16897        assert!(
16898            ok,
16899            "{what}: expected a NaN-flavoured missing, got {value:?}"
16900        );
16901    }
16902
16903    /// The four merge fixtures that were the last structural rows on
16904    /// br-frankenpandas-nywa8, run through the SAME entry point the conformance
16905    /// harness uses (`merge_dataframes_on_with_options`) on their exact
16906    /// payloads.
16907    ///
16908    /// THE RULE, and every line of it MEASURED against live pandas 2.2.3 rather
16909    /// than inferred from the differ: a lane widens iff the merge INVENTS a gap
16910    /// in THAT lane. The join type is irrelevant, and a lane that gains no gap
16911    /// keeps int64.
16912    ///
16913    /// ```text
16914    ///   l={'id':[1,2,3],'left_v':[10,20,30],'shared':[1,2,3]}
16915    ///   r={'id':[2],'right_v':[200],'shared':[9]}
16916    ///   l.merge(r, on='id', how='left')
16917    ///     id int64  left_v int64  shared_x int64      no gap  -> unchanged
16918    ///     right_v float64 [nan,200.0,nan]
16919    ///     shared_y float64 [nan,9.0,nan]              gap     -> widened
16920    ///
16921    ///   l={'id':[1,2],'left_v':[11,22]}  r={'id':[2,3],'right_v':[220,330]}
16922    ///   l.merge(r, on='id', how='right')
16923    ///     left_v float64 [22.0,nan]   right_v int64 [220,330]   id int64
16924    ///
16925    ///   l.merge(r, on='id', how='right', sort=True) over id l=[3,1] r=[2,1,3]
16926    ///     id int64 [1,2,3]  left_v float64 [10.0,nan,30.0]  right_v int64
16927    /// ```
16928    ///
16929    /// THE COMPOSITE OUTER CASE IS THE ONE WORTH THE TEST, because a single
16930    /// object column carries nywa8's two rules side by side. Measured on
16931    /// `lk2 = ['a', None, 'c']` outer-merged against `rk2 = ['a', None, 'd']`:
16932    ///
16933    /// ```text
16934    ///   lk2 dtype object, kinds ['str', 'NoneType', 'str', 'float']
16935    ///                                     ^ RULE 2          ^ RULE 1
16936    /// ```
16937    ///
16938    /// Row 1's `None` was SUPPLIED and object can store it, so pandas keeps it.
16939    /// Row 3's gap was INVENTED by the outer join, and pandas writes a float nan
16940    /// there even though the column is object. That is why the rule cannot be
16941    /// "derive the marker from the column dtype" — the same column answers
16942    /// differently per cell, and only the site that invents the gap knows which.
16943    #[test]
16944    fn merge_widens_only_the_lane_that_gains_an_invented_gap_nywa8() {
16945        // FP-P2D-014 dataframe_merge_column_left_missing_hardened
16946        let left = DataFrame::from_dict(
16947            &["id", "left_v", "shared"],
16948            vec![
16949                (
16950                    "id",
16951                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16952                ),
16953                (
16954                    "left_v",
16955                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
16956                ),
16957                (
16958                    "shared",
16959                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16960                ),
16961            ],
16962        )
16963        .unwrap();
16964        let right = DataFrame::from_dict(
16965            &["id", "right_v", "shared"],
16966            vec![
16967                ("id", vec![Scalar::Int64(2)]),
16968                ("right_v", vec![Scalar::Int64(200)]),
16969                ("shared", vec![Scalar::Int64(9)]),
16970            ],
16971        )
16972        .unwrap();
16973        let merged = merge_dataframes_on_with_options(
16974            &left,
16975            &right,
16976            &["id"],
16977            &["id"],
16978            JoinType::Left,
16979            MergeExecutionOptions::default(),
16980        )
16981        .unwrap();
16982        for gapless in ["id", "left_v", "shared_x"] {
16983            assert_eq!(
16984                merged.columns.get(gapless).unwrap().dtype(),
16985                DType::Int64,
16986                "{gapless} gains no gap and must stay int64"
16987            );
16988        }
16989        for gapped in ["right_v", "shared_y"] {
16990            let column = merged.columns.get(gapped).unwrap();
16991            assert_eq!(column.dtype(), DType::Float64, "{gapped} gains a gap");
16992            assert_nan_flavoured(&column.values()[0], gapped);
16993            assert_nan_flavoured(&column.values()[2], gapped);
16994        }
16995        assert_eq!(
16996            merged.columns.get("right_v").unwrap().values()[1],
16997            Scalar::Float64(200.0)
16998        );
16999        assert_eq!(
17000            merged.columns.get("shared_y").unwrap().values()[1],
17001            Scalar::Float64(9.0)
17002        );
17003
17004        // FP-P2D-014 dataframe_merge_column_right_order_strict
17005        let left = DataFrame::from_dict(
17006            &["id", "left_v"],
17007            vec![
17008                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17009                ("left_v", vec![Scalar::Int64(11), Scalar::Int64(22)]),
17010            ],
17011        )
17012        .unwrap();
17013        let right = DataFrame::from_dict(
17014            &["id", "right_v"],
17015            vec![
17016                ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
17017                ("right_v", vec![Scalar::Int64(220), Scalar::Int64(330)]),
17018            ],
17019        )
17020        .unwrap();
17021        let merged = merge_dataframes_on_with_options(
17022            &left,
17023            &right,
17024            &["id"],
17025            &["id"],
17026            JoinType::Right,
17027            MergeExecutionOptions::default(),
17028        )
17029        .unwrap();
17030        assert_eq!(merged.columns.get("id").unwrap().dtype(), DType::Int64);
17031        assert_eq!(merged.columns.get("right_v").unwrap().dtype(), DType::Int64);
17032        let left_v = merged.columns.get("left_v").unwrap();
17033        assert_eq!(left_v.dtype(), DType::Float64);
17034        assert_eq!(left_v.values()[0], Scalar::Float64(22.0));
17035        assert_nan_flavoured(&left_v.values()[1], "left_v");
17036
17037        // FP-P2D-037 dataframe_merge_sort_true_right_hardened
17038        let left = DataFrame::from_dict(
17039            &["id", "left_v"],
17040            vec![
17041                ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
17042                ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
17043            ],
17044        )
17045        .unwrap();
17046        let right = DataFrame::from_dict(
17047            &["id", "right_v"],
17048            vec![
17049                (
17050                    "id",
17051                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
17052                ),
17053                (
17054                    "right_v",
17055                    vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
17056                ),
17057            ],
17058        )
17059        .unwrap();
17060        let merged = merge_dataframes_on_with_options(
17061            &left,
17062            &right,
17063            &["id"],
17064            &["id"],
17065            JoinType::Right,
17066            MergeExecutionOptions {
17067                sort: true,
17068                ..MergeExecutionOptions::default()
17069            },
17070        )
17071        .unwrap();
17072        assert_eq!(merged.columns.get("id").unwrap().dtype(), DType::Int64);
17073        assert_eq!(merged.columns.get("right_v").unwrap().dtype(), DType::Int64);
17074        let left_v = merged.columns.get("left_v").unwrap();
17075        assert_eq!(left_v.dtype(), DType::Float64);
17076        assert_eq!(left_v.values()[0], Scalar::Float64(10.0));
17077        assert_nan_flavoured(&left_v.values()[1], "left_v");
17078        assert_eq!(left_v.values()[2], Scalar::Float64(30.0));
17079
17080        // FP-P2D-033 dataframe_merge_composite_left_right_alias_outer_hardened
17081        let left = DataFrame::from_dict(
17082            &["lk1", "lk2", "left_v"],
17083            vec![
17084                (
17085                    "lk1",
17086                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
17087                ),
17088                (
17089                    "lk2",
17090                    vec![
17091                        Scalar::Utf8("a".to_owned()),
17092                        Scalar::Null(NullKind::Null),
17093                        Scalar::Utf8("c".to_owned()),
17094                    ],
17095                ),
17096                (
17097                    "left_v",
17098                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
17099                ),
17100            ],
17101        )
17102        .unwrap();
17103        let right = DataFrame::from_dict(
17104            &["rk1", "rk2", "right_v"],
17105            vec![
17106                (
17107                    "rk1",
17108                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
17109                ),
17110                (
17111                    "rk2",
17112                    vec![
17113                        Scalar::Utf8("a".to_owned()),
17114                        Scalar::Null(NullKind::Null),
17115                        Scalar::Utf8("d".to_owned()),
17116                    ],
17117                ),
17118                (
17119                    "right_v",
17120                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
17121                ),
17122            ],
17123        )
17124        .unwrap();
17125        let merged = merge_dataframes_on_with_options(
17126            &left,
17127            &right,
17128            &["lk1", "lk2"],
17129            &["rk1", "rk2"],
17130            JoinType::Outer,
17131            MergeExecutionOptions::default(),
17132        )
17133        .unwrap();
17134        // Every numeric lane gains a gap under this outer merge, so all four widen.
17135        for numeric in ["lk1", "rk1", "left_v", "right_v"] {
17136            assert_eq!(
17137                merged.columns.get(numeric).unwrap().dtype(),
17138                DType::Float64,
17139                "{numeric} gains a gap under the outer merge"
17140            );
17141        }
17142        assert_nan_flavoured(&merged.columns.get("lk1").unwrap().values()[3], "lk1");
17143        assert_nan_flavoured(&merged.columns.get("left_v").unwrap().values()[3], "left_v");
17144        assert_nan_flavoured(&merged.columns.get("rk1").unwrap().values()[2], "rk1");
17145        assert_nan_flavoured(
17146            &merged.columns.get("right_v").unwrap().values()[2],
17147            "right_v",
17148        );
17149
17150        // The object lanes are the point: SUPPLIED None survives, INVENTED gap
17151        // is a nan, in the same column.
17152        let lk2 = merged.columns.get("lk2").unwrap();
17153        assert_eq!(lk2.values()[0], Scalar::Utf8("a".to_owned()));
17154        assert_eq!(
17155            lk2.values()[1],
17156            Scalar::Null(NullKind::Null),
17157            "lk2[1]'s None was SUPPLIED and object can hold it (nywa8 Rule 2)"
17158        );
17159        assert_eq!(lk2.values()[2], Scalar::Utf8("c".to_owned()));
17160        assert_nan_flavoured(&lk2.values()[3], "lk2[3] is an INVENTED gap (nywa8 Rule 1)");
17161
17162        let rk2 = merged.columns.get("rk2").unwrap();
17163        assert_eq!(rk2.values()[0], Scalar::Utf8("a".to_owned()));
17164        assert_eq!(
17165            rk2.values()[1],
17166            Scalar::Null(NullKind::Null),
17167            "rk2[1]'s None was SUPPLIED and object can hold it (nywa8 Rule 2)"
17168        );
17169        assert_nan_flavoured(&rk2.values()[2], "rk2[2] is an INVENTED gap (nywa8 Rule 1)");
17170        assert_eq!(rk2.values()[3], Scalar::Utf8("d".to_owned()));
17171    }
17172
17173    #[test]
17174    fn merge_left_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
17175        let left = DataFrame::from_dict(
17176            &["id", "v"],
17177            vec![
17178                (
17179                    "id",
17180                    vec![
17181                        Scalar::Int64(0),
17182                        Scalar::Int64(0),
17183                        Scalar::Int64(1),
17184                        Scalar::Int64(1),
17185                        Scalar::Int64(2),
17186                    ],
17187                ),
17188                (
17189                    "v",
17190                    vec![
17191                        Scalar::Int64(10),
17192                        Scalar::Int64(11),
17193                        Scalar::Int64(20),
17194                        Scalar::Int64(21),
17195                        Scalar::Int64(30),
17196                    ],
17197                ),
17198            ],
17199        )
17200        .unwrap();
17201        let right = DataFrame::from_dict(
17202            &["id", "w"],
17203            vec![
17204                (
17205                    "id",
17206                    vec![
17207                        Scalar::Int64(0),
17208                        Scalar::Int64(0),
17209                        Scalar::Int64(1),
17210                        Scalar::Int64(2),
17211                        Scalar::Int64(2),
17212                    ],
17213                ),
17214                (
17215                    "w",
17216                    vec![
17217                        Scalar::Int64(100),
17218                        Scalar::Int64(101),
17219                        Scalar::Int64(200),
17220                        Scalar::Int64(300),
17221                        Scalar::Int64(301),
17222                    ],
17223                ),
17224            ],
17225        )
17226        .unwrap();
17227
17228        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
17229        let generic = merge_dataframes_on_with_options(
17230            &left,
17231            &right,
17232            &["id"],
17233            &["id"],
17234            JoinType::Left,
17235            MergeExecutionOptions {
17236                sort: true,
17237                ..MergeExecutionOptions::default()
17238            },
17239        )
17240        .unwrap();
17241
17242        assert_eq!(fast.index, generic.index);
17243        assert_eq!(fast.column_order, generic.column_order);
17244        assert_eq!(fast.columns, generic.columns);
17245        assert_eq!(
17246            fast.columns.get("id").unwrap().values(),
17247            &[
17248                Scalar::Int64(0),
17249                Scalar::Int64(0),
17250                Scalar::Int64(0),
17251                Scalar::Int64(0),
17252                Scalar::Int64(1),
17253                Scalar::Int64(1),
17254                Scalar::Int64(2),
17255                Scalar::Int64(2),
17256            ]
17257        );
17258        assert_eq!(
17259            fast.columns.get("v").unwrap().values(),
17260            &[
17261                Scalar::Int64(10),
17262                Scalar::Int64(10),
17263                Scalar::Int64(11),
17264                Scalar::Int64(11),
17265                Scalar::Int64(20),
17266                Scalar::Int64(21),
17267                Scalar::Int64(30),
17268                Scalar::Int64(30),
17269            ]
17270        );
17271        assert_eq!(
17272            fast.columns.get("w").unwrap().values(),
17273            &[
17274                Scalar::Int64(100),
17275                Scalar::Int64(101),
17276                Scalar::Int64(100),
17277                Scalar::Int64(101),
17278                Scalar::Int64(200),
17279                Scalar::Int64(200),
17280                Scalar::Int64(300),
17281                Scalar::Int64(301),
17282            ]
17283        );
17284    }
17285
17286    #[test]
17287    fn merge_outer_ordered_unique_int64_subset_matches_generic_validated_route() {
17288        let left = DataFrame::from_dict(
17289            &["id", "v"],
17290            vec![
17291                (
17292                    "id",
17293                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
17294                ),
17295                (
17296                    "v",
17297                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
17298                ),
17299            ],
17300        )
17301        .unwrap();
17302        let right = DataFrame::from_dict(
17303            &["id", "w"],
17304            vec![
17305                (
17306                    "id",
17307                    vec![
17308                        Scalar::Int64(0),
17309                        Scalar::Int64(2),
17310                        Scalar::Int64(3),
17311                        Scalar::Int64(5),
17312                    ],
17313                ),
17314                (
17315                    "w",
17316                    vec![
17317                        Scalar::Int64(100),
17318                        Scalar::Int64(200),
17319                        Scalar::Int64(300),
17320                        Scalar::Int64(500),
17321                    ],
17322                ),
17323            ],
17324        )
17325        .unwrap();
17326
17327        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17328        let generic = merge_dataframes_on_with_options(
17329            &left,
17330            &right,
17331            &["id"],
17332            &["id"],
17333            JoinType::Outer,
17334            MergeExecutionOptions {
17335                validate_mode: Some(MergeValidateMode::OneToOne),
17336                ..MergeExecutionOptions::default()
17337            },
17338        )
17339        .unwrap();
17340
17341        assert_eq!(fast.index, generic.index);
17342        assert_eq!(fast.column_order, generic.column_order);
17343        assert_eq!(fast.columns, generic.columns);
17344        assert_eq!(
17345            fast.columns.get("id").unwrap().values(),
17346            &[
17347                Scalar::Int64(0),
17348                Scalar::Int64(1),
17349                Scalar::Int64(2),
17350                Scalar::Int64(3),
17351                Scalar::Int64(5)
17352            ]
17353        );
17354        let left_values = fast.columns.get("v").unwrap().values();
17355        assert_eq!(left_values[0], Scalar::Float64(10.0));
17356        assert_eq!(left_values[1], Scalar::Float64(11.0));
17357        assert!(left_values[2].is_missing());
17358        assert_eq!(left_values[3], Scalar::Float64(13.0));
17359        assert!(left_values[4].is_missing());
17360        let right_values = fast.columns.get("w").unwrap().values();
17361        assert_eq!(right_values[0], Scalar::Float64(100.0));
17362        assert!(right_values[1].is_missing());
17363        assert_eq!(right_values[2], Scalar::Float64(200.0));
17364        assert_eq!(right_values[3], Scalar::Float64(300.0));
17365        assert_eq!(right_values[4], Scalar::Float64(500.0));
17366    }
17367
17368    #[test]
17369    fn merge_outer_dense_int64_duplicates_matches_generic_validated_route() {
17370        let left = DataFrame::from_dict(
17371            &["id", "v"],
17372            vec![
17373                (
17374                    "id",
17375                    vec![
17376                        Scalar::Int64(2),
17377                        Scalar::Int64(0),
17378                        Scalar::Int64(2),
17379                        Scalar::Int64(1),
17380                        Scalar::Int64(5),
17381                    ],
17382                ),
17383                (
17384                    "v",
17385                    vec![
17386                        Scalar::Int64(10),
17387                        Scalar::Int64(11),
17388                        Scalar::Int64(12),
17389                        Scalar::Int64(13),
17390                        Scalar::Int64(15),
17391                    ],
17392                ),
17393            ],
17394        )
17395        .unwrap();
17396        let right = DataFrame::from_dict(
17397            &["id", "w"],
17398            vec![
17399                (
17400                    "id",
17401                    vec![
17402                        Scalar::Int64(2),
17403                        Scalar::Int64(2),
17404                        Scalar::Int64(3),
17405                        Scalar::Int64(0),
17406                    ],
17407                ),
17408                (
17409                    "w",
17410                    vec![
17411                        Scalar::Int64(200),
17412                        Scalar::Int64(201),
17413                        Scalar::Int64(300),
17414                        Scalar::Int64(400),
17415                    ],
17416                ),
17417            ],
17418        )
17419        .unwrap();
17420
17421        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17422        let generic = merge_dataframes_on_with_options(
17423            &left,
17424            &right,
17425            &["id"],
17426            &["id"],
17427            JoinType::Outer,
17428            MergeExecutionOptions {
17429                validate_mode: Some(MergeValidateMode::ManyToMany),
17430                ..MergeExecutionOptions::default()
17431            },
17432        )
17433        .unwrap();
17434
17435        assert_eq!(fast.index, generic.index);
17436        assert_eq!(fast.column_order, generic.column_order);
17437        assert_eq!(fast.columns, generic.columns);
17438        assert_eq!(
17439            fast.columns.get("id").unwrap().values(),
17440            &[
17441                Scalar::Int64(0),
17442                Scalar::Int64(1),
17443                Scalar::Int64(2),
17444                Scalar::Int64(2),
17445                Scalar::Int64(2),
17446                Scalar::Int64(2),
17447                Scalar::Int64(3),
17448                Scalar::Int64(5),
17449            ]
17450        );
17451        let left_values = fast.columns.get("v").unwrap().values();
17452        assert_eq!(left_values[0], Scalar::Float64(11.0));
17453        assert_eq!(left_values[1], Scalar::Float64(13.0));
17454        assert_eq!(left_values[2], Scalar::Float64(10.0));
17455        assert_eq!(left_values[5], Scalar::Float64(12.0));
17456        assert!(left_values[6].is_missing());
17457        assert_eq!(left_values[7], Scalar::Float64(15.0));
17458        let right_values = fast.columns.get("w").unwrap().values();
17459        assert_eq!(right_values[0], Scalar::Float64(400.0));
17460        assert!(right_values[1].is_missing());
17461        assert_eq!(right_values[2], Scalar::Float64(200.0));
17462        assert_eq!(right_values[3], Scalar::Float64(201.0));
17463        assert!(right_values[7].is_missing());
17464    }
17465
17466    #[test]
17467    fn merge_outer_all_matched_dense_int64_duplicates_matches_generic_validated_route() {
17468        let left = DataFrame::from_dict(
17469            &["id", "v"],
17470            vec![
17471                (
17472                    "id",
17473                    vec![
17474                        Scalar::Int64(2),
17475                        Scalar::Int64(1),
17476                        Scalar::Int64(2),
17477                        Scalar::Int64(1),
17478                    ],
17479                ),
17480                (
17481                    "v",
17482                    vec![
17483                        Scalar::Int64(20),
17484                        Scalar::Int64(10),
17485                        Scalar::Int64(21),
17486                        Scalar::Int64(11),
17487                    ],
17488                ),
17489            ],
17490        )
17491        .unwrap();
17492        let right = DataFrame::from_dict(
17493            &["id", "w"],
17494            vec![
17495                (
17496                    "id",
17497                    vec![
17498                        Scalar::Int64(1),
17499                        Scalar::Int64(2),
17500                        Scalar::Int64(1),
17501                        Scalar::Int64(2),
17502                    ],
17503                ),
17504                (
17505                    "w",
17506                    vec![
17507                        Scalar::Int64(100),
17508                        Scalar::Int64(200),
17509                        Scalar::Int64(101),
17510                        Scalar::Int64(201),
17511                    ],
17512                ),
17513            ],
17514        )
17515        .unwrap();
17516
17517        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17518        let generic = merge_dataframes_on_with_options(
17519            &left,
17520            &right,
17521            &["id"],
17522            &["id"],
17523            JoinType::Outer,
17524            MergeExecutionOptions {
17525                validate_mode: Some(MergeValidateMode::ManyToMany),
17526                ..MergeExecutionOptions::default()
17527            },
17528        )
17529        .unwrap();
17530
17531        assert_eq!(fast.index, generic.index);
17532        assert_eq!(fast.column_order, generic.column_order);
17533        assert_eq!(fast.columns, generic.columns);
17534        assert_eq!(
17535            generic.columns.get("id").unwrap().values(),
17536            &[
17537                Scalar::Int64(1),
17538                Scalar::Int64(1),
17539                Scalar::Int64(1),
17540                Scalar::Int64(1),
17541                Scalar::Int64(2),
17542                Scalar::Int64(2),
17543                Scalar::Int64(2),
17544                Scalar::Int64(2),
17545            ]
17546        );
17547        assert!(
17548            generic
17549                .columns
17550                .values()
17551                .all(|column| column.as_i64_slice().is_some())
17552        );
17553    }
17554
17555    #[test]
17556    fn merge_outer_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
17557        let left = DataFrame::from_dict(
17558            &["id", "v"],
17559            vec![
17560                (
17561                    "id",
17562                    vec![
17563                        Scalar::Int64(2),
17564                        Scalar::Int64(1),
17565                        Scalar::Int64(2),
17566                        Scalar::Int64(1),
17567                    ],
17568                ),
17569                (
17570                    "v",
17571                    vec![
17572                        Scalar::Int64(20),
17573                        Scalar::Int64(10),
17574                        Scalar::Int64(21),
17575                        Scalar::Int64(11),
17576                    ],
17577                ),
17578            ],
17579        )
17580        .unwrap();
17581        let right = DataFrame::from_dict(
17582            &["id", "w"],
17583            vec![
17584                (
17585                    "id",
17586                    vec![
17587                        Scalar::Int64(1),
17588                        Scalar::Int64(2),
17589                        Scalar::Int64(1),
17590                        Scalar::Int64(2),
17591                    ],
17592                ),
17593                (
17594                    "w",
17595                    vec![
17596                        Scalar::Int64(100),
17597                        Scalar::Int64(200),
17598                        Scalar::Int64(101),
17599                        Scalar::Int64(201),
17600                    ],
17601                ),
17602            ],
17603        )
17604        .unwrap();
17605
17606        let fused = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17607        let generic = merge_dataframes_on_with_options(
17608            &left,
17609            &right,
17610            &["id"],
17611            &["id"],
17612            JoinType::Outer,
17613            MergeExecutionOptions {
17614                validate_mode: Some(MergeValidateMode::ManyToMany),
17615                sort: true,
17616                ..MergeExecutionOptions::default()
17617            },
17618        )
17619        .unwrap();
17620
17621        assert_eq!(fused.index, generic.index);
17622        assert_eq!(fused.column_order, generic.column_order);
17623        assert_eq!(fused.columns, generic.columns);
17624    }
17625
17626    #[test]
17627    fn merge_left_contiguous_utf8_duplicates_matches_sorted_generic_route() {
17628        let s = |v: &str| Scalar::Utf8(v.to_owned());
17629        let left = DataFrame::from_dict(
17630            &["id", "v"],
17631            vec![
17632                ("id", vec![s("a"), s("a"), s("b"), s("c")]),
17633                (
17634                    "v",
17635                    vec![
17636                        Scalar::Int64(10),
17637                        Scalar::Int64(11),
17638                        Scalar::Int64(20),
17639                        Scalar::Int64(30),
17640                    ],
17641                ),
17642            ],
17643        )
17644        .unwrap();
17645        let right = DataFrame::from_dict(
17646            &["id", "w"],
17647            vec![
17648                ("id", vec![s("a"), s("a"), s("c")]),
17649                (
17650                    "w",
17651                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(300)],
17652                ),
17653            ],
17654        )
17655        .unwrap();
17656
17657        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
17658        let generic = merge_dataframes_on_with_options(
17659            &left,
17660            &right,
17661            &["id"],
17662            &["id"],
17663            JoinType::Left,
17664            MergeExecutionOptions {
17665                sort: true,
17666                ..MergeExecutionOptions::default()
17667            },
17668        )
17669        .unwrap();
17670
17671        assert_eq!(fast.index, generic.index);
17672        assert_eq!(fast.column_order, generic.column_order);
17673        assert_eq!(fast.columns, generic.columns);
17674        assert_eq!(
17675            fast.columns.get("id").unwrap().values(),
17676            &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c")]
17677        );
17678        assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
17679    }
17680
17681    #[test]
17682    fn merge_outer_object_gaps_are_nan_and_supplied_none_stays_7u2td() {
17683        // pandas 2.2.3: DataFrame({'k':['a','b'],'s':[None,'y']}).merge(
17684        //   DataFrame({'k2':['b','c'],'t':['p','q']}), left_on='k',
17685        //   right_on='k2', how='outer')
17686        //   -> k [a, b, nan]  s [None, y, nan]  k2 [nan, b, c]  t [nan, p, q]
17687        let text = |t: &str| Scalar::Utf8(t.to_owned());
17688        let nan = Scalar::Null(NullKind::NaN);
17689        let left = DataFrame::from_dict(
17690            &["k", "s"],
17691            vec![
17692                ("k", vec![text("a"), text("b")]),
17693                ("s", vec![Scalar::Null(NullKind::Null), text("y")]),
17694            ],
17695        )
17696        .unwrap();
17697        let right = DataFrame::from_dict(
17698            &["k2", "t"],
17699            vec![
17700                ("k2", vec![text("b"), text("c")]),
17701                ("t", vec![text("p"), text("q")]),
17702            ],
17703        )
17704        .unwrap();
17705        let merged = merge_dataframes_on_with_options(
17706            &left,
17707            &right,
17708            &["k"],
17709            &["k2"],
17710            JoinType::Outer,
17711            MergeExecutionOptions::default(),
17712        )
17713        .unwrap();
17714        let column = |name: &str| merged.columns.get(name).unwrap().values().to_vec();
17715        assert_eq!(column("k"), vec![text("a"), text("b"), nan.clone()]);
17716        assert_eq!(column("k2"), vec![nan.clone(), text("b"), text("c")]);
17717        assert_eq!(column("t"), vec![nan.clone(), text("p"), text("q")]);
17718        // NEGATIVE: the supplied None is kept beside the invented NaN.
17719        assert_eq!(
17720            column("s"),
17721            vec![Scalar::Null(NullKind::Null), text("y"), nan]
17722        );
17723    }
17724
17725    #[test]
17726    fn merge_outer_contiguous_utf8_duplicates_matches_sorted_generic_route() {
17727        let s = |v: &str| Scalar::Utf8(v.to_owned());
17728        let left = DataFrame::from_dict(
17729            &["id", "v"],
17730            vec![
17731                ("id", vec![s("a"), s("a"), s("b"), s("d")]),
17732                (
17733                    "v",
17734                    vec![
17735                        Scalar::Int64(10),
17736                        Scalar::Int64(11),
17737                        Scalar::Int64(20),
17738                        Scalar::Int64(40),
17739                    ],
17740                ),
17741            ],
17742        )
17743        .unwrap();
17744        let right = DataFrame::from_dict(
17745            &["id", "w"],
17746            vec![
17747                ("id", vec![s("a"), s("c"), s("a")]),
17748                (
17749                    "w",
17750                    vec![Scalar::Int64(100), Scalar::Int64(300), Scalar::Int64(101)],
17751                ),
17752            ],
17753        )
17754        .unwrap();
17755
17756        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17757        let generic = merge_dataframes_on_with_options(
17758            &left,
17759            &right,
17760            &["id"],
17761            &["id"],
17762            JoinType::Outer,
17763            MergeExecutionOptions {
17764                sort: true,
17765                ..MergeExecutionOptions::default()
17766            },
17767        )
17768        .unwrap();
17769
17770        assert_eq!(fast.index, generic.index);
17771        assert_eq!(fast.column_order, generic.column_order);
17772        assert_eq!(fast.columns, generic.columns);
17773        assert_eq!(
17774            fast.columns.get("id").unwrap().values(),
17775            &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c"), s("d")]
17776        );
17777        assert!(fast.columns.get("v").unwrap().values()[5].is_missing());
17778        assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
17779        assert!(fast.columns.get("w").unwrap().values()[6].is_missing());
17780    }
17781
17782    #[test]
17783    fn merge_outer_fixed_decimal_utf8_all_matched_fuses_sorted_output_wikcu() {
17784        let s = |v: &str| Scalar::Utf8(v.to_owned());
17785        let left = DataFrame::from_dict(
17786            &["id", "lv"],
17787            vec![
17788                (
17789                    "id",
17790                    vec![
17791                        s("k00000002"),
17792                        s("k00000000"),
17793                        s("k00000002"),
17794                        s("k00000001"),
17795                    ],
17796                ),
17797                (
17798                    "lv",
17799                    vec![
17800                        Scalar::Float64(20.0),
17801                        Scalar::Float64(0.0),
17802                        Scalar::Float64(21.0),
17803                        Scalar::Float64(10.0),
17804                    ],
17805                ),
17806            ],
17807        )
17808        .unwrap();
17809        let right = DataFrame::from_dict(
17810            &["id", "rv"],
17811            vec![
17812                ("id", vec![s("k00000000"), s("k00000001"), s("k00000002")]),
17813                (
17814                    "rv",
17815                    vec![
17816                        Scalar::Float64(100.0),
17817                        Scalar::Float64(110.0),
17818                        Scalar::Float64(120.0),
17819                    ],
17820                ),
17821            ],
17822        )
17823        .unwrap();
17824
17825        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17826        let generic = merge_dataframes_on_with_options(
17827            &left,
17828            &right,
17829            &["id"],
17830            &["id"],
17831            JoinType::Outer,
17832            MergeExecutionOptions {
17833                sort: true,
17834                ..MergeExecutionOptions::default()
17835            },
17836        )
17837        .unwrap();
17838
17839        assert_eq!(fast.index, generic.index);
17840        assert_eq!(fast.column_order, generic.column_order);
17841        assert_eq!(fast.columns, generic.columns);
17842        assert_eq!(
17843            fast.columns.get("id").unwrap().values(),
17844            &[
17845                s("k00000000"),
17846                s("k00000001"),
17847                s("k00000002"),
17848                s("k00000002")
17849            ]
17850        );
17851        assert_eq!(
17852            fast.columns.get("lv").unwrap().values(),
17853            &[
17854                Scalar::Float64(0.0),
17855                Scalar::Float64(10.0),
17856                Scalar::Float64(20.0),
17857                Scalar::Float64(21.0),
17858            ]
17859        );
17860    }
17861
17862    #[test]
17863    fn merge_right_dense_int64_duplicates_matches_generic_validated_route() {
17864        let left = DataFrame::from_dict(
17865            &["id", "v"],
17866            vec![
17867                (
17868                    "id",
17869                    vec![
17870                        Scalar::Int64(2),
17871                        Scalar::Int64(0),
17872                        Scalar::Int64(2),
17873                        Scalar::Int64(1),
17874                        Scalar::Int64(5),
17875                    ],
17876                ),
17877                (
17878                    "v",
17879                    vec![
17880                        Scalar::Int64(10),
17881                        Scalar::Int64(11),
17882                        Scalar::Int64(12),
17883                        Scalar::Int64(13),
17884                        Scalar::Int64(15),
17885                    ],
17886                ),
17887            ],
17888        )
17889        .unwrap();
17890        let right = DataFrame::from_dict(
17891            &["id", "w"],
17892            vec![
17893                (
17894                    "id",
17895                    vec![
17896                        Scalar::Int64(2),
17897                        Scalar::Int64(2),
17898                        Scalar::Int64(3),
17899                        Scalar::Int64(0),
17900                    ],
17901                ),
17902                (
17903                    "w",
17904                    vec![
17905                        Scalar::Int64(200),
17906                        Scalar::Int64(201),
17907                        Scalar::Int64(300),
17908                        Scalar::Int64(400),
17909                    ],
17910                ),
17911            ],
17912        )
17913        .unwrap();
17914
17915        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
17916        let generic = merge_dataframes_on_with_options(
17917            &left,
17918            &right,
17919            &["id"],
17920            &["id"],
17921            JoinType::Right,
17922            MergeExecutionOptions {
17923                validate_mode: Some(MergeValidateMode::ManyToMany),
17924                ..MergeExecutionOptions::default()
17925            },
17926        )
17927        .unwrap();
17928
17929        assert_eq!(fast.index, generic.index);
17930        assert_eq!(fast.column_order, generic.column_order);
17931        assert_eq!(fast.columns, generic.columns);
17932        assert_eq!(
17933            fast.columns.get("id").unwrap().values(),
17934            &[
17935                Scalar::Int64(2),
17936                Scalar::Int64(2),
17937                Scalar::Int64(2),
17938                Scalar::Int64(2),
17939                Scalar::Int64(3),
17940                Scalar::Int64(0),
17941            ]
17942        );
17943        let left_values = fast.columns.get("v").unwrap().values();
17944        assert_eq!(left_values[0], Scalar::Float64(10.0));
17945        assert_eq!(left_values[1], Scalar::Float64(12.0));
17946        assert_eq!(left_values[2], Scalar::Float64(10.0));
17947        assert_eq!(left_values[3], Scalar::Float64(12.0));
17948        assert!(left_values[4].is_missing());
17949        assert_eq!(left_values[5], Scalar::Float64(11.0));
17950        let right_values = fast.columns.get("w").unwrap().values();
17951        assert_eq!(right_values[0], Scalar::Int64(200));
17952        assert_eq!(right_values[1], Scalar::Int64(200));
17953        assert_eq!(right_values[2], Scalar::Int64(201));
17954        assert_eq!(right_values[3], Scalar::Int64(201));
17955        assert_eq!(right_values[4], Scalar::Int64(300));
17956        assert_eq!(right_values[5], Scalar::Int64(400));
17957    }
17958
17959    #[test]
17960    fn merge_right_dense_cycle_probe_declines_invented_gaps_66wab() {
17961        let left = DataFrame::from_dict(
17962            &["id", "v"],
17963            vec![
17964                (
17965                    "id",
17966                    vec![
17967                        Scalar::Int64(1),
17968                        Scalar::Int64(2),
17969                        Scalar::Int64(1),
17970                        Scalar::Int64(2),
17971                    ],
17972                ),
17973                (
17974                    "v",
17975                    vec![
17976                        Scalar::Int64(100),
17977                        Scalar::Int64(200),
17978                        Scalar::Int64(101),
17979                        Scalar::Int64(201),
17980                    ],
17981                ),
17982            ],
17983        )
17984        .unwrap();
17985        let right = DataFrame::from_dict(
17986            &["id", "w"],
17987            vec![
17988                (
17989                    "id",
17990                    vec![
17991                        Scalar::Int64(0),
17992                        Scalar::Int64(1),
17993                        Scalar::Int64(2),
17994                        Scalar::Int64(0),
17995                        Scalar::Int64(1),
17996                    ],
17997                ),
17998                (
17999                    "w",
18000                    vec![
18001                        Scalar::Int64(10),
18002                        Scalar::Int64(11),
18003                        Scalar::Int64(12),
18004                        Scalar::Int64(13),
18005                        Scalar::Int64(14),
18006                    ],
18007                ),
18008            ],
18009        )
18010        .unwrap();
18011        let left_key = left.columns().get("id").unwrap();
18012        let right_key = right.columns().get("id").unwrap();
18013        assert!(left_key.int64_dense_cycle_witness().is_some());
18014        assert!(right_key.int64_dense_cycle_witness().is_some());
18015        let suffixes = resolve_merge_suffixes(None);
18016
18017        let fused = build_single_key_dense_i64_right_merge_output(
18018            &left,
18019            &right,
18020            &["id"],
18021            &["id"],
18022            left_key,
18023            right_key,
18024            &suffixes,
18025        )
18026        .unwrap();
18027        assert!(fused.is_none());
18028    }
18029
18030    #[test]
18031    fn merge_left_right_all_matched_dense_int64_duplicates_match_generic_validated_route() {
18032        let left = DataFrame::from_dict(
18033            &["id", "v"],
18034            vec![
18035                (
18036                    "id",
18037                    vec![
18038                        Scalar::Int64(2),
18039                        Scalar::Int64(1),
18040                        Scalar::Int64(2),
18041                        Scalar::Int64(1),
18042                    ],
18043                ),
18044                (
18045                    "v",
18046                    vec![
18047                        Scalar::Int64(20),
18048                        Scalar::Int64(10),
18049                        Scalar::Int64(21),
18050                        Scalar::Int64(11),
18051                    ],
18052                ),
18053            ],
18054        )
18055        .unwrap();
18056        let right = DataFrame::from_dict(
18057            &["id", "w"],
18058            vec![
18059                (
18060                    "id",
18061                    vec![
18062                        Scalar::Int64(1),
18063                        Scalar::Int64(2),
18064                        Scalar::Int64(1),
18065                        Scalar::Int64(2),
18066                    ],
18067                ),
18068                (
18069                    "w",
18070                    vec![
18071                        Scalar::Int64(100),
18072                        Scalar::Int64(200),
18073                        Scalar::Int64(101),
18074                        Scalar::Int64(201),
18075                    ],
18076                ),
18077            ],
18078        )
18079        .unwrap();
18080
18081        for join_type in [JoinType::Left, JoinType::Right] {
18082            let fast = merge_dataframes(&left, &right, "id", join_type).unwrap();
18083            let generic = merge_dataframes_on_with_options(
18084                &left,
18085                &right,
18086                &["id"],
18087                &["id"],
18088                join_type,
18089                MergeExecutionOptions {
18090                    validate_mode: Some(MergeValidateMode::ManyToMany),
18091                    ..MergeExecutionOptions::default()
18092                },
18093            )
18094            .unwrap();
18095
18096            assert_eq!(fast.index, generic.index);
18097            assert_eq!(fast.column_order, generic.column_order);
18098            assert_eq!(fast.columns, generic.columns);
18099            assert!(
18100                generic
18101                    .columns
18102                    .values()
18103                    .all(|column| column.as_i64_slice().is_some())
18104            );
18105        }
18106    }
18107
18108    #[test]
18109    fn merge_right_all_matched_dense_int64_fused_output_matches_dense_materialization() {
18110        let left = DataFrame::from_dict(
18111            &["id", "v"],
18112            vec![
18113                (
18114                    "id",
18115                    vec![
18116                        Scalar::Int64(2),
18117                        Scalar::Int64(1),
18118                        Scalar::Int64(2),
18119                        Scalar::Int64(1),
18120                    ],
18121                ),
18122                (
18123                    "v",
18124                    vec![
18125                        Scalar::Int64(20),
18126                        Scalar::Int64(10),
18127                        Scalar::Int64(21),
18128                        Scalar::Int64(11),
18129                    ],
18130                ),
18131            ],
18132        )
18133        .unwrap();
18134        let right = DataFrame::from_dict(
18135            &["id", "w"],
18136            vec![
18137                (
18138                    "id",
18139                    vec![
18140                        Scalar::Int64(1),
18141                        Scalar::Int64(2),
18142                        Scalar::Int64(1),
18143                        Scalar::Int64(2),
18144                    ],
18145                ),
18146                (
18147                    "w",
18148                    vec![
18149                        Scalar::Int64(100),
18150                        Scalar::Int64(200),
18151                        Scalar::Int64(101),
18152                        Scalar::Int64(201),
18153                    ],
18154                ),
18155            ],
18156        )
18157        .unwrap();
18158
18159        let fused = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
18160        let left_key = left.columns().get("id").unwrap();
18161        let right_key = right.columns().get("id").unwrap();
18162        let (left_positions, right_positions) =
18163            dense_int64_right_positions(left_key, right_key).unwrap();
18164        let suffixes = resolve_merge_suffixes(None);
18165        let materialized = build_single_key_dense_right_merge_output(
18166            &left,
18167            &right,
18168            &["id"],
18169            &["id"],
18170            &left_positions,
18171            &right_positions,
18172            &suffixes,
18173        )
18174        .unwrap();
18175
18176        assert_eq!(fused.index, materialized.index);
18177        assert_eq!(fused.column_order, materialized.column_order);
18178        assert_eq!(fused.columns, materialized.columns);
18179        assert_eq!(
18180            fused.columns.get("id").unwrap().values(),
18181            &[
18182                Scalar::Int64(1),
18183                Scalar::Int64(1),
18184                Scalar::Int64(2),
18185                Scalar::Int64(2),
18186                Scalar::Int64(1),
18187                Scalar::Int64(1),
18188                Scalar::Int64(2),
18189                Scalar::Int64(2),
18190            ]
18191        );
18192        assert!(
18193            fused
18194                .columns
18195                .values()
18196                .all(|column| column.as_i64_slice().is_some())
18197        );
18198    }
18199
18200    #[test]
18201    fn merge_right_ordered_unique_int64_subset_matches_generic_validated_route() {
18202        let left = DataFrame::from_dict(
18203            &["id", "v"],
18204            vec![
18205                (
18206                    "id",
18207                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
18208                ),
18209                (
18210                    "v",
18211                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
18212                ),
18213            ],
18214        )
18215        .unwrap();
18216        let right = DataFrame::from_dict(
18217            &["id", "w"],
18218            vec![
18219                (
18220                    "id",
18221                    vec![
18222                        Scalar::Int64(0),
18223                        Scalar::Int64(2),
18224                        Scalar::Int64(3),
18225                        Scalar::Int64(5),
18226                    ],
18227                ),
18228                (
18229                    "w",
18230                    vec![
18231                        Scalar::Int64(100),
18232                        Scalar::Int64(200),
18233                        Scalar::Int64(300),
18234                        Scalar::Int64(500),
18235                    ],
18236                ),
18237            ],
18238        )
18239        .unwrap();
18240
18241        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
18242        let generic = merge_dataframes_on_with_options(
18243            &left,
18244            &right,
18245            &["id"],
18246            &["id"],
18247            JoinType::Right,
18248            MergeExecutionOptions {
18249                validate_mode: Some(MergeValidateMode::OneToOne),
18250                ..MergeExecutionOptions::default()
18251            },
18252        )
18253        .unwrap();
18254
18255        assert_eq!(fast.index, generic.index);
18256        assert_eq!(fast.column_order, generic.column_order);
18257        assert_eq!(fast.columns, generic.columns);
18258        assert_eq!(
18259            fast.columns.get("id").unwrap().values(),
18260            &[
18261                Scalar::Int64(0),
18262                Scalar::Int64(2),
18263                Scalar::Int64(3),
18264                Scalar::Int64(5)
18265            ]
18266        );
18267        let left_values = fast.columns.get("v").unwrap().values();
18268        assert_eq!(left_values[0], Scalar::Float64(10.0));
18269        assert!(left_values[1].is_missing());
18270        assert_eq!(left_values[2], Scalar::Float64(13.0));
18271        assert!(left_values[3].is_missing());
18272        let right_values = fast.columns.get("w").unwrap().values();
18273        assert_eq!(right_values[0], Scalar::Int64(100));
18274        assert_eq!(right_values[1], Scalar::Int64(200));
18275        assert_eq!(right_values[2], Scalar::Int64(300));
18276        assert_eq!(right_values[3], Scalar::Int64(500));
18277    }
18278
18279    #[test]
18280    fn merge_right_preserves_all_right_rows() {
18281        let left = make_left_df();
18282        let right = make_right_df();
18283        let merged = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
18284
18285        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
18286        assert_eq!(
18287            merged.columns.get("val_b").unwrap().values(),
18288            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
18289        );
18290        // val_a widens to Float64 because id=4 invents a missing value.
18291        assert_eq!(merged.columns.get("val_a").unwrap().dtype(), DType::Float64);
18292        assert_eq!(
18293            merged.columns.get("val_a").unwrap().values()[0],
18294            Scalar::Float64(20.0)
18295        );
18296        assert_eq!(
18297            merged.columns.get("val_a").unwrap().values()[1],
18298            Scalar::Float64(30.0)
18299        );
18300        assert_eq!(
18301            merged.columns.get("val_a").unwrap().values()[2],
18302            Scalar::Null(NullKind::NaN)
18303        );
18304    }
18305
18306    #[test]
18307    fn merge_outer_contains_all_rows() {
18308        let left = make_left_df();
18309        let right = make_right_df();
18310        let merged = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
18311
18312        // ids: 1, 2, 3 from left + 4 from right = 4 rows
18313        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
18314    }
18315
18316    #[test]
18317    fn merge_inner_sort_false_preserves_left_key_order() {
18318        let left = DataFrame::from_dict(
18319            &["id", "left_v"],
18320            vec![
18321                (
18322                    "id",
18323                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
18324                ),
18325                (
18326                    "left_v",
18327                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
18328                ),
18329            ],
18330        )
18331        .expect("left");
18332        let right = DataFrame::from_dict(
18333            &["id", "right_v"],
18334            vec![
18335                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
18336                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
18337            ],
18338        )
18339        .expect("right");
18340
18341        let merged = merge_dataframes_on_with_options(
18342            &left,
18343            &right,
18344            &["id"],
18345            &["id"],
18346            JoinType::Inner,
18347            MergeExecutionOptions::default(),
18348        )
18349        .expect("merge");
18350        assert_eq!(
18351            merged.columns.get("id").expect("id").values(),
18352            &[Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)]
18353        );
18354        assert_eq!(
18355            merged.columns.get("left_v").expect("left_v").values(),
18356            &[Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)]
18357        );
18358        assert_eq!(
18359            merged.columns.get("right_v").expect("right_v").values(),
18360            &[Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(200)]
18361        );
18362    }
18363
18364    #[test]
18365    fn merge_inner_sort_true_orders_join_keys_lexicographically() {
18366        let left = DataFrame::from_dict(
18367            &["id", "left_v"],
18368            vec![
18369                (
18370                    "id",
18371                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
18372                ),
18373                (
18374                    "left_v",
18375                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
18376                ),
18377            ],
18378        )
18379        .expect("left");
18380        let right = DataFrame::from_dict(
18381            &["id", "right_v"],
18382            vec![
18383                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
18384                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
18385            ],
18386        )
18387        .expect("right");
18388
18389        let merged = merge_dataframes_on_with_options(
18390            &left,
18391            &right,
18392            &["id"],
18393            &["id"],
18394            JoinType::Inner,
18395            MergeExecutionOptions {
18396                sort: true,
18397                ..MergeExecutionOptions::default()
18398            },
18399        )
18400        .expect("merge");
18401        assert_eq!(
18402            merged.columns.get("id").expect("id").values(),
18403            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2)]
18404        );
18405        assert_eq!(
18406            merged.columns.get("left_v").expect("left_v").values(),
18407            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(21)]
18408        );
18409        assert_eq!(
18410            merged.columns.get("right_v").expect("right_v").values(),
18411            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(200)]
18412        );
18413    }
18414
18415    #[test]
18416    fn merge_inner_sort_true_orders_float_keys_numerically() {
18417        let left = DataFrame::from_dict(
18418            &["id", "left_v"],
18419            vec![
18420                (
18421                    "id",
18422                    vec![
18423                        Scalar::Float64(1.5),
18424                        Scalar::Float64(-2.5),
18425                        Scalar::Float64(0.25),
18426                    ],
18427                ),
18428                (
18429                    "left_v",
18430                    vec![Scalar::Int64(15), Scalar::Int64(-25), Scalar::Int64(2)],
18431                ),
18432            ],
18433        )
18434        .expect("left");
18435        let right = DataFrame::from_dict(
18436            &["id", "right_v"],
18437            vec![
18438                (
18439                    "id",
18440                    vec![
18441                        Scalar::Float64(-2.5),
18442                        Scalar::Float64(0.25),
18443                        Scalar::Float64(1.5),
18444                    ],
18445                ),
18446                (
18447                    "right_v",
18448                    vec![Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)],
18449                ),
18450            ],
18451        )
18452        .expect("right");
18453
18454        let merged = merge_dataframes_on_with_options(
18455            &left,
18456            &right,
18457            &["id"],
18458            &["id"],
18459            JoinType::Inner,
18460            MergeExecutionOptions {
18461                sort: true,
18462                ..MergeExecutionOptions::default()
18463            },
18464        )
18465        .expect("merge");
18466
18467        assert_eq!(
18468            merged.columns.get("id").expect("id").values(),
18469            &[
18470                Scalar::Float64(-2.5),
18471                Scalar::Float64(0.25),
18472                Scalar::Float64(1.5)
18473            ]
18474        );
18475        assert_eq!(
18476            merged.columns.get("left_v").expect("left_v").values(),
18477            &[Scalar::Int64(-25), Scalar::Int64(2), Scalar::Int64(15)]
18478        );
18479        assert_eq!(
18480            merged.columns.get("right_v").expect("right_v").values(),
18481            &[Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)]
18482        );
18483    }
18484
18485    #[test]
18486    fn merge_right_sort_true_orders_join_keys_lexicographically() {
18487        let left = DataFrame::from_dict(
18488            &["id", "left_v"],
18489            vec![
18490                ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
18491                ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
18492            ],
18493        )
18494        .expect("left");
18495        let right = DataFrame::from_dict(
18496            &["id", "right_v"],
18497            vec![
18498                (
18499                    "id",
18500                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
18501                ),
18502                (
18503                    "right_v",
18504                    vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
18505                ),
18506            ],
18507        )
18508        .expect("right");
18509
18510        let merged = merge_dataframes_on_with_options(
18511            &left,
18512            &right,
18513            &["id"],
18514            &["id"],
18515            JoinType::Right,
18516            MergeExecutionOptions {
18517                sort: true,
18518                ..MergeExecutionOptions::default()
18519            },
18520        )
18521        .expect("merge");
18522        assert_eq!(
18523            merged.columns.get("id").expect("id").values(),
18524            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
18525        );
18526        assert_eq!(
18527            merged.columns.get("left_v").expect("left_v").values(),
18528            &[
18529                Scalar::Float64(10.0),
18530                Scalar::Null(NullKind::NaN),
18531                Scalar::Float64(30.0)
18532            ]
18533        );
18534        assert_eq!(
18535            merged.columns.get("right_v").expect("right_v").values(),
18536            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
18537        );
18538    }
18539
18540    #[test]
18541    fn merge_column_name_conflict_adds_suffixes() {
18542        let left = DataFrame::from_dict(
18543            &["id", "val"],
18544            vec![
18545                ("id", vec![Scalar::Int64(1)]),
18546                ("val", vec![Scalar::Int64(10)]),
18547            ],
18548        )
18549        .unwrap();
18550        let right = DataFrame::from_dict(
18551            &["id", "val"],
18552            vec![
18553                ("id", vec![Scalar::Int64(1)]),
18554                ("val", vec![Scalar::Int64(99)]),
18555            ],
18556        )
18557        .unwrap();
18558
18559        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
18560        assert!(merged.columns.contains_key("val_x"));
18561        assert!(merged.columns.contains_key("val_y"));
18562        assert_eq!(
18563            merged.columns.get("val_x").unwrap().values(),
18564            &[Scalar::Int64(10)]
18565        );
18566        assert_eq!(
18567            merged.columns.get("val_y").unwrap().values(),
18568            &[Scalar::Int64(99)]
18569        );
18570    }
18571
18572    #[test]
18573    fn merge_column_name_conflict_honors_custom_suffixes() {
18574        let left = DataFrame::from_dict(
18575            &["id", "val"],
18576            vec![
18577                ("id", vec![Scalar::Int64(1)]),
18578                ("val", vec![Scalar::Int64(10)]),
18579            ],
18580        )
18581        .expect("left");
18582        let right = DataFrame::from_dict(
18583            &["id", "val"],
18584            vec![
18585                ("id", vec![Scalar::Int64(1)]),
18586                ("val", vec![Scalar::Int64(99)]),
18587            ],
18588        )
18589        .expect("right");
18590
18591        let merged = merge_dataframes_on_with_options(
18592            &left,
18593            &right,
18594            &["id"],
18595            &["id"],
18596            JoinType::Inner,
18597            MergeExecutionOptions {
18598                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
18599                ..MergeExecutionOptions::default()
18600            },
18601        )
18602        .expect("merge");
18603        assert!(merged.columns.contains_key("val_L"));
18604        assert!(merged.columns.contains_key("val_R"));
18605        assert_eq!(
18606            merged.columns.get("val_L").expect("left suffixed").values(),
18607            &[Scalar::Int64(10)]
18608        );
18609        assert_eq!(
18610            merged
18611                .columns
18612                .get("val_R")
18613                .expect("right suffixed")
18614                .values(),
18615            &[Scalar::Int64(99)]
18616        );
18617    }
18618
18619    #[test]
18620    fn merge_column_name_conflict_allows_one_sided_suffix() {
18621        let left = DataFrame::from_dict(
18622            &["id", "val"],
18623            vec![
18624                ("id", vec![Scalar::Int64(1)]),
18625                ("val", vec![Scalar::Int64(10)]),
18626            ],
18627        )
18628        .expect("left");
18629        let right = DataFrame::from_dict(
18630            &["id", "val"],
18631            vec![
18632                ("id", vec![Scalar::Int64(1)]),
18633                ("val", vec![Scalar::Int64(99)]),
18634            ],
18635        )
18636        .expect("right");
18637
18638        let merged = merge_dataframes_on_with_options(
18639            &left,
18640            &right,
18641            &["id"],
18642            &["id"],
18643            JoinType::Inner,
18644            MergeExecutionOptions {
18645                suffixes: Some([None, Some("_r".to_owned())]),
18646                ..MergeExecutionOptions::default()
18647            },
18648        )
18649        .expect("merge");
18650        assert!(merged.columns.contains_key("val"));
18651        assert!(merged.columns.contains_key("val_r"));
18652        assert_eq!(
18653            merged.columns.get("val").expect("left unsuffixed").values(),
18654            &[Scalar::Int64(10)]
18655        );
18656        assert_eq!(
18657            merged
18658                .columns
18659                .get("val_r")
18660                .expect("right suffixed")
18661                .values(),
18662            &[Scalar::Int64(99)]
18663        );
18664    }
18665
18666    #[test]
18667    fn merge_column_name_conflict_rejects_missing_suffixes_for_overlap() {
18668        let left = DataFrame::from_dict(
18669            &["id", "val"],
18670            vec![
18671                ("id", vec![Scalar::Int64(1)]),
18672                ("val", vec![Scalar::Int64(10)]),
18673            ],
18674        )
18675        .expect("left");
18676        let right = DataFrame::from_dict(
18677            &["id", "val"],
18678            vec![
18679                ("id", vec![Scalar::Int64(1)]),
18680                ("val", vec![Scalar::Int64(99)]),
18681            ],
18682        )
18683        .expect("right");
18684
18685        let err = merge_dataframes_on_with_options(
18686            &left,
18687            &right,
18688            &["id"],
18689            &["id"],
18690            JoinType::Inner,
18691            MergeExecutionOptions {
18692                suffixes: Some([Some(String::new()), Some(String::new())]),
18693                ..MergeExecutionOptions::default()
18694            },
18695        )
18696        .expect_err("merge should reject overlapping columns without suffixes");
18697        assert!(format!("{err}").contains("columns overlap but no suffix specified"));
18698    }
18699
18700    #[test]
18701    fn merge_column_name_conflict_rejects_duplicate_output_columns_from_suffixes() {
18702        let left = DataFrame::from_dict(
18703            &["id", "val", "val_L"],
18704            vec![
18705                ("id", vec![Scalar::Int64(1)]),
18706                ("val", vec![Scalar::Int64(10)]),
18707                ("val_L", vec![Scalar::Int64(77)]),
18708            ],
18709        )
18710        .expect("left");
18711        let right = DataFrame::from_dict(
18712            &["id", "val"],
18713            vec![
18714                ("id", vec![Scalar::Int64(1)]),
18715                ("val", vec![Scalar::Int64(99)]),
18716            ],
18717        )
18718        .expect("right");
18719
18720        let err = merge_dataframes_on_with_options(
18721            &left,
18722            &right,
18723            &["id"],
18724            &["id"],
18725            JoinType::Inner,
18726            MergeExecutionOptions {
18727                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
18728                ..MergeExecutionOptions::default()
18729            },
18730        )
18731        .expect_err("merge should reject duplicate output names caused by suffixes");
18732        assert!(format!("{err}").contains("duplicate column"));
18733    }
18734
18735    #[test]
18736    fn merge_missing_key_column_errors() {
18737        let left = make_left_df();
18738        let right = make_right_df();
18739        let err = merge_dataframes(&left, &right, "nonexistent", JoinType::Inner)
18740            .expect_err("should fail");
18741        assert!(format!("{err}").contains("nonexistent"));
18742    }
18743
18744    #[test]
18745    fn merge_duplicate_keys_multiply_cardinality() {
18746        let left = DataFrame::from_dict(
18747            &["id", "a"],
18748            vec![
18749                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18750                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
18751            ],
18752        )
18753        .unwrap();
18754        let right = DataFrame::from_dict(
18755            &["id", "b"],
18756            vec![
18757                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18758                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
18759            ],
18760        )
18761        .unwrap();
18762
18763        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
18764        // 2 left × 2 right = 4 rows
18765        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
18766    }
18767
18768    #[test]
18769    fn ordered_identity_int64_guard_uses_strict_unique_certificate() {
18770        let left = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
18771        let right = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
18772        assert!(ordered_identity_int64_keys_match(&left, &right));
18773
18774        let duplicate_left = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
18775        let duplicate_right = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
18776        assert!(!ordered_identity_int64_keys_match(
18777            &duplicate_left,
18778            &duplicate_right
18779        ));
18780
18781        let unsorted_left = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
18782        let unsorted_right = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
18783        assert!(ordered_identity_int64_keys_match(
18784            &unsorted_left,
18785            &unsorted_right
18786        ));
18787    }
18788
18789    #[test]
18790    fn affine_i64_inner_plan_solves_nontrivial_stride_intersection() {
18791        let left = super::PositiveAffineI64Witness {
18792            start: -3,
18793            step: 4,
18794            len: 8,
18795        };
18796        let right = super::PositiveAffineI64Witness {
18797            start: 1,
18798            step: 6,
18799            len: 6,
18800        };
18801        assert_eq!(
18802            super::affine_i64_inner_position_plan(left, right),
18803            Some(super::AffineInnerPositionPlan {
18804                left_start: 1,
18805                left_step: 3,
18806                right_start: 0,
18807                right_step: 2,
18808                len: 3,
18809            })
18810        );
18811    }
18812
18813    #[test]
18814    fn affine_i64_inner_plan_matches_brute_force_small_domain() {
18815        const LENGTHS: [usize; 4] = [2, 3, 7, 11];
18816        for left_start in -8i128..=8 {
18817            for right_start in -8i128..=8 {
18818                for left_step in 1i128..=7 {
18819                    for right_step in 1i128..=7 {
18820                        for left_len in LENGTHS {
18821                            for right_len in LENGTHS {
18822                                let left = super::PositiveAffineI64Witness {
18823                                    start: left_start,
18824                                    step: left_step,
18825                                    len: left_len,
18826                                };
18827                                let right = super::PositiveAffineI64Witness {
18828                                    start: right_start,
18829                                    step: right_step,
18830                                    len: right_len,
18831                                };
18832                                let plan = super::affine_i64_inner_position_plan(left, right)
18833                                    .expect("small affine sequences cannot overflow");
18834                                let expected = (0..left_len)
18835                                    .flat_map(|left_row| {
18836                                        (0..right_len).filter_map(move |right_row| {
18837                                            let left_key = left_start
18838                                                + left_step * i128::try_from(left_row).unwrap();
18839                                            let right_key = right_start
18840                                                + right_step * i128::try_from(right_row).unwrap();
18841                                            (left_key == right_key).then_some((left_row, right_row))
18842                                        })
18843                                    })
18844                                    .collect::<Vec<_>>();
18845                                let actual = (0..plan.len)
18846                                    .map(|row| {
18847                                        (
18848                                            plan.left_start + row * plan.left_step,
18849                                            plan.right_start + row * plan.right_step,
18850                                        )
18851                                    })
18852                                    .collect::<Vec<_>>();
18853                                assert_eq!(actual, expected);
18854                            }
18855                        }
18856                    }
18857                }
18858            }
18859        }
18860    }
18861
18862    #[test]
18863    fn affine_i64_inner_merge_matches_left_major_values() {
18864        let left_keys = vec![-3, 1, 5, 9, 13, 17, 21, 25];
18865        let right_keys = vec![1, 7, 13, 19, 25, 31];
18866        let mut left_columns = std::collections::BTreeMap::new();
18867        left_columns.insert("id".to_owned(), Column::from_i64_values(left_keys));
18868        left_columns.insert(
18869            "left_value".to_owned(),
18870            Column::from_f64_values((0..8).map(|row| row as f64 + 0.5).collect()),
18871        );
18872        let left = DataFrame::new_with_column_order(
18873            Index::new_known_unique_int64_unit_range(0, 8),
18874            left_columns,
18875            vec!["id".to_owned(), "left_value".to_owned()],
18876        )
18877        .unwrap();
18878        let mut right_columns = std::collections::BTreeMap::new();
18879        right_columns.insert("id".to_owned(), Column::from_i64_values(right_keys));
18880        right_columns.insert(
18881            "right_value".to_owned(),
18882            Column::from_i64_values((100..106).collect()),
18883        );
18884        let right = DataFrame::new_with_column_order(
18885            Index::new_known_unique_int64_unit_range(0, 6),
18886            right_columns,
18887            vec!["id".to_owned(), "right_value".to_owned()],
18888        )
18889        .unwrap();
18890        let suffixes = resolve_merge_suffixes(None);
18891        let merged = super::build_single_key_affine_i64_inner_merge_output(
18892            &left,
18893            &right,
18894            &["id"],
18895            &["id"],
18896            left.columns().get("id").unwrap(),
18897            right.columns().get("id").unwrap(),
18898            &suffixes,
18899        )
18900        .unwrap()
18901        .expect("certified affine typed inputs must use the fast path");
18902
18903        assert_eq!(
18904            merged.columns.get("id").unwrap().values(),
18905            &[Scalar::Int64(1), Scalar::Int64(13), Scalar::Int64(25)]
18906        );
18907        assert_eq!(
18908            merged.columns.get("left_value").unwrap().values(),
18909            &[
18910                Scalar::Float64(1.5),
18911                Scalar::Float64(4.5),
18912                Scalar::Float64(7.5),
18913            ]
18914        );
18915        assert_eq!(
18916            merged.columns.get("right_value").unwrap().values(),
18917            &[Scalar::Int64(100), Scalar::Int64(102), Scalar::Int64(104)]
18918        );
18919    }
18920
18921    #[test]
18922    fn merge_identical_duplicate_keys_cross_join_values_jdupk() {
18923        // Identical left/right key columns that contain duplicates must NOT take
18924        // the identity 1:1 fast path: pandas cross-joins each duplicate, so a=10
18925        // and a=20 each pair with b=100 and b=200. (br-frankenpandas-jdupk)
18926        let left = DataFrame::from_dict(
18927            &["id", "a"],
18928            vec![
18929                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18930                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
18931            ],
18932        )
18933        .unwrap();
18934        let right = DataFrame::from_dict(
18935            &["id", "b"],
18936            vec![
18937                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18938                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
18939            ],
18940        )
18941        .unwrap();
18942
18943        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
18944        assert_eq!(
18945            merged.columns.get("a").unwrap().values(),
18946            &[
18947                Scalar::Int64(10),
18948                Scalar::Int64(10),
18949                Scalar::Int64(20),
18950                Scalar::Int64(20)
18951            ]
18952        );
18953        assert_eq!(
18954            merged.columns.get("b").unwrap().values(),
18955            &[
18956                Scalar::Int64(100),
18957                Scalar::Int64(200),
18958                Scalar::Int64(100),
18959                Scalar::Int64(200)
18960            ]
18961        );
18962    }
18963
18964    #[test]
18965    fn ordered_unique_utf8_inner_positions_match_left_major_hash_order_53lat() {
18966        let left = contiguous_utf8_column(&["a", "b", "d", "f"]);
18967        let right = contiguous_utf8_column(&["b", "c", "f"]);
18968        let (left_positions, right_positions) =
18969            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18970
18971        assert_eq!(left_positions, vec![1, 3]);
18972        assert_eq!(right_positions, vec![0, 2]);
18973
18974        let merged = merge_dataframes(
18975            &utf8_key_merge_frame(&["a", "b", "d", "f"], "lv", 10),
18976            &utf8_key_merge_frame(&["b", "c", "f"], "rv", 20),
18977            "id",
18978            JoinType::Inner,
18979        )
18980        .unwrap();
18981        assert_eq!(
18982            merged.columns.get("lv").unwrap().values(),
18983            &[Scalar::Int64(11), Scalar::Int64(13)]
18984        );
18985        assert_eq!(
18986            merged.columns.get("rv").unwrap().values(),
18987            &[Scalar::Int64(20), Scalar::Int64(22)]
18988        );
18989    }
18990
18991    #[test]
18992    fn sorted_contiguous_utf8_inner_positions_preserves_duplicate_order_codb() {
18993        let left = contiguous_utf8_column(&["a", "a", "b", "d"]);
18994        let right = contiguous_utf8_column(&["a", "a", "c", "d"]);
18995        let (left_bytes, left_offsets) = left.as_utf8_contiguous().expect("left contiguous");
18996        let (right_bytes, right_offsets) = right.as_utf8_contiguous().expect("right contiguous");
18997
18998        let (left_positions, right_positions) = sorted_contiguous_utf8_inner_positions(
18999            left_bytes,
19000            left_offsets,
19001            right_bytes,
19002            right_offsets,
19003        )
19004        .expect("sorted spans should use two-pointer merge");
19005
19006        assert_eq!(left_positions, vec![0, 0, 1, 1, 3]);
19007        assert_eq!(right_positions, vec![0, 1, 0, 1, 3]);
19008    }
19009
19010    #[test]
19011    fn sorted_contiguous_utf8_inner_positions_rejects_unsorted_input_codb() {
19012        let left = contiguous_utf8_column(&["b", "a"]);
19013        let right = contiguous_utf8_column(&["a", "b"]);
19014        let (left_bytes, left_offsets) = left.as_utf8_contiguous().expect("left contiguous");
19015        let (right_bytes, right_offsets) = right.as_utf8_contiguous().expect("right contiguous");
19016
19017        assert!(
19018            sorted_contiguous_utf8_inner_positions(
19019                left_bytes,
19020                left_offsets,
19021                right_bytes,
19022                right_offsets,
19023            )
19024            .is_none()
19025        );
19026    }
19027
19028    #[test]
19029    fn ordered_unique_utf8_seek_bound_preserves_late_overlap_lr52z() {
19030        let left = contiguous_utf8_column(&["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);
19031        let right = contiguous_utf8_column(&["h", "i", "j", "k"]);
19032        let (left_bytes, left_offsets) =
19033            strictly_increasing_utf8_key_spans(&left).expect("sorted left");
19034
19035        assert_eq!(utf8_span_lower_bound(left_bytes, left_offsets, b"h"), 7);
19036
19037        let (left_positions, right_positions) =
19038            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
19039        assert_eq!(left_positions, vec![7, 8, 9]);
19040        assert_eq!(right_positions, vec![0, 1, 2]);
19041
19042        let disjoint_left = contiguous_utf8_column(&["a", "b"]);
19043        let disjoint_right = contiguous_utf8_column(&["c", "d"]);
19044        let (left_positions, right_positions) =
19045            ordered_unique_utf8_inner_positions(&disjoint_left, &disjoint_right)
19046                .expect("ordered disjoint utf8 positions");
19047        assert!(left_positions.is_empty());
19048        assert!(right_positions.is_empty());
19049    }
19050
19051    #[test]
19052    fn ordered_unique_utf8_bulk_fixed_width_window_jbyuc11() {
19053        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
19054        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
19055
19056        let (left_positions, right_positions) =
19057            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
19058        assert_eq!(left_positions, vec![2, 3, 4]);
19059        assert_eq!(right_positions, vec![0, 1, 2]);
19060    }
19061
19062    #[test]
19063    fn ordered_unique_utf8_bulk_window_returns_range_plan_jbyuc11111() {
19064        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
19065        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
19066
19067        let plan =
19068            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
19069
19070        assert_eq!(
19071            plan,
19072            InnerPositionPlan::ContiguousRanges {
19073                left_start: 2,
19074                right_start: 0,
19075                len: 3
19076            }
19077        );
19078    }
19079
19080    #[test]
19081    fn ordered_unique_utf8_lower_hex_certificate_returns_range_plan_jbyuc111111() {
19082        let left =
19083            contiguous_utf8_column(&["id_0000000a", "id_0000000b", "id_0000000c", "id_0000000d"]);
19084        let right = contiguous_utf8_column(&["id_0000000c", "id_0000000d", "id_0000000e"]);
19085        let (_, _, left_cert) = left
19086            .as_lower_hex_sequence_utf8_contiguous()
19087            .expect("left sequence certificate");
19088        let (_, _, right_cert) = right
19089            .as_lower_hex_sequence_utf8_contiguous()
19090            .expect("right sequence certificate");
19091
19092        assert_eq!(
19093            ordered_utf8_lower_hex_overlap_len(left_cert, right_cert, 2, 4, 0, 3),
19094            Some(2)
19095        );
19096        assert_eq!(
19097            lower_hex_overlap_plan_from_certificates(&left, &right),
19098            Some(InnerPositionPlan::ContiguousRanges {
19099                left_start: 2,
19100                right_start: 0,
19101                len: 2
19102            })
19103        );
19104        let plan =
19105            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
19106        assert_eq!(
19107            plan,
19108            InnerPositionPlan::ContiguousRanges {
19109                left_start: 2,
19110                right_start: 0,
19111                len: 2
19112            }
19113        );
19114    }
19115
19116    #[test]
19117    fn ordered_unique_utf8_lower_hex_arithmetic_empty_overlap_jbyuc1111111111() {
19118        let left = contiguous_utf8_column(&["id_00000001", "id_00000002", "id_00000003"]);
19119        let right = contiguous_utf8_column(&["id_00000008", "id_00000009"]);
19120
19121        assert_eq!(
19122            lower_hex_overlap_plan_from_certificates(&left, &right),
19123            Some(InnerPositionPlan::Gather {
19124                left_positions: Vec::new(),
19125                right_positions: Vec::new(),
19126            })
19127        );
19128        let (left_positions, right_positions) =
19129            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
19130        assert!(left_positions.is_empty());
19131        assert!(right_positions.is_empty());
19132    }
19133
19134    #[test]
19135    fn ordered_unique_utf8_lower_hex_prefix_mismatch_falls_back_jbyuc1111111111() {
19136        let left = contiguous_utf8_column(&["aa_00000001", "aa_00000002", "aa_00000003"]);
19137        let right = contiguous_utf8_column(&["bb_00000001", "bb_00000002", "bb_00000003"]);
19138
19139        assert!(
19140            lower_hex_overlap_plan_from_certificates(&left, &right).is_none(),
19141            "matching lower-hex counters with different prefixes must not use arithmetic overlap"
19142        );
19143        let (left_positions, right_positions) =
19144            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
19145        assert!(left_positions.is_empty());
19146        assert!(right_positions.is_empty());
19147    }
19148
19149    #[test]
19150    fn ordered_utf8_contiguous_no_overlap_output_fast_path_jbyuc111111111() -> Result<(), String> {
19151        let left = utf8_key_merge_frame(
19152            &["id_00000000", "id_00000001", "id_00000002", "id_00000003"],
19153            "lv",
19154            10,
19155        );
19156        let right = utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "rv", 100);
19157        let plan = ordered_unique_utf8_inner_position_plan(
19158            left.columns()
19159                .get("id")
19160                .ok_or_else(|| "left key column missing".to_owned())?,
19161            right
19162                .columns()
19163                .get("id")
19164                .ok_or_else(|| "right key column missing".to_owned())?,
19165        )
19166        .ok_or_else(|| "ordered utf8 plan unavailable".to_owned())?;
19167        let InnerPositionPlan::ContiguousRanges {
19168            left_start,
19169            right_start,
19170            len,
19171        } = plan
19172        else {
19173            return Err("expected contiguous range plan".to_owned());
19174        };
19175
19176        let merged = build_single_key_inner_contiguous_no_overlap_output(
19177            &left,
19178            &right,
19179            &["id"],
19180            &["id"],
19181            PositionSelection::ContiguousRange {
19182                start: left_start,
19183                len,
19184            },
19185            PositionSelection::ContiguousRange {
19186                start: right_start,
19187                len,
19188            },
19189        )
19190        .ok_or_else(|| "no-overlap contiguous output fast path missed".to_owned())?;
19191
19192        assert_eq!(merged.column_order, ["id", "lv", "rv"]);
19193        let id_output = merged
19194            .columns
19195            .get("id")
19196            .ok_or_else(|| "id output missing".to_owned())?;
19197        let (prefix, certificate, certificate_len) = id_output
19198            .as_lower_hex_sequence_utf8()
19199            .ok_or_else(|| "id output lost lower-hex sequence witness".to_owned())?;
19200        assert_eq!(prefix, b"id_");
19201        assert_eq!(certificate.start(), 2);
19202        assert_eq!(certificate.hex_width(), 8);
19203        assert_eq!(certificate_len, 2);
19204        assert_eq!(
19205            id_output.values(),
19206            &[
19207                Scalar::Utf8("id_00000002".to_owned()),
19208                Scalar::Utf8("id_00000003".to_owned())
19209            ]
19210        );
19211        assert_eq!(
19212            merged
19213                .columns
19214                .get("lv")
19215                .ok_or_else(|| "lv output missing".to_owned())?
19216                .values(),
19217            &[Scalar::Int64(12), Scalar::Int64(13)]
19218        );
19219        assert_eq!(
19220            merged
19221                .columns
19222                .get("rv")
19223                .ok_or_else(|| "rv output missing".to_owned())?
19224                .values(),
19225            &[Scalar::Int64(100), Scalar::Int64(101)]
19226        );
19227
19228        let overlapping_right =
19229            utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "lv", 100);
19230        assert!(
19231            build_single_key_inner_contiguous_no_overlap_output(
19232                &left,
19233                &overlapping_right,
19234                &["id"],
19235                &["id"],
19236                PositionSelection::ContiguousRange {
19237                    start: left_start,
19238                    len,
19239                },
19240                PositionSelection::ContiguousRange {
19241                    start: right_start,
19242                    len,
19243                },
19244            )
19245            .is_none(),
19246            "overlapping non-key columns must keep the suffix/error generic path"
19247        );
19248        Ok(())
19249    }
19250
19251    #[test]
19252    fn ordered_unique_utf8_uncertified_fixed_width_still_matches_jbyuc111111() {
19253        let left = contiguous_utf8_column(&["k00A", "k00B", "k00C", "k00D"]);
19254        let right = contiguous_utf8_column(&["k00B", "k00D"]);
19255
19256        assert!(left.as_lower_hex_sequence_utf8_contiguous().is_none());
19257        assert!(right.as_lower_hex_sequence_utf8_contiguous().is_none());
19258        let (left_positions, right_positions) =
19259            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
19260        assert_eq!(left_positions, vec![1, 3]);
19261        assert_eq!(right_positions, vec![0, 1]);
19262    }
19263
19264    #[test]
19265    fn ordered_unique_utf8_fixed_width_gap_falls_back_jbyuc11() {
19266        let left = contiguous_utf8_column(&["k000", "k001", "k003", "k004"]);
19267        let right = contiguous_utf8_column(&["k001", "k002", "k004"]);
19268
19269        let (left_positions, right_positions) =
19270            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
19271        assert_eq!(left_positions, vec![1, 3]);
19272        assert_eq!(right_positions, vec![0, 2]);
19273    }
19274
19275    #[test]
19276    fn ordered_unique_utf8_rejects_unsorted_or_duplicate_keys_53lat() {
19277        let unsorted_left = contiguous_utf8_column(&["b", "a", "b"]);
19278        let duplicate_right = contiguous_utf8_column(&["b", "b", "a"]);
19279        assert!(ordered_unique_utf8_inner_positions(&unsorted_left, &duplicate_right).is_none());
19280
19281        let left = utf8_key_merge_frame(&["b", "a", "b"], "lv", 10);
19282        let right = utf8_key_merge_frame(&["b", "b", "a"], "rv", 20);
19283        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
19284
19285        assert_eq!(
19286            merged.columns.get("lv").unwrap().values(),
19287            &[
19288                Scalar::Int64(10),
19289                Scalar::Int64(10),
19290                Scalar::Int64(11),
19291                Scalar::Int64(12),
19292                Scalar::Int64(12)
19293            ]
19294        );
19295        assert_eq!(
19296            merged.columns.get("rv").unwrap().values(),
19297            &[
19298                Scalar::Int64(20),
19299                Scalar::Int64(21),
19300                Scalar::Int64(22),
19301                Scalar::Int64(20),
19302                Scalar::Int64(21)
19303            ]
19304        );
19305    }
19306
19307    #[test]
19308    fn merge_inner_int64_fast_paths_match_naive_reference_fuzz_jdupk() {
19309        // Differential guard: merge_dataframes dispatches int64 single-key inner
19310        // merges to ordered/identity/dense fast paths. Each MUST equal a naive
19311        // left-major nested-loop join for arbitrary int64 keys (sorted/unsorted,
19312        // unique/duplicate, overlapping/disjoint, negative). This is the
19313        // isomorphism proof those perf paths owe; it caught the identity-path
19314        // row-loss bug. (br-frankenpandas-rw0r5)
19315        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
19316        let mut next = || {
19317            state = state
19318                .wrapping_mul(6_364_136_223_846_793_005)
19319                .wrapping_add(1_442_695_040_888_963_407);
19320            state >> 33
19321        };
19322        for _ in 0..400 {
19323            let nl = (next() % 6 + 1) as usize;
19324            let nr = (next() % 6 + 1) as usize;
19325            // small key range forces collisions; offset gives negatives too
19326            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64 - 2).collect();
19327            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64 - 2).collect();
19328
19329            let left = DataFrame::from_dict(
19330                &["id", "a"],
19331                vec![
19332                    ("id", lk.iter().map(|&k| Scalar::Int64(k)).collect()),
19333                    (
19334                        "a",
19335                        (0..nl).map(|i| Scalar::Int64(i as i64 + 1000)).collect(),
19336                    ),
19337                ],
19338            )
19339            .unwrap();
19340            let right = DataFrame::from_dict(
19341                &["id", "b"],
19342                vec![
19343                    ("id", rk.iter().map(|&k| Scalar::Int64(k)).collect()),
19344                    (
19345                        "b",
19346                        (0..nr).map(|j| Scalar::Int64(j as i64 + 2000)).collect(),
19347                    ),
19348                ],
19349            )
19350            .unwrap();
19351
19352            let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
19353
19354            // Naive reference: pandas inner merge is left-major, right-minor,
19355            // with pandas 2.2.3 `_get_join_indexers` equal-left-len permutation (ml0az).
19356            let mut exp_left_pos = Vec::new();
19357            let mut exp_right_pos = Vec::new();
19358            for (i, &left_value) in lk.iter().enumerate() {
19359                for (j, &right_value) in rk.iter().enumerate() {
19360                    if left_value == right_value {
19361                        exp_left_pos.push(i);
19362                        exp_right_pos.push(j);
19363                    }
19364                }
19365            }
19366            super::permute_inner_merge_equal_left_len_positions(
19367                &[left.column("id").unwrap()],
19368                &mut exp_left_pos,
19369                &mut exp_right_pos,
19370            );
19371            let exp_a: Vec<Scalar> = exp_left_pos
19372                .iter()
19373                .map(|&i| Scalar::Int64(i as i64 + 1000))
19374                .collect();
19375            let exp_b: Vec<Scalar> = exp_right_pos
19376                .iter()
19377                .map(|&j| Scalar::Int64(j as i64 + 2000))
19378                .collect();
19379            assert_eq!(
19380                merged.columns.get("a").unwrap().values(),
19381                exp_a.as_slice(),
19382                "left payload mismatch for lk={lk:?} rk={rk:?}"
19383            );
19384            assert_eq!(
19385                merged.columns.get("b").unwrap().values(),
19386                exp_b.as_slice(),
19387                "right payload mismatch for lk={lk:?} rk={rk:?}"
19388            );
19389
19390            // Cardinality guard for left/right/outer (dtype/order independent —
19391            // catches the row-loss class regardless of int->float promotion).
19392            let inner_pairs = exp_a.len();
19393            let left_only = lk.iter().filter(|&key| !rk.contains(key)).count();
19394            let right_only = rk.iter().filter(|&key| !lk.contains(key)).count();
19395            for (how, expected_rows) in [
19396                (JoinType::Left, inner_pairs + left_only),
19397                (JoinType::Right, inner_pairs + right_only),
19398                (JoinType::Outer, inner_pairs + left_only + right_only),
19399            ] {
19400                let m = merge_dataframes(&left, &right, "id", how).unwrap();
19401                assert_eq!(
19402                    m.columns.get("id").unwrap().len(),
19403                    expected_rows,
19404                    "{how:?} cardinality mismatch for lk={lk:?} rk={rk:?}"
19405                );
19406            }
19407        }
19408    }
19409
19410    #[test]
19411    fn merge_null_nan_keys_metamorphic_unmatched_rows_do_not_disturb_inner_tn6qb8()
19412    -> Result<(), JoinError> {
19413        let left = DataFrame::from_dict(
19414            &["id", "left_v"],
19415            vec![
19416                (
19417                    "id",
19418                    vec![
19419                        Scalar::Float64(1.0),
19420                        Scalar::Null(NullKind::NaN),
19421                        Scalar::Null(NullKind::Null),
19422                        Scalar::Float64(2.0),
19423                    ],
19424                ),
19425                (
19426                    "left_v",
19427                    vec![
19428                        Scalar::Int64(10),
19429                        Scalar::Int64(20),
19430                        Scalar::Int64(21),
19431                        Scalar::Int64(30),
19432                    ],
19433                ),
19434            ],
19435        )?;
19436        let right = DataFrame::from_dict(
19437            &["id", "right_v"],
19438            vec![
19439                (
19440                    "id",
19441                    vec![
19442                        Scalar::Null(NullKind::Null),
19443                        Scalar::Float64(2.0),
19444                        Scalar::Float64(f64::NAN),
19445                    ],
19446                ),
19447                (
19448                    "right_v",
19449                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(201)],
19450                ),
19451            ],
19452        )?;
19453
19454        let baseline = merge_dataframes(&left, &right, "id", JoinType::Inner)?;
19455
19456        let left_with_unmatched = DataFrame::from_dict(
19457            &["id", "left_v"],
19458            vec![
19459                (
19460                    "id",
19461                    vec![
19462                        Scalar::Float64(1.0),
19463                        Scalar::Null(NullKind::NaN),
19464                        Scalar::Null(NullKind::Null),
19465                        Scalar::Float64(2.0),
19466                        Scalar::Float64(99.0),
19467                    ],
19468                ),
19469                (
19470                    "left_v",
19471                    vec![
19472                        Scalar::Int64(10),
19473                        Scalar::Int64(20),
19474                        Scalar::Int64(21),
19475                        Scalar::Int64(30),
19476                        Scalar::Int64(990),
19477                    ],
19478                ),
19479            ],
19480        )?;
19481        let right_with_unmatched = DataFrame::from_dict(
19482            &["id", "right_v"],
19483            vec![
19484                (
19485                    "id",
19486                    vec![
19487                        Scalar::Null(NullKind::Null),
19488                        Scalar::Float64(2.0),
19489                        Scalar::Float64(f64::NAN),
19490                        Scalar::Float64(100.0),
19491                    ],
19492                ),
19493                (
19494                    "right_v",
19495                    vec![
19496                        Scalar::Int64(200),
19497                        Scalar::Int64(300),
19498                        Scalar::Int64(201),
19499                        Scalar::Int64(1000),
19500                    ],
19501                ),
19502            ],
19503        )?;
19504
19505        // When left_len == output_len (5 == 5), pandas 2.2.3 `_get_join_indexers`
19506        // applies the ml0az permutation while preserving the exact matched multiset.
19507        let equal_len_transformed = merge_dataframes(
19508            &left_with_unmatched,
19509            &right_with_unmatched,
19510            "id",
19511            JoinType::Inner,
19512        )?;
19513        assert_eq!(
19514            merged_values(&equal_len_transformed, "left_v")?,
19515            &[
19516                Scalar::Int64(30),
19517                Scalar::Int64(21),
19518                Scalar::Int64(21),
19519                Scalar::Int64(20),
19520                Scalar::Int64(20),
19521            ]
19522        );
19523        assert_eq!(
19524            merged_values(&equal_len_transformed, "right_v")?,
19525            &[
19526                Scalar::Int64(300),
19527                Scalar::Int64(200),
19528                Scalar::Int64(201),
19529                Scalar::Int64(200),
19530                Scalar::Int64(201),
19531            ]
19532        );
19533
19534        // Adding two unmatched left rows keeps left_len != output_len (6 != 5),
19535        // so unmatched rows leave the exact inner merge row order invariant.
19536        let left_with_two_unmatched = DataFrame::from_dict(
19537            &["id", "left_v"],
19538            vec![
19539                (
19540                    "id",
19541                    vec![
19542                        Scalar::Float64(1.0),
19543                        Scalar::Null(NullKind::NaN),
19544                        Scalar::Null(NullKind::Null),
19545                        Scalar::Float64(2.0),
19546                        Scalar::Float64(99.0),
19547                        Scalar::Float64(101.0),
19548                    ],
19549                ),
19550                (
19551                    "left_v",
19552                    vec![
19553                        Scalar::Int64(10),
19554                        Scalar::Int64(20),
19555                        Scalar::Int64(21),
19556                        Scalar::Int64(30),
19557                        Scalar::Int64(990),
19558                        Scalar::Int64(1010),
19559                    ],
19560                ),
19561            ],
19562        )?;
19563        let transformed = merge_dataframes(
19564            &left_with_two_unmatched,
19565            &right_with_unmatched,
19566            "id",
19567            JoinType::Inner,
19568        )?;
19569
19570        assert_eq!(
19571            merged_values(&baseline, "left_v")?,
19572            merged_values(&transformed, "left_v")?
19573        );
19574        assert_eq!(
19575            merged_values(&baseline, "right_v")?,
19576            merged_values(&transformed, "right_v")?
19577        );
19578        assert_eq!(
19579            merged_values(&baseline, "left_v")?,
19580            &[
19581                Scalar::Int64(20),
19582                Scalar::Int64(20),
19583                Scalar::Int64(21),
19584                Scalar::Int64(21),
19585                Scalar::Int64(30),
19586            ]
19587        );
19588        assert_eq!(
19589            merged_values(&baseline, "right_v")?,
19590            &[
19591                Scalar::Int64(200),
19592                Scalar::Int64(201),
19593                Scalar::Int64(200),
19594                Scalar::Int64(201),
19595                Scalar::Int64(300),
19596            ]
19597        );
19598
19599        Ok(())
19600    }
19601
19602    #[test]
19603    fn merge_mixed_dtype_missing_keys_metamorphic_outer_both_equals_inner_tn6qb8()
19604    -> Result<(), JoinError> {
19605        let left = DataFrame::from_dict(
19606            &["id", "left_v"],
19607            vec![
19608                (
19609                    "id",
19610                    vec![
19611                        Scalar::Int64(1),
19612                        Scalar::Int64(2),
19613                        Scalar::Null(NullKind::NaN),
19614                        Scalar::Int64(3),
19615                    ],
19616                ),
19617                (
19618                    "left_v",
19619                    vec![
19620                        Scalar::Float64(10.0),
19621                        Scalar::Float64(20.0),
19622                        Scalar::Float64(30.0),
19623                        Scalar::Float64(40.0),
19624                    ],
19625                ),
19626            ],
19627        )?;
19628        let right = DataFrame::from_dict(
19629            &["id", "right_v"],
19630            vec![
19631                (
19632                    "id",
19633                    vec![
19634                        Scalar::Float64(1.0),
19635                        Scalar::Float64(2.5),
19636                        Scalar::Null(NullKind::Null),
19637                        Scalar::Float64(3.0),
19638                    ],
19639                ),
19640                (
19641                    "right_v",
19642                    vec![
19643                        Scalar::Float64(100.0),
19644                        Scalar::Float64(250.0),
19645                        Scalar::Float64(300.0),
19646                        Scalar::Float64(400.0),
19647                    ],
19648                ),
19649            ],
19650        )?;
19651        let options = MergeExecutionOptions {
19652            indicator_name: Some("_merge".to_owned()),
19653            sort: true,
19654            ..MergeExecutionOptions::default()
19655        };
19656
19657        let inner = merge_dataframes_on_with_options(
19658            &left,
19659            &right,
19660            &["id"],
19661            &["id"],
19662            JoinType::Inner,
19663            options.clone(),
19664        )?;
19665        let outer = merge_dataframes_on_with_options(
19666            &left,
19667            &right,
19668            &["id"],
19669            &["id"],
19670            JoinType::Outer,
19671            options,
19672        )?;
19673
19674        assert_eq!(
19675            merged_values(&inner, "left_v")?,
19676            merged_values_where_indicator(&outer, "left_v", "_merge", "both")?
19677        );
19678        assert_eq!(
19679            merged_values(&inner, "right_v")?,
19680            merged_values_where_indicator(&outer, "right_v", "_merge", "both")?
19681        );
19682        assert_eq!(
19683            merged_values(&inner, "left_v")?,
19684            &[
19685                Scalar::Float64(10.0),
19686                Scalar::Float64(40.0),
19687                Scalar::Float64(30.0)
19688            ]
19689        );
19690        assert_eq!(
19691            merged_values(&inner, "right_v")?,
19692            &[
19693                Scalar::Float64(100.0),
19694                Scalar::Float64(400.0),
19695                Scalar::Float64(300.0)
19696            ]
19697        );
19698        assert_eq!(
19699            merged_values(&outer, "_merge")?,
19700            &[
19701                Scalar::Utf8("both".to_owned()),
19702                Scalar::Utf8("left_only".to_owned()),
19703                Scalar::Utf8("right_only".to_owned()),
19704                Scalar::Utf8("both".to_owned()),
19705                Scalar::Utf8("both".to_owned()),
19706            ]
19707        );
19708
19709        Ok(())
19710    }
19711
19712    #[test]
19713    fn merge_cross_cartesian_product() {
19714        let left = make_left_df();
19715        let right = make_right_df();
19716
19717        let merged = merge_dataframes(&left, &right, "unused_key", JoinType::Cross).unwrap();
19718
19719        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
19720        assert_eq!(
19721            &merged.columns.get("id_x").unwrap().values()[0..3],
19722            &[Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)]
19723        );
19724        assert_eq!(
19725            &merged.columns.get("id_y").unwrap().values()[0..3],
19726            &[Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)]
19727        );
19728        assert_eq!(
19729            &merged.columns.get("val_a").unwrap().values()[0..3],
19730            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(10)]
19731        );
19732        assert_eq!(
19733            &merged.columns.get("val_b").unwrap().values()[0..3],
19734            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
19735        );
19736    }
19737
19738    #[test]
19739    fn merge_cross_does_not_require_on_column() {
19740        let left = make_left_df();
19741        let right = make_right_df();
19742
19743        let merged =
19744            merge_dataframes(&left, &right, "definitely_missing", JoinType::Cross).unwrap();
19745        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
19746    }
19747
19748    #[test]
19749    fn merge_cross_with_empty_side_yields_empty_rows() {
19750        let left = DataFrame::from_dict(
19751            &["l"],
19752            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
19753        )
19754        .unwrap();
19755        let right = DataFrame::from_dict(&["r"], vec![("r", vec![])]).unwrap();
19756
19757        let merged = merge_dataframes(&left, &right, "ignored", JoinType::Cross).unwrap();
19758        assert_eq!(merged.index.labels().len(), 0);
19759        assert!(merged.columns.get("l").unwrap().values().is_empty());
19760        assert!(merged.columns.get("r").unwrap().values().is_empty());
19761    }
19762
19763    /// A cross merge keeps each side's own column order, as pandas (the
19764    /// columns came back sorted by name; buwrx).
19765    #[test]
19766    fn merge_cross_keeps_each_sides_column_order_buwrx() {
19767        let ints = |values: [i64; 2]| values.map(Scalar::Int64).to_vec();
19768        let left = DataFrame::from_dict(
19769            &["z", "k", "a"],
19770            vec![
19771                ("z", ints([1, 2])),
19772                ("k", ints([3, 4])),
19773                ("a", ints([5, 6])),
19774            ],
19775        )
19776        .unwrap();
19777        let right = DataFrame::from_dict(
19778            &["k", "w", "b"],
19779            vec![
19780                ("k", ints([7, 8])),
19781                ("w", ints([9, 10])),
19782                ("b", ints([11, 12])),
19783            ],
19784        )
19785        .unwrap();
19786        let merged = merge_dataframes(&left, &right, "ignored", JoinType::Cross).unwrap();
19787        assert_eq!(merged.column_order, ["z", "k_x", "a", "k_y", "w", "b"]);
19788        assert_eq!(
19789            merged.columns.get("w").unwrap().values(),
19790            [9, 10, 9, 10].map(Scalar::Int64)
19791        );
19792        // NEGATIVE: the rows are still left-major.
19793        assert_eq!(
19794            merged.columns.get("z").unwrap().values(),
19795            [1, 1, 2, 2].map(Scalar::Int64)
19796        );
19797    }
19798
19799    #[test]
19800    fn text_and_int_keys_join_as_codes_in_row_order_j4657() {
19801        // A (text, int) merge key's text joins as int64 codes over both
19802        // sides' strings: an inner / left merge pairs each left row with its
19803        // equal right rows in their order (a left row without one kept by
19804        // the left join), as a loop over the rows pairs them; a contiguous
19805        // and a Scalar text column alike. NEGATIVE: "a" never meets "A" or
19806        // "a " (codes per byte string), a right-only string matches nothing,
19807        // the right's first string ("q") is not the left's first code's, an
19808        // outer merge sorts by the strings (codes would put "b" first), and
19809        // a missing text key still joins its missing peer (the generic path).
19810        // No inner merge here is as long as the left frame, where pandas 2.2
19811        // reorders the rows (br-frankenpandas-ml0az; br-frankenpandas-j4657).
19812        let left_text = ["b", "a", "A", "a", "c", "b", "a "];
19813        let left_int = [1_i64, 2, 2, 2, 7, 1, 2];
19814        let right_text = ["q", "a", "b", "a", "b", "A", "c", "c", "b"];
19815        let right_int = [5_i64, 2, 1, 2, 3, 9, 7, 7, 1];
19816        let frame = |text: Column, ints: &[i64], value: &str, base: i64| {
19817            let rows = ints.len();
19818            let mut columns = ColumnStore::new();
19819            columns.insert("t".to_owned(), text);
19820            columns.insert("i".to_owned(), Column::from_i64_values(ints.to_vec()));
19821            columns.insert(
19822                value.to_owned(),
19823                Column::from_i64_values((0..rows as i64).map(|row| base + row).collect()),
19824            );
19825            DataFrame::new_with_column_order(
19826                Index::new((0..rows as i64).map(IndexLabel::Int64).collect()),
19827                columns,
19828                vec!["t".to_owned(), "i".to_owned(), value.to_owned()],
19829            )
19830            .unwrap()
19831        };
19832        let scalar_text = |values: &[&str]| {
19833            Column::from_values(
19834                values
19835                    .iter()
19836                    .map(|value| Scalar::Utf8((*value).to_owned()))
19837                    .collect(),
19838            )
19839            .unwrap()
19840        };
19841        for contiguous in [true, false] {
19842            let text = |values: &[&str]| {
19843                if contiguous {
19844                    contiguous_utf8_column(values)
19845                } else {
19846                    scalar_text(values)
19847                }
19848            };
19849            let left = frame(text(&left_text), &left_int, "lv", 100);
19850            let right = frame(text(&right_text), &right_int, "rv", 200);
19851            for join_type in [JoinType::Inner, JoinType::Left] {
19852                let mut want: Vec<(Scalar, Scalar)> = Vec::new();
19853                for (l, key) in left_text.iter().zip(&left_int).enumerate() {
19854                    let matches: Vec<usize> = right_text
19855                        .iter()
19856                        .zip(&right_int)
19857                        .enumerate()
19858                        .filter(|(_, right_key)| *right_key == key)
19859                        .map(|(r, _)| r)
19860                        .collect();
19861                    for &r in &matches {
19862                        want.push((Scalar::Int64(100 + l as i64), Scalar::Int64(200 + r as i64)));
19863                    }
19864                    if matches.is_empty() && matches!(join_type, JoinType::Left) {
19865                        want.push((Scalar::Int64(100 + l as i64), Scalar::Null(NullKind::NaN)));
19866                    }
19867                }
19868                let merged = merge_dataframes_on(&left, &right, &["t", "i"], join_type).unwrap();
19869                let got: Vec<(Scalar, Scalar)> = merged
19870                    .columns
19871                    .get("lv")
19872                    .unwrap()
19873                    .values()
19874                    .iter()
19875                    .cloned()
19876                    .zip(merged.columns.get("rv").unwrap().values().iter().cloned())
19877                    .collect();
19878                assert_eq!(got.len(), want.len(), "{contiguous} {join_type:?}");
19879                for ((got_l, got_r), (want_l, want_r)) in got.iter().zip(&want) {
19880                    assert_eq!(got_l, want_l, "{contiguous} {join_type:?}");
19881                    assert_eq!(got_r.is_missing(), want_r.is_missing());
19882                    if !want_r.is_missing() {
19883                        assert_eq!(got_r.to_f64().ok(), want_r.to_f64().ok());
19884                    }
19885                }
19886                // The key columns are the strings, not their codes.
19887                let keys: Vec<Scalar> = want
19888                    .iter()
19889                    .map(|(l, _)| match l {
19890                        Scalar::Int64(row) => {
19891                            Scalar::Utf8(left_text[(*row - 100) as usize].to_owned())
19892                        }
19893                        _ => unreachable!(),
19894                    })
19895                    .collect();
19896                assert_eq!(merged.columns.get("t").unwrap().values(), keys.as_slice());
19897            }
19898            // Inner pairs: b/1's two left rows with right rows 2 and 8, a/2's
19899            // two with rows 1 and 3, c/7 with rows 6 and 7; A/2 none (right A
19900            // is 9), "a " none.
19901            let inner = merge_dataframes_on(&left, &right, &["t", "i"], JoinType::Inner).unwrap();
19902            assert_eq!(inner.columns.get("lv").unwrap().len(), 10);
19903            let outer = merge_dataframes_on(&left, &right, &["t", "i"], JoinType::Outer).unwrap();
19904            let outer_keys: Vec<String> = outer
19905                .columns
19906                .get("t")
19907                .unwrap()
19908                .values()
19909                .iter()
19910                .map(|value| match value {
19911                    Scalar::Utf8(text) => text.clone(),
19912                    other => format!("{other:?}"),
19913                })
19914                .collect();
19915            let mut sorted = outer_keys.clone();
19916            sorted.sort();
19917            assert_eq!(outer_keys, sorted, "{contiguous}");
19918        }
19919        // A missing text key meets its missing peer through the generic path.
19920        let left = frame(
19921            Column::from_values(vec![
19922                Scalar::Utf8("a".to_owned()),
19923                Scalar::Null(NullKind::Null),
19924            ])
19925            .unwrap(),
19926            &[1, 1],
19927            "lv",
19928            100,
19929        );
19930        let right = frame(
19931            Column::from_values(vec![
19932                Scalar::Null(NullKind::Null),
19933                Scalar::Utf8("a".to_owned()),
19934            ])
19935            .unwrap(),
19936            &[1, 1],
19937            "rv",
19938            200,
19939        );
19940        let merged = merge_dataframes_on(&left, &right, &["t", "i"], JoinType::Inner).unwrap();
19941        assert_eq!(
19942            merged.columns.get("lv").unwrap().values(),
19943            &[Scalar::Int64(100), Scalar::Int64(101)]
19944        );
19945        assert_eq!(
19946            merged.columns.get("rv").unwrap().values(),
19947            &[Scalar::Int64(201), Scalar::Int64(200)]
19948        );
19949    }
19950
19951    #[test]
19952    fn merge_composite_inner_multiplies_cardinality_for_duplicates() {
19953        let left = DataFrame::from_dict(
19954            &["k1", "k2", "left_v"],
19955            vec![
19956                (
19957                    "k1",
19958                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
19959                ),
19960                (
19961                    "k2",
19962                    vec![
19963                        Scalar::Utf8("a".to_owned()),
19964                        Scalar::Utf8("a".to_owned()),
19965                        Scalar::Utf8("b".to_owned()),
19966                    ],
19967                ),
19968                (
19969                    "left_v",
19970                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
19971                ),
19972            ],
19973        )
19974        .unwrap();
19975        let right = DataFrame::from_dict(
19976            &["k1", "k2", "right_v"],
19977            vec![
19978                (
19979                    "k1",
19980                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
19981                ),
19982                (
19983                    "k2",
19984                    vec![
19985                        Scalar::Utf8("a".to_owned()),
19986                        Scalar::Utf8("a".to_owned()),
19987                        Scalar::Utf8("c".to_owned()),
19988                    ],
19989                ),
19990                (
19991                    "right_v",
19992                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
19993                ),
19994            ],
19995        )
19996        .unwrap();
19997
19998        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
19999        assert_eq!(merged.columns.get("k1").unwrap().len(), 4);
20000        assert_eq!(
20001            merged.columns.get("k1").unwrap().values(),
20002            &[
20003                Scalar::Int64(1),
20004                Scalar::Int64(1),
20005                Scalar::Int64(1),
20006                Scalar::Int64(1)
20007            ]
20008        );
20009        assert_eq!(
20010            merged.columns.get("k2").unwrap().values(),
20011            &[
20012                Scalar::Utf8("a".to_owned()),
20013                Scalar::Utf8("a".to_owned()),
20014                Scalar::Utf8("a".to_owned()),
20015                Scalar::Utf8("a".to_owned())
20016            ]
20017        );
20018        assert_eq!(
20019            merged.columns.get("left_v").unwrap().values(),
20020            &[
20021                Scalar::Int64(10),
20022                Scalar::Int64(10),
20023                Scalar::Int64(20),
20024                Scalar::Int64(20)
20025            ]
20026        );
20027        assert_eq!(
20028            merged.columns.get("right_v").unwrap().values(),
20029            &[
20030                Scalar::Int64(100),
20031                Scalar::Int64(200),
20032                Scalar::Int64(100),
20033                Scalar::Int64(200)
20034            ]
20035        );
20036    }
20037
20038    #[test]
20039    fn merge_composite_outer_sorts_join_keys_lexicographically() {
20040        let left = DataFrame::from_dict(
20041            &["k1", "k2", "left_v"],
20042            vec![
20043                ("k1", vec![Scalar::Int64(2), Scalar::Int64(1)]),
20044                (
20045                    "k2",
20046                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("x".to_owned())],
20047                ),
20048                ("left_v", vec![Scalar::Int64(20), Scalar::Int64(10)]),
20049            ],
20050        )
20051        .unwrap();
20052        let right = DataFrame::from_dict(
20053            &["k1", "k2", "right_v"],
20054            vec![
20055                ("k1", vec![Scalar::Int64(2), Scalar::Int64(3)]),
20056                (
20057                    "k2",
20058                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("z".to_owned())],
20059                ),
20060                ("right_v", vec![Scalar::Int64(200), Scalar::Int64(300)]),
20061            ],
20062        )
20063        .unwrap();
20064
20065        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
20066        assert_eq!(
20067            merged.columns.get("k1").unwrap().values(),
20068            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
20069        );
20070        assert_eq!(
20071            merged.columns.get("k2").unwrap().values(),
20072            &[
20073                Scalar::Utf8("x".to_owned()),
20074                Scalar::Utf8("y".to_owned()),
20075                Scalar::Utf8("z".to_owned())
20076            ]
20077        );
20078        assert_eq!(
20079            merged.columns.get("left_v").unwrap().values(),
20080            &[
20081                Scalar::Float64(10.0),
20082                Scalar::Float64(20.0),
20083                Scalar::Null(NullKind::NaN)
20084            ]
20085        );
20086        assert_eq!(
20087            merged.columns.get("right_v").unwrap().values(),
20088            &[
20089                Scalar::Null(NullKind::NaN),
20090                Scalar::Float64(200.0),
20091                Scalar::Float64(300.0)
20092            ]
20093        );
20094    }
20095
20096    #[test]
20097    fn merge_composite_outer_contiguous_utf8_key_coalesce_matches_scalar_route_blackthrush() {
20098        let contiguous_frame =
20099            |k1: &[&str], k2: &[&str], value_name: &str, values: &[i64]| -> DataFrame {
20100                let index = Index::new(
20101                    (0..k1.len())
20102                        .map(|row| IndexLabel::Int64(row as i64))
20103                        .collect(),
20104                );
20105                let mut columns = ColumnStore::new();
20106                columns.insert("k1".to_owned(), contiguous_utf8_column(k1));
20107                columns.insert("k2".to_owned(), contiguous_utf8_column(k2));
20108                columns.insert(
20109                    value_name.to_owned(),
20110                    Column::from_i64_values(values.to_vec()),
20111                );
20112                DataFrame::new_with_column_order(
20113                    index,
20114                    columns,
20115                    vec!["k1".to_owned(), "k2".to_owned(), value_name.to_owned()],
20116                )
20117                .expect("contiguous frame")
20118            };
20119        let scalar_frame =
20120            |k1: &[&str], k2: &[&str], value_name: &str, values: &[i64]| -> DataFrame {
20121                DataFrame::from_dict(
20122                    &["k1", "k2", value_name],
20123                    vec![
20124                        (
20125                            "k1",
20126                            k1.iter()
20127                                .map(|value| Scalar::Utf8((*value).to_owned()))
20128                                .collect(),
20129                        ),
20130                        (
20131                            "k2",
20132                            k2.iter()
20133                                .map(|value| Scalar::Utf8((*value).to_owned()))
20134                                .collect(),
20135                        ),
20136                        (
20137                            value_name,
20138                            values.iter().copied().map(Scalar::Int64).collect(),
20139                        ),
20140                    ],
20141                )
20142                .expect("scalar frame")
20143            };
20144
20145        let left_fast =
20146            contiguous_frame(&["b", "a", "c"], &["y", "x", "z"], "left_v", &[20, 10, 30]);
20147        let right_fast = contiguous_frame(&["b", "d"], &["y", "w"], "right_v", &[200, 400]);
20148        let left_scalar = scalar_frame(&["b", "a", "c"], &["y", "x", "z"], "left_v", &[20, 10, 30]);
20149        let right_scalar = scalar_frame(&["b", "d"], &["y", "w"], "right_v", &[200, 400]);
20150
20151        let fast =
20152            merge_dataframes_on(&left_fast, &right_fast, &["k1", "k2"], JoinType::Outer).unwrap();
20153        let scalar =
20154            merge_dataframes_on(&left_scalar, &right_scalar, &["k1", "k2"], JoinType::Outer)
20155                .unwrap();
20156
20157        for name in ["k1", "k2", "left_v", "right_v"] {
20158            assert_eq!(
20159                fast.columns.get(name).unwrap().values(),
20160                scalar.columns.get(name).unwrap().values(),
20161                "column {name}"
20162            );
20163        }
20164        assert!(
20165            fast.columns
20166                .get("k1")
20167                .unwrap()
20168                .as_utf8_contiguous()
20169                .is_some()
20170        );
20171        assert!(
20172            fast.columns
20173                .get("k2")
20174                .unwrap()
20175                .as_utf8_contiguous()
20176                .is_some()
20177        );
20178    }
20179
20180    #[test]
20181    fn merge_composite_inner_matches_missing_key_components() {
20182        let left = DataFrame::from_dict(
20183            &["k1", "k2", "left_v"],
20184            vec![
20185                ("k1", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20186                (
20187                    "k2",
20188                    vec![Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())],
20189                ),
20190                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20191            ],
20192        )
20193        .unwrap();
20194        let right = DataFrame::from_dict(
20195            &["k1", "k2", "right_v"],
20196            vec![
20197                (
20198                    "k1",
20199                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
20200                ),
20201                (
20202                    "k2",
20203                    vec![
20204                        Scalar::Null(NullKind::Null),
20205                        Scalar::Utf8("a".to_owned()),
20206                        Scalar::Null(NullKind::Null),
20207                    ],
20208                ),
20209                (
20210                    "right_v",
20211                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
20212                ),
20213            ],
20214        )
20215        .unwrap();
20216
20217        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
20218        assert_eq!(
20219            merged.columns.get("k1").unwrap().values(),
20220            &[Scalar::Int64(1), Scalar::Int64(1)]
20221        );
20222        assert_eq!(
20223            merged.columns.get("k2").unwrap().values(),
20224            &[Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())]
20225        );
20226        assert_eq!(
20227            merged.columns.get("left_v").unwrap().values(),
20228            &[Scalar::Int64(10), Scalar::Int64(20)]
20229        );
20230        assert_eq!(
20231            merged.columns.get("right_v").unwrap().values(),
20232            &[Scalar::Int64(100), Scalar::Int64(200)]
20233        );
20234    }
20235
20236    #[test]
20237    fn merge_composite_outer_keeps_right_only_rows_with_missing_keys() {
20238        let left = DataFrame::from_dict(
20239            &["k1", "k2", "left_v"],
20240            vec![
20241                ("k1", vec![Scalar::Int64(1)]),
20242                ("k2", vec![Scalar::Null(NullKind::Null)]),
20243                ("left_v", vec![Scalar::Int64(10)]),
20244            ],
20245        )
20246        .unwrap();
20247        let right = DataFrame::from_dict(
20248            &["k1", "k2", "right_v"],
20249            vec![
20250                ("k1", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20251                (
20252                    "k2",
20253                    vec![Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)],
20254                ),
20255                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20256            ],
20257        )
20258        .unwrap();
20259
20260        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
20261        assert_eq!(
20262            merged.columns.get("k1").unwrap().values(),
20263            &[Scalar::Int64(1), Scalar::Int64(2)]
20264        );
20265        assert_eq!(
20266            merged.columns.get("k2").unwrap().values(),
20267            &[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)]
20268        );
20269        assert_eq!(
20270            merged.columns.get("left_v").unwrap().values(),
20271            &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
20272        );
20273        assert_eq!(
20274            merged.columns.get("right_v").unwrap().values(),
20275            &[Scalar::Int64(100), Scalar::Int64(200)]
20276        );
20277    }
20278
20279    #[test]
20280    fn merge_composite_missing_key_column_errors() {
20281        let left = DataFrame::from_dict(
20282            &["k1", "k2", "left_v"],
20283            vec![
20284                ("k1", vec![Scalar::Int64(1)]),
20285                ("k2", vec![Scalar::Utf8("x".to_owned())]),
20286                ("left_v", vec![Scalar::Int64(10)]),
20287            ],
20288        )
20289        .unwrap();
20290        let right = DataFrame::from_dict(
20291            &["k1", "right_v"],
20292            vec![
20293                ("k1", vec![Scalar::Int64(1)]),
20294                ("right_v", vec![Scalar::Int64(100)]),
20295            ],
20296        )
20297        .unwrap();
20298
20299        let err = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner)
20300            .expect_err("should fail");
20301        assert!(format!("{err}").contains("right DataFrame missing key column 'k2'"));
20302    }
20303
20304    #[test]
20305    fn merge_composite_key_alias_inner_keeps_both_key_sets() {
20306        let left = DataFrame::from_dict(
20307            &["lk1", "lk2", "left_v"],
20308            vec![
20309                (
20310                    "lk1",
20311                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
20312                ),
20313                (
20314                    "lk2",
20315                    vec![
20316                        Scalar::Utf8("a".to_owned()),
20317                        Scalar::Utf8("b".to_owned()),
20318                        Scalar::Utf8("c".to_owned()),
20319                    ],
20320                ),
20321                (
20322                    "left_v",
20323                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
20324                ),
20325            ],
20326        )
20327        .unwrap();
20328        let right = DataFrame::from_dict(
20329            &["rk1", "rk2", "right_v"],
20330            vec![
20331                (
20332                    "rk1",
20333                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
20334                ),
20335                (
20336                    "rk2",
20337                    vec![
20338                        Scalar::Utf8("b".to_owned()),
20339                        Scalar::Utf8("c".to_owned()),
20340                        Scalar::Utf8("d".to_owned()),
20341                    ],
20342                ),
20343                (
20344                    "right_v",
20345                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
20346                ),
20347            ],
20348        )
20349        .unwrap();
20350
20351        let merged = merge_dataframes_on_with(
20352            &left,
20353            &right,
20354            &["lk1", "lk2"],
20355            &["rk1", "rk2"],
20356            JoinType::Inner,
20357        )
20358        .unwrap();
20359        assert_eq!(
20360            merged.columns.get("lk1").unwrap().values(),
20361            &[Scalar::Int64(2), Scalar::Int64(3)]
20362        );
20363        assert_eq!(
20364            merged.columns.get("lk2").unwrap().values(),
20365            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
20366        );
20367        assert_eq!(
20368            merged.columns.get("left_v").unwrap().values(),
20369            &[Scalar::Int64(20), Scalar::Int64(30)]
20370        );
20371        assert_eq!(
20372            merged.columns.get("rk1").unwrap().values(),
20373            &[Scalar::Int64(2), Scalar::Int64(3)]
20374        );
20375        assert_eq!(
20376            merged.columns.get("rk2").unwrap().values(),
20377            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
20378        );
20379        assert_eq!(
20380            merged.columns.get("right_v").unwrap().values(),
20381            &[Scalar::Int64(200), Scalar::Int64(300)]
20382        );
20383    }
20384
20385    #[test]
20386    fn merge_composite_key_alias_outer_propagates_missing_per_side() {
20387        let left = DataFrame::from_dict(
20388            &["lk1", "lk2", "left_v"],
20389            vec![
20390                (
20391                    "lk1",
20392                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
20393                ),
20394                (
20395                    "lk2",
20396                    vec![
20397                        Scalar::Utf8("a".to_owned()),
20398                        Scalar::Null(NullKind::Null),
20399                        Scalar::Utf8("c".to_owned()),
20400                    ],
20401                ),
20402                (
20403                    "left_v",
20404                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
20405                ),
20406            ],
20407        )
20408        .unwrap();
20409        let right = DataFrame::from_dict(
20410            &["rk1", "rk2", "right_v"],
20411            vec![
20412                (
20413                    "rk1",
20414                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
20415                ),
20416                (
20417                    "rk2",
20418                    vec![
20419                        Scalar::Utf8("a".to_owned()),
20420                        Scalar::Null(NullKind::Null),
20421                        Scalar::Utf8("d".to_owned()),
20422                    ],
20423                ),
20424                (
20425                    "right_v",
20426                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
20427                ),
20428            ],
20429        )
20430        .unwrap();
20431
20432        let merged = merge_dataframes_on_with(
20433            &left,
20434            &right,
20435            &["lk1", "lk2"],
20436            &["rk1", "rk2"],
20437            JoinType::Outer,
20438        )
20439        .unwrap();
20440
20441        assert_eq!(
20442            merged.columns.get("lk1").unwrap().values(),
20443            &[
20444                Scalar::Float64(1.0),
20445                Scalar::Float64(2.0),
20446                Scalar::Float64(3.0),
20447                Scalar::Null(NullKind::NaN)
20448            ]
20449        );
20450        assert_eq!(
20451            merged.columns.get("rk1").unwrap().values(),
20452            &[
20453                Scalar::Float64(1.0),
20454                Scalar::Float64(2.0),
20455                Scalar::Null(NullKind::NaN),
20456                Scalar::Float64(4.0)
20457            ]
20458        );
20459        assert_eq!(
20460            merged.columns.get("left_v").unwrap().values(),
20461            &[
20462                Scalar::Float64(10.0),
20463                Scalar::Float64(20.0),
20464                Scalar::Float64(30.0),
20465                Scalar::Null(NullKind::NaN)
20466            ]
20467        );
20468        assert_eq!(
20469            merged.columns.get("right_v").unwrap().values(),
20470            &[
20471                Scalar::Float64(100.0),
20472                Scalar::Float64(200.0),
20473                Scalar::Null(NullKind::NaN),
20474                Scalar::Float64(400.0)
20475            ]
20476        );
20477    }
20478
20479    #[test]
20480    fn merge_key_alias_lists_must_have_equal_lengths() {
20481        let left = make_left_df();
20482        let right = make_right_df();
20483        let err = merge_dataframes_on_with(&left, &right, &["id", "id"], &["id"], JoinType::Inner)
20484            .expect_err("should fail");
20485        assert!(format!("{err}").contains("equal length"));
20486    }
20487
20488    #[test]
20489    fn merge_indicator_default_name_tracks_row_provenance() {
20490        let left = make_left_df();
20491        let right = make_right_df();
20492
20493        let merged = merge_dataframes_on_with_options(
20494            &left,
20495            &right,
20496            &["id"],
20497            &["id"],
20498            JoinType::Outer,
20499            MergeExecutionOptions {
20500                indicator_name: Some("_merge".to_owned()),
20501                ..MergeExecutionOptions::default()
20502            },
20503        )
20504        .expect("merge");
20505
20506        let indicator = merged.columns.get("_merge").expect("indicator");
20507        assert_eq!(
20508            indicator.values(),
20509            &[
20510                Scalar::Utf8("left_only".to_owned()),
20511                Scalar::Utf8("both".to_owned()),
20512                Scalar::Utf8("both".to_owned()),
20513                Scalar::Utf8("right_only".to_owned())
20514            ]
20515        );
20516        // pandas 2.2.3: _merge is a category over the fixed [left_only,
20517        // right_only, both] (br-frankenpandas-hrxn9), not an object column.
20518        assert_eq!(indicator.dtype(), fp_types::DType::Categorical);
20519        assert_eq!(
20520            indicator.categorical().map(|meta| meta.categories.clone()),
20521            Some(
20522                ["left_only", "right_only", "both"]
20523                    .map(|c| Scalar::Utf8(c.to_owned()))
20524                    .to_vec()
20525            )
20526        );
20527    }
20528
20529    #[test]
20530    fn merge_indicator_custom_name_preserves_suffix_behavior() {
20531        let left = DataFrame::from_dict(
20532            &["id", "val"],
20533            vec![
20534                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20535                ("val", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20536            ],
20537        )
20538        .unwrap();
20539        let right = DataFrame::from_dict(
20540            &["id", "val"],
20541            vec![
20542                ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
20543                ("val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
20544            ],
20545        )
20546        .unwrap();
20547
20548        let merged = merge_dataframes_on_with_options(
20549            &left,
20550            &right,
20551            &["id"],
20552            &["id"],
20553            JoinType::Outer,
20554            MergeExecutionOptions {
20555                indicator_name: Some("origin".to_owned()),
20556                ..MergeExecutionOptions::default()
20557            },
20558        )
20559        .expect("merge");
20560
20561        assert!(merged.columns.contains_key("val_x"));
20562        assert!(merged.columns.contains_key("val_y"));
20563        assert_eq!(
20564            merged.columns.get("origin").expect("indicator").values(),
20565            &[
20566                Scalar::Utf8("left_only".to_owned()),
20567                Scalar::Utf8("both".to_owned()),
20568                Scalar::Utf8("right_only".to_owned())
20569            ]
20570        );
20571    }
20572
20573    #[test]
20574    fn merge_indicator_rejects_conflicting_column_name() {
20575        let left = make_left_df();
20576        let right = make_right_df();
20577
20578        let err = merge_dataframes_on_with_options(
20579            &left,
20580            &right,
20581            &["id"],
20582            &["id"],
20583            JoinType::Inner,
20584            MergeExecutionOptions {
20585                indicator_name: Some("id".to_owned()),
20586                ..MergeExecutionOptions::default()
20587            },
20588        )
20589        .expect_err("expected indicator name conflict");
20590        assert!(format!("{err}").contains("conflicts with an existing column"));
20591    }
20592
20593    #[test]
20594    fn merge_cross_indicator_marks_all_rows_both() {
20595        // Restored after br-frankenpandas-glsam revert: pandas 2.2.3
20596        // supports `how='cross', indicator=...` and emits "both" for every
20597        // cross-product row (verified against FP-P2D-039 fixture provenance
20598        // pandas_version=2.2.3). The Explore-agent claim that pandas raises
20599        // was incorrect; this test locks in the actual pandas behavior.
20600        let left = DataFrame::from_dict(
20601            &["l"],
20602            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
20603        )
20604        .unwrap();
20605        let right = DataFrame::from_dict(&["r"], vec![("r", vec![Scalar::Int64(9)])]).unwrap();
20606
20607        let merged = merge_dataframes_on_with_options(
20608            &left,
20609            &right,
20610            &["ignored"],
20611            &["ignored"],
20612            JoinType::Cross,
20613            MergeExecutionOptions {
20614                indicator_name: Some("_merge".to_owned()),
20615                ..MergeExecutionOptions::default()
20616            },
20617        )
20618        .expect("cross merge");
20619        assert_eq!(
20620            merged.columns.get("_merge").expect("indicator").values(),
20621            &[
20622                Scalar::Utf8("both".to_owned()),
20623                Scalar::Utf8("both".to_owned())
20624            ]
20625        );
20626    }
20627
20628    #[test]
20629    fn merge_cross_validate_mode_contract_ohb5f() {
20630        let left = DataFrame::from_dict(
20631            &["l"],
20632            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
20633        )
20634        .expect("left");
20635        let right = DataFrame::from_dict(
20636            &["r"],
20637            vec![("r", vec![Scalar::Int64(10), Scalar::Int64(20)])],
20638        )
20639        .expect("right");
20640
20641        let many_to_many = merge_dataframes_on_with_options(
20642            &left,
20643            &right,
20644            &["missing_left_key"],
20645            &["missing_right_key"],
20646            JoinType::Cross,
20647            MergeExecutionOptions {
20648                validate_mode: Some(MergeValidateMode::ManyToMany),
20649                ..MergeExecutionOptions::default()
20650            },
20651        )
20652        .expect("cross merge validate=many_to_many");
20653        assert_eq!(many_to_many.index.len(), 4);
20654
20655        for validate_mode in [
20656            MergeValidateMode::OneToOne,
20657            MergeValidateMode::OneToMany,
20658            MergeValidateMode::ManyToOne,
20659        ] {
20660            let err = merge_dataframes_on_with_options(
20661                &left,
20662                &right,
20663                &["missing_left_key"],
20664                &["missing_right_key"],
20665                JoinType::Cross,
20666                MergeExecutionOptions {
20667                    validate_mode: Some(validate_mode),
20668                    ..MergeExecutionOptions::default()
20669                },
20670            )
20671            .expect_err("enforcing validate modes are not meaningful for cross joins");
20672            let message = format!("{err}");
20673            assert!(message.contains(validate_mode.as_str()));
20674            assert!(message.contains("not supported for cross join"));
20675        }
20676    }
20677
20678    #[test]
20679    fn merge_validate_one_to_one_rejects_duplicate_left_keys() {
20680        let left = DataFrame::from_dict(
20681            &["id", "left_v"],
20682            vec![
20683                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20684                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20685            ],
20686        )
20687        .expect("left frame");
20688        let right = DataFrame::from_dict(
20689            &["id", "right_v"],
20690            vec![
20691                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20692                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20693            ],
20694        )
20695        .expect("right frame");
20696
20697        let err = merge_dataframes_on_with_options(
20698            &left,
20699            &right,
20700            &["id"],
20701            &["id"],
20702            JoinType::Inner,
20703            MergeExecutionOptions {
20704                validate_mode: Some(MergeValidateMode::OneToOne),
20705                ..MergeExecutionOptions::default()
20706            },
20707        )
20708        .expect_err("one_to_one must reject duplicate left keys");
20709        assert!(format!("{err}").contains("left keys are not unique"));
20710    }
20711
20712    #[test]
20713    fn repeated_non_key_columns_keep_their_own_data_through_merge_i17d4() {
20714        // pandas 2.2.3: merging a frame whose columns are ['a', 'a', 'k'] on
20715        // 'k' keeps both 'a' columns, each its own data (the first was read
20716        // for both); when the other side has an 'a' too, each copy takes its
20717        // side's suffix (a_x, a_x beside a_y).
20718        let f = Scalar::Float64;
20719        let column = |values: [f64; 2]| {
20720            Column::new(DType::Float64, values.iter().map(|v| f(*v)).collect()).expect("column")
20721        };
20722        let left = DataFrame::new_with_column_order(
20723            Index::new(vec![0_i64.into(), 1_i64.into()]),
20724            ColumnStore::from_pairs(vec![
20725                ("a".to_owned(), column([1.0, 4.0])),
20726                ("a".to_owned(), column([5.75, 2.25])),
20727                ("k".to_owned(), column([1.0, 2.0])),
20728            ]),
20729            vec!["a".to_owned(), "a".to_owned(), "k".to_owned()],
20730        )
20731        .expect("left frame");
20732        let right = |other: &str| {
20733            DataFrame::from_dict(
20734                &["k", other],
20735                vec![("k", vec![f(1.0), f(2.0)]), (other, vec![f(5.0), f(6.0)])],
20736            )
20737            .expect("right frame")
20738        };
20739        let merge = |right: &DataFrame| {
20740            merge_dataframes_on_with_options(
20741                &left,
20742                right,
20743                &["k"],
20744                &["k"],
20745                JoinType::Inner,
20746                MergeExecutionOptions::default(),
20747            )
20748            .expect("merge")
20749        };
20750        let merged = merge(&right("z"));
20751        assert_eq!(merged.column_order, vec!["a", "a", "k", "z"]);
20752        let second_a = merged.columns.get_all("a").nth(1).expect("second a");
20753        assert_eq!(second_a.values(), &[f(5.75), f(2.25)]);
20754
20755        let suffixed = merge(&right("a"));
20756        assert_eq!(suffixed.column_order, vec!["a_x", "a_x", "k", "a_y"]);
20757        let second_x = suffixed.columns.get_all("a_x").nth(1).expect("second a_x");
20758        assert_eq!(second_x.values(), &[f(5.75), f(2.25)]);
20759        let right_a = suffixed.columns.get("a_y").expect("a_y");
20760        assert_eq!(right_a.values(), &[f(5.0), f(6.0)]);
20761
20762        // NEGATIVE: unique keys merge under their own names, unsuffixed.
20763        let plain = merge_dataframes_on_with_options(
20764            &right("q"),
20765            &right("z"),
20766            &["k"],
20767            &["k"],
20768            JoinType::Inner,
20769            MergeExecutionOptions::default(),
20770        )
20771        .expect("plain merge");
20772        assert_eq!(plain.column_order, vec!["k", "q", "z"]);
20773    }
20774
20775    #[test]
20776    fn merge_validate_one_to_one_names_both_sides_when_both_duplicate_z6jxh() {
20777        let left = DataFrame::from_dict(
20778            &["id", "left_v"],
20779            vec![
20780                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20781                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20782            ],
20783        )
20784        .expect("left frame");
20785        let right = DataFrame::from_dict(
20786            &["id", "right_v"],
20787            vec![
20788                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20789                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20790            ],
20791        )
20792        .expect("right frame");
20793
20794        let err = merge_dataframes_on_with_options(
20795            &left,
20796            &right,
20797            &["id"],
20798            &["id"],
20799            JoinType::Inner,
20800            MergeExecutionOptions {
20801                validate_mode: Some(MergeValidateMode::OneToOne),
20802                ..MergeExecutionOptions::default()
20803            },
20804        )
20805        .expect_err("one_to_one must reject keys repeated on both sides");
20806        // pandas 2.2.3: 'Merge keys are not unique in either left or right
20807        // dataset' - both sides named, not the left first (z6jxh).
20808        assert!(format!("{err}").contains("left and right keys are not unique"));
20809
20810        // The composite-key path (text keys) answers alike; NEGATIVE: with
20811        // only the right side repeating, only the right is named.
20812        let text_keys = |values: [&str; 2]| {
20813            DataFrame::from_dict(
20814                &["id"],
20815                vec![(
20816                    "id",
20817                    values.iter().map(|v| Scalar::Utf8((*v).into())).collect(),
20818                )],
20819            )
20820            .expect("text-keyed frame")
20821        };
20822        let validate = |left: &DataFrame, right: &DataFrame| {
20823            merge_dataframes_on_with_options(
20824                left,
20825                right,
20826                &["id"],
20827                &["id"],
20828                JoinType::Inner,
20829                MergeExecutionOptions {
20830                    validate_mode: Some(MergeValidateMode::OneToOne),
20831                    ..MergeExecutionOptions::default()
20832                },
20833            )
20834            .expect_err("one_to_one must reject a repeated key")
20835            .to_string()
20836        };
20837        let both = validate(&text_keys(["a", "a"]), &text_keys(["a", "a"]));
20838        assert!(
20839            both.contains("left and right keys are not unique"),
20840            "{both}"
20841        );
20842        let right_only = validate(&text_keys(["a", "b"]), &text_keys(["a", "a"]));
20843        assert!(
20844            right_only.contains(": right keys are not unique"),
20845            "{right_only}"
20846        );
20847    }
20848
20849    #[test]
20850    fn merge_validate_one_to_many_allows_duplicate_right_keys() {
20851        let left = DataFrame::from_dict(
20852            &["id", "left_v"],
20853            vec![
20854                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20855                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20856            ],
20857        )
20858        .expect("left frame");
20859        let right = DataFrame::from_dict(
20860            &["id", "right_v"],
20861            vec![
20862                (
20863                    "id",
20864                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
20865                ),
20866                (
20867                    "right_v",
20868                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(200)],
20869                ),
20870            ],
20871        )
20872        .expect("right frame");
20873
20874        let merged = merge_dataframes_on_with_options(
20875            &left,
20876            &right,
20877            &["id"],
20878            &["id"],
20879            JoinType::Inner,
20880            MergeExecutionOptions {
20881                validate_mode: Some(MergeValidateMode::OneToMany),
20882                ..MergeExecutionOptions::default()
20883            },
20884        )
20885        .expect("one_to_many should allow duplicate right keys");
20886        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
20887    }
20888
20889    #[test]
20890    fn merge_validate_one_to_many_rejects_duplicate_left_keys_9hsb3() {
20891        let left = DataFrame::from_dict(
20892            &["id", "left_v"],
20893            vec![
20894                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20895                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20896            ],
20897        )
20898        .expect("left frame");
20899        let right = DataFrame::from_dict(
20900            &["id", "right_v"],
20901            vec![
20902                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20903                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20904            ],
20905        )
20906        .expect("right frame");
20907
20908        let err = merge_dataframes_on_with_options(
20909            &left,
20910            &right,
20911            &["id"],
20912            &["id"],
20913            JoinType::Inner,
20914            MergeExecutionOptions {
20915                validate_mode: Some(MergeValidateMode::OneToMany),
20916                ..MergeExecutionOptions::default()
20917            },
20918        )
20919        .expect_err("one_to_many must reject duplicate left keys");
20920        assert!(format!("{err}").contains("left keys are not unique"));
20921    }
20922
20923    #[test]
20924    fn merge_validate_many_to_one_rejects_duplicate_right_keys() {
20925        let left = DataFrame::from_dict(
20926            &["id", "left_v"],
20927            vec![
20928                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20929                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20930            ],
20931        )
20932        .expect("left frame");
20933        let right = DataFrame::from_dict(
20934            &["id", "right_v"],
20935            vec![
20936                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
20937                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(101)]),
20938            ],
20939        )
20940        .expect("right frame");
20941
20942        let err = merge_dataframes_on_with_options(
20943            &left,
20944            &right,
20945            &["id"],
20946            &["id"],
20947            JoinType::Inner,
20948            MergeExecutionOptions {
20949                validate_mode: Some(MergeValidateMode::ManyToOne),
20950                ..MergeExecutionOptions::default()
20951            },
20952        )
20953        .expect_err("many_to_one must reject duplicate right keys");
20954        assert!(format!("{err}").contains("right keys are not unique"));
20955    }
20956
20957    #[test]
20958    fn merge_validate_many_to_one_allows_duplicate_left_keys_9hsb3() {
20959        let left = DataFrame::from_dict(
20960            &["id", "left_v"],
20961            vec![
20962                (
20963                    "id",
20964                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
20965                ),
20966                (
20967                    "left_v",
20968                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(20)],
20969                ),
20970            ],
20971        )
20972        .expect("left frame");
20973        let right = DataFrame::from_dict(
20974            &["id", "right_v"],
20975            vec![
20976                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20977                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20978            ],
20979        )
20980        .expect("right frame");
20981
20982        let merged = merge_dataframes_on_with_options(
20983            &left,
20984            &right,
20985            &["id"],
20986            &["id"],
20987            JoinType::Inner,
20988            MergeExecutionOptions {
20989                validate_mode: Some(MergeValidateMode::ManyToOne),
20990                ..MergeExecutionOptions::default()
20991            },
20992        )
20993        .expect("many_to_one should allow duplicate left keys");
20994        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
20995    }
20996
20997    #[test]
20998    fn merge_validate_many_to_many_allows_duplicates_on_both_sides() {
20999        let left = DataFrame::from_dict(
21000            &["id", "left_v"],
21001            vec![
21002                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
21003                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
21004            ],
21005        )
21006        .expect("left frame");
21007        let right = DataFrame::from_dict(
21008            &["id", "right_v"],
21009            vec![
21010                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
21011                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
21012            ],
21013        )
21014        .expect("right frame");
21015
21016        let merged = merge_dataframes_on_with_options(
21017            &left,
21018            &right,
21019            &["id"],
21020            &["id"],
21021            JoinType::Inner,
21022            MergeExecutionOptions {
21023                validate_mode: Some(MergeValidateMode::ManyToMany),
21024                ..MergeExecutionOptions::default()
21025            },
21026        )
21027        .expect("many_to_many should allow duplicate keys on both sides");
21028        assert_eq!(merged.columns.get("id").expect("id").values().len(), 4);
21029    }
21030
21031    #[test]
21032    fn join_series_cross_cartesian_product() {
21033        let left = Series::from_values(
21034            "left",
21035            vec!["a".into(), "b".into()],
21036            vec![Scalar::Int64(1), Scalar::Int64(2)],
21037        )
21038        .unwrap();
21039        let right = Series::from_values(
21040            "right",
21041            vec!["x".into(), "y".into()],
21042            vec![Scalar::Int64(10), Scalar::Int64(20)],
21043        )
21044        .unwrap();
21045
21046        let out = join_series(&left, &right, JoinType::Cross).unwrap();
21047        assert_eq!(out.index.labels().len(), 4);
21048        assert_eq!(
21049            out.left_values.values(),
21050            &[
21051                Scalar::Int64(1),
21052                Scalar::Int64(1),
21053                Scalar::Int64(2),
21054                Scalar::Int64(2)
21055            ]
21056        );
21057        assert_eq!(
21058            out.right_values.values(),
21059            &[
21060                Scalar::Int64(10),
21061                Scalar::Int64(20),
21062                Scalar::Int64(10),
21063                Scalar::Int64(20)
21064            ]
21065        );
21066    }
21067
21068    // ── DataFrameMergeExt trait tests ──
21069
21070    #[test]
21071    fn dataframe_merge_via_trait() {
21072        use fp_frame::DataFrame;
21073
21074        use super::{DataFrameMergeExt, merge_dataframes_on};
21075
21076        let left = DataFrame::from_series(vec![
21077            Series::from_values(
21078                "key",
21079                vec![0_i64.into(), 1_i64.into()],
21080                vec![Scalar::Int64(1), Scalar::Int64(2)],
21081            )
21082            .unwrap(),
21083            Series::from_values(
21084                "val_l",
21085                vec![0_i64.into(), 1_i64.into()],
21086                vec![Scalar::Int64(10), Scalar::Int64(20)],
21087            )
21088            .unwrap(),
21089        ])
21090        .unwrap();
21091
21092        let right = DataFrame::from_series(vec![
21093            Series::from_values(
21094                "key",
21095                vec![0_i64.into(), 1_i64.into()],
21096                vec![Scalar::Int64(1), Scalar::Int64(3)],
21097            )
21098            .unwrap(),
21099            Series::from_values(
21100                "val_r",
21101                vec![0_i64.into(), 1_i64.into()],
21102                vec![Scalar::Int64(100), Scalar::Int64(300)],
21103            )
21104            .unwrap(),
21105        ])
21106        .unwrap();
21107
21108        // Instance method
21109        let result = left.merge(&right, &["key"], JoinType::Inner).unwrap();
21110        assert_eq!(result.index.len(), 1); // only key=1 matches
21111
21112        // Standalone function should give same result
21113        let result2 = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner).unwrap();
21114        assert_eq!(result.index.len(), result2.index.len());
21115    }
21116
21117    // ── merge_asof tests ──
21118
21119    fn compute_asof_matches_datetime64_former_nsslz(
21120        left: super::Datetime64AsofKey<'_>,
21121        right: super::Datetime64AsofKey<'_>,
21122        direction: super::AsofDirection,
21123        allow_exact_matches: bool,
21124        tolerance: Option<f64>,
21125    ) -> Vec<Option<usize>> {
21126        let mut right_valid_values = Vec::new();
21127        let mut right_valid_positions = Vec::new();
21128        for i in 0..right.data.len() {
21129            if right.is_valid(i) {
21130                right_valid_values.push(right.data[i]);
21131                right_valid_positions.push(i);
21132            }
21133        }
21134        super::compute_asof_matches_datetime64_prepared(
21135            left,
21136            &right_valid_values,
21137            Some(&right_valid_positions),
21138            direction,
21139            allow_exact_matches,
21140            tolerance,
21141        )
21142    }
21143
21144    #[test]
21145    fn merge_asof_datetime64_borrowed_dense_right_matches_former_nsslz() {
21146        let dense_left = Column::from_datetime64_values_with_validity(
21147            vec![-15, -10, -5, 0, 5, 30, 35],
21148            ValidityMask::all_valid(7),
21149        );
21150        let dense_right = Column::from_datetime64_values_with_validity(
21151            vec![-10, 0, 10, 20, 30],
21152            ValidityMask::all_valid(5),
21153        );
21154
21155        let nat_right = Column::from_datetime64_values_with_validity(
21156            vec![fp_types::Timestamp::NAT, -10, 0, 20, 30],
21157            ValidityMask::all_valid(5),
21158        );
21159        let nat_left = Column::from_datetime64_values_with_validity(
21160            vec![fp_types::Timestamp::NAT, -10, -5, 0, 5, 30, 35],
21161            ValidityMask::all_valid(7),
21162        );
21163
21164        for (left, right) in [
21165            (&dense_left, &dense_right),
21166            (&dense_left, &nat_right),
21167            (&nat_left, &dense_right),
21168        ] {
21169            let left_key = super::datetime64_key_parts(left).expect("Datetime64 left key");
21170            let right_key = super::datetime64_key_parts(right).expect("Datetime64 right key");
21171            for direction in [
21172                super::AsofDirection::Backward,
21173                super::AsofDirection::Forward,
21174                super::AsofDirection::Nearest,
21175            ] {
21176                for allow_exact_matches in [false, true] {
21177                    for tolerance in [None, Some(7.0)] {
21178                        assert_eq!(
21179                            super::compute_asof_matches_datetime64(
21180                                left_key,
21181                                right_key,
21182                                direction,
21183                                allow_exact_matches,
21184                                tolerance,
21185                            ),
21186                            compute_asof_matches_datetime64_former_nsslz(
21187                                left_key,
21188                                right_key,
21189                                direction,
21190                                allow_exact_matches,
21191                                tolerance,
21192                            ),
21193                            "direction={direction:?} exact={allow_exact_matches} tolerance={tolerance:?}",
21194                        );
21195                    }
21196                }
21197            }
21198        }
21199    }
21200
21201    #[test]
21202    #[ignore = "foreground release A/B only"]
21203    fn datetime64_asof_borrowed_dense_right_ab_nsslz() {
21204        use std::{hint::black_box, time::Instant};
21205
21206        const ITEMS: usize = 131_072;
21207        const SAMPLES: usize = 10;
21208
21209        fn elapsed(run: impl FnOnce() -> Vec<Option<usize>>) -> u128 {
21210            let started = Instant::now();
21211            let output = black_box(run());
21212            black_box(output.len());
21213            let elapsed = started.elapsed().as_nanos();
21214            drop(output);
21215            elapsed
21216        }
21217
21218        let left = Column::from_datetime64_values_with_validity(
21219            (0..ITEMS).map(|i| i as i64 * 4 + 1).collect(),
21220            ValidityMask::all_valid(ITEMS),
21221        );
21222        let right = Column::from_datetime64_values_with_validity(
21223            (0..ITEMS).map(|i| i as i64 * 4).collect(),
21224            ValidityMask::all_valid(ITEMS),
21225        );
21226        let left_key = super::datetime64_key_parts(&left).expect("Datetime64 left key");
21227        let right_key = super::datetime64_key_parts(&right).expect("Datetime64 right key");
21228        let former = || {
21229            compute_asof_matches_datetime64_former_nsslz(
21230                left_key,
21231                right_key,
21232                super::AsofDirection::Backward,
21233                true,
21234                None,
21235            )
21236        };
21237        let candidate = || {
21238            super::compute_asof_matches_datetime64(
21239                left_key,
21240                right_key,
21241                super::AsofDirection::Backward,
21242                true,
21243                None,
21244            )
21245        };
21246
21247        assert_eq!(candidate(), former());
21248        black_box(former());
21249        black_box(candidate());
21250
21251        let mut former_ns = Vec::with_capacity(SAMPLES);
21252        let mut candidate_ns = Vec::with_capacity(SAMPLES);
21253        for sample in 0..SAMPLES {
21254            if sample.is_multiple_of(2) {
21255                former_ns.push(elapsed(former));
21256                candidate_ns.push(elapsed(candidate));
21257            } else {
21258                candidate_ns.push(elapsed(candidate));
21259                former_ns.push(elapsed(former));
21260            }
21261        }
21262        former_ns.sort_unstable();
21263        candidate_ns.sort_unstable();
21264        let former_p50 = former_ns[SAMPLES / 2];
21265        let candidate_p50 = candidate_ns[SAMPLES / 2];
21266        println!(
21267            "datetime64_asof_borrowed_dense_right_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}x",
21268            former_p50 as f64 / candidate_p50 as f64,
21269        );
21270        println!("former_samples_ns={former_ns:?}");
21271        println!("candidate_samples_ns={candidate_ns:?}");
21272    }
21273
21274    #[test]
21275    fn merge_asof_default_options_keep_exact_matches() {
21276        let left = fp_frame::DataFrame::from_dict(
21277            &["t"],
21278            vec![("t", vec![Scalar::Int64(1), Scalar::Int64(2)])],
21279        )
21280        .unwrap();
21281        let right = fp_frame::DataFrame::from_dict(
21282            &["t", "v"],
21283            vec![
21284                ("t", vec![Scalar::Int64(1), Scalar::Int64(2)]),
21285                ("v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
21286            ],
21287        )
21288        .unwrap();
21289        for options in [
21290            super::MergeAsofOptions::default(),
21291            super::MergeAsofOptions::new(),
21292        ] {
21293            let result = super::merge_asof_with_options(
21294                &left,
21295                &right,
21296                "t",
21297                super::AsofDirection::Backward,
21298                options,
21299            )
21300            .unwrap();
21301            assert_eq!(result.columns["v"].values(), &[10.into(), 20.into()]);
21302        }
21303        let result = super::merge_asof_with_options(
21304            &left,
21305            &right,
21306            "t",
21307            super::AsofDirection::Backward,
21308            super::MergeAsofOptions::default().allow_exact_matches(false),
21309        )
21310        .unwrap();
21311        assert!(result.columns["v"].values()[0].is_missing());
21312        assert_eq!(result.columns["v"].values()[1], Scalar::Float64(10.0));
21313    }
21314
21315    #[test]
21316    fn merge_asof_rejects_missing_ordering_keys_in_every_match_path() {
21317        let cases = [
21318            (
21319                DType::Int64,
21320                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
21321            ),
21322            (
21323                DType::Float64,
21324                vec![
21325                    Scalar::Float64(1.0),
21326                    Scalar::Float64(2.0),
21327                    Scalar::Float64(3.0),
21328                ],
21329            ),
21330            (
21331                DType::datetime64_naive(),
21332                vec![
21333                    Scalar::Datetime64(1),
21334                    Scalar::Datetime64(2),
21335                    Scalar::Datetime64(3),
21336                ],
21337            ),
21338            (
21339                DType::Timedelta64,
21340                vec![
21341                    Scalar::Timedelta64(1),
21342                    Scalar::Timedelta64(2),
21343                    Scalar::Timedelta64(3),
21344                ],
21345            ),
21346        ];
21347        for (dtype, values) in cases {
21348            let frame = |values: Vec<Scalar>| {
21349                let mut columns = ColumnStore::new();
21350                columns.insert("t".to_owned(), Column::new(dtype.clone(), values).unwrap());
21351                columns.insert("g".to_owned(), Column::from_i64_values(vec![1, 1, 1]));
21352                fp_frame::DataFrame::new_with_column_order(
21353                    Index::new_known_unique_int64_unit_range(0, 3),
21354                    columns,
21355                    vec!["t".to_owned(), "g".to_owned()],
21356                )
21357                .unwrap()
21358            };
21359            let clean = frame(values.clone());
21360            let mut missing = values;
21361            // The null diagnostic takes precedence over an earlier inversion.
21362            missing.swap(0, 1);
21363            missing[2] = Scalar::Null(NullKind::NaN);
21364            let invalid = frame(missing);
21365            for (side, left, right) in [("left", &invalid, &clean), ("right", &clean, &invalid)] {
21366                for by in [None, Some(vec!["g".to_owned()])] {
21367                    for direction in [
21368                        super::AsofDirection::Backward,
21369                        super::AsofDirection::Forward,
21370                        super::AsofDirection::Nearest,
21371                    ] {
21372                        let error = super::merge_asof_with_options(
21373                            left,
21374                            right,
21375                            "t",
21376                            direction,
21377                            super::MergeAsofOptions {
21378                                by: by.clone(),
21379                                ..Default::default()
21380                            },
21381                        )
21382                        .expect_err("missing ordering keys must fail before matching");
21383                        assert!(matches!(
21384                            error,
21385                            super::JoinError::Frame(
21386                                fp_frame::FrameError::CompatibilityRejected(message)
21387                            ) if message == format!("Merge keys contain null values on {side} side")
21388                        ));
21389                    }
21390                }
21391            }
21392        }
21393    }
21394
21395    #[test]
21396    fn merge_asof_group_keys_use_value_equality() {
21397        let left = fp_frame::DataFrame::from_dict(
21398            &["t", "g", "h"],
21399            vec![
21400                ("t", vec![2.into(), 4.into(), 6.into(), 8.into()]),
21401                (
21402                    "g",
21403                    vec![
21404                        Scalar::Float64(-0.0),
21405                        Scalar::Float64(0.0),
21406                        Scalar::Float64(1.0),
21407                        Scalar::Null(NullKind::NaN),
21408                    ],
21409                ),
21410                ("h", vec![Scalar::Utf8("x".to_owned()); 4]),
21411            ],
21412        )
21413        .unwrap();
21414        let right = fp_frame::DataFrame::from_dict(
21415            &["u", "g", "h", "v"],
21416            vec![
21417                ("u", vec![1.into(), 3.into(), 5.into(), 7.into()]),
21418                (
21419                    "g",
21420                    vec![
21421                        Scalar::Float64(0.0),
21422                        Scalar::Float64(-0.0),
21423                        Scalar::Float64(1.0),
21424                        Scalar::Null(NullKind::Null),
21425                    ],
21426                ),
21427                ("h", vec![Scalar::Utf8("x".to_owned()); 4]),
21428                ("v", vec![10.into(), 30.into(), 50.into(), 70.into()]),
21429            ],
21430        )
21431        .unwrap();
21432        for by in [vec!["g".to_owned()], vec!["g".to_owned(), "h".to_owned()]] {
21433            let result = super::merge_asof_on_with_options(
21434                &left,
21435                &right,
21436                "t",
21437                "u",
21438                super::AsofDirection::Backward,
21439                super::MergeAsofOptions::default().by(by),
21440            )
21441            .unwrap();
21442            assert_eq!(
21443                result.columns["v"].values(),
21444                &[10.into(), 30.into(), 50.into(), 70.into()]
21445            );
21446        }
21447    }
21448
21449    #[test]
21450    fn merge_asof_group_identity_is_independent_of_group_key_count() {
21451        use fp_types::{Interval, IntervalClosed, Period, PeriodFreq};
21452
21453        let period = |ordinal, freq| Scalar::Period(Period::new(ordinal, freq));
21454        let interval = |left, right, closed| Scalar::Interval(Interval::new(left, right, closed));
21455        let cases = [
21456            (
21457                "object booleans and integers",
21458                vec![
21459                    Scalar::Bool(true),
21460                    Scalar::Bool(false),
21461                    Scalar::Utf8("1".to_owned()),
21462                    Scalar::Int64(9_007_199_254_740_993),
21463                ],
21464                vec![
21465                    Scalar::Int64(1),
21466                    Scalar::Int64(0),
21467                    Scalar::Int64(1),
21468                    Scalar::Int64(9_007_199_254_740_992),
21469                ],
21470                [
21471                    [Some(0.0), Some(1.0), None, None],
21472                    [Some(0.0), Some(1.0), None, None],
21473                    [Some(0.0), Some(1.0), None, None],
21474                ],
21475            ),
21476            (
21477                "period frequency",
21478                vec![
21479                    period(0, PeriodFreq::Monthly),
21480                    period(0, PeriodFreq::Daily),
21481                    period(1, PeriodFreq::Monthly),
21482                    period(2, PeriodFreq::Monthly),
21483                ],
21484                vec![
21485                    period(0, PeriodFreq::Daily),
21486                    period(0, PeriodFreq::Monthly),
21487                    period(1, PeriodFreq::Monthly),
21488                    period(3, PeriodFreq::Monthly),
21489                ],
21490                [
21491                    [None, Some(0.0), Some(2.0), None],
21492                    [Some(1.0), None, Some(2.0), None],
21493                    [Some(1.0), Some(0.0), Some(2.0), None],
21494                ],
21495            ),
21496            (
21497                "interval endpoints and closedness",
21498                vec![
21499                    Scalar::Interval(
21500                        Interval::new(-0.0, 1.0, IntervalClosed::Right).with_int_endpoints(),
21501                    ),
21502                    interval(0.0, 1.0, IntervalClosed::Left),
21503                    interval(2.0, 3.0, IntervalClosed::Right),
21504                    interval(4.0, 5.0, IntervalClosed::Right),
21505                ],
21506                vec![
21507                    interval(0.0, 1.0, IntervalClosed::Left),
21508                    interval(0.0, 1.0, IntervalClosed::Right),
21509                    interval(2.0, 3.0, IntervalClosed::Right),
21510                    interval(4.0, 5.0, IntervalClosed::Left),
21511                ],
21512                [
21513                    [None, Some(0.0), Some(2.0), None],
21514                    [Some(1.0), None, Some(2.0), None],
21515                    [Some(1.0), Some(0.0), Some(2.0), None],
21516                ],
21517            ),
21518        ];
21519
21520        for (case, left_groups, right_groups, expected) in cases {
21521            for float_ordering in [false, true] {
21522                let frame = |groups: Vec<Scalar>, value_name: &str| {
21523                    let ordering = if float_ordering {
21524                        Column::from_f64_values(vec![1.0, 2.0, 3.0, 4.0])
21525                    } else {
21526                        Column::from_i64_values(vec![1, 2, 3, 4])
21527                    };
21528                    fp_frame::DataFrame::new_with_column_order(
21529                        Index::new_known_unique_int64_unit_range(0, 4),
21530                        ColumnStore::from_pairs([
21531                            ("t".to_owned(), ordering),
21532                            ("g".to_owned(), Column::from_object_values(groups)),
21533                            ("h".to_owned(), Column::from_i64_constant(7, 4)),
21534                            (
21535                                value_name.to_owned(),
21536                                Column::from_i64_values(vec![0, 1, 2, 3]),
21537                            ),
21538                        ]),
21539                        vec![
21540                            "t".to_owned(),
21541                            "g".to_owned(),
21542                            "h".to_owned(),
21543                            value_name.to_owned(),
21544                        ],
21545                    )
21546                    .unwrap()
21547                };
21548                let left = frame(left_groups.clone(), "left_row");
21549                let right = frame(right_groups.clone(), "right_row");
21550                // Exercise object equality without constructor coercion.
21551                assert_eq!(left.column("g").unwrap().values(), left_groups.as_slice());
21552                assert_eq!(right.column("g").unwrap().values(), right_groups.as_slice());
21553
21554                for (direction, expected_rows) in [
21555                    super::AsofDirection::Backward,
21556                    super::AsofDirection::Forward,
21557                    super::AsofDirection::Nearest,
21558                ]
21559                .into_iter()
21560                .zip(expected)
21561                {
21562                    // A constant second grouping key must not change matches.
21563                    // Each expected row is an original right-input position;
21564                    // the None entries are genuine nonmatching groups.
21565                    for by in [vec!["g".to_owned()], vec!["g".to_owned(), "h".to_owned()]] {
21566                        let result = super::merge_asof_with_options(
21567                            &left,
21568                            &right,
21569                            "t",
21570                            direction,
21571                            super::MergeAsofOptions::default().by(by.clone()),
21572                        )
21573                        .unwrap();
21574                        let actual: Vec<Option<f64>> = result.columns["right_row"]
21575                            .values()
21576                            .iter()
21577                            .map(|value| {
21578                                if value.is_missing() {
21579                                    None
21580                                } else {
21581                                    Some(value.to_f64().unwrap())
21582                                }
21583                            })
21584                            .collect();
21585                        assert_eq!(
21586                            actual.as_slice(),
21587                            expected_rows.as_slice(),
21588                            "{case}, float_ordering={float_ordering}, direction={direction:?}, by={by:?}"
21589                        );
21590                    }
21591                }
21592            }
21593        }
21594    }
21595
21596    #[test]
21597    fn merge_asof_rejects_group_and_numeric_width_mismatches() {
21598        let left = fp_frame::DataFrame::from_dict(
21599            &["t", "g"],
21600            vec![
21601                ("t", vec![1.into(), 2.into()]),
21602                ("g", vec![1.into(), 2.into()]),
21603            ],
21604        )
21605        .unwrap();
21606        let right = fp_frame::DataFrame::from_dict(
21607            &["u", "h"],
21608            vec![
21609                ("u", vec![1.into(), 2.into()]),
21610                ("h", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
21611            ],
21612        )
21613        .unwrap();
21614        let error = super::merge_asof_on_with_options(
21615            &left,
21616            &right,
21617            "t",
21618            "u",
21619            super::AsofDirection::Backward,
21620            super::MergeAsofOptions {
21621                left_by: Some(vec!["g".to_owned()]),
21622                right_by: Some(vec!["h".to_owned()]),
21623                ..Default::default()
21624            },
21625        )
21626        .expect_err("asof grouping keys must have matching dtypes");
21627        assert!(error.to_string().contains("incompatible merge keys"));
21628        let narrow = left
21629            .column("t")
21630            .unwrap()
21631            .cast_to_width(fp_types::NumericWidth::Int32, false)
21632            .unwrap();
21633        let right = right.with_column("u", narrow).unwrap();
21634        let error = super::merge_asof_on_with_options(
21635            &left,
21636            &right,
21637            "t",
21638            "u",
21639            super::AsofDirection::Backward,
21640            super::MergeAsofOptions::default(),
21641        )
21642        .expect_err("equal storage types must not hide a numeric width mismatch");
21643        assert!(error.to_string().contains("right dtype('int32')"));
21644    }
21645
21646    #[test]
21647    fn merge_asof_distinct_ordering_and_grouping_keys() {
21648        let left = fp_frame::DataFrame::from_dict(
21649            &["t", "symbol", "venue", "price"],
21650            vec![
21651                (
21652                    "t",
21653                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(5)],
21654                ),
21655                (
21656                    "symbol",
21657                    vec![
21658                        Scalar::Utf8("a".into()),
21659                        Scalar::Utf8("b".into()),
21660                        Scalar::Utf8("a".into()),
21661                    ],
21662                ),
21663                (
21664                    "venue",
21665                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
21666                ),
21667                (
21668                    "price",
21669                    vec![Scalar::Int64(7), Scalar::Int64(8), Scalar::Int64(9)],
21670                ),
21671            ],
21672        )
21673        .unwrap();
21674        let right = fp_frame::DataFrame::from_dict(
21675            &["u", "ticker", "venue", "price"],
21676            vec![
21677                (
21678                    "u",
21679                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
21680                ),
21681                (
21682                    "ticker",
21683                    vec![
21684                        Scalar::Utf8("a".into()),
21685                        Scalar::Utf8("b".into()),
21686                        Scalar::Utf8("a".into()),
21687                    ],
21688                ),
21689                (
21690                    "venue",
21691                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
21692                ),
21693                (
21694                    "price",
21695                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
21696                ),
21697            ],
21698        )
21699        .unwrap();
21700        let options = super::MergeAsofOptions {
21701            left_by: Some(vec!["symbol".to_owned(), "venue".to_owned()]),
21702            right_by: Some(vec!["ticker".to_owned(), "venue".to_owned()]),
21703            suffixes: Some([Some("_trade".to_owned()), Some("_quote".to_owned())]),
21704            ..super::MergeAsofOptions::new()
21705        };
21706        let result = super::merge_asof_on_with_options(
21707            &left,
21708            &right,
21709            "t",
21710            "u",
21711            super::AsofDirection::Backward,
21712            options,
21713        )
21714        .unwrap();
21715        assert_eq!(
21716            result.column_order,
21717            [
21718                "t",
21719                "symbol",
21720                "venue",
21721                "price_trade",
21722                "u",
21723                "ticker",
21724                "price_quote"
21725            ]
21726        );
21727        assert_eq!(
21728            result.columns["u"].values(),
21729            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)]
21730        );
21731        assert_eq!(
21732            result.columns["price_quote"].values(),
21733            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
21734        );
21735    }
21736
21737    #[test]
21738    fn merge_asof_exact_integer_keys_do_not_round_or_treat_min_as_nat() {
21739        for base in [1_i64 << 53, i64::MIN] {
21740            let left = fp_frame::DataFrame::from_dict(
21741                &["t", "g"],
21742                vec![
21743                    ("t", vec![Scalar::Int64(base), Scalar::Int64(base + 3)]),
21744                    ("g", vec![Scalar::Int64(1), Scalar::Int64(1)]),
21745                ],
21746            )
21747            .unwrap();
21748            let right = fp_frame::DataFrame::from_dict(
21749                &["u", "g", "v"],
21750                vec![
21751                    ("u", vec![Scalar::Int64(base + 1), Scalar::Int64(base + 4)]),
21752                    ("g", vec![Scalar::Int64(1), Scalar::Int64(1)]),
21753                    ("v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
21754                ],
21755            )
21756            .unwrap();
21757            for by in [None, Some(vec!["g".to_owned()])] {
21758                let options = super::MergeAsofOptions {
21759                    by,
21760                    ..super::MergeAsofOptions::new()
21761                };
21762                let result = super::merge_asof_on_with_options(
21763                    &left,
21764                    &right,
21765                    "t",
21766                    "u",
21767                    super::AsofDirection::Backward,
21768                    options,
21769                )
21770                .unwrap();
21771                assert!(result.columns["v"].values()[0].is_missing());
21772                assert_eq!(result.columns["v"].values()[1], Scalar::Float64(10.0));
21773            }
21774        }
21775    }
21776
21777    #[test]
21778    fn merge_asof_grouped_datetimes_span_years_without_losing_nanoseconds() {
21779        let frame = |key: &str, times: Vec<i64>| {
21780            let mut columns = ColumnStore::new();
21781            columns.insert(
21782                key.to_owned(),
21783                Column::from_temporal_nanos(DType::datetime64_naive(), times),
21784            );
21785            columns.insert("g".to_owned(), Column::from_i64_values(vec![1, 1]));
21786            columns.insert("v".to_owned(), Column::from_i64_values(vec![10, 20]));
21787            fp_frame::DataFrame::new_with_column_order(
21788                Index::new_known_unique_int64_unit_range(0, 2),
21789                columns,
21790                vec![key.to_owned(), "g".to_owned(), "v".to_owned()],
21791            )
21792            .unwrap()
21793        };
21794        let left = frame("t", vec![1, 100_000_000_000_000_001]);
21795        let right = frame("u", vec![2, 100_000_000_000_000_002]);
21796        let result = super::merge_asof_on_with_options(
21797            &left,
21798            &right,
21799            "t",
21800            "u",
21801            super::AsofDirection::Backward,
21802            super::MergeAsofOptions::new().by(vec!["g".to_owned()]),
21803        )
21804        .unwrap();
21805        assert!(result.columns["v_y"].values()[0].is_missing());
21806        assert_eq!(result.columns["v_y"].values()[1], Scalar::Float64(10.0));
21807    }
21808
21809    #[test]
21810    fn merge_asof_rejects_incomplete_or_conflicting_group_key_options() {
21811        let frame = fp_frame::DataFrame::from_dict(
21812            &["t", "g"],
21813            vec![("t", vec![Scalar::Int64(1)]), ("g", vec![Scalar::Int64(1)])],
21814        )
21815        .unwrap();
21816        for options in [
21817            super::MergeAsofOptions {
21818                left_by: Some(vec!["g".to_owned()]),
21819                ..super::MergeAsofOptions::new()
21820            },
21821            super::MergeAsofOptions {
21822                left_by: Some(vec!["g".to_owned()]),
21823                right_by: Some(vec![]),
21824                ..super::MergeAsofOptions::new()
21825            },
21826            super::MergeAsofOptions {
21827                by: Some(vec!["g".to_owned()]),
21828                right_by: Some(vec!["g".to_owned()]),
21829                ..super::MergeAsofOptions::new()
21830            },
21831        ] {
21832            assert!(
21833                super::merge_asof_with_options(
21834                    &frame,
21835                    &frame,
21836                    "t",
21837                    super::AsofDirection::Backward,
21838                    options
21839                )
21840                .is_err()
21841            );
21842        }
21843    }
21844
21845    #[test]
21846    fn merge_asof_gather_preserves_float32_with_and_without_unmatched_rows() {
21847        let left = fp_frame::DataFrame::from_dict(
21848            &["t"],
21849            vec![("t", vec![Scalar::Int64(1), Scalar::Int64(3)])],
21850        )
21851        .unwrap();
21852        let right = fp_frame::DataFrame::from_dict(
21853            &["u", "v"],
21854            vec![
21855                ("u", vec![Scalar::Int64(2), Scalar::Int64(4)]),
21856                ("v", vec![Scalar::Float64(1.25), Scalar::Float64(2.5)]),
21857            ],
21858        )
21859        .unwrap();
21860        let source = right
21861            .column("v")
21862            .unwrap()
21863            .cast_to_width(fp_types::NumericWidth::Float32, false)
21864            .unwrap();
21865        let right = right.with_column("v", source).unwrap();
21866        for direction in [
21867            super::AsofDirection::Backward,
21868            super::AsofDirection::Forward,
21869        ] {
21870            let merged = super::merge_asof_on_with_options(
21871                &left,
21872                &right,
21873                "t",
21874                "u",
21875                direction,
21876                super::MergeAsofOptions::new(),
21877            )
21878            .unwrap();
21879            let result = &merged.columns["v"];
21880            assert_eq!(result.dtype(), DType::Float64);
21881            assert_eq!(result.width(), Some(fp_types::NumericWidth::Float32));
21882            if direction == super::AsofDirection::Backward {
21883                assert!(result.values()[0].is_missing());
21884                assert_eq!(result.values()[1], Scalar::Float64(1.25));
21885            } else {
21886                assert_eq!(
21887                    result.values(),
21888                    &[Scalar::Float64(1.25), Scalar::Float64(2.5)]
21889                );
21890            }
21891        }
21892    }
21893
21894    #[test]
21895    fn merge_asof_backward() {
21896        use super::DataFrameMergeExt;
21897
21898        // Left: trades at times 1, 3, 5, 7
21899        let left = fp_frame::DataFrame::from_dict(
21900            &["time", "price"],
21901            vec![
21902                (
21903                    "time",
21904                    vec![
21905                        Scalar::Int64(1),
21906                        Scalar::Int64(3),
21907                        Scalar::Int64(5),
21908                        Scalar::Int64(7),
21909                    ],
21910                ),
21911                (
21912                    "price",
21913                    vec![
21914                        Scalar::Float64(100.0),
21915                        Scalar::Float64(101.0),
21916                        Scalar::Float64(102.0),
21917                        Scalar::Float64(103.0),
21918                    ],
21919                ),
21920            ],
21921        )
21922        .unwrap();
21923
21924        // Right: quotes at times 2, 4, 6
21925        let right = fp_frame::DataFrame::from_dict(
21926            &["time", "bid"],
21927            vec![
21928                (
21929                    "time",
21930                    vec![Scalar::Int64(2), Scalar::Int64(4), Scalar::Int64(6)],
21931                ),
21932                (
21933                    "bid",
21934                    vec![
21935                        Scalar::Float64(99.5),
21936                        Scalar::Float64(100.5),
21937                        Scalar::Float64(101.5),
21938                    ],
21939                ),
21940            ],
21941        )
21942        .unwrap();
21943
21944        let result = left.merge_asof(&right, "time", "backward").unwrap();
21945        // For time=1: no right row <= 1, so bid=NaN
21946        // For time=3: last right row <= 3 is time=2 → bid=99.5
21947        // For time=5: last right row <= 5 is time=4 → bid=100.5
21948        // For time=7: last right row <= 7 is time=6 → bid=101.5
21949        let bid_col = result.columns.get("bid").unwrap();
21950        assert!(bid_col.values()[0].is_missing());
21951        assert_eq!(bid_col.values()[1], Scalar::Float64(99.5));
21952        assert_eq!(bid_col.values()[2], Scalar::Float64(100.5));
21953        assert_eq!(bid_col.values()[3], Scalar::Float64(101.5));
21954    }
21955
21956    /// A right column that gains an UNMATCHED row gains a gap, and an all-valid
21957    /// numpy int64 cannot hold one — pandas widens that column to float64,
21958    /// exactly as it does across the join family.
21959    ///
21960    /// Measured, live pandas 2.2.3:
21961    /// ```text
21962    ///   L = DataFrame({'time':[1,5,10], 'left_val':[10,50,100]})
21963    ///   R = DataFrame({'time':[2,6],    'right_val':[20,60]})
21964    ///   pd.merge_asof(L, R, on='time', direction='forward')
21965    ///     right_val -> [20.0, 60.0, NaN]  dtype float64
21966    ///     dtypes: time int64, left_val int64, right_val float64
21967    ///
21968    ///   L2 = DataFrame({'time':[1,5]}, ...); R2 = DataFrame({'time':[2,4]}, ...)
21969    ///   pd.merge_asof(L2, R2, on='time', direction='backward')
21970    ///     right_val -> [NaN, 40.0]        dtype float64
21971    ///
21972    ///   with every left row matched (times 3,7 against 2,4)
21973    ///     right_val -> [20, 40]           dtype int64
21974    /// ```
21975    /// The rule is PER COLUMN here — `time` and `left_val` gain no gap and stay
21976    /// int64 — unlike `Series.unstack`, where a gap widens the whole frame
21977    /// because it reshapes one block. Both fixtures on FP-P2D-056 pinned the
21978    /// present values as int64 beside the NaN, which is FrankenPandas' own
21979    /// pre-fix answer.
21980    #[test]
21981    fn merge_asof_unmatched_row_widens_that_column_to_float64() {
21982        use super::DataFrameMergeExt;
21983
21984        let int_frame = |name: &str, times: Vec<i64>, vals: Vec<i64>| {
21985            fp_frame::DataFrame::from_dict(
21986                &["time", name],
21987                vec![
21988                    (
21989                        "time",
21990                        times.into_iter().map(Scalar::Int64).collect::<Vec<_>>(),
21991                    ),
21992                    (
21993                        name,
21994                        vals.into_iter().map(Scalar::Int64).collect::<Vec<_>>(),
21995                    ),
21996                ],
21997            )
21998            .unwrap()
21999        };
22000
22001        let left = int_frame("left_val", vec![1, 5, 10], vec![10, 50, 100]);
22002        let right = int_frame("right_val", vec![2, 6], vec![20, 60]);
22003        let forward = left.merge_asof(&right, "time", "forward").unwrap();
22004        assert_eq!(
22005            forward.columns.get("right_val").unwrap().values(),
22006            &[
22007                Scalar::Float64(20.0),
22008                Scalar::Float64(60.0),
22009                Scalar::Null(NullKind::NaN),
22010            ]
22011        );
22012        // The columns that gain NO gap keep int64 — this is per column, not
22013        // frame-wide.
22014        assert_eq!(
22015            forward.columns.get("left_val").unwrap().values(),
22016            &[Scalar::Int64(10), Scalar::Int64(50), Scalar::Int64(100)]
22017        );
22018        assert_eq!(
22019            forward.columns.get("time").unwrap().dtype(),
22020            fp_types::DType::Int64
22021        );
22022
22023        let backward = int_frame("left_val", vec![1, 5], vec![10, 50])
22024            .merge_asof(
22025                &int_frame("right_val", vec![2, 4], vec![20, 40]),
22026                "time",
22027                "backward",
22028            )
22029            .unwrap();
22030        assert_eq!(
22031            backward.columns.get("right_val").unwrap().values(),
22032            &[Scalar::Null(NullKind::NaN), Scalar::Float64(40.0)]
22033        );
22034
22035        // The control that this is about the GAP and not about merge_asof always
22036        // widening: with every left row matched, right_val stays int64.
22037        let matched = int_frame("left_val", vec![3, 7], vec![10, 50])
22038            .merge_asof(
22039                &int_frame("right_val", vec![2, 4], vec![20, 40]),
22040                "time",
22041                "backward",
22042            )
22043            .unwrap();
22044        assert_eq!(
22045            matched.columns.get("right_val").unwrap().values(),
22046            &[Scalar::Int64(20), Scalar::Int64(40)]
22047        );
22048    }
22049
22050    #[test]
22051    fn merge_asof_forward() {
22052        use super::AsofDirection;
22053
22054        let left = fp_frame::DataFrame::from_dict(
22055            &["time", "val"],
22056            vec![
22057                ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
22058                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(30.0)]),
22059            ],
22060        )
22061        .unwrap();
22062
22063        let right = fp_frame::DataFrame::from_dict(
22064            &["time", "quote"],
22065            vec![
22066                ("time", vec![Scalar::Int64(2), Scalar::Int64(5)]),
22067                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(50.0)]),
22068            ],
22069        )
22070        .unwrap();
22071
22072        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
22073        // time=1: first right >= 1 is time=2 → quote=20
22074        // time=3: first right >= 3 is time=5 → quote=50
22075        let quote_col = result.columns.get("quote").unwrap();
22076        assert_eq!(quote_col.values()[0], Scalar::Float64(20.0));
22077        assert_eq!(quote_col.values()[1], Scalar::Float64(50.0));
22078    }
22079
22080    #[test]
22081    fn merge_asof_nearest() {
22082        use super::AsofDirection;
22083
22084        let left = fp_frame::DataFrame::from_dict(
22085            &["time", "val"],
22086            vec![
22087                ("time", vec![Scalar::Int64(3), Scalar::Int64(7)]),
22088                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
22089            ],
22090        )
22091        .unwrap();
22092
22093        let right = fp_frame::DataFrame::from_dict(
22094            &["time", "ref_val"],
22095            vec![
22096                (
22097                    "time",
22098                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
22099                ),
22100                (
22101                    "ref_val",
22102                    vec![
22103                        Scalar::Float64(100.0),
22104                        Scalar::Float64(500.0),
22105                        Scalar::Float64(1000.0),
22106                    ],
22107                ),
22108            ],
22109        )
22110        .unwrap();
22111
22112        let result = super::merge_asof(&left, &right, "time", AsofDirection::Nearest).unwrap();
22113        // time=3: nearest is 1(dist=2) or 5(dist=2), first found = 1 → ref_val=100
22114        // Actually: for nearest, it finds the one with smallest dist. dist(3,1)=2, dist(3,5)=2
22115        // ties go to first found, so ref_val = 100
22116        // time=7: nearest is 5(dist=2) or 10(dist=3) → ref_val=500
22117        let ref_col = result.columns.get("ref_val").unwrap();
22118        assert_eq!(ref_col.values()[1], Scalar::Float64(500.0)); // time=7 → 5 is nearest
22119    }
22120
22121    #[test]
22122    fn merge_asof_nearest_excludes_exact_finds_neighbor() {
22123        // Regression: with direction=nearest and allow_exact_matches=false,
22124        // an exact-equal key must be skipped over to reach the nearest
22125        // non-equal key, rather than yielding no match. Verified against
22126        // pandas 2.2.3: merge_asof(left=5, right=[3,5,5], nearest,
22127        // allow_exact_matches=False) -> matches value 3.
22128        use super::{AsofDirection, MergeAsofOptions};
22129
22130        let left = fp_frame::DataFrame::from_dict(
22131            &["time", "val"],
22132            vec![
22133                ("time", vec![Scalar::Int64(5)]),
22134                ("val", vec![Scalar::Int64(1)]),
22135            ],
22136        )
22137        .unwrap();
22138        let right = fp_frame::DataFrame::from_dict(
22139            &["time", "ref_val"],
22140            vec![
22141                (
22142                    "time",
22143                    vec![Scalar::Int64(3), Scalar::Int64(5), Scalar::Int64(5)],
22144                ),
22145                (
22146                    "ref_val",
22147                    vec![
22148                        Scalar::Float64(10.0),
22149                        Scalar::Float64(20.0),
22150                        Scalar::Float64(30.0),
22151                    ],
22152                ),
22153            ],
22154        )
22155        .unwrap();
22156
22157        let opts = MergeAsofOptions::new().allow_exact_matches(false);
22158        let result =
22159            super::merge_asof_with_options(&left, &right, "time", AsofDirection::Nearest, opts)
22160                .unwrap();
22161        let ref_col = result.columns.get("ref_val").unwrap();
22162        assert_eq!(ref_col.values()[0], Scalar::Float64(10.0)); // value 3 is nearest non-exact
22163    }
22164
22165    #[test]
22166    fn merge_asof_exact_match() {
22167        use super::AsofDirection;
22168
22169        let left = fp_frame::DataFrame::from_dict(
22170            &["time", "val"],
22171            vec![
22172                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
22173                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
22174            ],
22175        )
22176        .unwrap();
22177
22178        let right = fp_frame::DataFrame::from_dict(
22179            &["time", "quote"],
22180            vec![
22181                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
22182                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(40.0)]),
22183            ],
22184        )
22185        .unwrap();
22186
22187        // Backward: exact match should work (right_val <= left_val includes ==).
22188        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
22189        assert_eq!(
22190            result.columns.get("quote").unwrap().values()[0],
22191            Scalar::Float64(20.0)
22192        );
22193        assert_eq!(
22194            result.columns.get("quote").unwrap().values()[1],
22195            Scalar::Float64(40.0)
22196        );
22197
22198        // Forward: exact match should work (right_val >= left_val includes ==).
22199        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
22200        assert_eq!(
22201            result.columns.get("quote").unwrap().values()[0],
22202            Scalar::Float64(20.0)
22203        );
22204    }
22205
22206    #[test]
22207    fn merge_asof_datetime64_wide_ns_range_uses_i64_path() {
22208        use super::AsofDirection;
22209
22210        let day_ns = 86_400_000_000_000i64;
22211        let base = 1_600_000_000_000_000_000i64;
22212        let dt = |days: i64| Scalar::Datetime64(base + days * day_ns);
22213
22214        let left = fp_frame::DataFrame::from_dict(
22215            &["time", "val"],
22216            vec![
22217                ("time", vec![dt(0), dt(200), dt(400)]),
22218                (
22219                    "val",
22220                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
22221                ),
22222            ],
22223        )
22224        .unwrap();
22225
22226        let right = fp_frame::DataFrame::from_dict(
22227            &["time", "quote"],
22228            vec![
22229                ("time", vec![dt(-1), dt(199), dt(401)]),
22230                (
22231                    "quote",
22232                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
22233                ),
22234            ],
22235        )
22236        .unwrap();
22237
22238        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
22239        let quote_col = result.columns.get("quote").unwrap();
22240        assert_eq!(quote_col.values()[0], Scalar::Int64(10));
22241        assert_eq!(quote_col.values()[1], Scalar::Int64(20));
22242        assert_eq!(quote_col.values()[2], Scalar::Int64(20));
22243    }
22244
22245    #[test]
22246    fn merge_asof_no_matches_backward() {
22247        use super::AsofDirection;
22248
22249        let left = fp_frame::DataFrame::from_dict(
22250            &["time", "val"],
22251            vec![
22252                ("time", vec![Scalar::Int64(1)]),
22253                ("val", vec![Scalar::Float64(10.0)]),
22254            ],
22255        )
22256        .unwrap();
22257
22258        // Right starts at time=5, so backward from time=1 finds nothing.
22259        let right = fp_frame::DataFrame::from_dict(
22260            &["time", "quote"],
22261            vec![
22262                ("time", vec![Scalar::Int64(5)]),
22263                ("quote", vec![Scalar::Float64(50.0)]),
22264            ],
22265        )
22266        .unwrap();
22267
22268        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
22269        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
22270    }
22271
22272    #[test]
22273    fn merge_asof_no_matches_forward() {
22274        use super::AsofDirection;
22275
22276        let left = fp_frame::DataFrame::from_dict(
22277            &["time", "val"],
22278            vec![
22279                ("time", vec![Scalar::Int64(10)]),
22280                ("val", vec![Scalar::Float64(10.0)]),
22281            ],
22282        )
22283        .unwrap();
22284
22285        // Right ends at time=5, so forward from time=10 finds nothing.
22286        let right = fp_frame::DataFrame::from_dict(
22287            &["time", "quote"],
22288            vec![
22289                ("time", vec![Scalar::Int64(5)]),
22290                ("quote", vec![Scalar::Float64(50.0)]),
22291            ],
22292        )
22293        .unwrap();
22294
22295        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
22296        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
22297    }
22298
22299    #[test]
22300    fn merge_asof_nan_in_key() {
22301        use super::AsofDirection;
22302
22303        let left = fp_frame::DataFrame::from_dict(
22304            &["time", "val"],
22305            vec![
22306                (
22307                    "time",
22308                    vec![
22309                        Scalar::Int64(1),
22310                        Scalar::Null(NullKind::NaN),
22311                        Scalar::Int64(5),
22312                    ],
22313                ),
22314                (
22315                    "val",
22316                    vec![
22317                        Scalar::Float64(10.0),
22318                        Scalar::Float64(20.0),
22319                        Scalar::Float64(30.0),
22320                    ],
22321                ),
22322            ],
22323        )
22324        .unwrap();
22325
22326        let right = fp_frame::DataFrame::from_dict(
22327            &["time", "quote"],
22328            vec![
22329                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
22330                (
22331                    "quote",
22332                    vec![Scalar::Float64(200.0), Scalar::Float64(400.0)],
22333                ),
22334            ],
22335        )
22336        .unwrap();
22337
22338        // pandas 2.2.3 rejects missing ordering keys even when dtypes agree.
22339        let error = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
22340            .expect_err("missing left ordering keys must be rejected");
22341        assert!(matches!(
22342            error,
22343            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
22344                if message == "Merge keys contain null values on left side"
22345        ));
22346    }
22347
22348    #[test]
22349    fn merge_asof_rejects_incompatible_key_dtypes_sopel() {
22350        use super::{AsofDirection, MergeAsofOptions};
22351
22352        // pandas 2.2.3: a NaN makes the left `time` column float64, and
22353        // `merge_asof` refuses it against an int64 right key rather than
22354        // coercing both to a common numeric lane.
22355        let left = fp_frame::DataFrame::from_dict(
22356            &["time", "left_val", "group"],
22357            vec![
22358                (
22359                    "time",
22360                    vec![
22361                        Scalar::Float64(1.0),
22362                        Scalar::Null(NullKind::NaN),
22363                        Scalar::Float64(4.0),
22364                    ],
22365                ),
22366                (
22367                    "left_val",
22368                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
22369                ),
22370                (
22371                    "group",
22372                    vec![
22373                        Scalar::Utf8("a".into()),
22374                        Scalar::Utf8("a".into()),
22375                        Scalar::Utf8("a".into()),
22376                    ],
22377                ),
22378            ],
22379        )
22380        .unwrap();
22381        let right = fp_frame::DataFrame::from_dict(
22382            &["time", "right_val", "group"],
22383            vec![
22384                ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
22385                ("right_val", vec![Scalar::Int64(100), Scalar::Int64(300)]),
22386                (
22387                    "group",
22388                    vec![Scalar::Utf8("a".into()), Scalar::Utf8("a".into())],
22389                ),
22390            ],
22391        )
22392        .unwrap();
22393
22394        for options in [
22395            MergeAsofOptions::new(),
22396            MergeAsofOptions::new().by(vec!["group".to_owned()]),
22397        ] {
22398            let error = super::merge_asof_with_options(
22399                &left,
22400                &right,
22401                "time",
22402                AsofDirection::Backward,
22403                options,
22404            )
22405            .expect_err("mixed float64/int64 asof keys must be rejected");
22406            assert!(matches!(
22407                error,
22408                super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
22409                    if message.contains("incompatible merge keys")
22410                        && message.contains("float64")
22411                        && message.contains("int64")
22412            ));
22413        }
22414
22415        // This is the fixture-shaped representation: the null marker makes
22416        // the left lane nullable Int64, while the all-valid right lane stays
22417        // numpy int64. pandas rejects that pair as incompatible too.
22418        let mut nullable_columns = ColumnStore::new();
22419        nullable_columns.insert(
22420            "time".to_owned(),
22421            Column::new(
22422                DType::Int64Nullable,
22423                vec![
22424                    Scalar::Int64(1),
22425                    Scalar::Null(NullKind::NaN),
22426                    Scalar::Int64(4),
22427                ],
22428            )
22429            .unwrap(),
22430        );
22431        nullable_columns.insert(
22432            "left_val".to_owned(),
22433            Column::from_i64_values(vec![10, 20, 30]),
22434        );
22435        let nullable_left = fp_frame::DataFrame::new_with_column_order(
22436            Index::new_known_unique_int64_unit_range(0, 3),
22437            nullable_columns,
22438            vec!["time".to_owned(), "left_val".to_owned()],
22439        )
22440        .unwrap();
22441        let error = super::merge_asof(&nullable_left, &right, "time", AsofDirection::Backward)
22442            .expect_err("nullable Int64 and int64 asof keys must be rejected");
22443        assert!(matches!(
22444            error,
22445            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
22446                if message.contains("incompatible merge keys")
22447                    && message.contains("left dtype('Int64')")
22448                    && message.contains("right dtype('int64')")
22449        ));
22450    }
22451
22452    #[test]
22453    fn merge_asof_nan_in_right_key() {
22454        use super::AsofDirection;
22455
22456        // A missing ordering key also invalidates the right input; it must
22457        // not be skipped while matching the remaining candidates.
22458        let left = fp_frame::DataFrame::from_dict(
22459            &["time", "val"],
22460            vec![
22461                (
22462                    "time",
22463                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(5)],
22464                ),
22465                (
22466                    "val",
22467                    vec![
22468                        Scalar::Float64(10.0),
22469                        Scalar::Float64(20.0),
22470                        Scalar::Float64(30.0),
22471                    ],
22472                ),
22473            ],
22474        )
22475        .unwrap();
22476
22477        let right = fp_frame::DataFrame::from_dict(
22478            &["time", "quote"],
22479            vec![
22480                (
22481                    "time",
22482                    vec![
22483                        Scalar::Int64(2),
22484                        Scalar::Null(NullKind::NaN),
22485                        Scalar::Int64(4),
22486                    ],
22487                ),
22488                (
22489                    "quote",
22490                    vec![
22491                        Scalar::Float64(200.0),
22492                        Scalar::Float64(999.0),
22493                        Scalar::Float64(400.0),
22494                    ],
22495                ),
22496            ],
22497        )
22498        .unwrap();
22499
22500        let error = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
22501            .expect_err("missing right ordering keys must be rejected");
22502        assert!(matches!(
22503            error,
22504            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
22505                if message == "Merge keys contain null values on right side"
22506        ));
22507    }
22508
22509    #[test]
22510    fn merge_asof_overlapping_columns_apply_suffixes() {
22511        use super::AsofDirection;
22512
22513        let left = fp_frame::DataFrame::from_dict(
22514            &["time", "shared", "left_only"],
22515            vec![
22516                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
22517                ("shared", vec![Scalar::Int64(10), Scalar::Int64(20)]),
22518                ("left_only", vec![Scalar::Int64(1), Scalar::Int64(2)]),
22519            ],
22520        )
22521        .unwrap();
22522
22523        let right = fp_frame::DataFrame::from_dict(
22524            &["time", "shared", "right_only"],
22525            vec![
22526                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
22527                ("shared", vec![Scalar::Int64(100), Scalar::Int64(200)]),
22528                ("right_only", vec![Scalar::Int64(9), Scalar::Int64(8)]),
22529            ],
22530        )
22531        .unwrap();
22532
22533        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
22534        let shared_left = result.columns.get("shared_x").unwrap().values();
22535        let shared_right = result.columns.get("shared_y").unwrap().values();
22536
22537        assert_eq!(shared_left[0], Scalar::Int64(10));
22538        assert_eq!(shared_left[1], Scalar::Int64(20));
22539        assert_eq!(shared_right[0], Scalar::Int64(100));
22540        assert_eq!(shared_right[1], Scalar::Int64(200));
22541    }
22542
22543    #[test]
22544    fn merge_asof_duplicate_column_gets_suffix() {
22545        use super::AsofDirection;
22546
22547        // Both left and right have a "val" column besides the key.
22548        let left = fp_frame::DataFrame::from_dict(
22549            &["time", "val"],
22550            vec![
22551                ("time", vec![Scalar::Int64(1)]),
22552                ("val", vec![Scalar::Float64(10.0)]),
22553            ],
22554        )
22555        .unwrap();
22556
22557        let right = fp_frame::DataFrame::from_dict(
22558            &["time", "val"],
22559            vec![
22560                ("time", vec![Scalar::Int64(1)]),
22561                ("val", vec![Scalar::Float64(99.0)]),
22562            ],
22563        )
22564        .unwrap();
22565
22566        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
22567        // Overlapping columns should receive default merge suffixes.
22568        assert!(result.columns.contains_key("val_x"));
22569        assert!(result.columns.contains_key("val_y"));
22570        assert_eq!(
22571            result.columns.get("val_x").unwrap().values()[0],
22572            Scalar::Float64(10.0)
22573        );
22574        assert_eq!(
22575            result.columns.get("val_y").unwrap().values()[0],
22576            Scalar::Float64(99.0)
22577        );
22578    }
22579
22580    #[test]
22581    fn merge_asof_missing_column_errors() {
22582        use super::AsofDirection;
22583
22584        let left =
22585            fp_frame::DataFrame::from_dict(&["a"], vec![("a", vec![Scalar::Int64(1)])]).unwrap();
22586
22587        let right =
22588            fp_frame::DataFrame::from_dict(&["b"], vec![("b", vec![Scalar::Int64(1)])]).unwrap();
22589
22590        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward);
22591        assert!(err.is_err());
22592    }
22593
22594    #[test]
22595    fn merge_asof_invalid_direction_errors() {
22596        let left =
22597            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
22598                .unwrap();
22599        let right =
22600            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
22601                .unwrap();
22602
22603        let err = left.merge_asof(&right, "time", "sideways");
22604        assert!(matches!(
22605            err,
22606            Err(super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg)))
22607                if msg.contains("invalid direction")
22608        ));
22609    }
22610
22611    #[test]
22612    fn merge_asof_unsorted_left_errors() {
22613        use super::AsofDirection;
22614
22615        let left = fp_frame::DataFrame::from_dict(
22616            &["time", "val"],
22617            vec![
22618                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
22619                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
22620            ],
22621        )
22622        .unwrap();
22623
22624        let right = fp_frame::DataFrame::from_dict(
22625            &["time", "quote"],
22626            vec![
22627                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
22628                (
22629                    "quote",
22630                    vec![Scalar::Float64(100.0), Scalar::Float64(200.0)],
22631                ),
22632            ],
22633        )
22634        .unwrap();
22635
22636        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
22637            .expect_err("unsorted left should error");
22638        assert!(matches!(
22639            err,
22640            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
22641                if msg.contains("sorted")
22642        ));
22643    }
22644
22645    #[test]
22646    fn merge_asof_unsorted_right_errors() {
22647        use super::AsofDirection;
22648
22649        let left = fp_frame::DataFrame::from_dict(
22650            &["time", "val"],
22651            vec![
22652                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
22653                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
22654            ],
22655        )
22656        .unwrap();
22657
22658        let right = fp_frame::DataFrame::from_dict(
22659            &["time", "quote"],
22660            vec![
22661                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
22662                (
22663                    "quote",
22664                    vec![Scalar::Float64(200.0), Scalar::Float64(100.0)],
22665                ),
22666            ],
22667        )
22668        .unwrap();
22669
22670        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
22671            .expect_err("unsorted right should error");
22672        assert!(matches!(
22673            err,
22674            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
22675                if msg.contains("sorted")
22676        ));
22677    }
22678
22679    #[test]
22680    fn merge_asof_non_numeric_key_errors() {
22681        use super::AsofDirection;
22682
22683        let left = fp_frame::DataFrame::from_dict(
22684            &["time", "val"],
22685            vec![
22686                ("time", vec![Scalar::Utf8("a".into())]),
22687                ("val", vec![Scalar::Float64(10.0)]),
22688            ],
22689        )
22690        .unwrap();
22691
22692        let right = fp_frame::DataFrame::from_dict(
22693            &["time", "quote"],
22694            vec![
22695                ("time", vec![Scalar::Utf8("b".into())]),
22696                ("quote", vec![Scalar::Float64(20.0)]),
22697            ],
22698        )
22699        .unwrap();
22700
22701        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
22702            .expect_err("non-numeric key should error");
22703        assert!(matches!(
22704            err,
22705            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
22706                if msg.contains("numeric")
22707        ));
22708    }
22709
22710    #[test]
22711    fn merge_asof_preserves_all_left_rows() {
22712        use super::AsofDirection;
22713
22714        let left = fp_frame::DataFrame::from_dict(
22715            &["time", "val"],
22716            vec![
22717                (
22718                    "time",
22719                    vec![
22720                        Scalar::Int64(1),
22721                        Scalar::Int64(2),
22722                        Scalar::Int64(3),
22723                        Scalar::Int64(4),
22724                        Scalar::Int64(5),
22725                    ],
22726                ),
22727                (
22728                    "val",
22729                    vec![
22730                        Scalar::Float64(10.0),
22731                        Scalar::Float64(20.0),
22732                        Scalar::Float64(30.0),
22733                        Scalar::Float64(40.0),
22734                        Scalar::Float64(50.0),
22735                    ],
22736                ),
22737            ],
22738        )
22739        .unwrap();
22740
22741        let right = fp_frame::DataFrame::from_dict(
22742            &["time", "quote"],
22743            vec![
22744                ("time", vec![Scalar::Int64(3)]),
22745                ("quote", vec![Scalar::Float64(300.0)]),
22746            ],
22747        )
22748        .unwrap();
22749
22750        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
22751        // All 5 left rows should be present.
22752        assert_eq!(result.index.len(), 5);
22753    }
22754
22755    // ── merge_asof options tests ──
22756
22757    #[test]
22758    fn merge_asof_allow_exact_matches_false_backward() {
22759        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
22760
22761        // Left: keys 1, 2, 3
22762        let left = fp_frame::DataFrame::from_dict(
22763            &["time", "val"],
22764            vec![
22765                (
22766                    "time",
22767                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
22768                ),
22769                (
22770                    "val",
22771                    vec![
22772                        Scalar::Float64(10.0),
22773                        Scalar::Float64(20.0),
22774                        Scalar::Float64(30.0),
22775                    ],
22776                ),
22777            ],
22778        )
22779        .unwrap();
22780
22781        // Right: keys 1, 2, 3 (exact matches exist)
22782        let right = fp_frame::DataFrame::from_dict(
22783            &["time", "quote"],
22784            vec![
22785                (
22786                    "time",
22787                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
22788                ),
22789                (
22790                    "quote",
22791                    vec![
22792                        Scalar::Float64(100.0),
22793                        Scalar::Float64(200.0),
22794                        Scalar::Float64(300.0),
22795                    ],
22796                ),
22797            ],
22798        )
22799        .unwrap();
22800
22801        // With allow_exact_matches=true (default), all should match
22802        let result_with_exact = merge_asof_with_options(
22803            &left,
22804            &right,
22805            "time",
22806            AsofDirection::Backward,
22807            MergeAsofOptions::new(),
22808        )
22809        .unwrap();
22810
22811        let quote_col = result_with_exact.columns.get("quote").unwrap();
22812        assert_eq!(quote_col.values()[0], Scalar::Float64(100.0)); // 1 matches 1
22813        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0)); // 2 matches 2
22814        assert_eq!(quote_col.values()[2], Scalar::Float64(300.0)); // 3 matches 3
22815
22816        // With allow_exact_matches=false, exact matches should be excluded
22817        let result_no_exact = merge_asof_with_options(
22818            &left,
22819            &right,
22820            "time",
22821            AsofDirection::Backward,
22822            MergeAsofOptions::new().allow_exact_matches(false),
22823        )
22824        .unwrap();
22825
22826        let quote_col_no_exact = result_no_exact.columns.get("quote").unwrap();
22827        // 1 has no previous right key, should be null
22828        assert!(matches!(quote_col_no_exact.values()[0], Scalar::Null(_)));
22829        // 2 should match previous (1)
22830        assert_eq!(quote_col_no_exact.values()[1], Scalar::Float64(100.0));
22831        // 3 should match previous (2)
22832        assert_eq!(quote_col_no_exact.values()[2], Scalar::Float64(200.0));
22833    }
22834
22835    #[test]
22836    fn merge_asof_tolerance() {
22837        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
22838
22839        // Left: keys 1, 5, 10
22840        let left = fp_frame::DataFrame::from_dict(
22841            &["time", "val"],
22842            vec![
22843                (
22844                    "time",
22845                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
22846                ),
22847                (
22848                    "val",
22849                    vec![
22850                        Scalar::Float64(10.0),
22851                        Scalar::Float64(50.0),
22852                        Scalar::Float64(100.0),
22853                    ],
22854                ),
22855            ],
22856        )
22857        .unwrap();
22858
22859        // Right: keys 2, 6
22860        let right = fp_frame::DataFrame::from_dict(
22861            &["time", "quote"],
22862            vec![
22863                ("time", vec![Scalar::Int64(2), Scalar::Int64(6)]),
22864                (
22865                    "quote",
22866                    vec![Scalar::Float64(200.0), Scalar::Float64(600.0)],
22867                ),
22868            ],
22869        )
22870        .unwrap();
22871
22872        // With tolerance=2, matches within 2 units are valid
22873        let result = merge_asof_with_options(
22874            &left,
22875            &right,
22876            "time",
22877            AsofDirection::Backward,
22878            MergeAsofOptions::new().tolerance(2.0),
22879        )
22880        .unwrap();
22881
22882        let quote_col = result.columns.get("quote").unwrap();
22883        // 1 < 2, no previous match, null
22884        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
22885        // 5 finds 2 (diff = 3), but tolerance is 2, so null
22886        assert!(matches!(quote_col.values()[1], Scalar::Null(_)));
22887        // 10 finds 6 (diff = 4), but tolerance is 2, so null
22888        assert!(matches!(quote_col.values()[2], Scalar::Null(_)));
22889
22890        // With tolerance=5, all should match
22891        let result_wider = merge_asof_with_options(
22892            &left,
22893            &right,
22894            "time",
22895            AsofDirection::Backward,
22896            MergeAsofOptions::new().tolerance(5.0),
22897        )
22898        .unwrap();
22899
22900        let quote_col_wider = result_wider.columns.get("quote").unwrap();
22901        // 1 < 2, still no previous
22902        assert!(matches!(quote_col_wider.values()[0], Scalar::Null(_)));
22903        // 5 finds 2 (diff = 3 <= 5)
22904        assert_eq!(quote_col_wider.values()[1], Scalar::Float64(200.0));
22905        // 10 finds 6 (diff = 4 <= 5)
22906        assert_eq!(quote_col_wider.values()[2], Scalar::Float64(600.0));
22907    }
22908
22909    #[test]
22910    fn merge_asof_by_column() {
22911        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
22912
22913        // Left: two groups (A and B), each with times
22914        let left = fp_frame::DataFrame::from_dict(
22915            &["group", "time", "val"],
22916            vec![
22917                (
22918                    "group",
22919                    vec![
22920                        Scalar::Utf8("A".into()),
22921                        Scalar::Utf8("A".into()),
22922                        Scalar::Utf8("B".into()),
22923                        Scalar::Utf8("B".into()),
22924                    ],
22925                ),
22926                (
22927                    "time",
22928                    vec![
22929                        Scalar::Int64(1),
22930                        Scalar::Int64(2),
22931                        Scalar::Int64(3),
22932                        Scalar::Int64(4),
22933                    ],
22934                ),
22935                (
22936                    "val",
22937                    vec![
22938                        Scalar::Float64(10.0),
22939                        Scalar::Float64(30.0),
22940                        Scalar::Float64(20.0),
22941                        Scalar::Float64(40.0),
22942                    ],
22943                ),
22944            ],
22945        )
22946        .unwrap();
22947
22948        // Right: same groups with quotes
22949        let right = fp_frame::DataFrame::from_dict(
22950            &["group", "time", "quote"],
22951            vec![
22952                (
22953                    "group",
22954                    vec![
22955                        Scalar::Utf8("A".into()),
22956                        Scalar::Utf8("B".into()),
22957                        Scalar::Utf8("A".into()),
22958                    ],
22959                ),
22960                (
22961                    "time",
22962                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
22963                ),
22964                (
22965                    "quote",
22966                    vec![
22967                        Scalar::Float64(200.0),
22968                        Scalar::Float64(400.0),
22969                        Scalar::Float64(300.0),
22970                    ],
22971                ),
22972            ],
22973        )
22974        .unwrap();
22975
22976        // Merge with 'by' column
22977        let result = merge_asof_with_options(
22978            &left,
22979            &right,
22980            "time",
22981            AsofDirection::Backward,
22982            MergeAsofOptions::new().by(vec!["group".to_string()]),
22983        )
22984        .unwrap();
22985
22986        let quote_col = result.columns.get("quote").unwrap();
22987        // Left after 2d3338b1's reorder is (A,1), (A,2), (B,3), (B,4) — globally
22988        // sorted by time. Right is (A,2), (B,3), (A,4). Backward grouped asof:
22989        // Row 0: (A,1) → no right A with time <= 1 → null
22990        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
22991        // Row 1: (A,2) → right A time=2 → 200.0
22992        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0));
22993        // Row 2: (B,3) → right B time=3 → 400.0
22994        assert_eq!(quote_col.values()[2], Scalar::Float64(400.0));
22995        // Row 3: (B,4) → right B time=3 (latest <= 4) → 400.0
22996        assert_eq!(quote_col.values()[3], Scalar::Float64(400.0));
22997    }
22998
22999    #[test]
23000    fn merge_asof_by_column_requires_globally_sorted_left_keys() {
23001        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
23002
23003        let left = fp_frame::DataFrame::from_dict(
23004            &["group", "time"],
23005            vec![
23006                (
23007                    "group",
23008                    vec![
23009                        Scalar::Utf8("A".into()),
23010                        Scalar::Utf8("A".into()),
23011                        Scalar::Utf8("B".into()),
23012                        Scalar::Utf8("B".into()),
23013                    ],
23014                ),
23015                (
23016                    "time",
23017                    vec![
23018                        Scalar::Int64(1),
23019                        Scalar::Int64(3),
23020                        Scalar::Int64(1),
23021                        Scalar::Int64(2),
23022                    ],
23023                ),
23024            ],
23025        )
23026        .unwrap();
23027        let right = fp_frame::DataFrame::from_dict(
23028            &["group", "time", "quote"],
23029            vec![
23030                (
23031                    "group",
23032                    vec![
23033                        Scalar::Utf8("A".into()),
23034                        Scalar::Utf8("B".into()),
23035                        Scalar::Utf8("A".into()),
23036                    ],
23037                ),
23038                (
23039                    "time",
23040                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
23041                ),
23042                (
23043                    "quote",
23044                    vec![
23045                        Scalar::Float64(10.0),
23046                        Scalar::Float64(20.0),
23047                        Scalar::Float64(30.0),
23048                    ],
23049                ),
23050            ],
23051        )
23052        .unwrap();
23053
23054        let err = merge_asof_with_options(
23055            &left,
23056            &right,
23057            "time",
23058            AsofDirection::Backward,
23059            MergeAsofOptions::new().by(vec!["group".to_string()]),
23060        )
23061        .expect_err("pandas requires globally sorted left keys even with by=");
23062        assert!(matches!(
23063            err,
23064            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
23065                if message.contains("left") && message.contains("sorted")
23066        ));
23067    }
23068
23069    #[test]
23070    fn merge_asof_by_column_requires_globally_sorted_right_keys() {
23071        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
23072
23073        let left = fp_frame::DataFrame::from_dict(
23074            &["group", "time"],
23075            vec![
23076                (
23077                    "group",
23078                    vec![
23079                        Scalar::Utf8("A".into()),
23080                        Scalar::Utf8("B".into()),
23081                        Scalar::Utf8("A".into()),
23082                    ],
23083                ),
23084                (
23085                    "time",
23086                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
23087                ),
23088            ],
23089        )
23090        .unwrap();
23091        let right = fp_frame::DataFrame::from_dict(
23092            &["group", "time", "quote"],
23093            vec![
23094                (
23095                    "group",
23096                    vec![
23097                        Scalar::Utf8("A".into()),
23098                        Scalar::Utf8("A".into()),
23099                        Scalar::Utf8("B".into()),
23100                    ],
23101                ),
23102                (
23103                    "time",
23104                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(2)],
23105                ),
23106                (
23107                    "quote",
23108                    vec![
23109                        Scalar::Float64(10.0),
23110                        Scalar::Float64(30.0),
23111                        Scalar::Float64(20.0),
23112                    ],
23113                ),
23114            ],
23115        )
23116        .unwrap();
23117
23118        let err = merge_asof_with_options(
23119            &left,
23120            &right,
23121            "time",
23122            AsofDirection::Backward,
23123            MergeAsofOptions::new().by(vec!["group".to_string()]),
23124        )
23125        .expect_err("pandas requires globally sorted right keys even with by=");
23126        assert!(matches!(
23127            err,
23128            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
23129                if message.contains("right") && message.contains("sorted")
23130        ));
23131    }
23132
23133    #[test]
23134    fn merge_ordered_sorts_and_ffills_values() {
23135        let left = fp_frame::DataFrame::from_dict(
23136            &["date", "left_val"],
23137            vec![
23138                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
23139                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
23140            ],
23141        )
23142        .unwrap();
23143
23144        let right = fp_frame::DataFrame::from_dict(
23145            &["date", "right_val"],
23146            vec![
23147                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
23148                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
23149            ],
23150        )
23151        .unwrap();
23152
23153        let result = super::merge_ordered(&left, &right, &["date"], Some("ffill")).unwrap();
23154        let frame = fp_frame::DataFrame::new(result.index, result.columns).unwrap();
23155
23156        assert_eq!(
23157            frame.column("date").unwrap().values(),
23158            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
23159        );
23160        // TEST-CHANGE (hayfo): left_val is int64, as live pandas 2.2.3's
23161        // (it asserted the float64 the value fill left behind).
23162        assert_eq!(
23163            frame.column("left_val").unwrap().values(),
23164            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(30)]
23165        );
23166        // NEGATIVE: a leading gap stays NaN, so the column stays float64.
23167        assert_eq!(
23168            frame.column("right_val").unwrap().values(),
23169            &[
23170                Scalar::Null(NullKind::NaN),
23171                Scalar::Float64(200.0),
23172                Scalar::Float64(300.0),
23173            ]
23174        );
23175    }
23176
23177    /// A filled bool column stays bool, a suffixed overlap its side's int64
23178    /// (live pandas 2.2.3: v bool, s_x int64, s_y float64).
23179    #[test]
23180    fn merge_ordered_ffill_keeps_each_sides_dtype() {
23181        let left = fp_frame::DataFrame::from_dict(
23182            &["k", "v", "s"],
23183            vec![
23184                ("k", vec![Scalar::Int64(1), Scalar::Int64(3)]),
23185                ("v", vec![Scalar::Bool(true), Scalar::Bool(false)]),
23186                ("s", vec![Scalar::Int64(1), Scalar::Int64(2)]),
23187            ],
23188        )
23189        .unwrap();
23190        let right = fp_frame::DataFrame::from_dict(
23191            &["k", "s"],
23192            vec![
23193                ("k", vec![Scalar::Int64(2), Scalar::Int64(3)]),
23194                ("s", vec![Scalar::Int64(5), Scalar::Int64(6)]),
23195            ],
23196        )
23197        .unwrap();
23198        let result = super::merge_ordered(&left, &right, &["k"], Some("ffill")).unwrap();
23199        let frame = fp_frame::DataFrame::new(result.index, result.columns).unwrap();
23200        assert_eq!(
23201            frame.column("v").unwrap().values(),
23202            &[Scalar::Bool(true), Scalar::Bool(true), Scalar::Bool(false)]
23203        );
23204        assert_eq!(
23205            frame.column("s_x").unwrap().values(),
23206            &[Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)]
23207        );
23208        assert_eq!(frame.column("s_y").unwrap().dtype(), DType::Float64);
23209    }
23210
23211    #[test]
23212    fn merge_ordered_ffill_preserves_missing_source_cells() {
23213        let left = fp_frame::DataFrame::from_dict(
23214            &["k", "value", "row"],
23215            vec![
23216                ("k", vec![1.into(), 3.into(), 5.into()]),
23217                (
23218                    "value",
23219                    vec![
23220                        Scalar::Float64(1.0),
23221                        Scalar::Null(NullKind::NaN),
23222                        Scalar::Float64(3.0),
23223                    ],
23224                ),
23225                ("row", vec![10.into(), 30.into(), 50.into()]),
23226            ],
23227        )
23228        .unwrap();
23229        let right =
23230            fp_frame::DataFrame::from_dict(&["k"], vec![("k", vec![2.into(), 4.into(), 6.into()])])
23231                .unwrap();
23232        let merged = super::merge_ordered(&left, &right, &["k"], Some("ffill")).unwrap();
23233        assert_eq!(
23234            merged.columns["k"].values(),
23235            &[1.into(), 2.into(), 3.into(), 4.into(), 5.into(), 6.into()],
23236        );
23237        let values = merged.columns["value"].values();
23238        assert_eq!(values[0], Scalar::Float64(1.0));
23239        assert_eq!(values[1], Scalar::Float64(1.0));
23240        assert!(values[2].is_missing());
23241        assert!(values[3].is_missing());
23242        assert_eq!(values[4], Scalar::Float64(3.0));
23243        assert_eq!(values[5], Scalar::Float64(3.0));
23244        assert_eq!(
23245            merged.columns["row"].values(),
23246            &[
23247                10.into(),
23248                10.into(),
23249                30.into(),
23250                30.into(),
23251                50.into(),
23252                50.into()
23253            ],
23254        );
23255    }
23256
23257    #[test]
23258    fn merge_ordered_separate_keys_and_join_directions() {
23259        let left = fp_frame::DataFrame::from_dict(
23260            &["a", "value"],
23261            vec![
23262                ("a", vec![3.into(), 1.into()]),
23263                ("value", vec![30.into(), 10.into()]),
23264            ],
23265        )
23266        .unwrap();
23267        let right = fp_frame::DataFrame::from_dict(
23268            &["b", "value"],
23269            vec![
23270                ("b", vec![2.into(), 3.into()]),
23271                ("value", vec![20.into(), 300.into()]),
23272            ],
23273        )
23274        .unwrap();
23275        for (how, rows) in [
23276            (JoinType::Outer, 3),
23277            (JoinType::Left, 2),
23278            (JoinType::Right, 2),
23279            (JoinType::Inner, 1),
23280        ] {
23281            let result = super::merge_ordered_with_options(
23282                &left,
23283                &right,
23284                &["a"],
23285                &["b"],
23286                how,
23287                Some("ffill"),
23288                super::MergeExecutionOptions {
23289                    suffixes: Some([Some("_left".to_owned()), Some("_right".to_owned())]),
23290                    ..Default::default()
23291                },
23292            )
23293            .unwrap();
23294            assert_eq!(result.index.len(), rows);
23295            assert_eq!(result.column_order, ["a", "value_left", "b", "value_right"]);
23296            if how == JoinType::Outer {
23297                assert_eq!(
23298                    result.columns["a"].values(),
23299                    &[1.into(), 1.into(), 3.into()]
23300                );
23301                assert_eq!(result.columns["value_left"].dtype(), DType::Int64);
23302                assert!(result.columns["b"].values()[0].is_missing());
23303                assert_eq!(result.columns["b"].values()[1], Scalar::Float64(2.0));
23304            }
23305        }
23306    }
23307
23308    #[test]
23309    fn merge_ordered_suffixes_distinct_key_overlapping_right_payload() {
23310        let left = fp_frame::DataFrame::from_dict(
23311            &["lk", "rk"],
23312            vec![
23313                ("lk", vec![1.into(), 3.into()]),
23314                ("rk", vec![100.into(), 200.into()]),
23315            ],
23316        )
23317        .unwrap();
23318        let right = fp_frame::DataFrame::from_dict(
23319            &["lk", "rk"],
23320            vec![
23321                ("lk", vec![90.into(), 91.into()]),
23322                ("rk", vec![2.into(), 3.into()]),
23323            ],
23324        )
23325        .unwrap();
23326        let result = super::merge_ordered_with_options(
23327            &left,
23328            &right,
23329            &["lk"],
23330            &["rk"],
23331            JoinType::Outer,
23332            None,
23333            super::MergeExecutionOptions::default(),
23334        )
23335        .unwrap();
23336        assert_eq!(result.column_order, ["lk_x", "rk_x", "lk_y", "rk_y"]);
23337        assert_eq!(result.columns["lk_x"].values()[0], Scalar::Float64(1.0));
23338        assert!(result.columns["lk_x"].values()[1].is_missing());
23339        assert_eq!(result.columns["lk_y"].values()[1], Scalar::Float64(90.0));
23340        assert_eq!(result.columns["rk_y"].values()[1], Scalar::Float64(2.0));
23341    }
23342
23343    #[test]
23344    fn merge_ordered_grouped_ffill_is_local_and_preserves_source_nulls_u6p7i() {
23345        let left = fp_frame::DataFrame::from_dict(
23346            &["g", "t", "value"],
23347            vec![
23348                (
23349                    "g",
23350                    vec![
23351                        Scalar::Utf8("b".to_owned()),
23352                        Scalar::Utf8("a".to_owned()),
23353                        Scalar::Utf8("b".to_owned()),
23354                    ],
23355                ),
23356                ("t", vec![3.into(), 1.into(), 1.into()]),
23357                (
23358                    "value",
23359                    vec![
23360                        Scalar::Float64(30.0),
23361                        Scalar::Null(NullKind::NaN),
23362                        Scalar::Float64(10.0),
23363                    ],
23364                ),
23365            ],
23366        )
23367        .unwrap();
23368        let right = fp_frame::DataFrame::from_dict(
23369            &["t", "other"],
23370            vec![
23371                ("t", vec![2.into(), 4.into()]),
23372                ("other", vec![200.into(), 400.into()]),
23373            ],
23374        )
23375        .unwrap();
23376        let result = super::merge_ordered_grouped_with_options(
23377            &left,
23378            &right,
23379            &["t"],
23380            &["t"],
23381            JoinType::Outer,
23382            Some("ffill"),
23383            &super::MergeOrderedGroupBy::Left(vec!["g".to_owned()]),
23384            super::MergeExecutionOptions::default(),
23385        )
23386        .unwrap();
23387        assert_eq!(result.column_order, ["g", "t", "value", "other"]);
23388        assert_eq!(
23389            result.columns["t"].values(),
23390            &[
23391                1.into(),
23392                2.into(),
23393                3.into(),
23394                4.into(),
23395                1.into(),
23396                2.into(),
23397                4.into()
23398            ]
23399        );
23400        assert_eq!(
23401            result.columns["g"]
23402                .values()
23403                .iter()
23404                .map(Scalar::as_str)
23405                .collect::<Vec<_>>(),
23406            vec![
23407                Some("b"),
23408                Some("b"),
23409                Some("b"),
23410                Some("b"),
23411                Some("a"),
23412                Some("a"),
23413                Some("a")
23414            ]
23415        );
23416        let values = result.columns["value"].values();
23417        assert_eq!(
23418            &values[..4],
23419            &[
23420                Scalar::Float64(10.0),
23421                Scalar::Float64(10.0),
23422                Scalar::Float64(30.0),
23423                Scalar::Float64(30.0),
23424            ]
23425        );
23426        assert!(values[4..].iter().all(Scalar::is_missing));
23427        let other = result.columns["other"].values();
23428        assert!(other[0].is_missing());
23429        assert!(
23430            other[4].is_missing(),
23431            "forward fill must restart for group a"
23432        );
23433        assert_eq!(other[1], Scalar::Float64(200.0));
23434        assert_eq!(other[2], Scalar::Float64(200.0));
23435        assert_eq!(other[3], Scalar::Float64(400.0));
23436        assert_eq!(other[5], Scalar::Float64(200.0));
23437        assert_eq!(other[6], Scalar::Float64(400.0));
23438        assert_eq!(result.columns["value"].dtype(), DType::Float64);
23439        assert_eq!(result.columns["other"].dtype(), DType::Float64);
23440    }
23441
23442    #[test]
23443    fn merge_ordered_grouped_unmatched_first_keeps_source_order_u6p7i() {
23444        let left = fp_frame::DataFrame::from_dict(
23445            &["g", "t", "v"],
23446            vec![
23447                (
23448                    "g",
23449                    vec![
23450                        Scalar::Utf8("z".to_owned()),
23451                        Scalar::Utf8("a".to_owned()),
23452                        Scalar::Utf8("z".to_owned()),
23453                    ],
23454                ),
23455                ("t", vec![5.into(), 1.into(), 3.into()]),
23456                ("v", vec![50.into(), 10.into(), 30.into()]),
23457            ],
23458        )
23459        .unwrap();
23460        let right = fp_frame::DataFrame::from_dict(
23461            &["g", "t", "w"],
23462            vec![
23463                (
23464                    "g",
23465                    vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("b".to_owned())],
23466                ),
23467                ("t", vec![2.into(), 4.into()]),
23468                ("w", vec![20.into(), 40.into()]),
23469            ],
23470        )
23471        .unwrap();
23472        let result = super::merge_ordered_grouped_with_options(
23473            &left,
23474            &right,
23475            &["t"],
23476            &["t"],
23477            JoinType::Inner,
23478            Some("ffill"),
23479            &super::MergeOrderedGroupBy::Left(vec!["g".to_owned()]),
23480            super::MergeExecutionOptions::default(),
23481        )
23482        .unwrap();
23483        // pandas preserves an unmatched group even for an inner merge.
23484        // Its unsuffixed columns define the schema of the whole result.
23485        assert_eq!(result.column_order, ["g", "t", "v", "w"]);
23486        assert_eq!(result.columns["t"].values(), &[5.into(), 3.into()]);
23487        assert_eq!(result.columns["v"].values(), &[50.into(), 30.into()]);
23488        assert!(
23489            result.columns["g"]
23490                .values()
23491                .iter()
23492                .all(|value| value.as_str() == Some("z"))
23493        );
23494        assert!(result.columns["w"].values().iter().all(Scalar::is_missing));
23495        assert_eq!(result.columns["w"].dtype(), DType::Float64);
23496    }
23497
23498    #[test]
23499    fn merge_ordered_right_groups_match_composite_keys_u6p7i() {
23500        let left = fp_frame::DataFrame::from_dict(
23501            &["g", "h", "lk", "v"],
23502            vec![
23503                (
23504                    "g",
23505                    vec![Scalar::Utf8("x".to_owned()), Scalar::Utf8("x".to_owned())],
23506                ),
23507                ("h", vec![1.into(), 2.into()]),
23508                ("lk", vec![2.into(), 4.into()]),
23509                ("v", vec![20.into(), 40.into()]),
23510            ],
23511        )
23512        .unwrap();
23513        let right = fp_frame::DataFrame::from_dict(
23514            &["g", "h", "rk", "v"],
23515            vec![
23516                (
23517                    "g",
23518                    vec![Scalar::Utf8("x".to_owned()), Scalar::Utf8("x".to_owned())],
23519                ),
23520                ("h", vec![2.into(), 1.into()]),
23521                ("rk", vec![3.into(), 1.into()]),
23522                ("v", vec![300.into(), 100.into()]),
23523            ],
23524        )
23525        .unwrap();
23526        let result = super::merge_ordered_grouped_with_options(
23527            &left,
23528            &right,
23529            &["lk"],
23530            &["rk"],
23531            JoinType::Outer,
23532            Some("ffill"),
23533            &super::MergeOrderedGroupBy::Right(vec!["g".to_owned(), "h".to_owned()]),
23534            super::MergeExecutionOptions {
23535                suffixes: Some([Some("_l".to_owned()), Some("_r".to_owned())]),
23536                ..Default::default()
23537            },
23538        )
23539        .unwrap();
23540        assert_eq!(
23541            result.column_order,
23542            [
23543                "g_l", "h_l", "lk", "v_l", "g_r", "h_r", "rk", "v_r", "g", "h"
23544            ]
23545        );
23546        assert_eq!(
23547            result.columns["h"].values(),
23548            &[2.into(), 2.into(), 1.into(), 1.into()]
23549        );
23550        assert_eq!(
23551            result.columns["rk"].values(),
23552            &[3.into(), 3.into(), 1.into(), 1.into()]
23553        );
23554        assert_eq!(
23555            result.columns["v_r"].values(),
23556            &[300.into(), 300.into(), 100.into(), 100.into()]
23557        );
23558        let left_values = result.columns["v_l"].values();
23559        assert!(left_values[0].is_missing());
23560        assert_eq!(left_values[1], Scalar::Float64(40.0));
23561        assert!(left_values[2].is_missing());
23562        assert_eq!(left_values[3], Scalar::Float64(20.0));
23563        assert_eq!(result.columns["h"].dtype(), DType::Int64);
23564        assert_eq!(result.columns["v_r"].dtype(), DType::Int64);
23565    }
23566
23567    #[test]
23568    fn merge_ordered_grouped_empty_inner_keeps_schema_and_dtypes_u6p7i() {
23569        let left = fp_frame::DataFrame::from_dict(
23570            &["g", "t", "v"],
23571            vec![
23572                (
23573                    "g",
23574                    vec![Scalar::Utf8("b".to_owned()), Scalar::Utf8("a".to_owned())],
23575                ),
23576                ("t", vec![1.into(), 3.into()]),
23577                ("v", vec![10.into(), 30.into()]),
23578            ],
23579        )
23580        .unwrap();
23581        let right = fp_frame::DataFrame::from_dict(
23582            &["t", "w"],
23583            vec![
23584                ("t", vec![2.into(), 4.into()]),
23585                ("w", vec![20.into(), 40.into()]),
23586            ],
23587        )
23588        .unwrap();
23589        let result = super::merge_ordered_grouped_with_options(
23590            &left,
23591            &right,
23592            &["t"],
23593            &["t"],
23594            JoinType::Inner,
23595            None,
23596            &super::MergeOrderedGroupBy::Left(vec!["g".to_owned()]),
23597            super::MergeExecutionOptions::default(),
23598        )
23599        .unwrap();
23600        assert!(result.index.is_empty());
23601        assert_eq!(result.column_order, ["g", "t", "v", "w"]);
23602        assert_eq!(result.columns["g"].dtype(), DType::Utf8);
23603        for name in ["t", "v", "w"] {
23604            assert_eq!(result.columns[name].dtype(), DType::Int64);
23605            assert!(result.columns[name].is_empty());
23606        }
23607    }
23608
23609    #[test]
23610    fn merge_ordered_grouped_visits_unused_categories_after_observed_u6p7i() {
23611        let left = fp_frame::DataFrame::from_dict(
23612            &["g", "t", "v"],
23613            vec![
23614                (
23615                    "g",
23616                    vec![Scalar::Utf8("b".to_owned()), Scalar::Utf8("a".to_owned())],
23617                ),
23618                ("t", vec![1.into(), 2.into()]),
23619                ("v", vec![10.into(), 20.into()]),
23620            ],
23621        )
23622        .unwrap()
23623        .with_column(
23624            "g",
23625            Column::from_categorical_codes(
23626                vec![1, 0],
23627                fp_types::CategoricalMetadata {
23628                    categories: vec![
23629                        Scalar::Utf8("a".to_owned()),
23630                        Scalar::Utf8("b".to_owned()),
23631                        Scalar::Utf8("c".to_owned()),
23632                    ],
23633                    ordered: false,
23634                },
23635            ),
23636        )
23637        .unwrap();
23638        let right = fp_frame::DataFrame::from_dict(
23639            &["t", "w"],
23640            vec![
23641                ("t", vec![2.into(), 3.into()]),
23642                ("w", vec![200.into(), 300.into()]),
23643            ],
23644        )
23645        .unwrap();
23646        let result = super::merge_ordered_grouped_with_options(
23647            &left,
23648            &right,
23649            &["t"],
23650            &["t"],
23651            JoinType::Outer,
23652            None,
23653            &super::MergeOrderedGroupBy::Left(vec!["g".to_owned()]),
23654            super::MergeExecutionOptions::default(),
23655        )
23656        .unwrap();
23657        assert_eq!(
23658            result.columns["g"]
23659                .values()
23660                .iter()
23661                .map(Scalar::as_str)
23662                .collect::<Vec<_>>(),
23663            vec![
23664                Some("b"),
23665                Some("b"),
23666                Some("b"),
23667                Some("a"),
23668                Some("a"),
23669                Some("c"),
23670                Some("c")
23671            ]
23672        );
23673        assert_eq!(
23674            result.columns["t"].values(),
23675            &[
23676                1.into(),
23677                2.into(),
23678                3.into(),
23679                2.into(),
23680                3.into(),
23681                2.into(),
23682                3.into()
23683            ]
23684        );
23685        assert_eq!(result.columns["g"].dtype(), DType::Utf8);
23686        assert!(
23687            result.columns["v"].values()[5..]
23688                .iter()
23689                .all(Scalar::is_missing)
23690        );
23691    }
23692
23693    #[test]
23694    fn merge_ordered_grouped_rejects_absent_or_empty_groups_u6p7i() {
23695        let left = fp_frame::DataFrame::from_dict(
23696            &["g", "t"],
23697            vec![
23698                (
23699                    "g",
23700                    vec![Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)],
23701                ),
23702                ("t", vec![1.into(), 3.into()]),
23703            ],
23704        )
23705        .unwrap();
23706        let right = fp_frame::DataFrame::from_dict(&["t"], vec![("t", vec![2.into()])]).unwrap();
23707        for (names, expected) in [
23708            (vec!["g".to_owned()], "No objects to concatenate"),
23709            (vec![], "No group keys passed!"),
23710            (vec!["missing".to_owned()], "missing key column 'missing'"),
23711        ] {
23712            let error = super::merge_ordered_grouped_with_options(
23713                &left,
23714                &right,
23715                &["t"],
23716                &["t"],
23717                JoinType::Outer,
23718                None,
23719                &super::MergeOrderedGroupBy::Left(names),
23720                super::MergeExecutionOptions::default(),
23721            )
23722            .expect_err("invalid group selection");
23723            assert!(error.to_string().contains(expected), "{error}");
23724        }
23725    }
23726
23727    #[test]
23728    fn merge_ordered_invalid_fill_method_errors() {
23729        let left = fp_frame::DataFrame::from_dict(
23730            &["date", "left_val"],
23731            vec![
23732                ("date", vec![Scalar::Int64(1)]),
23733                ("left_val", vec![Scalar::Int64(10)]),
23734            ],
23735        )
23736        .unwrap();
23737
23738        let right = fp_frame::DataFrame::from_dict(
23739            &["date", "right_val"],
23740            vec![
23741                ("date", vec![Scalar::Int64(2)]),
23742                ("right_val", vec![Scalar::Int64(200)]),
23743            ],
23744        )
23745        .unwrap();
23746
23747        let err = super::merge_ordered(&left, &right, &["date"], Some("sideways"))
23748            .expect_err("invalid fill method should error");
23749        assert!(matches!(
23750            err,
23751            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
23752                if message.contains("fill_method must be 'ffill' or None")
23753        ));
23754    }
23755
23756    #[test]
23757    fn merge_ordered_rejects_bfill_like_pandas() {
23758        let left = fp_frame::DataFrame::from_dict(
23759            &["date", "left_val"],
23760            vec![
23761                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
23762                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
23763            ],
23764        )
23765        .unwrap();
23766
23767        let right = fp_frame::DataFrame::from_dict(
23768            &["date", "right_val"],
23769            vec![
23770                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
23771                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
23772            ],
23773        )
23774        .unwrap();
23775
23776        let err = super::merge_ordered(&left, &right, &["date"], Some("bfill"))
23777            .expect_err("pandas only accepts fill_method='ffill' or None");
23778        assert!(matches!(
23779            err,
23780            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
23781                if message.contains("fill_method must be 'ffill' or None")
23782        ));
23783    }
23784
23785    // ── join() pandas-named alias (br-frankenpandas-nk54a) ──────────────
23786
23787    #[test]
23788    fn dataframe_join_aliases_join_on_index() {
23789        use std::collections::BTreeMap;
23790
23791        use fp_columnar::Column;
23792        use fp_frame::DataFrame;
23793        use fp_index::Index;
23794        use fp_types::{DType, Scalar};
23795
23796        use super::DataFrameMergeExt;
23797
23798        fn build(name1: &str, name2: &str, vals1: &[i64], vals2: &[i64]) -> DataFrame {
23799            let mut cols = BTreeMap::new();
23800            cols.insert(
23801                name1.to_owned(),
23802                Column::new(
23803                    DType::Int64,
23804                    vals1.iter().map(|v| Scalar::Int64(*v)).collect(),
23805                )
23806                .unwrap(),
23807            );
23808            cols.insert(
23809                name2.to_owned(),
23810                Column::new(
23811                    DType::Int64,
23812                    vals2.iter().map(|v| Scalar::Int64(*v)).collect(),
23813                )
23814                .unwrap(),
23815            );
23816            DataFrame::new_with_column_order(
23817                Index::new(
23818                    (0..vals1.len() as i64)
23819                        .map(fp_index::IndexLabel::Int64)
23820                        .collect(),
23821                ),
23822                cols,
23823                vec![name1.to_owned(), name2.to_owned()],
23824            )
23825            .unwrap()
23826        }
23827
23828        let left = build("a", "b", &[10, 20, 30], &[1, 2, 3]);
23829        let right = build("c", "d", &[100, 200, 300], &[7, 8, 9]);
23830
23831        let via_join = left.join(&right, super::JoinType::Inner).unwrap();
23832        let via_join_on_index = left.join_on_index(&right, super::JoinType::Inner).unwrap();
23833
23834        // Both produce the same MergedDataFrame shape & values.
23835        let join_keys: Vec<&String> = via_join.columns.keys().collect();
23836        let idx_keys: Vec<&String> = via_join_on_index.columns.keys().collect();
23837        assert_eq!(join_keys, idx_keys);
23838        assert_eq!(via_join.index, via_join_on_index.index);
23839        for k in via_join.columns.keys() {
23840            assert_eq!(
23841                via_join.columns.get(k).unwrap().values(),
23842                via_join_on_index.columns.get(k).unwrap().values(),
23843                "column {k} differs"
23844            );
23845        }
23846    }
23847
23848    /// The branch-free ordered outer merge answers the three-way merge's
23849    /// positions - interleaved, equal and disjoint keys, either side
23850    /// exhausted first, an empty side (br-frankenpandas-m3z4g). NEGATIVE:
23851    /// a key that is not strictly increasing takes no ordered merge.
23852    #[test]
23853    fn ordered_outer_positions_match_the_three_way_merge_m3z4g() {
23854        type Positions = (Vec<Option<usize>>, Vec<Option<usize>>);
23855        let reference = |left: &[i64], right: &[i64]| -> Positions {
23856            let (mut l, mut r) = (0, 0);
23857            let (mut out_left, mut out_right) = (Vec::new(), Vec::new());
23858            while l < left.len() || r < right.len() {
23859                let take_left = r == right.len() || (l < left.len() && left[l] <= right[r]);
23860                let take_right = l == left.len() || (r < right.len() && right[r] <= left[l]);
23861                out_left.push(take_left.then_some(l));
23862                out_right.push(take_right.then_some(r));
23863                l += usize::from(take_left);
23864                r += usize::from(take_right);
23865            }
23866            (out_left, out_right)
23867        };
23868        let twos: Vec<i64> = (0..40).map(|k| k * 2).collect();
23869        let threes: Vec<i64> = (0..40).map(|k| k * 3).collect();
23870        let late: Vec<i64> = (100..110).collect();
23871        let cases: [(&[i64], &[i64]); 6] = [
23872            (&twos, &threes),
23873            (&threes, &twos),
23874            (&twos, &twos),
23875            (&twos, &late),
23876            (&late, &twos),
23877            (&twos, &[]),
23878        ];
23879        for (left, right) in cases {
23880            let got = ordered_unique_int64_outer_positions(
23881                &Column::from_i64_values(left.to_vec()),
23882                &Column::from_i64_values(right.to_vec()),
23883            );
23884            assert_eq!(got, Some(reference(left, right)), "{left:?} {right:?}");
23885        }
23886        let repeated = Column::from_i64_values(vec![1, 2, 2, 3]);
23887        assert!(
23888            ordered_unique_int64_outer_positions(&repeated, &Column::from_i64_values(vec![1]))
23889                .is_none()
23890        );
23891    }
23892}
23893
23894#[cfg(test)]
23895mod typed_validate_cardinality_uza04 {
23896    //! `validate=` must stop costing the whole fast-path family.
23897    //!
23898    //! br-frankenpandas-uza04. `validate_merge_cardinality` lives in exactly
23899    //! one place — the generic `collect_composite_keys` branch — so
23900    //! `validate_mode_allows_fast_positions` returned false for every enforcing
23901    //! mode purely to route execution there. Asking for a cardinality guarantee
23902    //! therefore disabled `dense_packed_int64_inner_positions`, the typed
23903    //! two-key and multi-key position paths, and the single-key inner/left
23904    //! shortcuts, and additionally built a `Vec<CompositeJoinKey>` off
23905    //! `column.values()[row]` on both sides.
23906    //!
23907    //! `typed_validate_merge_cardinality` settles the common shape (one
23908    //! all-valid Int64 key) off the raw buffer, so a PASSING validation lets
23909    //! the merge take the same path it would have taken with no `validate=`.
23910    //! These tests pin the two things that has to preserve: the rejections, and
23911    //! the output.
23912
23913    use fp_columnar::Column;
23914    use fp_frame::DataFrame;
23915    use fp_index::Index;
23916    use fp_types::{NullKind, Scalar};
23917
23918    use super::{
23919        JoinType, MergeExecutionOptions, MergeValidateMode, merge_dataframes_on_with,
23920        merge_dataframes_on_with_options, typed_single_int64_key_has_duplicates,
23921    };
23922
23923    fn int_frame(name: &str, keys: Vec<i64>, payload: Vec<i64>) -> DataFrame {
23924        let index = Index::new_known_unique_int64_unit_range(0, keys.len());
23925        DataFrame::new_with_column_order(
23926            index,
23927            std::collections::BTreeMap::from([
23928                ("id".to_owned(), Column::from_i64_values(keys)),
23929                (name.to_owned(), Column::from_i64_values(payload)),
23930            ]),
23931            vec!["id".to_owned(), name.to_owned()],
23932        )
23933        .expect("typed int frame")
23934    }
23935
23936    fn merge(
23937        left: &DataFrame,
23938        right: &DataFrame,
23939        validate: Option<MergeValidateMode>,
23940    ) -> Result<super::MergedDataFrame, super::JoinError> {
23941        merge_dataframes_on_with_options(
23942            left,
23943            right,
23944            &["id"],
23945            &["id"],
23946            JoinType::Inner,
23947            MergeExecutionOptions {
23948                validate_mode: validate,
23949                ..MergeExecutionOptions::default()
23950            },
23951        )
23952    }
23953
23954    /// THE DUPLICATE-KEY NEGATIVE CASE. The typed checker is now what rejects a
23955    /// non-unique left key under `one_to_many`, so it has to reject with the
23956    /// same message the generic checker produced — a caller cannot tell which
23957    /// one ran.
23958    #[test]
23959    fn duplicate_left_keys_still_reject_under_one_to_many_uza04() {
23960        let left = int_frame("left_v", vec![1, 2, 2, 3], vec![10, 20, 21, 30]);
23961        let right = int_frame("right_v", vec![1, 2, 3], vec![100, 200, 300]);
23962        let error = merge(&left, &right, Some(MergeValidateMode::OneToMany))
23963            .expect_err("duplicate left keys must be rejected");
23964        assert!(
23965            format!("{error}")
23966                .contains("merge validate='one_to_many' failed: left keys are not unique"),
23967            "message must match the generic checker exactly, got: {error}"
23968        );
23969    }
23970
23971    #[test]
23972    fn duplicate_right_keys_still_reject_under_many_to_one_uza04() {
23973        let left = int_frame("left_v", vec![1, 2, 3], vec![10, 20, 30]);
23974        let right = int_frame("right_v", vec![1, 2, 2], vec![100, 200, 201]);
23975        let error = merge(&left, &right, Some(MergeValidateMode::ManyToOne))
23976            .expect_err("duplicate right keys must be rejected");
23977        assert!(
23978            format!("{error}")
23979                .contains("merge validate='many_to_one' failed: right keys are not unique"),
23980            "message must match the generic checker exactly, got: {error}"
23981        );
23982    }
23983
23984    /// PRECEDENCE. With BOTH sides duplicated under `one_to_one`, pandas —
23985    /// and the generic checker — name BOTH sides ('not unique in either left
23986    /// or right dataset'; this pinned a left-first report pandas 2.2.3 does
23987    /// not make, z6jxh). The typed checker must not answer from whichever
23988    /// side it happened to inspect first.
23989    #[test]
23990    fn one_to_one_names_both_sides_when_both_repeat_uza04() {
23991        let left = int_frame("left_v", vec![1, 1, 2], vec![10, 11, 20]);
23992        let right = int_frame("right_v", vec![1, 1, 2], vec![100, 101, 200]);
23993        let error = merge(&left, &right, Some(MergeValidateMode::OneToOne))
23994            .expect_err("both sides duplicated must be rejected");
23995        let message = format!("{error}");
23996        assert!(
23997            message.contains("left and right keys are not unique"),
23998            "both sides must be named, got: {message}"
23999        );
24000    }
24001
24002    #[test]
24003    fn one_to_one_still_catches_a_right_only_duplicate_uza04() {
24004        let left = int_frame("left_v", vec![1, 2, 3], vec![10, 20, 30]);
24005        let right = int_frame("right_v", vec![1, 2, 2], vec![100, 200, 201]);
24006        let error = merge(&left, &right, Some(MergeValidateMode::OneToOne))
24007            .expect_err("right duplicate must be rejected");
24008        assert!(
24009            format!("{error}")
24010                .contains("merge validate='one_to_one' failed: right keys are not unique"),
24011            "got: {error}"
24012        );
24013    }
24014
24015    /// THE SAFETY PROPERTY OF THE WHOLE LEVER: a validation that PASSES must
24016    /// leave the merge output byte-identical to the unvalidated merge, because
24017    /// it now takes the same fast path. If enabling those paths changed row
24018    /// order, pairing, or column content, this is what catches it.
24019    #[test]
24020    fn a_passing_validation_produces_the_unvalidated_output_uza04() {
24021        let left = int_frame("left_v", vec![5, 1, 4, 2, 3], vec![50, 10, 40, 20, 30]);
24022        let right = int_frame("right_v", vec![3, 1, 2, 9], vec![300, 100, 200, 900]);
24023
24024        let unvalidated = merge(&left, &right, None).expect("plain merge");
24025        for mode in [
24026            MergeValidateMode::OneToOne,
24027            MergeValidateMode::OneToMany,
24028            MergeValidateMode::ManyToOne,
24029            MergeValidateMode::ManyToMany,
24030        ] {
24031            let validated = merge(&left, &right, Some(mode)).expect("validation should pass");
24032            assert_eq!(
24033                validated.index.len(),
24034                unvalidated.index.len(),
24035                "{mode:?}: row count changed"
24036            );
24037            assert_eq!(
24038                validated.column_order, unvalidated.column_order,
24039                "{mode:?}: column order changed"
24040            );
24041            for name in ["id", "left_v", "right_v"] {
24042                assert_eq!(
24043                    validated.columns.get(name).expect("column").values(),
24044                    unvalidated.columns.get(name).expect("column").values(),
24045                    "{mode:?}: column {name} differs from the unvalidated merge"
24046                );
24047            }
24048        }
24049    }
24050
24051    /// NON-VACUITY, both directions. Every assertion above would still pass if
24052    /// the typed checker declined everything and the generic path did all the
24053    /// work — the lever would simply not exist.
24054    #[test]
24055    fn the_typed_checker_fires_on_typed_keys_and_declines_otherwise_uza04() {
24056        let unique = Column::from_i64_values(vec![1, 2, 3]);
24057        assert_eq!(
24058            typed_single_int64_key_has_duplicates(&[&unique]),
24059            Some(false),
24060            "an all-valid Int64 key must be answered typed"
24061        );
24062        let duplicated = Column::from_i64_values(vec![1, 2, 2]);
24063        assert_eq!(
24064            typed_single_int64_key_has_duplicates(&[&duplicated]),
24065            Some(true),
24066            "and duplicates must be seen"
24067        );
24068
24069        // A key with a missing value has no contiguous all-valid buffer, so the
24070        // typed checker declines and null-key duplicate semantics stay owned by
24071        // the generic path.
24072        let nullable = Column::from_values(vec![
24073            Scalar::Int64(1),
24074            Scalar::Null(NullKind::Null),
24075            Scalar::Int64(3),
24076        ])
24077        .expect("nullable int column");
24078        assert_eq!(
24079            typed_single_int64_key_has_duplicates(&[&nullable]),
24080            None,
24081            "a nullable key must decline"
24082        );
24083
24084        // Utf8 keys decline too (this lever is Int64-only for now).
24085        let text = Column::from_values(vec![
24086            Scalar::Utf8("a".to_owned()),
24087            Scalar::Utf8("b".to_owned()),
24088        ])
24089        .expect("utf8 column");
24090        assert_eq!(
24091            typed_single_int64_key_has_duplicates(&[&text]),
24092            None,
24093            "a Utf8 key must decline"
24094        );
24095
24096        // Multi-key merges decline: the composite question is not this one.
24097        assert_eq!(
24098            typed_single_int64_key_has_duplicates(&[&unique, &duplicated]),
24099            None,
24100            "more than one key column must decline"
24101        );
24102    }
24103
24104    /// A shape the typed checker DECLINES must still be validated — the generic
24105    /// path has to keep running for it. A nullable left key with a repeated
24106    /// value under `one_to_many` is the case that would silently start passing
24107    /// if the skip flag were set too broadly.
24108    #[test]
24109    fn a_declined_shape_is_still_validated_by_the_generic_path_uza04() {
24110        let index = Index::new_known_unique_int64_unit_range(0, 3);
24111        let left = DataFrame::new_with_column_order(
24112            index,
24113            std::collections::BTreeMap::from([
24114                (
24115                    "id".to_owned(),
24116                    Column::from_values(vec![
24117                        Scalar::Int64(1),
24118                        Scalar::Int64(1),
24119                        Scalar::Null(NullKind::Null),
24120                    ])
24121                    .expect("nullable id column"),
24122                ),
24123                (
24124                    "left_v".to_owned(),
24125                    Column::from_i64_values(vec![10, 11, 30]),
24126                ),
24127            ]),
24128            vec!["id".to_owned(), "left_v".to_owned()],
24129        )
24130        .expect("nullable left frame");
24131        let right = int_frame("right_v", vec![1, 2, 3], vec![100, 200, 300]);
24132
24133        let error = merge(&left, &right, Some(MergeValidateMode::OneToMany))
24134            .expect_err("a duplicated nullable left key must still be rejected");
24135        assert!(
24136            format!("{error}").contains("left keys are not unique"),
24137            "the generic checker must still own declined shapes, got: {error}"
24138        );
24139    }
24140
24141    #[test]
24142    fn merge_suffix_collision_preserves_duplicate_columns() {
24143        let left = fp_frame::DataFrame::from_dict_with_index(
24144            vec![
24145                ("key", vec![Scalar::Int64(1)]),
24146                ("a", vec![Scalar::Int64(10)]),
24147                ("a_y", vec![Scalar::Int64(20)]),
24148            ],
24149            vec![0_i64.into()],
24150        )
24151        .unwrap();
24152
24153        let right = fp_frame::DataFrame::from_dict_with_index(
24154            vec![
24155                ("key", vec![Scalar::Int64(1)]),
24156                ("a", vec![Scalar::Int64(30)]),
24157            ],
24158            vec![0_i64.into()],
24159        )
24160        .unwrap();
24161
24162        let options = MergeExecutionOptions {
24163            suffixes: Some([Some("_x".to_string()), Some("_y".to_string())]),
24164            ..MergeExecutionOptions::default()
24165        };
24166
24167        let merged = merge_dataframes_on_with_options(
24168            &left,
24169            &right,
24170            &["key"],
24171            &["key"],
24172            JoinType::Inner,
24173            options,
24174        )
24175        .expect("merge with suffix collision should succeed and produce duplicate columns");
24176
24177        assert_eq!(
24178            merged.column_order,
24179            vec![
24180                "key".to_string(),
24181                "a_x".to_string(),
24182                "a_y".to_string(),
24183                "a_y".to_string()
24184            ]
24185        );
24186        assert_eq!(merged.columns.occurrences("a_y"), 2);
24187        assert_eq!(
24188            merged.columns.column_at(2).unwrap().values(),
24189            &[Scalar::Int64(20)]
24190        );
24191        assert_eq!(
24192            merged.columns.column_at(3).unwrap().values(),
24193            &[Scalar::Int64(30)]
24194        );
24195    }
24196
24197    #[test]
24198    fn merge_suffixes_intra_frame_duplicate_rejected() {
24199        // Left side collision: left has val and val_L, suffix _L produces duplicate val_L
24200        let left = fp_frame::DataFrame::from_dict_with_index(
24201            vec![
24202                ("id", vec![Scalar::Int64(1)]),
24203                ("val", vec![Scalar::Int64(10)]),
24204                ("val_L", vec![Scalar::Int64(77)]),
24205            ],
24206            vec![0_i64.into()],
24207        )
24208        .unwrap();
24209
24210        let right = fp_frame::DataFrame::from_dict_with_index(
24211            vec![
24212                ("id", vec![Scalar::Int64(1)]),
24213                ("val", vec![Scalar::Int64(100)]),
24214            ],
24215            vec![0_i64.into()],
24216        )
24217        .unwrap();
24218
24219        let options = MergeExecutionOptions {
24220            suffixes: Some([Some("_L".to_string()), Some("_R".to_string())]),
24221            ..MergeExecutionOptions::default()
24222        };
24223
24224        let err = merge_dataframes_on_with_options(
24225            &left,
24226            &right,
24227            &["id"],
24228            &["id"],
24229            JoinType::Inner,
24230            options.clone(),
24231        )
24232        .expect_err("merge causing duplicate column within left must be rejected");
24233
24234        assert!(
24235            format!("{err}").contains("duplicate columns {'val_L'}"),
24236            "expected duplicate columns error, got: {err}"
24237        );
24238
24239        // Right side collision: right has val and val_R, suffix _R produces duplicate val_R
24240        let right_with_dup = fp_frame::DataFrame::from_dict_with_index(
24241            vec![
24242                ("id", vec![Scalar::Int64(1)]),
24243                ("val", vec![Scalar::Int64(100)]),
24244                ("val_R", vec![Scalar::Int64(88)]),
24245            ],
24246            vec![0_i64.into()],
24247        )
24248        .unwrap();
24249
24250        let left_simple = fp_frame::DataFrame::from_dict_with_index(
24251            vec![
24252                ("id", vec![Scalar::Int64(1)]),
24253                ("val", vec![Scalar::Int64(10)]),
24254            ],
24255            vec![0_i64.into()],
24256        )
24257        .unwrap();
24258
24259        let err_r = merge_dataframes_on_with_options(
24260            &left_simple,
24261            &right_with_dup,
24262            &["id"],
24263            &["id"],
24264            JoinType::Inner,
24265            options,
24266        )
24267        .expect_err("merge causing duplicate column within right must be rejected");
24268
24269        assert!(
24270            format!("{err_r}").contains("duplicate columns {'val_R'}"),
24271            "expected duplicate columns error, got: {err_r}"
24272        );
24273    }
24274
24275    #[test]
24276    fn inner_merge_equal_left_len_with_duplicates_matches_pandas_ml0az() {
24277        let left = fp_frame::DataFrame::from_dict_with_index(
24278            vec![
24279                (
24280                    "k",
24281                    vec![
24282                        Scalar::Int64(2),
24283                        Scalar::Int64(1),
24284                        Scalar::Int64(9),
24285                        Scalar::Int64(2),
24286                    ],
24287                ),
24288                (
24289                    "lv",
24290                    vec![
24291                        Scalar::Int64(10),
24292                        Scalar::Int64(20),
24293                        Scalar::Int64(30),
24294                        Scalar::Int64(40),
24295                    ],
24296                ),
24297            ],
24298            vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
24299        )
24300        .unwrap();
24301        let right = fp_frame::DataFrame::from_dict_with_index(
24302            vec![
24303                (
24304                    "k",
24305                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
24306                ),
24307                (
24308                    "rv",
24309                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
24310                ),
24311            ],
24312            vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
24313        )
24314        .unwrap();
24315
24316        let merged =
24317            merge_dataframes_on_with(&left, &right, &["k"], &["k"], JoinType::Inner).unwrap();
24318        assert_eq!(
24319            merged.columns.get("k").unwrap().values(),
24320            &[
24321                Scalar::Int64(2),
24322                Scalar::Int64(1),
24323                Scalar::Int64(1),
24324                Scalar::Int64(2),
24325            ]
24326        );
24327        assert_eq!(
24328            merged.columns.get("lv").unwrap().values(),
24329            &[
24330                Scalar::Int64(10),
24331                Scalar::Int64(20),
24332                Scalar::Int64(20),
24333                Scalar::Int64(40),
24334            ]
24335        );
24336        assert_eq!(
24337            merged.columns.get("rv").unwrap().values(),
24338            &[
24339                Scalar::Int64(300),
24340                Scalar::Int64(100),
24341                Scalar::Int64(200),
24342                Scalar::Int64(300),
24343            ]
24344        );
24345    }
24346}
24347
24348#[cfg(test)]
24349mod extension_join_key_tests {
24350    use fp_columnar::Column;
24351    use fp_frame::{ColumnStore, DataFrame};
24352    use fp_index::Index;
24353    use fp_types::{DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar};
24354
24355    use super::{
24356        JoinType, MergeExecutionOptions, MergeValidateMode, MergedDataFrame, merge_dataframes,
24357        merge_dataframes_on_with_options,
24358    };
24359
24360    type KeyFactory = fn(i32) -> Scalar;
24361
24362    fn frame(keys: Vec<Scalar>, dtype: DType, side: &str) -> DataFrame {
24363        frame_column(Column::new(dtype, keys).unwrap(), side)
24364    }
24365
24366    fn frame_column(keys: Column, side: &str) -> DataFrame {
24367        let len = keys.len();
24368        let rows = (0..len)
24369            .map(|row| i64::try_from(row).expect("small fixture"))
24370            .collect();
24371        DataFrame::new_with_column_order(
24372            Index::new_known_unique_int64_unit_range(0, len),
24373            ColumnStore::from_pairs([
24374                ("key".to_owned(), keys),
24375                (side.to_owned(), Column::from_i64_values(rows)),
24376            ]),
24377            vec!["key".to_owned(), side.to_owned()],
24378        )
24379        .unwrap()
24380    }
24381
24382    fn row_pairs(merged: &MergedDataFrame) -> Vec<(Option<f64>, Option<f64>)> {
24383        let row = |value: &Scalar| {
24384            if value.is_missing() {
24385                None
24386            } else {
24387                Some(value.to_f64().unwrap())
24388            }
24389        };
24390        merged.columns["left_row"]
24391            .values()
24392            .iter()
24393            .zip(merged.columns["right_row"].values())
24394            .map(|(left, right)| (row(left), row(right)))
24395            .collect()
24396    }
24397
24398    fn period(ordinal: i32) -> Scalar {
24399        Scalar::Period(Period::new(i64::from(ordinal), PeriodFreq::Monthly))
24400    }
24401
24402    fn interval(left: i32) -> Scalar {
24403        Scalar::Interval(Interval::new(
24404            f64::from(left),
24405            f64::from(left) + 1.0,
24406            IntervalClosed::Right,
24407        ))
24408    }
24409
24410    fn assert_join_values(dtype: DType, key: fn(i32) -> Scalar, missing: Scalar) {
24411        let left = frame(
24412            vec![key(2), key(0), key(2), missing.clone()],
24413            dtype.clone(),
24414            "left_row",
24415        );
24416        let right = frame(
24417            vec![key(1), key(2), missing, key(2)],
24418            dtype.clone(),
24419            "right_row",
24420        );
24421        // Recorded from the live pandas 2.2.3 oracle: keep the duplicate
24422        // product, and match a missing key only to the other missing key.
24423        let cases = [
24424            (
24425                JoinType::Inner,
24426                vec![
24427                    (Some(0.0), Some(1.0)),
24428                    (Some(0.0), Some(3.0)),
24429                    (Some(2.0), Some(1.0)),
24430                    (Some(2.0), Some(3.0)),
24431                    (Some(3.0), Some(2.0)),
24432                ],
24433            ),
24434            (
24435                JoinType::Left,
24436                vec![
24437                    (Some(0.0), Some(1.0)),
24438                    (Some(0.0), Some(3.0)),
24439                    (Some(1.0), None),
24440                    (Some(2.0), Some(1.0)),
24441                    (Some(2.0), Some(3.0)),
24442                    (Some(3.0), Some(2.0)),
24443                ],
24444            ),
24445            (
24446                JoinType::Right,
24447                vec![
24448                    (None, Some(0.0)),
24449                    (Some(0.0), Some(1.0)),
24450                    (Some(2.0), Some(1.0)),
24451                    (Some(3.0), Some(2.0)),
24452                    (Some(0.0), Some(3.0)),
24453                    (Some(2.0), Some(3.0)),
24454                ],
24455            ),
24456        ];
24457        for (how, expected) in cases {
24458            let merged = merge_dataframes_on_with_options(
24459                &left,
24460                &right,
24461                &["key"],
24462                &["key"],
24463                how,
24464                MergeExecutionOptions::default(),
24465            )
24466            .unwrap();
24467            assert_eq!(row_pairs(&merged), expected, "{dtype:?} {how:?}");
24468        }
24469        // Exercise the independent single-key shortcut too.
24470        let shortcut = merge_dataframes(&left, &right, "key", JoinType::Inner).unwrap();
24471        assert_eq!(shortcut.index.len(), 5);
24472
24473        // With no missing keys, outer/sort=True must order by the actual
24474        // Period ordinals or Interval endpoints, not just the variant tag.
24475        let left = frame(vec![key(2), key(0), key(2)], dtype.clone(), "left_row");
24476        let right = frame(vec![key(1), key(2), key(2)], dtype, "right_row");
24477        for sort in [false, true] {
24478            let merged = merge_dataframes_on_with_options(
24479                &left,
24480                &right,
24481                &["key"],
24482                &["key"],
24483                JoinType::Outer,
24484                MergeExecutionOptions {
24485                    sort,
24486                    ..Default::default()
24487                },
24488            )
24489            .unwrap();
24490            assert_eq!(
24491                row_pairs(&merged),
24492                vec![
24493                    (Some(1.0), None),
24494                    (None, Some(0.0)),
24495                    (Some(0.0), Some(1.0)),
24496                    (Some(0.0), Some(2.0)),
24497                    (Some(2.0), Some(1.0)),
24498                    (Some(2.0), Some(2.0)),
24499                ]
24500            );
24501        }
24502    }
24503
24504    #[test]
24505    fn period_keys_preserve_values_duplicates_and_nat() {
24506        assert_join_values(
24507            DType::Period,
24508            period,
24509            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly)),
24510        );
24511    }
24512
24513    #[test]
24514    fn interval_keys_preserve_values_duplicates_and_missing() {
24515        assert_join_values(DType::Interval, interval, Scalar::Null(NullKind::NaN));
24516    }
24517
24518    #[test]
24519    fn sorted_temporal_merges_put_nat_first_and_keep_duplicate_order() {
24520        let families: [(DType, KeyFactory); 3] = [
24521            (DType::Period, period),
24522            (DType::Timedelta64, |value| {
24523                Scalar::Timedelta64(i64::from(value))
24524            }),
24525            (DType::Datetime64 { tz: None }, |value| {
24526                Scalar::Datetime64(i64::from(value))
24527            }),
24528        ];
24529        for (dtype, key) in families {
24530            let left = frame(
24531                vec![key(2), key(0), key(2), Scalar::Null(NullKind::NaT)],
24532                dtype.clone(),
24533                "left_row",
24534            );
24535            let right = frame(
24536                vec![key(1), key(2), Scalar::Null(NullKind::NaT), key(2)],
24537                dtype.clone(),
24538                "right_row",
24539            );
24540            let product = [
24541                (Some(0.0), Some(1.0)),
24542                (Some(0.0), Some(3.0)),
24543                (Some(2.0), Some(1.0)),
24544                (Some(2.0), Some(3.0)),
24545            ];
24546            for how in [
24547                JoinType::Inner,
24548                JoinType::Left,
24549                JoinType::Right,
24550                JoinType::Outer,
24551            ] {
24552                let mut expected = vec![(Some(3.0), Some(2.0))];
24553                if matches!(how, JoinType::Left | JoinType::Outer) {
24554                    expected.push((Some(1.0), None));
24555                }
24556                if matches!(how, JoinType::Right | JoinType::Outer) {
24557                    expected.push((None, Some(0.0)));
24558                }
24559                if how == JoinType::Right {
24560                    expected.extend([product[0], product[2], product[1], product[3]]);
24561                } else {
24562                    expected.extend(product);
24563                }
24564                for sort in [false, true] {
24565                    if !sort && how != JoinType::Outer {
24566                        continue;
24567                    }
24568                    let merged = merge_dataframes_on_with_options(
24569                        &left,
24570                        &right,
24571                        &["key"],
24572                        &["key"],
24573                        how,
24574                        MergeExecutionOptions {
24575                            sort,
24576                            ..Default::default()
24577                        },
24578                    )
24579                    .unwrap();
24580                    assert_eq!(row_pairs(&merged), expected, "{dtype:?} {how:?} {sort}");
24581                }
24582            }
24583        }
24584    }
24585
24586    #[test]
24587    fn sorted_non_temporal_merges_keep_missing_last() {
24588        let families: [(DType, KeyFactory); 2] = [
24589            (DType::Interval, interval),
24590            (DType::Float64, |value| Scalar::Float64(f64::from(value))),
24591        ];
24592        for (dtype, key) in families {
24593            let left = frame(
24594                vec![Scalar::Null(NullKind::NaN), key(1), key(0)],
24595                dtype.clone(),
24596                "left_row",
24597            );
24598            let right = frame(
24599                vec![key(0), Scalar::Null(NullKind::NaN), key(2)],
24600                dtype,
24601                "right_row",
24602            );
24603            let merged = merge_dataframes(&left, &right, "key", JoinType::Outer).unwrap();
24604            assert_eq!(
24605                row_pairs(&merged),
24606                vec![
24607                    (Some(2.0), Some(0.0)),
24608                    (Some(1.0), None),
24609                    (None, Some(2.0)),
24610                    (Some(0.0), Some(1.0)),
24611                ]
24612            );
24613        }
24614    }
24615
24616    #[test]
24617    fn categorical_merges_use_compatible_left_dictionary_order() {
24618        for ordered in [false, true] {
24619            for right_categories in [["c", "b", "a"], ["a", "b", "c"], ["a", "b", "d"]] {
24620                let left = frame_column(
24621                    Column::from_categorical_codes(
24622                        vec![0, 1, -1],
24623                        fp_types::CategoricalMetadata::new(
24624                            ["c", "b", "a"].map(|v| Scalar::Utf8(v.to_owned())).to_vec(),
24625                            ordered,
24626                        ),
24627                    ),
24628                    "left_row",
24629                );
24630                let right = frame_column(
24631                    Column::from_categorical_codes(
24632                        vec![if right_categories[0] == "c" { 2 } else { 0 }, 1, -1],
24633                        fp_types::CategoricalMetadata::new(
24634                            right_categories
24635                                .map(|v| Scalar::Utf8(v.to_owned()))
24636                                .to_vec(),
24637                            ordered,
24638                        ),
24639                    ),
24640                    "right_row",
24641                );
24642                let compatible = right_categories == ["c", "b", "a"]
24643                    || (!ordered && right_categories == ["a", "b", "c"]);
24644                let expected = if compatible {
24645                    vec![
24646                        (Some(2.0), Some(2.0)),
24647                        (Some(0.0), None),
24648                        (Some(1.0), Some(1.0)),
24649                        (None, Some(0.0)),
24650                    ]
24651                } else {
24652                    vec![
24653                        (None, Some(0.0)),
24654                        (Some(1.0), Some(1.0)),
24655                        (Some(0.0), None),
24656                        (Some(2.0), Some(2.0)),
24657                    ]
24658                };
24659                for sort in [false, true] {
24660                    let merged = merge_dataframes_on_with_options(
24661                        &left,
24662                        &right,
24663                        &["key"],
24664                        &["key"],
24665                        JoinType::Outer,
24666                        MergeExecutionOptions {
24667                            sort,
24668                            ..Default::default()
24669                        },
24670                    )
24671                    .unwrap();
24672                    assert_eq!(
24673                        row_pairs(&merged),
24674                        expected,
24675                        "{ordered} {right_categories:?}"
24676                    );
24677                }
24678            }
24679        }
24680    }
24681
24682    #[test]
24683    fn categorical_numeric_dtype_mismatch_uses_value_order() {
24684        let left = frame_column(
24685            Column::from_categorical_codes(
24686                vec![0, 1, -1],
24687                fp_types::CategoricalMetadata::new(vec![Scalar::Int64(2), Scalar::Int64(1)], false),
24688            ),
24689            "left_row",
24690        );
24691        let right = frame_column(
24692            Column::from_categorical_codes(
24693                vec![0, 1, -1],
24694                fp_types::CategoricalMetadata::new(
24695                    vec![Scalar::Float64(1.0), Scalar::Float64(2.0)],
24696                    false,
24697                ),
24698            ),
24699            "right_row",
24700        );
24701        let merged = merge_dataframes(&left, &right, "key", JoinType::Outer).unwrap();
24702        assert_eq!(
24703            row_pairs(&merged),
24704            vec![
24705                (Some(1.0), Some(0.0)),
24706                (Some(0.0), Some(1.0)),
24707                (Some(2.0), Some(2.0)),
24708            ]
24709        );
24710    }
24711
24712    #[test]
24713    fn composite_temporal_sort_places_nat_within_each_prefix() {
24714        let keys = vec![
24715            Scalar::Null(NullKind::NaT),
24716            period(2),
24717            Scalar::Null(NullKind::NaT),
24718            period(0),
24719        ];
24720        let groups = Column::new(
24721            DType::Utf8,
24722            ["b", "a", "a", "b"]
24723                .map(|v| Scalar::Utf8(v.to_owned()))
24724                .to_vec(),
24725        )
24726        .unwrap();
24727        let left = frame(keys.clone(), DType::Period, "left_row")
24728            .with_column("group", groups.clone())
24729            .unwrap();
24730        let right = frame(keys, DType::Period, "right_row")
24731            .with_column("group", groups)
24732            .unwrap();
24733        let merged = merge_dataframes_on_with_options(
24734            &left,
24735            &right,
24736            &["group", "key"],
24737            &["group", "key"],
24738            JoinType::Inner,
24739            MergeExecutionOptions {
24740                sort: true,
24741                ..Default::default()
24742            },
24743        )
24744        .unwrap();
24745        assert_eq!(
24746            row_pairs(&merged),
24747            vec![
24748                (Some(2.0), Some(2.0)),
24749                (Some(1.0), Some(1.0)),
24750                (Some(0.0), Some(0.0)),
24751                (Some(3.0), Some(3.0)),
24752            ]
24753        );
24754    }
24755
24756    #[test]
24757    fn extension_keys_validate_real_cardinality() {
24758        for (dtype, keys) in [
24759            (DType::Period, vec![period(2), period(0), period(1)]),
24760            (DType::Interval, vec![interval(2), interval(0), interval(1)]),
24761        ] {
24762            let left = frame(keys.clone(), dtype.clone(), "left_row");
24763            let right = frame(keys.clone(), dtype.clone(), "right_row");
24764            let options = MergeExecutionOptions {
24765                validate_mode: Some(MergeValidateMode::OneToOne),
24766                ..Default::default()
24767            };
24768            let merged = merge_dataframes_on_with_options(
24769                &left,
24770                &right,
24771                &["key"],
24772                &["key"],
24773                JoinType::Inner,
24774                options.clone(),
24775            )
24776            .unwrap();
24777            assert_eq!(
24778                row_pairs(&merged),
24779                vec![
24780                    (Some(0.0), Some(0.0)),
24781                    (Some(1.0), Some(1.0)),
24782                    (Some(2.0), Some(2.0)),
24783                ]
24784            );
24785            let repeated = frame(vec![keys[0].clone(), keys[0].clone()], dtype, "right_row");
24786            assert!(
24787                merge_dataframes_on_with_options(
24788                    &left,
24789                    &repeated,
24790                    &["key"],
24791                    &["key"],
24792                    JoinType::Inner,
24793                    options,
24794                )
24795                .is_err()
24796            );
24797        }
24798    }
24799
24800    #[test]
24801    fn period_keys_include_frequency() {
24802        let left = frame(vec![period(0)], DType::Period, "left_row");
24803        let right = frame(
24804            vec![Scalar::Period(Period::new(0, PeriodFreq::Daily))],
24805            DType::Period,
24806            "right_row",
24807        );
24808        let merged = merge_dataframes(&left, &right, "key", JoinType::Inner).unwrap();
24809        assert!(
24810            merged.index.is_empty(),
24811            "equal ordinals on different frequency axes must not match"
24812        );
24813    }
24814
24815    #[test]
24816    fn interval_keys_match_numeric_endpoints_and_distinguish_closedness() {
24817        let integer = Interval::new(-0.0, 1.0, IntervalClosed::Right).with_int_endpoints();
24818        let left = frame(vec![Scalar::Interval(integer)], DType::Interval, "left_row");
24819        let right = frame(
24820            vec![
24821                Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Left)),
24822                interval(0),
24823            ],
24824            DType::Interval,
24825            "right_row",
24826        );
24827        let merged = merge_dataframes(&left, &right, "key", JoinType::Inner).unwrap();
24828        assert_eq!(row_pairs(&merged), vec![(Some(0.0), Some(1.0))]);
24829    }
24830
24831    #[test]
24832    fn interval_sort_uses_closed_spelling_when_endpoints_tie() {
24833        let keys = [
24834            IntervalClosed::Right,
24835            IntervalClosed::Left,
24836            IntervalClosed::Both,
24837            IntervalClosed::Neither,
24838        ]
24839        .map(|closed| Scalar::Interval(Interval::new(0.0, 1.0, closed)));
24840        let left = frame(keys.to_vec(), DType::Interval, "left_row");
24841        let right = frame(keys.to_vec(), DType::Interval, "right_row");
24842        let merged = merge_dataframes_on_with_options(
24843            &left,
24844            &right,
24845            &["key"],
24846            &["key"],
24847            JoinType::Inner,
24848            MergeExecutionOptions {
24849                sort: true,
24850                ..Default::default()
24851            },
24852        )
24853        .unwrap();
24854        assert_eq!(
24855            row_pairs(&merged),
24856            vec![
24857                (Some(2.0), Some(2.0)),
24858                (Some(1.0), Some(1.0)),
24859                (Some(3.0), Some(3.0)),
24860                (Some(0.0), Some(0.0)),
24861            ]
24862        );
24863    }
24864
24865    #[test]
24866    fn extension_key_order_is_transitive_with_floats_and_strings() {
24867        let keys = [
24868            Scalar::Int64(0),
24869            Scalar::Float64(0.5),
24870            Scalar::Utf8("key".to_owned()),
24871            period(0),
24872            interval(0),
24873        ]
24874        .map(|value| super::scalar_to_key_component(&value));
24875        for left in &keys {
24876            for middle in &keys {
24877                for right in &keys {
24878                    if left < middle && middle < right {
24879                        assert!(
24880                            left < right,
24881                            "non-transitive join keys: {left:?} < {middle:?} < {right:?}"
24882                        );
24883                    }
24884                }
24885            }
24886        }
24887    }
24888
24889    #[test]
24890    fn composite_keys_keep_each_extension_component() {
24891        let left = frame(
24892            vec![period(0), period(0), period(1)],
24893            DType::Period,
24894            "left_row",
24895        )
24896        .with_column(
24897            "span",
24898            Column::new(DType::Interval, vec![interval(0), interval(1), interval(0)]).unwrap(),
24899        )
24900        .unwrap();
24901        let right = frame(
24902            vec![period(0), period(1), period(1)],
24903            DType::Period,
24904            "right_row",
24905        )
24906        .with_column(
24907            "span",
24908            Column::new(DType::Interval, vec![interval(1), interval(0), interval(2)]).unwrap(),
24909        )
24910        .unwrap();
24911        let merged = merge_dataframes_on_with_options(
24912            &left,
24913            &right,
24914            &["key", "span"],
24915            &["key", "span"],
24916            JoinType::Inner,
24917            MergeExecutionOptions::default(),
24918        )
24919        .unwrap();
24920        assert_eq!(
24921            row_pairs(&merged),
24922            vec![(Some(1.0), Some(0.0)), (Some(2.0), Some(1.0))]
24923        );
24924    }
24925}
24926
24927#[cfg(test)]
24928mod asof_indexer_contract_tests {
24929    use std::collections::BTreeMap;
24930
24931    use fp_columnar::Column;
24932    use fp_frame::DataFrame;
24933    use fp_index::Index;
24934    use fp_types::Scalar;
24935
24936    use super::{AsofDirection, MergeAsofOptions, merge_asof_on_with_indexer};
24937
24938    #[test]
24939    fn source_indexer_matches_emitted_rows_for_simple_and_grouped_exact_integer_keys() {
24940        let base = (1_i64 << 53) + 1;
24941        let left = DataFrame::new(
24942            Index::from_range(0, 3, 1),
24943            BTreeMap::from([
24944                (
24945                    "time".to_owned(),
24946                    Column::from_i64_values_owned(vec![base + 1, base + 3, base + 5]),
24947                ),
24948                (
24949                    "group".to_owned(),
24950                    Column::from_values(vec![
24951                        Scalar::from("a"),
24952                        Scalar::from("b"),
24953                        Scalar::from("a"),
24954                    ])
24955                    .unwrap(),
24956                ),
24957            ]),
24958        )
24959        .unwrap();
24960        let right = DataFrame::new(
24961            Index::from_range(0, 3, 1),
24962            BTreeMap::from([
24963                (
24964                    "tick".to_owned(),
24965                    Column::from_i64_values_owned(vec![base + 2, base + 3, base + 4]),
24966                ),
24967                (
24968                    "bucket".to_owned(),
24969                    Column::from_values(vec![
24970                        Scalar::from("a"),
24971                        Scalar::from("a"),
24972                        Scalar::from("b"),
24973                    ])
24974                    .unwrap(),
24975                ),
24976                (
24977                    "right_row".to_owned(),
24978                    Column::from_i64_values_owned(vec![100, 101, 102]),
24979                ),
24980            ]),
24981        )
24982        .unwrap();
24983        for grouped in [false, true] {
24984            for (direction, simple, groups) in [
24985                (
24986                    AsofDirection::Backward,
24987                    [None, Some(1), Some(2)],
24988                    [None, None, Some(1)],
24989                ),
24990                (
24991                    AsofDirection::Forward,
24992                    [Some(0), Some(1), None],
24993                    [Some(0), Some(2), None],
24994                ),
24995                (
24996                    AsofDirection::Nearest,
24997                    [Some(0), Some(1), Some(2)],
24998                    [Some(0), Some(2), Some(1)],
24999                ),
25000            ] {
25001                let options = MergeAsofOptions {
25002                    left_by: grouped.then(|| vec!["group".to_owned()]),
25003                    right_by: grouped.then(|| vec!["bucket".to_owned()]),
25004                    ..MergeAsofOptions::new()
25005                };
25006                let (merged, positions) =
25007                    merge_asof_on_with_indexer(&left, &right, "time", "tick", direction, options)
25008                        .unwrap();
25009                assert_eq!(
25010                    positions.as_slice(),
25011                    if grouped { &groups } else { &simple }
25012                );
25013                assert_eq!(merged.columns["time"], left.columns()["time"]);
25014                for (row, position) in positions.iter().enumerate() {
25015                    let actual = merged.columns["right_row"].scalar_at(row).unwrap();
25016                    match position {
25017                        Some(source) => assert_eq!(
25018                            actual.to_f64().unwrap(),
25019                            100.0 + f64::from(u32::try_from(*source).unwrap())
25020                        ),
25021                        None => assert!(actual.is_missing()),
25022                    }
25023                }
25024            }
25025        }
25026    }
25027}